简体   繁体   English

获取USDT余额(erc20代币)

[英]Get USDT balance (erc20 token)

Im trying to get balance of USDT address (erc20 token).我正在尝试获取 USDT 地址(erc20 代币)的余额。

func tetherAmount(addrHex string) {
    conn, err := ethclient.Dial("https://mainnet.infura.io/v3/[api_here]")
    if err != nil {
        log.Fatal("Whoops something went wrong!", err)
    }

    contract, err := NewTetherToken(common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7"), conn)
    if err != nil {
        log.Fatalf("Failed to initiate contract: %v", err)
    }

    // this func return *big.Int, error
    amount, _ := contract.BalanceOf(&bind.CallOpts{}, common.HexToAddress(addrHex))
    fmt.Println("amount:", amount)
}

With this code I got next result:使用此代码,我得到了下一个结果:

amount: 917750889

real balance of this randomly taken address is 917.750889 USDT.这个随机取地址的实际余额是917.750889 USDT。 So how can I convert gotten result (917750889) to simple format (usdt)?那么如何将得到的结果(917750889)转换为简单格式(usdt)?

for those in need:对于有需要的人:

func tetherAmount(addrHex string) {
    conn, err := ethclient.Dial("https://mainnet.infura.io/v3/[api_here]")
    if err != nil {
        log.Fatal("Whoops something went wrong!", err)
    }

    contract, err := NewTetherToken(common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7"), conn)
    if err != nil {
        log.Fatalf("Failed to initiate contract: %v", err)
    }

    amount, _ := contract.BalanceOf(&bind.CallOpts{}, common.HexToAddress(addrHex))
    decimals, _ := contract.Decimals(&bind.CallOpts{})

    fmt.Println("amount:", float64(amount.Int64())/math.Pow(float64(10), float64(decimals.Int64())))
}

USDT has 6 decimal places. USDT 有 6 位小数。 You can get this number by calling the contract's decimals() function.你可以通过调用合约的 decimals decimals() function 得到这个数字。

And then you divide the amount by 10 ^ decimals .然后你将amount除以10 ^ decimals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM