Blockchain on Golang Part2: Balance Operations
In this chapter, I will explain how to check a wallet’s balance on the blockchain.
The previous section, Part1: Wallet Operations. Before I explained how to connect blockchain networks, creating and importing wallet operations.
Check Balance
Let’s assume that we only have the wallet address as a string like 0x5B4….
Step 1: Converting Hex String to Account
This code provides converting hexadecimal string address to common.Address type.
account := common.HexToAddress("0x71c7656......")
Step 2: Fetching Balance
BalanceAt function takes 3 params. These are context as a Context type, and account as a common.Address type and blockNumber as a *big.Int type. Also this function returns the wei balance of the given account.
If you want the last balance in the wallet, set blockNumber to nil.
balance,err:=client.BalanceAt(context.Background(),account, nil)
If you want the balance in a specific block in the wallet, you should set blockNumber.
balance,err:=client.BalanceAt(context.Background(),account, 8831291)
Output: 25893180161173005034
Step 3: Converting to Wei to Float
I have balance as a wei type but I want to convert to float type. Firstly I need big.Float object for converting process. I set balance as a string type to the floating object. Finally, I multiply this float value by 10^18.
floatBalance := new(big.Float)
floatBalance.SetString(balance.String())
floatValue := new(big.Float).Quo(floatBalance, big.NewFloat(math.Pow10(18)))fmt.Println(floatValue)
//152.37995227233822494
Final Step: WalletBalance Function
This function gives wallet address as a string and returns balance both wei and float types.
func WalletBalance(address string) (*big.Int, *big.Float) {
account := common.HexToAddress(address)
balance, err := client.BalanceAt(context.Background(), account, nil)
if err != nil {
log.Fatal(err)
}
floatBalance := new(big.Float)
floatBalance.SetString(balance.String())
ethValue := new(big.Float).Quo(floatBalance, big.NewFloat(math.Pow10(18)))
return balance, ethValue
}
Final Step 2 : WalletBalanceByBlock Function
func WalletBalanceByBlock(address string, block int64) (*big.Int, *big.Float) {
account := common.HexToAddress(address)
blockNumber := big.NewInt(block)
balance, err := client.BalanceAt(context.Background(), account, blockNumber)
if err != nil {
log.Fatal(err)
}
floatBalance := new(big.Float)
floatBalance.SetString(balance.String())
ethValue := new(big.Float).Quo(floatBalance, big.NewFloat(math.Pow10(18)))
return balance, ethValue
}
Final: Full Code
Conclusion
By using these two functions, you can be able to check the latest and historical balance of your wallet.
Project Codes
The next article will be about the transfer operations of wallets on the blockchain.