npm i web3
to install web3.js. The code in this guide is compatible with web3.js V4
.getBalances
function creates a new BatchRequest
object using web3.BatchRequest()
.
The function then loops through each address in the addresses
array and creates a new request to get the balance of that address using web3.eth.getBalance.request()
. It adds each request to the batch using batch.add()
.
Finally, the function executes the batch request using batch.execute()
. When executed, the requests in the batch are sent to the Ethereum network simultaneously, and the callback functions are executed when the responses are received.
Call
, calls each one, and returns an array of the results along with the block number in which the function was called. It is designed to be used as a general-purpose aggregator for calling other contracts on the Ethereum blockchain.
main
function iterates through each address in the addressArr
array and creates a call object for each address. These call objects use the multicall library to retrieve the ether balance for each address.
Once all of the call objects have been created and pushed to the calls
array, the multicall library’s aggregate
function is called with the array of call objects and the configuration object. This function aggregates the results of all of the calls into a single object, which is stored in the result
variable.
Finally, the code logs the “result” to the console and calculates the time it took to receive the “result”, which is also logged to the console.
You will need to install the multicall.js library to run this code.
Parallel single requests | Batch request | Multicall | |
---|---|---|---|
Round 1 | 1.789 | 1.49 | 1.447 |
Round 2 | 1.896 | 1.159 | 1.54 |
Round 3 | 2.337 | 1.113 | 2.132 |
Round 4 | 2.942 | 1.224 | 1.609 |
Round 5 | 1.638 | 1.602 | 2.012 |
ownerOf
from BAYC’s smart contract.
Sending multiple HTTP requests in parallel:
Parallel single requests | Batch request | Multicall | |
---|---|---|---|
Round 1 | 1.693 | 1.931 | 1.878 |
Round 2 | 1.717 | 1.592 | 1.195 |
Round 3 | 1.712 | 1.617 | 2.183 |
Round 4 | 2.103 | 1.589 | 1.3 |
Round 5 | 2.785 | 1.416 | 1.429 |
If I package 100 requests into a single batch request, does that count as 1 request or 100 requests on Chainstack?
If I package 100 calls into a single multicall request, does that count as 1 request or 100 requests?
Is there any hard limit for the number of calls to multicall contracts?