Skip to content

Commit

Permalink
update Sponsor
Browse files Browse the repository at this point in the history
  • Loading branch information
cherry-yl-sh committed May 27, 2024
1 parent 499de5e commit 3f6e98e
Show file tree
Hide file tree
Showing 11 changed files with 284 additions and 33 deletions.
15 changes: 9 additions & 6 deletions common/model/sponsor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ package model
import "math/big"

type DepositSponsorRequest struct {
Source string
Amount *big.Float
TxReceipt string
Source string
Amount *big.Float
TxHash string

TxInfo map[string]string
PayUserId string
IsTestNet bool
}
type WithdrawSponsorRequest struct {
Source string
Amount *big.Float
TxReceipt string
Amount *big.Float

PayUserId string
IsTestNet bool
TxInfo map[string]string
TxHash string
}
type GetSponsorTransactionsRequest struct {
}
Expand Down
10 changes: 5 additions & 5 deletions common/network/ethereum_adaptable_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,12 +338,12 @@ func parseOpToMapV7(input user_op.UserOpInput) map[string]string {
opMap := make(map[string]string)
opMap["sender"] = input.Sender.String()
opMap["Nonce"] = input.Nonce.String()
opMap["initCode"] = utils.EncodeToStringWithPrefix(input.InitCode[:])
opMap["accountGasLimits"] = utils.EncodeToStringWithPrefix(input.AccountGasLimits[:])
opMap["initCode"] = utils.EncodeToHexStringWithPrefix(input.InitCode[:])
opMap["accountGasLimits"] = utils.EncodeToHexStringWithPrefix(input.AccountGasLimits[:])
opMap["preVerificationGas"] = input.PreVerificationGas.String()
opMap["gasFees"] = utils.EncodeToStringWithPrefix(input.GasFees[:])
opMap["paymasterAndData"] = utils.EncodeToStringWithPrefix(input.PaymasterAndData[:])
opMap["signature"] = utils.EncodeToStringWithPrefix(input.Signature[:])
opMap["gasFees"] = utils.EncodeToHexStringWithPrefix(input.GasFees[:])
opMap["paymasterAndData"] = utils.EncodeToHexStringWithPrefix(input.PaymasterAndData[:])
opMap["signature"] = utils.EncodeToHexStringWithPrefix(input.Signature[:])
return opMap
}

Expand Down
2 changes: 1 addition & 1 deletion common/utils/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func GetGasEntryPointGasPrice(maxFeePerGas *big.Int, maxPriorityFeePerGas *big.I
return GetMinValue(maxFeePerGas, combineFee)
}

