There are a few issues with the accepted answer:
- 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. - 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()
blocksblockNumbers.forEach((blockNumber) => {
batch.add(
web3.eth.getBlock.request(blockNumber, storeLocalCopy)
)
})
batch.execute()