If you are wondering how to start with Ethereum (or any other EVM) blockchain and go lang, this article will be right for you.
I’ll try to keep it straightforward and as simple as possible, am assuming you have basic knowledge of Go and don’t have to explain to you how to install it and compile a program - let’s dive in.
At first install go-ethereum/ethclient package by running:
go get github.com/ethereum/go-ethereum/ethclientin your go project root directory.You need to have access to RPC endpoint to a blockchain - for example you can get one at QuickNode. In this article I will be using Avalanche Fuji Testnet but it could be easily Ethereum Mainnet, Optimism or Arbitrum, it doesn’t matter as all of them are EVM (Ethereum Virtual Machine) blockchains.
Creating new client is easy, you just need to have RPC endpoint to which you can connect.
In example below am using WebSocket endpoint provided by QuickNode to connect to Avalanche Fuji Testnet:
rpcURL := "wss://indulgent-clean-dawn.avalanche-testnet.discover.quiknode.pro/[API_KEY]/ext/bc/C/ws/"
client, err := ethclient.Dial(rpcURL)
if err != nil {
panic(err)
}
Once you have established connection and have a client, you can start sending RPC commands to the blockchain network.
In this example will show how to listen to new blocks numbers - useful if you want to get information about newly mined blocks.
headers := make(chan *types.Header)
sub, err := client.SubscribeNewHead(context.Background(), headers) if err != nil {
panic(err)
}
for {
select {
case err := <-sub.Err():
panic(err)
case header := <-headers:
fmt.Println(header.Number)
}
}
This example will listen for new block numbers, each time we receive information about new block number it will be printed out in the console.
Once you have block number you can ask blockchain to provide information about that block.
block, err := client.BlockByNumber(context.Background(), blockNumber)
if err != nil {
panic(err)
}
// block hash in hexadecimal
fmt.Println(block.Hash().Hex())
// block nonce
fmt.Println(block.Nonce())
// amount of transactions in this block
fmt.Println(len(block.Transactions()))
To get transaction details, you could iterate over block.Transactions() and ask for details of each of the hashes, simply by calling TransactionByHash
for _, tx := range block.Transactions() {
txDetails, isPending, err := client.TransactionByHash(context.Background(), tx.Hash())
// print cost of the transaction - gas fees + msg.value
fmt.Println(txDetails.Cost())
}
Hope that this short article can bring you more clarity on how to start with go-ethereum in go lang.
If you would have any questions feel free to message me on Twitter.
Cover photo

