-1

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) ?

Volker
  • 40,468
  • 7
  • 81
  • 87
root
  • 13
  • 1
  • 4

2 Answers2

3

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.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • What if I want to use the address of USDT on polygon as payment methods inside my smart contract(monthly subscription concepts) how many decimals should I add to 1 USDT for example 18 or 6? – David Jay Jun 15 '22 at 15:15
  • @DavidJay The USDT token on Polygon also uses 6 decimals, so you add 6 decimal places - https://polygonscan.com/token/0xc2132d05d31c914a87c6611c10748aeb04b58e8f – Petr Hejda Jun 15 '22 at 20:31
1

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())))
}
root
  • 13
  • 1
  • 4