func EncodeToStringWithPrefix(data []byte) string {
func EncodeToHexStringWithPrefix(data []byte) string {
res := hex.EncodeToString(data)
if res[:2] != "0x" {
return "0x" + res
Expand Down
2 changes: 1 addition & 1 deletion common/utils/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestPackIntTo32Bytes(t *testing.T) {

bytes := PackIntTo32Bytes(big.NewInt(2312), big.NewInt(2312))

resStr := EncodeToStringWithPrefix(bytes[:])
resStr := EncodeToHexStringWithPrefix(bytes[:])
t.Logf("resStr: %s\n", resStr)
}

Expand Down
2 changes: 2 additions & 0 deletions rpc_server/routers/routers_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func init() {
PublicRouterMaps = append(PublicRouterMaps, RouterMap{string(GetSponsorLog), []RestfulMethod{GET}, v1.GetSponsorDepositAndWithdrawTransactions})
PublicRouterMaps = append(PublicRouterMaps, RouterMap{string(DepositSponsor), []RestfulMethod{POST}, v1.DepositSponsor})
PublicRouterMaps = append(PublicRouterMaps, RouterMap{string(WithdrawSponsor), []RestfulMethod{POST}, v1.WithdrawSponsor})
PublicRouterMaps = append(PublicRouterMaps, RouterMap{string(GetSponsorData), []RestfulMethod{GET}, v1.GetSponsorMetaData})
}

type Path string
Expand All @@ -27,4 +28,5 @@ const (
GetSponsorLog Path = "api/v1/paymaster_sponsor/deposit_log"
DepositSponsor Path = "api/v1/paymaster_sponsor/deposit"
WithdrawSponsor Path = "api/v1/paymaster_sponsor/withdraw"
GetSponsorData Path = "api/v1/paymaster_sponsor/data"
)
2 changes: 1 addition & 1 deletion schedulor/UserOpEventListener.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func UserOpEventComunicate(network global_const.Network, event ContractUserOpera
return
}
if !event.Success {
err := sponsor_manager.ReleaseUserOpHashLock(event.UserOpHash[:])
err := sponsor_manager.ReleaseUserOpHashLock(event.UserOpHash[:], true)
if err != nil {
logrus.Errorf("ReleaseUserOpHashLock failed: %v", err)
}
Expand Down
6 changes: 3 additions & 3 deletions service/operator/try_pay_user_op_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func postExecute(apiKeyModel *model.ApiKeyModel, userOp *user_op.UserOpInput, st
Erc20TokenCost: gasResponse.Erc20TokenCost,

UserOpResponse: &model.UserOpResponse{
PayMasterAndData: utils.EncodeToStringWithPrefix(paymasterData),
PayMasterAndData: utils.EncodeToHexStringWithPrefix(paymasterData),
PreVerificationGas: gasResponse.OpEstimateGas.PreVerificationGas,
MaxFeePerGas: gasResponse.OpEstimateGas.MaxFeePerGas,
MaxPriorityFeePerGas: gasResponse.OpEstimateGas.MaxPriorityFeePerGas,
Expand All @@ -189,8 +189,8 @@ func postExecute(apiKeyModel *model.ApiKeyModel, userOp *user_op.UserOpInput, st
}

if strategy.GetStrategyEntrypointVersion() == global_const.EntrypointV07 {
result.UserOpResponse.AccountGasLimit = utils.EncodeToStringWithPrefix(gasResponse.OpEstimateGas.AccountGasLimit[:])
result.UserOpResponse.GasFees = utils.EncodeToStringWithPrefix(gasResponse.OpEstimateGas.GasFees[:])
result.UserOpResponse.AccountGasLimit = utils.EncodeToHexStringWithPrefix(gasResponse.OpEstimateGas.AccountGasLimit[:])
result.UserOpResponse.GasFees = utils.EncodeToHexStringWithPrefix(gasResponse.OpEstimateGas.GasFees[:])
result.UserOpResponse.PaymasterVerificationGasLimit = gasResponse.OpEstimateGas.PaymasterVerificationGasLimit
result.UserOpResponse.PaymasterPostOpGasLimit = gasResponse.OpEstimateGas.PaymasterPostOpGasLimit
}
Expand Down
59 changes: 57 additions & 2 deletions sponsor_manager/sponsor_balance_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package sponsor_manager

import (
"AAStarCommunity/EthPaymaster_BackService/common/model"
"AAStarCommunity/EthPaymaster_BackService/config"
"fmt"
"math/big"
)

Expand All @@ -17,7 +17,7 @@ type UserSponsorBalanceDBModel struct {
}

func (UserSponsorBalanceDBModel) TableName() string {
return config.GetStrategyConfigTableName()
return "relay_user_sponsor_balance"
}

func CreateSponsorBalance(balanceModel *UserSponsorBalanceDBModel) error {
Expand All @@ -39,3 +39,58 @@ func getUserSponsorBalance(userId string, isTestNet bool) (balanceModel *UserSpo
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", userId).Where("is_test_net = ?", isTestNet).First(&balanceModel)
return balanceModel, tx.Error
}

// BigFloat wraps big.Float to implement sql.Scanner
type BigFloat struct {
*big.Float
}

// Scan implements the sql.Scanner interface for BigFloat
func (b *BigFloat) Scan(value interface{}) error {
if b == nil {
fmt.Println("BigFloat Scan value is nil")
return nil
}
fmt.Println("BigFloat Scan value", value)
switch v := value.(type) {
case string:

if _, ok := b.SetString(v); !ok {
return fmt.Errorf("failed to parse string as *big.Float: %s", v)
}
case []byte:
fmt.Println("BigFloat Scan value Case Byte", value)

if _, ok := b.SetString(string(v)); !ok {
return fmt.Errorf("failed to parse byte slice as *big.Float: %s", string(v))
}
default:
return fmt.Errorf("unsupported type: %T", v)
}
return nil
}

func SelectUserSponsorBalanceDBModelWithScanList() (userSponsorBalanceDBModelWithScanList []UserSponsorBalanceDBModelWithScan, err error) {
userSponsorBalanceDBModelWithScanList = make([]UserSponsorBalanceDBModelWithScan, 0)
tx := relayDB.Model(&UserSponsorBalanceDBModelWithScan{}).Find(&userSponsorBalanceDBModelWithScanList)
if tx.Error != nil {
err = tx.Error
return
}
fmt.Println(userSponsorBalanceDBModelWithScanList)
return userSponsorBalanceDBModelWithScanList, nil
}

type UserSponsorBalanceDBModelWithScan struct {
model.BaseData
PayUserId string `gorm:"type:varchar(255);index" json:"pay_user_id"`
AvailableBalance float64 `gorm:"type:numeric(30,18)" json:"available_balance"`
LockBalance float64 `gorm:"type:numeric(30,18)" json:"lock_balance"`
Source string `gorm:"type:varchar(255)" json:"source"`
SponsorAddress string `gorm:"type:varchar(255)" json:"sponsor_address"`
IsTestNet bool `gorm:"type:boolean" json:"is_test_net"`
}

func (UserSponsorBalanceDBModelWithScan) TableName() string {
return "relay_user_sponsor_balance"
}
37 changes: 35 additions & 2 deletions sponsor_manager/sponsor_changelog_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package sponsor_manager
import (
"AAStarCommunity/EthPaymaster_BackService/common/global_const"
"AAStarCommunity/EthPaymaster_BackService/common/model"
"AAStarCommunity/EthPaymaster_BackService/config"
"gorm.io/datatypes"
"math/big"
)
Expand All @@ -21,10 +20,14 @@ type UserSponsorBalanceUpdateLogDBModel struct {
}

func (UserSponsorBalanceUpdateLogDBModel) TableName() string {
return config.GetStrategyConfigTableName()
return "relay_user_sponsor_balance_update_log"
}

func AddBalanceChangeLog(changeDbModel *UserSponsorBalanceUpdateLogDBModel) error {
return relayDB.Create(changeDbModel).Error
}
func LogBalanceChange(updateType global_const.UpdateType, balanceType global_const.BalanceType, data interface{}, amount *big.Float) {

//TODO
return
}
Expand All @@ -35,3 +38,33 @@ func GetDepositAndWithDrawLog(userId string, IsTestNet bool) (models []*UserSpon
}
return models, nil
}
func LockBalanceChangeLog(payUserid string, userOpHash string, amount *big.Float, isTestNet bool, updateReason string) error {
logModel := &UserSponsorBalanceUpdateLogDBModel{
PayUserId: payUserid,
Amount: amount,
UserOpHash: userOpHash,
Source: "GasTank",
IsTestNet: isTestNet,
}
return relayDB.Create(logModel).Error
}
func GetChangeModel(updateType global_const.UpdateType, payUserId string, txHash string, isTestNet bool) (ChangeModel *UserSponsorBalanceUpdateLogDBModel, err error) {
if updateType == global_const.UpdateTypeDeposit || updateType == global_const.UpdateTypeWithdraw {

tx := relayDB.Model(ChangeModel).Where("tx_hash = ?", txHash).Where("pay_user_id", payUserId).Where("update_type = ?", global_const.UpdateTypeDeposit).Where("is_test_net", isTestNet).First(&ChangeModel)
if tx.Error != nil {
return nil, tx.Error
} else {
return ChangeModel, nil
}
} else if updateType == global_const.UpdateTypeLock || updateType == global_const.UpdateTypeRelease {
tx := relayDB.Model(ChangeModel).Where("user_op_hash = ?", txHash).Where("update_type = ?", global_const.UpdateTypeLock).Where("is_test_net", isTestNet).First(&ChangeModel)
if tx.Error != nil {
return nil, tx.Error
} else {
return ChangeModel, nil
}
} else {
return nil, nil
}
}
Loading

0 comments on commit 3f6e98e

Please sign in to comment.