Web3JS Gas Estimate – How to Estimate Gas Limit When Using web3.eth.sendSignedTransaction

gas-estimateweb3js

I am using web3 to transfer tokens by using web3.eth.sendSignedTransaction.

When I am setting the parameter rawTx like

var rawTx = {

     "from"      : walletbase,       
     "nonce"     : value, 
     "gasPrice"  : web3.utils.toHex(2000000000), //2 gwei
      "gasLimit"  : estimateGas,
      "to"        : contractAddr,     
      "value"     : "0x00",
      "data"      : data,
      // "chainId"    : 3
  }

I want to set the gasLimit dynamically.
I tried to calculate the gasLimit by using web3.eth.estimateGas like:

web3.eth.estimateGas({

          to  : toAddress,
          data: data
          })

But the value is lower than need. I always got error like:

Error: Transaction ran out of gas. Please provide more gas:

Do you have better way to calculate the gasLimit? Thank you.

Best Answer

Include nonce field in estimate gas calculation.

 web3.eth.estimateGas({
     "from"      : walletbase,       
     "nonce"     : value, 
     "to"        : contractAddr,     
     "data"      : data
})
Related Topic