Querying Ethereum Wallet Balances with Geth
Step 1: Import the required packages:
import (
“context”
“fmt”
“log”“github.com/ethereum/go-ethereum”
“github.com/ethereum/go-ethereum/common”
“github.com/ethereum/go-ethereum/ethclient”
)
Step 2: Copy your address from Infura as shown in the above picture and then in the code define the Ethereum address for which you want to query the balance:
address := common.HexToAddress(“0xYOUR_ADDRESS”)
Note:
Replace 0xYOUR_ADDRESS with the actual Ethereum address.
Step 3: You can now query the balance of your Ethereum address using the below code snippet function where we are setting up the Ethereum client connection and then returning the balance of your account.
Go
balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } fmt.Println( "Wallet Balance:" , balance) |
Code:
Go
package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { // Ethereum client connection setup client, err := ethclient.Dial( "https://mainnet.infura.io/v3/YOUR_INFURA_API" ) if err != nil { log.Fatal(err) } // Ethereum address to check balance address := common.HexToAddress( "0xYOUR_ADDRESS" ) // Retrieve the wallet balance balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Print the wallet balance fmt.Println( "Wallet Balance:" , balance) } |
Output: Once you have entered your address and infura API in the above code your output might look like this:
Note:
The wallet balance is in wei the smallest unit of Ether.
Ethereum Development with Golang
Ethereum is a blockchain-based platform that enables developers to create decentralized applications (dApps) and smart contracts. Ethereum’s native cryptocurrency is Ether (ETH), which is used to pay transaction fees and incentivize miners to secure the network.
Go, also known as Golang, is a programming language developed by Google. It is a compiled language that is designed to be efficient, concise, and easy to use. Go is often used for building web applications, network servers, and other types of software that require high performance.