From 2d8fcb5a16badf3d471aa011d11dfec298ee3f5d Mon Sep 17 00:00:00 2001 From: dylanyang Date: Thu, 23 May 2024 17:10:57 +0800 Subject: [PATCH] add DB --- common/model/strategy.go | 2 +- .../dashboard_service/dashboard_service.go | 7 - service/operator/try_pay_user_op_execute.go | 12 +- sponsor_manager/sponsor_repo.go | 27 ---- sponsor_manager/sponsor_service.go | 136 ++++++++++++++++++ 5 files changed, 146 insertions(+), 38 deletions(-) delete mode 100644 sponsor_manager/sponsor_repo.go create mode 100644 sponsor_manager/sponsor_service.go diff --git a/common/model/strategy.go b/common/model/strategy.go index ee2528d6..6f942d36 100644 --- a/common/model/strategy.go +++ b/common/model/strategy.go @@ -42,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 { diff --git a/service/dashboard_service/dashboard_service.go b/service/dashboard_service/dashboard_service.go index 1aa668b3..31fc45d9 100644 --- a/service/dashboard_service/dashboard_service.go +++ b/service/dashboard_service/dashboard_service.go @@ -18,14 +18,12 @@ import ( var ( configDB *gorm.DB - relayDB *gorm.DB onlyOnce = sync.Once{} ) func Init() { onlyOnce.Do(func() { configDBDsn := config.GetConfigDBDSN() - relayDBDsn := config.GetRelayDBDSN() configDBVar, err := gorm.Open(postgres.Open(configDBDsn), &gorm.Config{}) if err != nil { @@ -33,11 +31,6 @@ func Init() { } configDB = configDBVar - relayDBVar, err := gorm.Open(postgres.Open(relayDBDsn), &gorm.Config{}) - if err != nil { - panic(err) - } - relayDB = relayDBVar }) } diff --git a/service/operator/try_pay_user_op_execute.go b/service/operator/try_pay_user_op_execute.go index 3ea30128..8eed061a 100644 --- a/service/operator/try_pay_user_op_execute.go +++ b/service/operator/try_pay_user_op_execute.go @@ -98,9 +98,13 @@ func executePay(input *ExecutePayInput) (*model.PayReceipt, error) { return nil, nil } if config.IsSponsorWhitelist(input.UserOpSender) { - logrus.Debugf("Not Need ExecutePay In SponsorWhitelist") + logrus.Debugf("Not Need ExecutePay In SponsorWhitelist [%s]", input.UserOpSender) return nil, nil } + //if config.IsTestNet(input.Network) { + // logrus.Debugf("Not Need ExecutePay In TestNet [%s]", input.Network) + // return nil, nil + //} // Get Deposit Balance var payUserKey string if input.ProjectSponsor == true { @@ -112,7 +116,7 @@ func executePay(input *ExecutePayInput) (*model.PayReceipt, error) { if err != nil { return nil, err } - gasUsdCost, err := price_compoent.GetTokenCostInUsd(global_const.TokenTypeETH, input.MaxTxGasCostInEther) + gasUsdCost, err := price_compoent.GetTokenCostInUsd(input.GasToken, input.MaxTxGasCostInEther) if err != nil { return nil, err } @@ -120,7 +124,7 @@ 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.LockBalance(payUserKey, input.UserOpHash, input.Network, + err = sponsor_manager.LockUserBalance(payUserKey, input.UserOpHash, input.Network, gasUsdCost) if err != nil { return nil, err @@ -140,6 +144,7 @@ type ExecutePayInput struct { MaxTxGasCostInEther *big.Float UserOpHash []byte Network global_const.Network + GasToken global_const.TokenType } func postExecute(apiKeyModel *model.ApiKeyModel, userOp *user_op.UserOpInput, strategy *model.Strategy, gasResponse *model.ComputeGasResponse, paymasterDataInput *paymaster_data.PaymasterDataInput) (*model.TryPayUserOpResponse, error) { @@ -159,6 +164,7 @@ func postExecute(apiKeyModel *model.ApiKeyModel, userOp *user_op.UserOpInput, st MaxTxGasCostInEther: gasResponse.TotalGasDetail.MaxTxGasCostInEther, UserOpHash: userOpHash, Network: strategy.GetNewWork(), + GasToken: strategy.GetGasToken(), }) if err != nil { return nil, xerrors.Errorf("postExecute executePay Error: [%w]", err) diff --git a/sponsor_manager/sponsor_repo.go b/sponsor_manager/sponsor_repo.go deleted file mode 100644 index fbe553eb..00000000 --- a/sponsor_manager/sponsor_repo.go +++ /dev/null @@ -1,27 +0,0 @@ -package sponsor_manager - -import ( - "AAStarCommunity/EthPaymaster_BackService/common/global_const" - "math/big" -) - -func GetAvailableBalance(userId string) (balance *big.Float, err error) { - // TODO - return big.NewFloat(12.1), nil -} - -func LockBalance(userId string, userOpHash []byte, network global_const.Network, - lockAmount *big.Float) (err error) { - //TODO - return nil -} - -func ReleaseBalanceWithActualCost(userId string, userOpHash []byte, network global_const.Network, - actualGasCost *big.Float) (err error) { - //TODO - return nil -} -func ReleaseUserOpHashLock(userOpHash []byte) (err error) { - //TODO - return nil -} diff --git a/sponsor_manager/sponsor_service.go b/sponsor_manager/sponsor_service.go new file mode 100644 index 00000000..4458c41d --- /dev/null +++ b/sponsor_manager/sponsor_service.go @@ -0,0 +1,136 @@ +package sponsor_manager + +import ( + "AAStarCommunity/EthPaymaster_BackService/common/global_const" + "AAStarCommunity/EthPaymaster_BackService/common/model" + "AAStarCommunity/EthPaymaster_BackService/config" + "errors" + "golang.org/x/xerrors" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "math/big" + "sync" +) + +var ( + relayDB *gorm.DB + onlyOnce = sync.Once{} +) + +func Init() { + onlyOnce.Do(func() { + relayDBDsn := config.GetRelayDBDSN() + + relayDBVar, err := gorm.Open(postgres.Open(relayDBDsn), &gorm.Config{}) + if err != nil { + panic(err) + } + relayDB = relayDBVar + }) +} + +type UpdateType string +type BalanceType string + +const ( + Deposit UpdateType = "deposit" + Lock UpdateType = "lock" + Withdraw UpdateType = "withdraw" + Release UpdateType = "release" + + AvailableBalance BalanceType = "available_balance" + LockBalance BalanceType = "lock_balance" +) + +type UserSponsorBalanceDBModel struct { + model.BaseData + PayUserId string `gorm:"type:varchar(255);index" json:"pay_user_id"` + AvailableBalance *big.Float `gorm:"type:numeric(30,18)" json:"available_balance"` + LockBalance *big.Float `gorm:"type:numeric(30,18)" json:"lock_balance"` +} + +type DepositBalanceInput struct { + Source string + Signature string + Amount *big.Float + TxReceipt string +} + +func (UserSponsorBalanceDBModel) TableName() string { + return config.GetStrategyConfigTableName() +} + +type UserSponsorBalanceUpdateLogDBModel struct { + model.BaseData + Amount *big.Float `gorm:"type:numeric(30,18)" json:"amount"` + UpdateType UpdateType `gorm:"type:varchar(20)" json:"update_type"` +} + +func (UserSponsorBalanceUpdateLogDBModel) TableName() string { + return config.GetStrategyConfigTableName() +} + +//----------Functions---------- + +func GetAvailableBalance(userId string) (balance *big.Float, err error) { + balanceModel, err := getUserSponsorBalance(userId) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, xerrors.Errorf("No Balance Deposit Here ") + } + return nil, err + } + return balanceModel.AvailableBalance, nil +} + +func LockUserBalance(userId string, userOpHash []byte, network global_const.Network, + lockAmount *big.Float) (err error) { + balanceModel, err := getUserSponsorBalance(userId) + if errors.Is(err, gorm.ErrRecordNotFound) { + return xerrors.Errorf("No Balance Deposit Here ") + } + if err != nil { + return err + } + lockBalance := new(big.Float).Add(balanceModel.LockBalance, lockAmount) + 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 + } + + return nil +} + +func ReleaseBalanceWithActualCost(userId string, userOpHash []byte, network global_const.Network, + actualGasCost *big.Float) (err error) { + //TODO + return nil +} +func ReleaseUserOpHashLock(userOpHash []byte) (err error) { + //TODO + return nil +} + +func DepositSponsorBalance(input *DepositBalanceInput) (err error) { + //TODO + return nil + +} + +func LogBalanceChange(balanceType BalanceType, data interface{}, amount *big.Float) (err error) { + //TODO + return nil +} + +func getUserSponsorBalance(userId string) (balanceModel *UserSponsorBalanceDBModel, err error) { + relayDB.Model(&UserSponsorBalanceDBModel{}).Where("pay_user_id = ?", userId).First(&balanceModel) + return balanceModel, nil +} +func CreateSponsorBalance(userId string) (err error) { + //TODO + return nil +}