以太坊的账户要么是钱包地址,要么是智能合约地址,类似0x71c7656ec7ab88b098defb751b7401b5f6d8976f,改地址是20个字节。为了使用go-ethereum账户地址,必须先将他们转为go-ethereum类型。common.Address 以太坊地址类型
address := common.HexToAddress("0x71c7656ec7ab88b098defb751b7401b5f6d8976f") fmt.Println(address.Hex())
余额账户
读取账户余额调用BalanceAt方法。
package accountimport ("context""fmt""log""math/big""github.com/ethereum/go-ethereum/common""github.com/ethereum/go-ethereum/ethclient"
)func GetBalance() {client, err := ethclient.Dial("https://mainnet.infura.io/v3/0b5c18e5bcd0407787cc7d319dbb056b")if err != nil {log.Fatal("connect rpc error")}defer client.Close()account := common.HexToAddress("0x0B3Bb070d190992c6567E9F0bc325426C813EE4C")//传入账户地址和可选的区块号。区块号设置nil,即返回最新的余额。balance, err := client.BalanceAt(context.Background(), account, nil)if err != nil {log.Fatal("get balance error")}fmt.Println("balance:", balance)//显示未ETH单位fmt.Println("balance in ETH:", new(big.Float).Quo(new(big.Float).SetInt(balance), big.NewFloat(1e18))) //0.001399288346059696 ETH
}