wallet/pkg/eth/eth_approve.go

64 lines
1.6 KiB
Go
Raw Normal View History

2024-08-31 14:46:20 +00:00
package eth;
import (
"context"
"math/big"
"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"
)
func (e *EthAccount) ApproveUSDTSpender(spender string, amount string) (string, error) {
client, err := ethclient.Dial(ethNode.rpcNode)
if err != nil {
return "", err
}
metodId := crypto.Keccak256Hash([]byte("approve(address,uint256)")).Bytes()[:4]
paddedAddress := common.LeftPadBytes(common.HexToAddress(spender).Bytes(), 32)
amountToSend := floatStringToDec(amount, ethNode.usdtContractDecimals)
paddedAmount := common.LeftPadBytes(amountToSend.Bytes(), 32)
var data []byte
data = append(data, metodId...)
data = append(data, paddedAddress...)
data = append(data, paddedAmount...)
nonce, err := client.PendingNonceAt(context.Background(), e.address)
if err != nil {
return "", err
}
gasLimit := uint64(60000)
gasTipCap, err := client.SuggestGasTipCap(context.Background())
if err != nil {
return "", err
}
chainId, _ := client.ChainID(context.Background())
toAddress := common.HexToAddress(ethNode.usdtContractAddress)
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: chainId,
To: &toAddress,
Nonce: nonce,
Value: big.NewInt(0),
Gas: gasLimit,
Data: data,
GasTipCap: gasTipCap,
GasFeeCap: big.NewInt(20000000000),
})
signedTx, err := e.SignTx(tx)
if err != nil {
return "", err
}
err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
return "", err
}
return signedTx.Hash().Hex(), nil
}