How can I get latest 10 block data by using web3.js like most block explorer does?

up vote 1 down vote accepted

There are a few issues with the accepted answer:

  1. as @Lam-Le mentions, .getBlock() and .getBlockNumber() are both asynchronous so if a new block is created during the loop not only will you no longer obtain the 'latest' blocks but you will also have duplicates.
  2. the loop creates an disproportionate amount of network request (2 x i+1).

To solve the first concern you must keep a reference to the latest blockNumber:

const latest = await web3.eth.getBlockNumber()

In order to reduce the amount of network request web3 you can use BatchRequests.

const batch = new web3.eth.BatchRequest()
batch.add(web3.eth.getBlock.request(blockNumber, callback))
batch.execute()

Notice that in order to pass the arguments to the function, you need to use the special request method.

Putting them together, you can retrieve the last n blocks with:

const latest = await web3.eth.getBlockNumber()
const blockNumbers = _range(latest - n, latest + 1, 1)
const batch = new web3.eth.BatchRequest()

blockNumbers.forEach((blockNumber) => {
  batch.add(
    web3.eth.getBlock.request(blockNumber, storeLocalCopy)
  )
})

batch.execute()
New contributor
vilsbole is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Use web3.eth.getBlock with web3.eth.blockNumber

for (var i=0; i < 10; i++) {
  console.log(web3.eth.getBlock(web3.eth.blockNumber - i));
}
  • 3
    should cache web3.eth.blockNumber in local variable before looping in case new incoming block – Lam Le Aug 21 at 7:16
  • 1
    If a new block appears, more logic may also be desired because the data is no longer the "latest". But upvoted, good point by @LamLe. – eth Sep 11 at 11:26

There is the filter functionality available within the web3.js library that is extremely well documented. It is designed for exactly that purpose.

It is also worth looking at the JSONRPC documentation to understand how this functionality works behind the scenes.

Copy/paste from the docs with a slight modification:

var filter = web3.eth.filter({toBlock:'latest'});

filter.watch(function (error, log) {
 console.log(log); //  {"address":"0x0000000000000000000000000000000000000000", "data":"0x0000000000000000000000000000000000000000000000000000000000000000", ...}
});

// get all past logs again.
var myResults = filter.get(function(error, logs){ ... });
...
// stops and uninstalls the filter
filter.stopWatching();

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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