Overview
Overview
This Recipe shows you how to use web3.js and the
Promise.all
method in JavaScript to efficiently fetch the account balance of an address for 500 blocks.This method is more efficient compared to running a for
loop.Environment setup
Environment setup
Install node.js in case it is not installed yet.Create a new directory for your project, then install the web3.js library:
npm install web3
Get your Chainstack endpoint
Get your Chainstack endpoint
To run this code, you will need a Chainstack account and an Ethereum archive node.
The code
The code
This code this script fetches the balance of a given Ethereum address for each of the last 500 blocks and prints the balance and the time taken to fetch all the balances to the console.
getBalanceAtBlock(blockNum)
: This asynchronous function is designed to get the balance of the specified Ethereum address at a specific block number. It uses theweb3.eth.getBalance
method to fetch the balance in Wei and then converts it into Ether usingweb3.utils.fromWei
. The resulting balance is logged to the console.- main(): This is the main function of the script. It starts by getting the current block number on the Ethereum blockchain using web3.eth.getBlockNumber(). It then sets an endBlock which is 500 blocks behind the current block.
Run the code
Run the code
Now you can get your endpoint and paste it into the endpoint const. Then you can run it with node YOUR_SCRIPT_NAMEThe console will log the time needed to execute the function plus the results of the queries.
The example here only shows a few responses.
Understanding the response
Understanding the response
As you can see in the console, it took about 3 seconds to get the responses for all 500 blocks, which is a significant improvement compared to sending each request using a for loop.You might notice that the order of the blocks logged in the console is not sequential; this is because when you use
Promise.all
with an array of promises, the promises are all started at approximately the same time, and they will resolve (or reject) as soon as they are done, without any regard for the order in which they were started.