0

New to solidity programming and I discovered this today at this site:

var contract = new web3.eth.Contract(abi, address);
var batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.execute();

Which is great because I have been cutting and pasting a slew of web3 commands in the web3 console.

But I'm not sure how to actually execute a web3.js file containing the batch commands in the web3 console.

Would I say something like ./web3.js?

Not quite sure how to actually run the file containing the batch commands.

Thanks

3 Answers 3

0
>loadScript("/path/to/file/filename.js")
>yourFunction(params)
0

BatchRequest feature is not for batching your requests into files. It is for sending several Web3 RPC requests inside single HTTP(s) request. See JSON RPC documentation for details about how RPC batches work on low level.

What you probably need is either put your requests into separate .js file and load it via loadScript("path/to/file.js");.

0

Developer advocate at Chainstack here!

You can use web3.js to send batches of web3 requests. The following example shows how to send a batch to get the balance from multiple addresses.

This method is much more efficient for this kind of use case compared to running a loop.

const Web3 = require("web3");
const NODE_URL = "YOUR_CHAINSTACK_ENDPOINT";
const web3 = new Web3(NODE_URL);

const addresses = [
  "0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326",
  "0x2bB42C655DdDe64EE508a0Bf29f9D1c6150Bee5F",
];

async function getBalances() {

  const startTime = Date.now()

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

  // Loop through each address and add a getBalance request to the batch
  addresses.forEach((address) => {
    const request = web3.eth.getBalance.request(address, (error, balance) => {
      if (error) {
        console.error(error);
      } else {
        var timeFromStart = Date.now() - startTime
        console.log(`${address} has a balance of ${Number(web3.utils.fromWei(balance, 'ether')).toFixed(3)} ETH retrieved in: ${timeFromStart / 1000} seconds.`);
      }
    });
    batch.add(request);
  });

  console.log("Batch request:");
  console.log(batch.requests);

  // Send the batch request
  batch.execute();
}

getBalances();

You can learn more about batches and other methods to run this kind of request on the guide in the Chainstack developer portal: HTTP batch request VS multicall contract

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.