Search code examples
ethereumgetherc20

Get USDT balance (erc20 token)


Im trying to get balance of USDT address (erc20 token).

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. So how can I convert gotten result (917750889) to simple format (usdt) ?


Solution

  • USDT has 6 decimal places. You can get this number by calling the contract's decimals() function.

    And then you divide the amount by 10 ^ decimals.