Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Monitor and optimize #26

Merged
merged 30 commits into from
Jun 6, 2024
Merged
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
84502e7
update go.mod
cherry-yl-sh May 13, 2024
c80f2b1
update relay model
cherry-yl-sh May 17, 2024
45a67c0
update relay model
cherry-yl-sh May 17, 2024
f863ebf
Strategy Restriction
cherry-yl-sh May 20, 2024
4f6cae7
Strategy Restriction
cherry-yl-sh May 21, 2024
1d82fee
Strategy Restriction
cherry-yl-sh May 21, 2024
1e8de6f
mod init add DeleteAt
cherry-yl-sh May 21, 2024
317455d
go mod init
cherry-yl-sh May 21, 2024
69d948b
optimize API
cherry-yl-sh May 21, 2024
2a1f57e
optimize API
cherry-yl-sh May 21, 2024
1d26e1b
Merge remote-tracking branch 'origin/dylan/config_interate' into gas_…
cherry-yl-sh May 21, 2024
7b1c01d
Gas Tank
cherry-yl-sh May 21, 2024
37e82f1
Merge remote-tracking branch 'origin/main' into gas_tank_v1
cherry-yl-sh May 21, 2024
0b9f00f
update merge
cherry-yl-sh May 21, 2024
2d8fcb5
add DB
cherry-yl-sh May 23, 2024
2498654
add DB
cherry-yl-sh May 23, 2024
e7cf691
add Sponsor
cherry-yl-sh May 24, 2024
499de5e
update Sponsor
cherry-yl-sh May 24, 2024
3f6e98e
update Sponsor
cherry-yl-sh May 27, 2024
c4141cf
Fix Float Problem
cherry-yl-sh May 27, 2024
9754d6d
update Sponsor
cherry-yl-sh May 28, 2024
3d9736b
update Sponsor
cherry-yl-sh May 28, 2024
2ab2e64
update Sponsor
cherry-yl-sh May 28, 2024
7c79240
update Sponsor
cherry-yl-sh May 28, 2024
cdc3a21
add Paymaster Mertics Log
cherry-yl-sh May 29, 2024
12d8c55
add Paymaster Mertics Log
cherry-yl-sh May 29, 2024
f99e5e4
resolve Comment
cherry-yl-sh Jun 4, 2024
6c60da7
Merge branch 'main' into monitor_and_optimize
cherry-yl-sh Jun 5, 2024
3c1391f
resolve Comment
cherry-yl-sh Jun 5, 2024
0bc2ba2
resolve Comment
cherry-yl-sh Jun 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update Sponsor
cherry-yl-sh committed May 24, 2024
commit 499de5e72561beb439393de2d6663486ddd5c696
2 changes: 2 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -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"
@@ -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()
3 changes: 2 additions & 1 deletion common/global_const/pay_type.go
Original file line number Diff line number Diff line change
@@ -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"
)
5 changes: 2 additions & 3 deletions common/model/api_response.go
Original file line number Diff line number Diff line change
@@ -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 {
2 changes: 2 additions & 0 deletions common/model/sponsor.go
Original file line number Diff line number Diff line change
@@ -7,12 +7,14 @@ type DepositSponsorRequest struct {
Amount *big.Float
TxReceipt string
PayUserId string
IsTestNet bool
}
type WithdrawSponsorRequest struct {
Source string
Amount *big.Float
TxReceipt string
PayUserId string
IsTestNet bool
}
type GetSponsorTransactionsRequest struct {
}
2 changes: 1 addition & 1 deletion common/paymaster_pay_type/paymaster_data_generate.go
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion config/config_test.go
Original file line number Diff line number Diff line change
@@ -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")
2 changes: 1 addition & 1 deletion gas_executor/gas_validate.go
Original file line number Diff line number Diff line change
@@ -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
}
43 changes: 41 additions & 2 deletions rpc_server/api/v1/sponsor.go
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"net/http"
"strconv"
)

