Go查询以太坊代币余额

用Go语言实现查询以太坊代币余额

Posted by HonorJoey on April 7, 2020

Go语言实现查询以太坊代币余额

代码:

import (
    "fmt"
    "github.com/ethereum/go-ethereum/accounts/abi/bind"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
    "github.com/honorjoey/ethtest/contracts"
)

func BalanceToken(Net, tokenAddress, address string) (string, error) {
	client, err := ethclient.Dial(Net)
	if err != nil {
		return "", err
	}

	// Golem (GNT) Address
	tokenAddr := common.HexToAddress(tokenAddress)
	instance, err := contracts.NewTobaToken(tokenAddr, client)
	if err != nil {
		return "", err
	}

	addr := common.HexToAddress(address)
	bal, err := instance.BalanceOf(&bind.CallOpts{}, addr)
	if err != nil {
		return "", err
	}
	//bal.Div(bal, big.NewInt(1000000000000000000))
	return bal.String(), nil
}

func main() {
	bal, _ := BalanceToken("ETHNetAddress", "contractAddress", "ethAddress")
	fmt.Println(bal)
}