Ethers.js: How to send batch requests with Infura

Hello Infura frens :raised_hands:t4:

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

We will take advantage of Ethers.js using the JsonRpcBatchProvider method, you may find all the relevant details in the Ethers.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 { providers, JsonRpcBatchProvider } = require('ethers');

const infuraProvider = new providers.InfuraProvider('goerli', 'YOUR_INFURA_API_KEY');
const batchProvider = new JsonRpcBatchProvider(infuraProvider);

const requests = [
  {
    method: 'eth_getBalance',
    params: ['0x742d35Cc6634C0532925a3b844Bc454e4438f44e', 'latest'],
  },
  {
    method: 'eth_getTransactionCount',
    params: ['0x742d35Cc6634C0532925a3b844Bc454e4438f44e', 'latest'],
  },
];

batchProvider.send(requests).then((results) => {
  console.log(results);
});
11 Likes

tns alot dear bro u working so hard tnx

3 Likes

@Flaveeu Very useful post!
Is it possible to call also multiple functions in a smart contract at once? In one transaction?
Thanks!

1 Like

Hi, could you please elaborate a bit on your use case? I would like to give you a helping hand and enhance the above script.

2 Likes

@Flaveeu thanks for the reply.
I would like to batch several operations into one single transaction.
What I’m trying to do, is allowing my users to link their connected address to a nickname and in the same time mint a PFP. So, if one of the operation fails, the transaction fails. Can this be done from the frontend side? Thanks!

1 Like