Skip to content

Commit

Permalink
test_optimize (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
cherry-yl-sh authored Jun 21, 2024
1 parent 58f453d commit 4d6fb39
Show file tree
Hide file tree
Showing 24 changed files with 222 additions and 127 deletions.
2 changes: 1 addition & 1 deletion common/global_const/common_const.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const (

ContextKeyApiMoDel = "api_model"
StrategyStatusDisable StrategyStatus = "disable"
StrategyStatusAchieve StrategyStatus = "enable"
StrategyStatusAchive StrategyStatus = "enable"
)

var (
Expand Down
15 changes: 11 additions & 4 deletions common/model/api_key_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@ package model
import "golang.org/x/time/rate"

type ApiKeyModel struct {
Disable bool `json:"disable"`
ApiKey string `json:"api_key"`
RateLimit rate.Limit `json:"rate_limit"`
UserId int64 `json:"user_id"`
Disable bool `json:"disable"`
ApiKey string `json:"api_key"`
RateLimit rate.Limit `json:"rate_limit"`
UserId int64 `json:"user_id"`
NetWorkLimitEnable bool `json:"network_limit_enable"`
DomainWhitelist []string `json:"domain_whitelist"`
IPWhiteList []string `json:"ip_white_list"`
PaymasterEnable bool `json:"paymaster_enable"`
Erc20PaymasterEnable bool `json:"erc20_paymaster_enable"`
ProjectSponsorPaymasterEnable bool `json:"project_sponsor_paymaster_enable"`
UserPayPaymasterEnable bool `json:"user_pay_paymaster_enable"`
}
10 changes: 8 additions & 2 deletions common/model/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,26 @@ import (
const EnvKey = "Env"
const ProdEnv = "prod"
const DevEnv = "dev"
const UnitEnv = "unit"

type Env struct {
Name string // env Name, like `prod`, `dev` and etc.,
Debugger bool // whether to use debugger
}

func (env *Env) IsDevelopment() bool {
return strings.EqualFold(DevEnv, env.Name)
return strings.EqualFold(DevEnv, env.Name) || strings.EqualFold(UnitEnv, env.Name)
}
func (env *Env) IsUnit() bool {
return strings.EqualFold(UnitEnv, env.Name)
}

func (env *Env) IsProduction() bool {
return strings.EqualFold(ProdEnv, env.Name)
}

func (env *Env) GetEnvName() *string {
return &env.Name
}
func (env *Env) SetUnitEnv() {
env.Name = UnitEnv
}
14 changes: 6 additions & 8 deletions common/model/secret_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,15 @@ 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"`
SponsorConfig SponsorConfig `json:"sponsor_config"`
}
type SponsorConfig struct {
SponsorDepositAddress string `json:"sponsor_deposit_address"`
SponsorDepositPrivateKey string `json:"sponsor_deposit_private_key"`
DashBoardSignerAddress string `json:"dashboard_signer_address"`
DepositTestNetUrl string `json:"deposit_test_net_url"`
DepositMainNetUrl string `json:"deposit_main_net_url"`
SponsorTestClientUrl string `json:"sponsor_client_rpc_test_net"`
SponsorMainClientUrl string `json:"sponsor_client_rpc_main_net"`
SponsorDepositAddress string `json:"sponsor_deposit_address"`
SponsorWithdrawPrivateKey string `json:"sponsor_withdraw_private_key"`
DashBoardSignerAddress string `json:"dashboard_signer_address"`
SponsorTestClientUrl string `json:"sponsor_client_rpc_test_net"`
SponsorMainClientUrl string `json:"sponsor_client_rpc_main_net"`
FreeSponsorWhitelist []string `json:"free_sponsor_whitelist"`
}

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

type DepositSponsorRequest struct {
TimeStamp int64 `json:"time_stamp"`
DepositAddress string `json:"deposit_address"`
TxHash string `json:"tx_hash"`
IsTestNet bool `json:"is_test_net"`
PayUserId string `json:"pay_user_id"`
DepositSource string `json:"deposit_source"`
TimeStamp int64 `json:"time_stamp"`
TxHash string `json:"tx_hash"`
IsTestNet bool `json:"is_test_net"`
PayUserId string `json:"pay_user_id"`
DepositSource string `json:"deposit_source"`
}
type WithdrawSponsorRequest struct {
Amount float64 `json:"amount"`
Expand Down
55 changes: 33 additions & 22 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/envirment"
"AAStarCommunity/EthPaymaster_BackService/schedulor"
"context"
"crypto/ecdsa"
Expand Down Expand Up @@ -96,28 +97,35 @@ 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,
eventListener: eventListener,
webSocketClient: webSocketClient,
ethExecutor := &EthereumExecutor{
network: network,
Client: client,
ChainId: chainId,
GethClient: geth,
}

if !envirment.Environment.IsUnit() {
logrus.Infof("Init EventListener network :[%s]", network)
wsUrl := config.GetNewWorkClientURl(network)
wsUrl = strings.Replace(wsUrl, "https", "wss", 1)
logrus.Debugf("wsUrl: %s", wsUrl)
webSocketClient, err := ethclient.Dial(wsUrl)
if err != nil {
panic(err)
}

eventListener, err := schedulor.NewEventListener(webSocketClient, network)
if err != nil {
panic(err)
}
go eventListener.Listen()
ethExecutor.eventListener = eventListener
ethExecutor.webSocketClient = webSocketClient
}
executorMap[network] = ethExecutor

return executorMap[network]
}
Expand Down Expand Up @@ -493,7 +501,7 @@ func GetAuth(chainId *big.Int, privateKey *ecdsa.PrivateKey) (*bind.TransactOpts
Context: context.Background(),
}, nil
}
func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, strategy *model.Strategy) ([]byte, string, error) {
func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, strategy *model.Strategy, paymasterDataInput *paymaster_data.PaymasterDataInput) ([]byte, string, error) {
version := strategy.GetStrategyEntrypointVersion()
erc20Token := common.HexToAddress("0x")
payType := strategy.GetPayType()
Expand Down Expand Up @@ -523,7 +531,7 @@ func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, str
}
jsonString, _ := json.Marshal(contractUserOp)
logrus.Debug("opString :", string(jsonString))
hash, err := contract.GetHash(&bind.CallOpts{}, contractUserOp, strategy.ExecuteRestriction.EffectiveEndTime, strategy.ExecuteRestriction.EffectiveStartTime, erc20Token, big.NewInt(0))
hash, err := contract.GetHash(&bind.CallOpts{}, contractUserOp, paymasterDataInput.ValidUntil, paymasterDataInput.ValidAfter, erc20Token, big.NewInt(0))
if err != nil {
return nil, "", err
}
Expand All @@ -547,7 +555,7 @@ func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, str

