4

It's a seemingly simple operation but I can't find an obvious way to do this using the go-ethereum library.

Given a blockchain client like so:

client, err := ethclient.Dial("http://localhost:8545")

The only available methods are:

BalanceAt
BlockByHash
BlockByNumber
CallContract
Close
CodeAt
EstimateGas
FilterLogs
HeaderByHash
HeaderByNumber
NetworkID
NonceAt
PendingBalanceAt
PendingCallContract
PendingCodeAt
PendingNonceAt
PendingStorageAt
PendingTransactionCount
SendTransaction
StorageAt
SubscribeFilterLogs
SubscribeNewHead
SuggestGasPrice
SyncProgress
TransactionByHash
TransactionCount
TransactionInBlock
TransactionReceipt
TransactionSender

Which does not include GetBlockNumber like it does in web3.js for example.

2
  • What do you mean by that @Jorropo
    – Dcompoze
    Commented May 11, 2018 at 11:18
  • you usually do it by eth.getBlock('latest') or, eth_getBlockByNumber('latest')
    – Nulik
    Commented May 11, 2018 at 22:13

2 Answers 2

3

Here's a full example of how to get the current (highest) block number using Go (from the Ethereum Development with Go book):

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)
    }

    fmt.Println(header.Number.String()) // 5671744
}
1
  • Works great. Thx Miguel. Commented Aug 7, 2018 at 18:39
2

I found the answer in a GitHub issue: https://github.com/ethereum/go-ethereum/pull/15907

You can retrieve the latest header with ethclient.HeaderByNumber(nil, nil), from which you can just pull the block number. The ethclient API is not meant to be a Go counterpart of the RPC spec (which is quite badly designed), rather an intuitive was to interface Ethereum from Go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.