1
This commit is contained in:
@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go-admin/abis"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@ -38,7 +37,11 @@ const erc20ABI = `[
|
||||
]`
|
||||
|
||||
// GetERC20Balance 查询 ERC-20 代币余额并转换为正常单位 (使用 decimal)
|
||||
func GetERC20Balance(client *ethclient.Client, tokenAbi abis.TokenABI, accountAddress string) (decimal.Decimal, error) {
|
||||
// tokenAddress: 代币合约地址
|
||||
// accountAddress: 账户地址
|
||||
// decimals: 代币精度
|
||||
// 返回值: 代币余额 (decimal.Decimal)
|
||||
func GetERC20Balance(client *ethclient.Client, tokenAddress, accountAddress string, decimals int) (decimal.Decimal, error) {
|
||||
// 1. 解析 ABI
|
||||
contractABI, err := abi.JSON(strings.NewReader(erc20ABI))
|
||||
if err != nil {
|
||||
@ -51,7 +54,7 @@ func GetERC20Balance(client *ethclient.Client, tokenAbi abis.TokenABI, accountAd
|
||||
return decimal.Zero, fmt.Errorf("构造 balanceOf 调用数据失败: %w", err)
|
||||
}
|
||||
|
||||
address := common.HexToAddress(tokenAbi.TestAddress)
|
||||
address := common.HexToAddress(tokenAddress)
|
||||
// 3. 执行 balanceOf 调用
|
||||
balanceResult, err := client.CallContract(context.Background(), ethereum.CallMsg{
|
||||
To: &address,
|
||||
@ -74,7 +77,7 @@ func GetERC20Balance(client *ethclient.Client, tokenAbi abis.TokenABI, accountAd
|
||||
|
||||
// 8. 转换为正常单位 (使用 decimal)
|
||||
balanceDecimal := decimal.NewFromBigInt(balance, 0) // Create decimal from big.Int
|
||||
decimalFactor := decimal.NewFromInt(10).Pow(decimal.NewFromInt(int64(tokenAbi.Decimals)))
|
||||
decimalFactor := decimal.NewFromInt(10).Pow(decimal.NewFromInt(int64(decimals)))
|
||||
readableBalance := balanceDecimal.Div(decimalFactor)
|
||||
|
||||
return readableBalance, nil
|
||||
|
||||
Reference in New Issue
Block a user