2

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.

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

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.

1

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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