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.

In this post, you'll write a simple script using Web3.js and Infura for sending batch requests.

You'll take advantage of Web3.js by using the batch request method. You can find all the relevant details in the Web3.js documentation.

Don't forget to use your Infura API key.

Your script will send two requests using eth_getBalance and eth_getTransactionCount, then 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 you'll use 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)
})
Was this helpful?
Connect MetaMask to provide feedback
What is this?
This is a trial feedback system that uses Verax to record your feedback as onchain attestations on Linea Mainnet. When you vote, submit a transaction in your wallet.