Please tell me an example of code in GOlang that connects to the contract and checks the balance of the ERC20 token / transfer tokens / gets the name of the token. I looked for examples and did not find anything worthwhile, everything is connected to their local contract
1 Answer
you can refer this link https://goethereumbook.org/smart-contract-read-erc20
for simplicity you can also directly use the package github.com/liyue201/erc20-go/erc20 and call the balance functions like this
func getERC20Balance(address string, tokenAddress string) big.Float {
tokenAddressHex := common.HexToAddress(tokenAddress)
addressHex := common.HexToAddress(tokenAddress)
client, err := ethclient.Dial("https://rinkeby.infura.io")
if err != nil {
log.Fatal(err)
}
instance, err := erc20.NewGGToken(tokenAddressHex, client)
if err != nil {
log.Fatal(err)
}
bal, err := instance.BalanceOf(nil, addressHex)
if err != nil {
log.Fatal(err)
}
name, err := instance.Name(nil)
if err != nil {
log.Fatal(err)
}
symbol, err := instance.Symbol(nil)
if err != nil {
log.Fatal(err)
}
decimals, err := instance.Decimals(nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("name: %s\n", name) // "name: Golem Network"
fmt.Printf("symbol: %s\n", symbol) // "symbol: GNT"
fmt.Printf("decimals: %v\n", decimals) // "decimals: 18"
fmt.Printf("wei: %s\n", bal) // "wei: 74605500647408739782407023"
fbal := new(big.Float)
fbal.SetString(bal.String())
value := new(big.Float).Quo(fbal, big.NewFloat(math.Pow10(int(decimals))))
fmt.Printf("balance: %f\n", value) // "balance: 74605500.647409"
return *value
}
hope this helps!