Skip to content

Commit

Permalink
update Deposit
Browse files Browse the repository at this point in the history
  • Loading branch information
cherry-yl-sh committed Jun 7, 2024
1 parent 1bd6aa1 commit b9830dc
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 24 deletions.
17 changes: 12 additions & 5 deletions common/model/secret_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,18 @@ type SecretConfig struct {

NetWorkSecretConfigMap map[string]NetWorkSecretConfig `json:"network_secret_configs"`

ConfigDBConfig DBConfig `json:"config_db_config"`
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"`
ConfigDBConfig DBConfig `json:"config_db_config"`
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"`
DashBoardSignerAddress string `json:"dashboard_signer_address"`
DepositTestNetUrl string `json:"deposit_test_net_url"`
DepositMainNetUrl string `json:"deposit_main_net_url"`
}

type NetWorkSecretConfig struct {
Expand Down
13 changes: 6 additions & 7 deletions common/model/sponsor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ package model
import "math/big"

type DepositSponsorRequest struct {
Source string `json:"source"`
Amount *big.Float `json:"amount"`
TxHash string `json:"tx_hash"`

TxInfo map[string]string `json:"tx_info"`
PayUserId string `json:"pay_user_id"`
IsTestNet bool `json:"is_test_net"`
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"`
}
type WithdrawSponsorRequest struct {
Amount *big.Float
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,7 @@ func secretConfigInit(secretConfigPath string) {
signerConfig[global_const.Network(network)] = eoa
}
}

func IsSponsorWhitelist(address string) bool {

//TODO
Expand Down Expand Up @@ -68,6 +69,10 @@ func GetSigner(network global_const.Network) *global_const.EOA {
func GetAPIKeyTableName() string {
return secretConfig.ApiKeyTableName
}
func GetSponsorConfig() *model.SponsorConfig {
//TODO
return &secretConfig.SponsorConfig
}
func GetStrategyConfigTableName() string {
return secretConfig.StrategyConfigTableName
}
Expand Down
145 changes: 135 additions & 10 deletions rpc_server/api/v1/sponsor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ package v1
import (
"AAStarCommunity/EthPaymaster_BackService/common/global_const"
"AAStarCommunity/EthPaymaster_BackService/common/model"
"AAStarCommunity/EthPaymaster_BackService/common/price_compoent"
"AAStarCommunity/EthPaymaster_BackService/common/utils"
"AAStarCommunity/EthPaymaster_BackService/config"
"AAStarCommunity/EthPaymaster_BackService/sponsor_manager"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"golang.org/x/xerrors"
"gorm.io/gorm"
"log"
"math/big"
"net/http"
"strconv"
)

var sourcePublicKeyMap = map[string]string{
"Dashboard": "0x17EE97b5F4Ab8a4b2CfEcfb42b66718F15557687",
}

// DepositSponsor
// @Tags Sponsor
// @Description Deposit Sponsor
Expand All @@ -34,22 +44,137 @@ func DepositSponsor(ctx *gin.Context) {
response.SetHttpCode(http.StatusBadRequest).FailCode(ctx, http.StatusBadRequest, errStr)
return
}
signerAddress, ok := sourcePublicKeyMap["Dashboard"]
if !ok {
response.SetHttpCode(http.StatusInternalServerError).FailCode(ctx, http.StatusInternalServerError, "Invalid Source")
inputJson, err := json.Marshal(request)
if err != nil {
response.SetHttpCode(http.StatusInternalServerError).FailCode(ctx, http.StatusInternalServerError, err.Error())
return
}
var signerAddress string
if request.DepositSource == "dashboard" {
signerAddress = config.GetSponsorConfig().DashBoardSignerAddress
} else {
response.SetHttpCode(http.StatusBadRequest).FailCode(ctx, http.StatusBadRequest, "Deposit Source Error :Not Support Source")
return
}
logrus.Debugf("Signer Address [%v]", signerAddress)

//TODO Add Signature Verification
result, err := sponsor_manager.DepositSponsor(&request)
err = ValidateSignature(ctx.GetHeader("relay_hash"), ctx.GetHeader("relay_signature"), inputJson, signerAddress)
if err != nil {
response.SetHttpCode(http.StatusBadRequest).FailCode(ctx, http.StatusBadRequest, err.Error())
return
}
sender, amount, err := validateDeposit(&request)

if err != nil {
response.SetHttpCode(http.StatusBadRequest).FailCode(ctx, http.StatusBadRequest, err.Error())
return
}

depositInput := sponsor_manager.DepositSponsorInput{
From: sender.Hex(),
Amount: amount,
TxHash: request.TxHash,
PayUserId: request.PayUserId,
}
result, err := sponsor_manager.DepositSponsor(&depositInput)
if err != nil {
response.SetHttpCode(http.StatusInternalServerError).FailCode(ctx, http.StatusInternalServerError, err.Error())
return
}

response.WithDataSuccess(ctx, result)
return
}
func ValidateSignature(originHash string, signatureHex string, inputJson []byte, signerAddress string) error {
hash := sha256.New()
hash.Write(inputJson)
hashBytes := hash.Sum(nil)
hashHex := hex.EncodeToString(hashBytes)
if hashHex != originHash {
return xerrors.Errorf("Hash Not Match")
}
signerAddressHex := common.HexToAddress(signerAddress)

hashByte, _ := utils.DecodeStringWithPrefix(originHash)
signatureByte, _ := utils.DecodeStringWithPrefix(signatureHex)
pubKey, err := crypto.SigToPub(hashByte, signatureByte)
if err != nil {
log.Fatalf("Failed to recover public key: %v", err)
}
recoveredAddr := crypto.PubkeyToAddress(*pubKey)
if signerAddressHex != recoveredAddr {
return xerrors.Errorf("Signer Address Not Match")
}
return nil

}
func validateDeposit(request *model.DepositSponsorRequest) (sender *common.Address, amount *big.Float, err error) {
txHash := request.TxHash
client, err := ethclient.Dial("https://opt-sepolia.g.alchemy.com/v2/_z0GaU6Zk8RfIR1guuli8nqMdb8RPdp0")
if err != nil {
return nil, nil, err
}
// check tx
_, err = sponsor_manager.GetLogByTxHash(txHash)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil, err
}
}
tx, err := GetInfoByHash(txHash, client)
if err != nil {
return nil, nil, err
}
if tx.Type() != types.DynamicFeeTxType {
return nil, nil, xerrors.Errorf("Tx Type is not DynamicFeeTxType")
}
logrus.Info(tx.Type())
txSender, err := types.Sender(types.NewLondonSigner(tx.ChainId()), tx)
if err != nil {
logrus.Errorf("Get Sender Error [%v]", err)
return nil, nil, err
}
sender = &txSender
if request.IsTestNet {
//Only ETH
if tx.Value().Uint64() == 0 {

return nil, nil, xerrors.Errorf("Tx Value is 0")
}
if tx.To() == nil {
return nil, nil, xerrors.Errorf("Tx To Address is nil")
}
if tx.To().Hex() != config.GetSponsorConfig().SponsorDepositAddress {
return nil, nil, xerrors.Errorf("Tx To Address is not Sponsor Address")
}
value := tx.Value()
valueFloat := new(big.Float).SetInt(value)
amount, err = price_compoent.GetTokenCostInUsd(global_const.TokenTypeETH, valueFloat)
if err != nil {
return nil, nil, err
}
} else {
//contractAddress := tx.To()
//chain_service.CheckContractAddressAccess(contractAddress,"")
//Only Usdt

}
return sender, amount, nil

}

func GetInfoByHash(txHash string, client *ethclient.Client) (*types.Transaction, error) {
txHashHex := common.HexToHash(txHash)
//TODO consider about pending
tx, _, err := client.TransactionByHash(context.Background(), txHashHex)
if err != nil {
if err.Error() == "not found" {
return nil, xerrors.Errorf("Transaction [%s] not found", txHash)
}
return nil, err
}

return tx, nil
}

// WithdrawSponsor
// @Tags Sponsor
Expand Down
39 changes: 39 additions & 0 deletions rpc_server/api/v1/sponsor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package v1

import (
"AAStarCommunity/EthPaymaster_BackService/common/model"
"AAStarCommunity/EthPaymaster_BackService/config"
"AAStarCommunity/EthPaymaster_BackService/sponsor_manager"
"testing"
)

func TestValidateDeposit(t *testing.T) {
config.InitConfig("../../../config/basic_strategy_config.json", "../../../config/basic_config.json", "../../../config/secret_config.json")
sponsor_manager.Init()
request := &model.DepositSponsorRequest{
DepositAddress: "0xFD44DF0Fe211d5EFDBe1423483Fcb3FDeF84540f",
TxHash: "0x367428ad744c2fd80054283f7143b934d630433f9c40a411d91e65893dbabdf1",
PayUserId: "5",
DepositSource: "dashboard",
IsTestNet: true,
}
sender, amount, err := validateDeposit(request)
if err != nil {
t.Error(err)
return
}
t.Logf("sender: %v, amount: %v", sender.Hex(), amount.String())

}
func TestValidateSignature(t *testing.T) {
originHash := "0x367428ad744c2fd80054283f7143b934d630433f9c40a411d91e65893dbabdf1"
signatureHex := "0x367428ad744c2fd80054283f7143b934d630433f9c40a411d91e65893dbabdf1"
inputJson := []byte("0x367428ad744c2fd80054283f7143b934d630433f9c40a411d91e65893dbabdf1")
signerAddress := "0xFD44DF0Fe211d5EFDBe1423483Fcb3FDeF84540f"
err := ValidateSignature(originHash, signatureHex, inputJson, signerAddress)
if err != nil {
t.Error(err)
return
}
t.Logf("ValidateSignature success")
}
22 changes: 20 additions & 2 deletions sponsor_manager/sponsor_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,27 @@ func ReleaseUserOpHashLockWhenFail(userOpHash []byte, isTestNet bool) (*UserSpon
return balanceModel, nil
}

//----------Functions----------
func GetLogByTxHash(txHash string) (*UserSponsorBalanceUpdateLogDBModel, error) {
changeModel := &UserSponsorBalanceUpdateLogDBModel{}
err := relayDB.Where("tx_hash = ?", txHash).First(changeModel).Error
if err != nil {
return nil, err
}
return changeModel, nil
}

// ----------Functions----------
type DepositSponsorInput struct {
TxHash string `json:"tx_hash"`
From string `json:"from"`
To string `json:"to"`
Amount *big.Float
IsTestNet bool `json:"is_test_net"`
PayUserId string `json:"pay_user_id"`
TxInfo map[string]string
}

func DepositSponsor(input *model.DepositSponsorRequest) (*UserSponsorBalanceDBModel, error) {
func DepositSponsor(input *DepositSponsorInput) (*UserSponsorBalanceDBModel, error) {

balanceModel, err := FindUserSponsorBalance(input.PayUserId, input.IsTestNet)
if err != nil {
Expand Down

0 comments on commit b9830dc

Please sign in to comment.