// DepositSponsor
@@ -17,6 +18,7 @@ import (
// @Accept json
// @Product json
// @Param request body DepositSponsorRequest true "DepositSponsorRequest Model
// @Param is_test_net path boolean true "Is Test Net"
// @Router /api/v1/paymaster_sponsor/deposit [post]
// @Success 200
func DepositSponsor(ctx *gin.Context) {
@@ -43,6 +45,7 @@ func DepositSponsor(ctx *gin.Context) {
// @Accept json
// @Product json
// @Param request body WithdrawSponsorRequest true "WithdrawSponsorRequest Model"
// @Param is_test_net path boolean true "Is Test Net"
// @Router /api/v1/paymaster_sponsor/withdraw [post]
// @Success 200
func WithdrawSponsor(ctx *gin.Context) {
@@ -75,12 +78,16 @@ type SponsorDepositTransaction struct {
// @Accept json
// @Product json
// @Param userId path string true "User Id"
// @Param is_test_net path boolean true "Is Test Net"
// @Router /api/v1/paymaster_sponsor/deposit_log
// @Success 200
func GetSponsorDepositAndWithdrawTransactions(ctx *gin.Context) {
userId := ctx.Param("userId")
userId := ctx.Param("user_id")
textNet := ctx.Param("is_test_net")
// convertTOBool
isTestNet, _ := strconv.ParseBool(textNet)
response := model.GetResponse()
models, err := sponsor_manager.GetDepositAndWithDrawLog(userId)
models, err := sponsor_manager.GetDepositAndWithDrawLog(userId, isTestNet)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
response.FailCode(ctx, 301, "No Deposit Transactions")
@@ -97,3 +104,35 @@ func GetSponsorDepositAndWithdrawTransactions(ctx *gin.Context) {
response.WithDataSuccess(ctx, trans)
return
}

type SponsorMetaResponse struct {
AvailableBalance string `json:"available_balance"`
SponsorAddress string `json:"sponsor_address"`
}

// GetSponsorMetaData
// @Tags Sponsor
// @Description Get Sponsor Balance
// @Accept json
// @Product json
// @Param userId path string true "User Id"
// @Router /api/v1/paymaster_sponsor/balance/{userId}
// @Success 200
func GetSponsorMetaData(ctx *gin.Context) {
userId := ctx.Param("userId")
textNet := ctx.Param("is_test_net")
isTestNet, _ := strconv.ParseBool(textNet)
response := model.GetResponse()
balance, err := sponsor_manager.FindUserSponsorBalance(userId, isTestNet)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
response.FailCode(ctx, 301, "No Balance")
}
}
result := SponsorMetaResponse{
AvailableBalance: balance.AvailableBalance.String(),
SponsorAddress: balance.SponsorAddress,
}
response.WithDataSuccess(ctx, result)
return
}
4 changes: 2 additions & 2 deletions service/dashboard_service/dashboard_service.go
Original file line number Diff line number Diff line change
@@ -142,7 +142,7 @@ func convertStrategyDBModelToStrategy(strategyDBModel *StrategyDBModel, entryPoi
},
PaymasterInfo: &model.PaymasterInfo{
PayMasterAddress: config.GetPaymasterAddress(network, entryPointVersion),
PayType: global_const.PayTypeVerifying,
PayType: global_const.PayTypeProjectSponsor,
IsProjectErc20PayEnable: false,
},
ExecuteRestriction: strategyExecuteRestriction,
@@ -171,7 +171,7 @@ func GetSuitableStrategy(entryPointVersion global_const.EntrypointVersion, chain
gasToken := config.GetGasToken(chain)
entryPointAddress := config.GetEntrypointAddress(chain, entryPointVersion)
paymasterAddress := config.GetPaymasterAddress(chain, entryPointVersion)
payType := global_const.PayTypeVerifying
payType := global_const.PayTypeUserSponsor
isPerc20Enable := false
if gasUseToken != "" {
payType = global_const.PayTypeERC20
13 changes: 7 additions & 6 deletions service/operator/try_pay_user_op_execute.go
Original file line number Diff line number Diff line change
@@ -92,7 +92,7 @@ func ValidateGas(userOp *user_op.UserOpInput, gasComputeResponse *model.ComputeG
return nil
}

func executePay(input *ExecutePayInput) (*model.PayReceipt, error) {
func executePay(input *ExecutePayInput) (*model.PayResponse, error) {
if input.PayType == global_const.PayTypeERC20 {
logrus.Debugf("Not Need ExecutePay In ERC20 PayType")
return nil, nil
@@ -101,6 +101,7 @@ func executePay(input *ExecutePayInput) (*model.PayReceipt, error) {
logrus.Debugf("Not Need ExecutePay In SponsorWhitelist [%s]", input.UserOpSender)
return nil, nil
}
// TODO
//if config.IsTestNet(input.Network) {
// logrus.Debugf("Not Need ExecutePay In TestNet [%s]", input.Network)
// return nil, nil
@@ -112,7 +113,8 @@ func executePay(input *ExecutePayInput) (*model.PayReceipt, error) {
} else {
payUserKey = input.UserOpSender
}
depositBalance, err := sponsor_manager.GetAvailableBalance(payUserKey)
isTestNet := config.IsTestNet(input.Network)
depositBalance, err := sponsor_manager.GetAvailableBalance(payUserKey, isTestNet)
if err != nil {
return nil, err
}
@@ -124,15 +126,14 @@ func executePay(input *ExecutePayInput) (*model.PayReceipt, error) {
return nil, xerrors.Errorf("Insufficient balance [%s] not Enough to Pay Cost [%s]", depositBalance.String(), gasUsdCost.String())
}
//Lock Deposit Balance
err = sponsor_manager.LockUserBalance(payUserKey, input.UserOpHash, input.Network,
err = sponsor_manager.LockUserBalance(payUserKey, input.UserOpHash, isTestNet,
gasUsdCost)
if err != nil {
return nil, err
}

return &model.PayReceipt{
TransactionHash: "0x110406d44ec1681fcdab1df2310181dee26ff43c37167b2c9c496b35cce69437",
Sponsor: "aastar",
return &model.PayResponse{
PayType: input.PayType,
}, nil
}

13 changes: 9 additions & 4 deletions sponsor_manager/sponsor_balance_repository.go
Original file line number Diff line number Diff line change
@@ -13,6 +13,7 @@ type UserSponsorBalanceDBModel struct {
LockBalance *big.Float `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 (UserSponsorBalanceDBModel) TableName() string {
@@ -22,15 +23,19 @@ func (UserSponsorBalanceDBModel) TableName() string {
func CreateSponsorBalance(balanceModel *UserSponsorBalanceDBModel) error {
return relayDB.Create(balanceModel).Error
}
func FindUserSponsorBalance(userId string) (balanceModel *UserSponsorBalanceDBModel, err error) {
func FindUserSponsorBalance(userId string, isTestNet bool) (balanceModel *UserSponsorBalanceDBModel, err error) {
balanceModel = &UserSponsorBalanceDBModel{}
tx := relayDB.Where("pay_user_id = ?", userId).First(balanceModel)
tx := relayDB.Where("pay_user_id = ?", userId).Where("is_test_net = ?", isTestNet).First(balanceModel)
if tx.Error != nil {
return nil, tx.Error
}
return balanceModel, nil
}
func UpdateSponsorBalance(balanceModel *UserSponsorBalanceDBModel) error {
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", balanceModel.PayUserId).Updates(balanceModel)
func UpdateSponsor(balanceModel *UserSponsorBalanceDBModel, isTestNet bool) error {
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", balanceModel.PayUserId).Where("is_test_net = ?", isTestNet).Updates(balanceModel)
return tx.Error
}
func getUserSponsorBalance(userId string, isTestNet bool) (balanceModel *UserSponsorBalanceDBModel, err error) {
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", userId).Where("is_test_net = ?", isTestNet).First(&balanceModel)
return balanceModel, tx.Error
}
5 changes: 3 additions & 2 deletions sponsor_manager/sponsor_changelog_repository.go
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@ type UserSponsorBalanceUpdateLogDBModel struct {
TxHash string `gorm:"type:varchar(255)" json:"tx_hash"`
TxInfo datatypes.JSON `gorm:"type:json" json:"tx_info"`
Source string `gorm:"type:varchar(255)" json:"source"`
IsTestNet bool `gorm:"type:boolean" json:"is_test_net"`
}

func (UserSponsorBalanceUpdateLogDBModel) TableName() string {
@@ -27,8 +28,8 @@ func LogBalanceChange(updateType global_const.UpdateType, balanceType global_con
//TODO
return
}
func GetDepositAndWithDrawLog(userId string) (models []*UserSponsorBalanceUpdateLogDBModel, err error) {
tx := relayDB.Model(&UserSponsorBalanceUpdateLogDBModel{}).Where("pay_user_id = ?", userId).Where("update_type = ?", global_const.UpdateTypeDeposit).Or("update_type = ?", global_const.UpdateTypeWithdraw).Find(&models)
func GetDepositAndWithDrawLog(userId string, IsTestNet bool) (models []*UserSponsorBalanceUpdateLogDBModel, err error) {
tx := relayDB.Model(&UserSponsorBalanceUpdateLogDBModel{}).Where("pay_user_id = ?", userId).Where("is_test_net = ?", IsTestNet).Where("update_type = ?", global_const.UpdateTypeDeposit).Or("update_type = ?", global_const.UpdateTypeWithdraw).Find(&models)
if tx.Error != nil {
return nil, tx.Error
}
51 changes: 19 additions & 32 deletions sponsor_manager/sponsor_service.go
Original file line number Diff line number Diff line change
@@ -31,8 +31,8 @@ func Init() {

//----------Functions----------

func GetAvailableBalance(userId string) (balance *big.Float, err error) {
balanceModel, err := getUserSponsorBalance(userId)
func GetAvailableBalance(userId string, isTestNet bool) (balance *big.Float, err error) {
balanceModel, err := getUserSponsorBalance(userId, isTestNet)

if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -43,9 +43,11 @@ func GetAvailableBalance(userId string) (balance *big.Float, err error) {
return balanceModel.AvailableBalance, nil
}

func LockUserBalance(userId string, userOpHash []byte, network global_const.Network,
// LockUserBalance
// Reduce AvailableBalance and Increase LockBalance
func LockUserBalance(userId string, userOpHash []byte, isTestNet bool,
lockAmount *big.Float) (err error) {
balanceModel, err := getUserSponsorBalance(userId)
balanceModel, err := getUserSponsorBalance(userId, isTestNet)
if errors.Is(err, gorm.ErrRecordNotFound) {
return xerrors.Errorf("No Balance Deposit Here ")
}
@@ -56,9 +58,9 @@ func LockUserBalance(userId string, userOpHash []byte, network global_const.Netw
availableBalance := new(big.Float).Sub(balanceModel.AvailableBalance, lockAmount)
balanceModel.LockBalance = lockBalance
balanceModel.AvailableBalance = availableBalance
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", userId).Updates(balanceModel)
if tx.Error != nil {
return tx.Error
err = UpdateSponsor(balanceModel, isTestNet)
if err != nil {
return err
}
LogBalanceChange(global_const.UpdateTypeLock, global_const.BalanceTypeLockBalance, userOpHash, lockAmount)
return nil
@@ -76,44 +78,38 @@ type ReleaseUserOpHashLockInput struct {

func ReleaseUserOpHashLock(userOpHash []byte) (err error) {
// Get ChangeLog By UserOpHash
//TODO
return nil
}

func getUserSponsorBalance(userId string) (balanceModel *UserSponsorBalanceDBModel, err error) {
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", userId).First(&balanceModel)
return balanceModel, tx.Error
}

//----------Functions----------

func DepositSponsor(input *model.DepositSponsorRequest) (balanceModel *UserSponsorBalanceDBModel, err error) {
//TODO
balanceModel, err = FindUserSponsorBalance(input.PayUserId)
balanceModel, err = FindUserSponsorBalance(input.PayUserId, input.IsTestNet)
if errors.Is(err, gorm.ErrRecordNotFound) {
balanceModel.AvailableBalance = input.Amount
balanceModel.PayUserId = input.PayUserId
balanceModel.LockBalance = big.NewFloat(0)
tx := relayDB.Create(&balanceModel)
if tx.Error != nil {
return nil, tx.Error
balanceModel.IsTestNet = input.IsTestNet
err = CreateSponsorBalance(balanceModel)
if err != nil {
return nil, err
}
}
if err != nil {
return nil, err
}
newAvailableBalance := new(big.Float).Add(balanceModel.AvailableBalance, input.Amount)
balanceModel.AvailableBalance = newAvailableBalance
tx := relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", input.PayUserId).Updates(balanceModel)
if tx.Error != nil {
return nil, tx.Error
err = UpdateSponsor(balanceModel, input.IsTestNet)
if err != nil {
return nil, err
}
LogBalanceChange(global_const.UpdateTypeDeposit, global_const.BalanceTypeAvailableBalance, input, input.Amount)
return balanceModel, nil
}

func WithDrawSponsor(input *model.WithdrawSponsorRequest) (balanceModel *UserSponsorBalanceDBModel, err error) {
balanceModel, err = FindUserSponsorBalance(input.PayUserId)
balanceModel, err = FindUserSponsorBalance(input.PayUserId, input.IsTestNet)
if err != nil {
return nil, err
}
@@ -122,19 +118,10 @@ func WithDrawSponsor(input *model.WithdrawSponsorRequest) (balanceModel *UserSpo
}
newAvailableBalance := new(big.Float).Sub(balanceModel.AvailableBalance, input.Amount)
balanceModel.AvailableBalance = newAvailableBalance
err = UpdateSponsorBalance(balanceModel)
err = UpdateSponsor(balanceModel, input.IsTestNet)
if err != nil {
return nil, err
}
LogBalanceChange(global_const.UpdateTypeWithdraw, global_const.BalanceTypeAvailableBalance, input, input.Amount)
return balanceModel, nil
}
func GetSponsorTransactionList() (err error) {
//TODO
return nil
}

func GetSponsorMetaData() (err error) {
//TODO
return nil
}