jsonString, _ := json.Marshal(packUserOp)
logrus.Debug("opString:", string(jsonString))
hash, err := contract.GetHash(&bind.CallOpts{}, packUserOp, strategy.ExecuteRestriction.EffectiveEndTime, strategy.ExecuteRestriction.EffectiveStartTime, erc20Token, big.NewInt(0))
hash, err := contract.GetHash(&bind.CallOpts{}, packUserOp, paymasterDataInput.ValidUntil, paymasterDataInput.ValidAfter, erc20Token, big.NewInt(0))
if err != nil {
return nil, "", err
}
Expand All @@ -559,7 +567,7 @@ func (executor *EthereumExecutor) GetUserOpHash(userOp *user_op.UserOpInput, str

}
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)
userOpHash, _, hashErr := executor.GetUserOpHash(userOp, strategy, paymasterDataInput)
if hashErr != nil {
logrus.Errorf("GetUserOpHash error [%v]", err)
return nil, nil, err
Expand All @@ -570,6 +578,9 @@ func (executor *EthereumExecutor) GetPaymasterData(userOp *user_op.UserOpInput,
return nil, nil, err
}
dataGenerateFunc := paymaster_pay_type.GetGenerateFunc(strategy.GetPayType())
if dataGenerateFunc == nil {
return nil, nil, xerrors.Errorf("payType [%s] not support", strategy.GetPayType())
}
paymasterData, generateDataErr := dataGenerateFunc(paymasterDataInput, signature)
if generateDataErr != nil {
return nil, nil, generateDataErr
Expand Down
9 changes: 8 additions & 1 deletion common/network/ethereum_adaptable_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"encoding/json"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
"math/big"
"testing"
"time"
)
Expand Down Expand Up @@ -267,7 +268,13 @@ func testGetUserOpHash(t *testing.T, input user_op.UserOpInput, strategy *model.
input.AccountGasLimits = user_op.DummyAccountGasLimits
input.GasFees = user_op.DummyGasFees
}
res, _, err := executor.GetUserOpHash(&input, strategy)
now := time.Now()
start := now.Add(-1 * time.Second)
end := now.Add(5 * time.Minute)
res, _, err := executor.GetUserOpHash(&input, strategy, &paymaster_data.PaymasterDataInput{
ValidUntil: big.NewInt(end.Unix()),
ValidAfter: big.NewInt(start.Unix()),
})
if err != nil {
t.Error(err)
return
Expand Down
10 changes: 6 additions & 4 deletions common/paymaster_data/paymaster_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
"math/big"
"time"
)

type PaymasterDataInput struct {
Expand All @@ -22,8 +23,9 @@ type PaymasterDataInput struct {
}

func NewPaymasterDataInput(strategy *model.Strategy) *PaymasterDataInput {
start := strategy.ExecuteRestriction.EffectiveStartTime
end := strategy.ExecuteRestriction.EffectiveEndTime
now := time.Now()
start := now.Add(-1 * time.Second)
end := now.Add(5 * time.Minute)
var tokenAddress string
if strategy.GetPayType() == global_const.PayTypeERC20 {
tokenAddress = config.GetTokenAddress(strategy.GetNewWork(), strategy.Erc20TokenType)
Expand All @@ -35,8 +37,8 @@ func NewPaymasterDataInput(strategy *model.Strategy) *PaymasterDataInput {

return &PaymasterDataInput{
Paymaster: *strategy.GetPaymasterAddress(),
ValidUntil: big.NewInt(end.Int64()),
ValidAfter: big.NewInt(start.Int64()),
ValidUntil: big.NewInt(end.Unix()),
ValidAfter: big.NewInt(start.Unix()),
ERC20Token: common.HexToAddress(tokenAddress),
ExchangeRate: big.NewInt(0),
PayType: strategy.GetPayType(),
Expand Down
1 change: 1 addition & 0 deletions common/paymaster_pay_type/paymaster_data_generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var basicPaymasterDataFunc = func(data *paymaster_data.PaymasterDataInput, signa
func init() {
paymasterDataFuncMap[global_const.PayTypeProjectSponsor] = basicPaymasterDataFunc
paymasterDataFuncMap[global_const.PayTypeERC20] = basicPaymasterDataFunc
paymasterDataFuncMap[global_const.PayTypeUserSponsor] = 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)
if err != nil {
Expand Down
13 changes: 12 additions & 1 deletion common/price_compoent/price_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"AAStarCommunity/EthPaymaster_BackService/common/global_const"
"AAStarCommunity/EthPaymaster_BackService/config"
"fmt"
"github.com/sirupsen/logrus"
"golang.org/x/xerrors"
"io"
"io/ioutil"
Expand Down Expand Up @@ -56,12 +57,22 @@ func GetPriceUsd(tokenType global_const.TokenType) (float64, error) {
req.Header.Add("x-cg-demo-api-key", config.GetPriceOracleApiKey())

res, _ := http.DefaultClient.Do(req)
logrus.Debugf("get price req: %v", req)
logrus.Debugf("get price response: %v", res)
if res == nil {
return 0, xerrors.Errorf("get price error: %w", "response is nil")
}
if res.StatusCode != 200 {
return 0, xerrors.Errorf("get price error: %w", res.Status)

}

defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
bodystr := string(body)
strarr := strings.Split(bodystr, ":")
usdstr := strings.TrimRight(strarr[2], "}}")
defer res.Body.Close()

return strconv.ParseFloat(usdstr, 64)
}

Expand Down
2 changes: 1 addition & 1 deletion common/utils/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func GenerateMockUservOperation() *map[string]any {
"maxPriorityFeePerGas": "0x59682f00",
"nonce": "0x00",
"preVerificationGas": "0xae64",
"sender": "0xffdb071c2b58ccc10ad386f9bb4e8d3d664ce73c",
"sender": "0xFfDB071C2b58CCC10Ad386f9Bb4E8d3d664CE73c",
"signature": "0xaa846693598194980f3bf50486be854704534c1622d0c2ee895a5a1ebe1508221909a27cc7971d9f522c8df13b9d8a6ee446d09ea7635f31c59d77d35d1281421c",
"verificationGasLimit": "0x05fa35",
}
Expand Down
24 changes: 2 additions & 22 deletions config/basic_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
"ethereum-sepolia": {
"chain_id": "11155111",
"is_test": true,
"rpc_url": "https://eth-sepolia.g.alchemy.com/v2",
"api_key": "wKeLycGxgYRykgf0aGfcpEkUtqyLQg4v",
"signer_key" : "752d81d71afd0b25a09f24718baf82c0846cc3b68122cfb3a1d41529c8a46b05",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
"v06_paymaster_address" : "0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
Expand All @@ -19,9 +16,6 @@
"optimism-sepolia": {
"chain_id": "11155420",
"is_test": true,
"rpc_url": "https://opt-sepolia.g.alchemy.com/v2",
"api_key": "_z0GaU6Zk8RfIR1guuli8nqMdb8RPdp0",
"signer_key" : "1d8a58126e87e53edc7b24d58d1328230641de8c4242c135492bf5560e0ff421",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
"v06_paymaster_address" : "0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
Expand All @@ -35,9 +29,6 @@
"arbitrum-sepolia": {
"chain_id": "421614",
"is_test": true,
"rpc_url": "https://arb-sepolia.g.alchemy.com/v2",
"api_key": "xSBkiidslrZmlcWUOSF3AluKx0A9g_kl",
"signer_key" : "752d81d71afd0b25a09f24718baf82c0846cc3b68122cfb3a1d41529c8a46b05",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
"v06_paymaster_address" : "0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
Expand All @@ -51,9 +42,6 @@
"scroll-sepolia": {
"chain_id": "534351",
"is_test": true,
"rpc_url": "https://sepolia-rpc.scroll.io",
"api_key": "9DGRNUARDVGDPZWN2G55I3Y5NG7HQJBUTH",
"signer_key" : "752d81d71afd0b25a09f24718baf82c0846cc3b68122cfb3a1d41529c8a46b05",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
"v06_paymaster_address" : "0x0Fa9ee28202F8602E9a4C99Af799C75C29AFbC89",
Expand All @@ -67,9 +55,6 @@
"starknet-sepolia": {
"chain_id": "534351",
"is_test": true,
"rpc_url": "https://starknet-sepolia.infura.io/v3",
"api_key": "0284f5a9fc55476698079b24e2f97909",
"signer_key" : "752d81d71afd0b25a09f24718baf82c0846cc3b68122cfb3a1d41529c8a46b05",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
"v06_paymaster_address" : "0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
Expand All @@ -83,9 +68,6 @@
"base-sepolia": {
"chain_id": "84532",
"is_test": true,
"rpc_url": "https://base-sepolia.g.alchemy.com/v2",
"api_key": "zUhtd18b2ZOTIJME6rv2Uwz9q7PBnnsa",
"signer_key" : "752d81d71afd0b25a09f24718baf82c0846cc3b68122cfb3a1d41529c8a46b05",
"v06_entrypoint_address" : "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
"v07_entrypoint_address" : "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
"v06_paymaster_address" : "0xa86cFf572E299B2704FBBCF77dcbbc7FEfFbcA06",
Expand Down Expand Up @@ -121,8 +103,7 @@
},
"support_paymaster": {
"ethereum-sepolia": [
"0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
"0x3Da96267B98a33267249734FD8FFeC75093D3085"
"0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f"
],
"optimism-sepolia": [
"0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
Expand All @@ -140,6 +121,5 @@
"0xF2147CA7f18e8014b76e1A98BaffC96ebB90a29f",
"0x2"
]
},
"price_oracle_api_key": "CG-ioE6p8cmmSFBFwJnKECCbZ7U"
}
}
Loading

0 comments on commit 4d6fb39

Please sign in to comment.