I cant seem to find any way to get the number or transactions within a block using the block number in golang.. anyone have any idea how to do this
1 Answer
To get the number of transactions in a block you can use client.TransactionCount(...)
or len(block.Transactions())
. Here's a full example:
package main
import (
"context"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://mainnet.infura.io")
if err != nil {
log.Fatal(err)
}
header, err := client.HeaderByNumber(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
blockNumber := big.NewInt(5671744)
block, err := client.BlockByNumber(context.Background(), blockNumber)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(block.Transactions())) // 144
count, err := client.TransactionCount(context.Background(), block.Hash())
if err != nil {
log.Fatal(err)
}
fmt.Println(count) // 144
}
For more examples, check out the Ethereum Development with Go guide book.