Skip to main content

Web3.js: How to send batch requests with Infura

info

This tutorial makes use of Web3.js v1.x.x. Not all functionality might work with Web3.js v4.

Hello Infura frens 🙌

In this post, we will write a simple script using Web3.js and Infura for sending batch requests.

We will take advantage of Web3.js using the batch request method, you may find all the relevant details in the Web3.js documentation.

Please don’t forget to use your Infura API Key.

Our script will send 2 requests using eth_getBalance and eth_getTransactionCount and afterward print the results.

const Web3 = require("web3");
const { BatchRequest } = require("web3-batch-request");

// Connect to the Ethereum network via Infura
const web3 = new Web3(
new Web3.providers.HttpProvider("https://goerli.infura.io/v3/YOUR-API-KEY"),
);

// Create a new batch request
const batch = new BatchRequest(web3);

// The Ethereum address for which to retrieve the balance and transaction count
const address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

// Add requests to the batch
batch.add(web3.eth.getBalance, address, "latest");
batch.add(web3.eth.getTransactionCount, address, "latest");

// Execute the batch request
batch
.execute()
.then((results) => {
console.log(
`Balance: ${web3.utils.fromWei(results[0].result, "ether")} ETH`,
);
console.log(`Transaction Count: ${results[1].result}`);
})
.catch((error) => {
console.error(error);
});

I hope that this helps you, see you next time!