0

I'm writing a script that will send 10 MATIC to 1,000 addresses. What I have written so far seems to achieve this on my local Ganache server (pretending ETH is MATIC). But I am assuming this is going to fall over and die on the polygon mainnet? What would be considered better practice?

I have considered just using wait() on the tx response, so it will just do 1 at a time, but this is a last resort as it'll be slow.

import {providers, utils, Wallet} from 'ethers'
import {NonceManager} from '@ethersproject/experimental'

const SECRET_KEY = 'xyz...'
const RPC = 'http://127.0.0.1:7545' // ganache server
const GAS_LIMIT = 100_000

async function execute() {
  
  const wallets = [
    '0x00...' // x 1,000
  ]
  
  // Load and validate secret key
  const provider = new providers.JsonRpcProvider(RPC)
  const signer = new Wallet(SECRET_KEY, provider)
  const publicKey = await signer.getAddress()

  // Handles the nonce for each transaction
  const manager = new NonceManager(signer)
  
  for (const wallet of wallets) {

    const tx = {
      from: publicKey,
      to: wallet,
      value: utils.parseEther('10'),
      gasLimit: utils.hexlify(GAS_LIMIT),
      gasPrice: await signer.getGasPrice(),
    }

    await manager.sendTransaction(tx)
      .then(async response => {
        console.log('success', response.hash)
        // I could use `await response.wait()` here for synchronicity, but its super slow
      })
      .catch(error => {
        console.log(error)
      })
  }
}

execute()
  .then(() => {
    console.log('all done')
  })
  .catch(error => {
    console.log('error', error)
  })

1 Answer 1

1

You Can use Web3 Batch Request

Listing an Example Below

var contract = new web3.eth.Contract(abi, address);

var batch = new web3.BatchRequest(); batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback)); batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}, callback2)); batch.execute();

This Will Excecute the Transactions in a batch.

But if you are using A public JSON-RPC then there might be an limit of Batch Request.

2
  • is web3 browser only? Do you have a link to the package/docs? ty!
    – Ari
    Dec 27, 2022 at 22:09
  • No Web3 is not browser only. You can refer here for the Docs web3js docs
    – Noooblien
    Dec 30, 2022 at 7:55

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.