Skip to content

Commit

Permalink
gas tank (#23)
Browse files Browse the repository at this point in the history
gas Tank
  • Loading branch information
cherry-yl-sh authored Jun 4, 2024
1 parent ac28d11 commit f0b4f58
Show file tree
Hide file tree
Showing 31 changed files with 1,298 additions and 82 deletions.
2 changes: 2 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"AAStarCommunity/EthPaymaster_BackService/envirment"
"AAStarCommunity/EthPaymaster_BackService/rpc_server/routers"
"AAStarCommunity/EthPaymaster_BackService/service/dashboard_service"
"AAStarCommunity/EthPaymaster_BackService/sponsor_manager"
"flag"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -69,6 +70,7 @@ func initEngine(strategyPath string, basicConfigPath string, secretPath string)
logrus.SetLevel(logrus.InfoLevel)
}
dashboard_service.Init()
sponsor_manager.Init()
logrus.Infof("Environment: %s", envirment.Environment.Name)
logrus.Infof("Debugger: %v", envirment.Environment.Debugger)
Engine = routers.SetRouters()
Expand Down
2 changes: 1 addition & 1 deletion common/data_utils/data_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func GetUserOpWithPaymasterAndDataForSimulate(op user_op.UserOpInput, strategy *
op.CallGasLimit = global_const.DummyCallGasLimit
}

paymasterData, err := executor.GetPaymasterData(&op, strategy, paymasterDataInput)
paymasterData, _, err := executor.GetPaymasterData(&op, strategy, paymasterDataInput)
if err != nil {
return nil, err
}
Expand Down
3 changes: 2 additions & 1 deletion common/global_const/pay_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package global_const
type PayType string

const (
PayTypeVerifying PayType = "PayTypeVerifying"
PayTypeProjectSponsor PayType = "PayTypeProjectSponsor"
PayTypeERC20 PayType = "PayTypeERC20"
PayTypeSuperVerifying PayType = "PayTypeSuperVerifying"
PayTypeUserSponsor PayType = "PayTypeUserSponsor"
)
17 changes: 17 additions & 0 deletions common/global_const/sponsor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package global_const

type UpdateType string

const (
UpdateTypeDeposit UpdateType = "deposit"
UpdateTypeLock UpdateType = "lock"
UpdateTypeWithdraw UpdateType = "withdraw"
UpdateTypeRelease UpdateType = "release"
)

type BalanceType string

const (
BalanceTypeAvailableBalance BalanceType = "available_balance"
BalanceTypeLockBalance BalanceType = "lock_balance"
)
7 changes: 4 additions & 3 deletions common/model/api_key_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package model
import "golang.org/x/time/rate"

type ApiKeyModel struct {
Disable bool `gorm:"column:disable;type:bool" json:"disable"`
ApiKey string `gorm:"column:api_key;type:varchar(255)" json:"api_key"`
RateLimit rate.Limit `gorm:"column:rate_limit;type:int" json:"rate_limit"`
Disable bool `json:"disable"`
ApiKey string `json:"api_key"`
RateLimit rate.Limit `json:"rate_limit"`
UserId int64 `json:"user_id"`
}
5 changes: 2 additions & 3 deletions common/model/api_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ type UserOpEstimateGas struct {
PaymasterPostOpGasLimit *big.Int `json:"paymasterPostOpGasLimit" binding:"required"`
GasFees *[32]byte `json:"gasFees" binding:"required"`
}
type PayReceipt struct {
TransactionHash string `json:"transaction_hash"`
Sponsor string `json:"sponsor"`
type PayResponse struct {
PayType global_const.PayType `json:"pay_type"`
}

type GetSupportEntryPointResponse struct {
Expand Down
1 change: 1 addition & 0 deletions common/model/secret_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type SecretConfig struct {
RelayDBConfig DBConfig `json:"relay_db_config"`
ApiKeyTableName string `json:"api_key_table_name"`
StrategyConfigTableName string `json:"strategy_config_table_name"`
FreeSponsorWhitelist []string `json:"free_sponsor_whitelist"`
}

type NetWorkSecretConfig struct {
Expand Down
28 changes: 28 additions & 0 deletions common/model/sponsor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package model

import "math/big"

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

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

PayUserId string
IsTestNet bool
TxInfo map[string]string
TxHash string
}
type GetSponsorTransactionsRequest struct {
}
type GetSponsorMetaDataRequest struct {
}

type Transaction struct {
}
5 changes: 3 additions & 2 deletions common/model/strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ type Strategy struct {
EntryPointInfo *EntryPointInfo `json:"entrypoint_info"`
Description string `json:"description"`
ExecuteRestriction *StrategyExecuteRestriction `json:"execute_restriction"`
Erc20TokenType global_const.TokenType
Erc20TokenType global_const.TokenType `json:"-"`
ProjectSponsor bool `json:"-"`
}
type PaymasterInfo struct {
PayMasterAddress *common.Address `json:"paymaster_address"`
Expand All @@ -41,7 +42,7 @@ func (strategy *Strategy) GetNewWork() global_const.Network {
return strategy.NetWorkInfo.NetWork
}

func (strategy *Strategy) GetUseToken() global_const.TokenType {
func (strategy *Strategy) GetGasToken() global_const.TokenType {
return strategy.NetWorkInfo.GasToken
}
func (strategy *Strategy) GetPayType() global_const.PayType {
Expand Down
52 changes: 37 additions & 15 deletions common/network/ethereum_adaptable_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"AAStarCommunity/EthPaymaster_BackService/common/user_op"
"AAStarCommunity/EthPaymaster_BackService/common/utils"
"AAStarCommunity/EthPaymaster_BackService/config"
"AAStarCommunity/EthPaymaster_BackService/schedulor"
"context"
"crypto/ecdsa"
"encoding/hex"
Expand All @@ -29,6 +30,7 @@ import (
"github.com/sirupsen/logrus"
"golang.org/x/xerrors"
"math/big"
"strings"
"sync"
)

Expand Down Expand Up @@ -59,10 +61,12 @@ func init() {

type EthereumExecutor struct {
BaseExecutor
Client *ethclient.Client
GethClient *gethclient.Client
network global_const.Network
ChainId *big.Int
Client *ethclient.Client
GethClient *gethclient.Client
network global_const.Network
ChainId *big.Int
eventListener schedulor.EventListener
webSocketClient *ethclient.Client
}

var mu sync.Mutex
Expand Down Expand Up @@ -92,12 +96,27 @@ func GetEthereumExecutor(network global_const.Network) *EthereumExecutor {
if !success {
panic(xerrors.Errorf("chainId %s is invalid", config.GetChainId(network)))
}
wsUrl := config.GetNewWorkClientURl(network)
wsUrl = strings.Replace(wsUrl, "https", "wss", 1)
webSocketClient, err := ethclient.Dial(wsUrl)
if err != nil {
panic(err)
}

eventListener, err := schedulor.NewEventListener(webSocketClient, network)
if err != nil {
panic(err)
}
go eventListener.Listen()
logrus.Debugf("after Lesten network :[%s]", network)
geth := gethclient.New(client.Client())
executorMap[network] = &EthereumExecutor{
network: network,
Client: client,
ChainId: chainId,
GethClient: geth,
network: network,
Client: client,
ChainId: chainId,
GethClient: geth,
eventListener: eventListener,
webSocketClient: webSocketClient,
}

return executorMap[network]
Expand Down Expand Up @@ -539,18 +558,21 @@ func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, str
}

}
func (executor *EthereumExecutor) GetPaymasterData(userOp *user_op.UserOpInput, strategy *model.Strategy, paymasterDataInput *paymaster_data.PaymasterDataInput) ([]byte, error) {
userOpHash, _, err := executor.GetUserOpHash(userOp, strategy)
if err != nil {
func (executor *EthereumExecutor) GetPaymasterData(userOp *user_op.UserOpInput, strategy *model.Strategy, paymasterDataInput *paymaster_data.PaymasterDataInput) (paymasterData []byte, userOpHash []byte, err error) {
userOpHash, _, hashErr := executor.GetUserOpHash(userOp, strategy)
if hashErr != nil {
logrus.Errorf("GetUserOpHash error [%v]", err)
return nil, err
return nil, nil, err
}
signer := config.GetSigner(strategy.GetNewWork())
signature, err := utils.GetSign(userOpHash, signer.PrivateKey)
if err != nil {
return nil, err
return nil, nil, err
}
dataGenerateFunc := paymaster_pay_type.GetGenerateFunc(strategy.GetPayType())
paymasterData, err := dataGenerateFunc(paymasterDataInput, signature)
return paymasterData, err
paymasterData, generateDataErr := dataGenerateFunc(paymasterDataInput, signature)
if generateDataErr != nil {
return nil, nil, generateDataErr
}
return paymasterData, userOpHash, nil
}
14 changes: 7 additions & 7 deletions common/network/ethereum_adaptable_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ func testGetPaymasterData(t *testing.T, chain global_const.Network, input *user_
dataInput := paymaster_data.NewPaymasterDataInput(strategy)
dataInput.PaymasterPostOpGasLimit = global_const.DummyPaymasterPostoperativelyBigint
dataInput.PaymasterVerificationGasLimit = global_const.DummyPaymasterOversimplificationBigint
paymasterData, err := executor.GetPaymasterData(input, strategy, dataInput)
paymasterData, _, err := executor.GetPaymasterData(input, strategy, dataInput)
if err != nil {
t.Error(err)
return
Expand All @@ -301,7 +301,7 @@ func testSimulateHandleOp(t *testing.T, chain global_const.Network, strategy *mo
dataInput := paymaster_data.NewPaymasterDataInput(strategy)
op.AccountGasLimits = user_op.DummyAccountGasLimits
op.GasFees = user_op.DummyGasFees
paymasterData, err := sepoliaExector.GetPaymasterData(op, strategy, dataInput)
paymasterData, _, err := sepoliaExector.GetPaymasterData(op, strategy, dataInput)
if err != nil {
t.Error(err)
return
Expand Down 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/paymaster_pay_type/paymaster_data_generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ var basicPaymasterDataFunc = func(data *paymaster_data.PaymasterDataInput, signa
}

func init() {
paymasterDataFuncMap[global_const.PayTypeVerifying] = basicPaymasterDataFunc
paymasterDataFuncMap[global_const.PayTypeProjectSponsor] = basicPaymasterDataFunc
paymasterDataFuncMap[global_const.PayTypeERC20] = basicPaymasterDataFunc
paymasterDataFuncMap[global_const.PayTypeSuperVerifying] = func(data *paymaster_data.PaymasterDataInput, signature []byte) ([]byte, error) {
packed, err := BasicPaymasterDataAbiV06.Pack(data.ValidUntil, data.ValidAfter, data.ERC20Token, data.ExchangeRate)
Expand Down
10 changes: 10 additions & 0 deletions common/price_compoent/price_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io"
"io/ioutil"
"log"
"math/big"
"net/http"
"net/url"
"os"
Expand All @@ -29,6 +30,15 @@ func init() {
URLMap[global_const.TokenTypeOP] = "https://api.coingecko.com/api/v3/simple/price?ids=optimism&vs_currencies=usd"
}

func GetTokenCostInUsd(tokenType global_const.TokenType, amount *big.Float) (*big.Float, error) {
price, err := GetPriceUsd(tokenType)
if err != nil {
return nil, xerrors.Errorf("get price error: %w", err)
}
amountInUsd := new(big.Float).Mul(new(big.Float).SetFloat64(price), amount)
return amountInUsd, nil
}

func GetPriceUsd(tokenType global_const.TokenType) (float64, error) {

if global_const.IsStableToken(tokenType) {
Expand Down
18 changes: 17 additions & 1 deletion common/utils/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/ethereum/go-ethereum/rpc"
"github.com/sirupsen/logrus"
"golang.org/x/xerrors"
"gorm.io/gorm"
"math/big"
"regexp"
"runtime"
Expand Down Expand Up @@ -97,7 +98,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 Expand Up @@ -200,3 +201,18 @@ func GetCurrentGoroutineStack() string {
n := runtime.Stack(buf[:], false)
return string(buf[:n])
}
func DBTransactional(db *gorm.DB, handle func() error) (err error) {
tx := db.Begin()
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit().Error
}
}()
err = handle()
return
}
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: 1 addition & 1 deletion config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestConfigInit(t *testing.T) {
t.Error("strategy is nil")
return
}
strategySuit, err := GetSuitableStrategy(global_const.EntrypointV06, global_const.EthereumSepolia, global_const.PayTypeVerifying)
strategySuit, err := GetSuitableStrategy(global_const.EntrypointV06, global_const.EthereumSepolia, global_const.PayTypeProjectSponsor)
if err != nil {

t.Error("strategySuit is nil")
Expand Down
5 changes: 5 additions & 0 deletions config/secret_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ func secretConfigInit(secretConfigPath string) {
signerConfig[global_const.Network(network)] = eoa
}
}
func IsSponsorWhitelist(address string) bool {

//TODO
return true
}
func GetNetworkSecretConfig(network global_const.Network) model.NetWorkSecretConfig {
return secretConfig.NetWorkSecretConfigMap[string(network)]
}
Expand Down
2 changes: 1 addition & 1 deletion gas_executor/gas_validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ var (
)

func init() {
gasValidateFuncMap[global_const.PayTypeVerifying] = verifyingGasValidateFunc
gasValidateFuncMap[global_const.PayTypeProjectSponsor] = verifyingGasValidateFunc
gasValidateFuncMap[global_const.PayTypeERC20] = erc20GasValidateFunc
gasValidateFuncMap[global_const.PayTypeSuperVerifying] = superGasValidateFunc
}
Expand Down
4 changes: 3 additions & 1 deletion rpc_server/api/v1/paymaster.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ func TryPayUserOperationMethod() MethodFunctionFunc {
}
logrus.Debugf("After Validate ")

if result, err := operator.TryPayUserOpExecute(request); err != nil {
apiKeyModel := ctx.MustGet(global_const.ContextKeyApiMoDel)

if result, err := operator.TryPayUserOpExecute(apiKeyModel.(*model.ApiKeyModel), request); err != nil {
return nil, xerrors.Errorf("TryPayUserOpExecute ERROR [%v]", err)
} else {
return result, nil
Expand Down
Loading

0 comments on commit f0b4f58

Please sign in to comment.