Can someone suggest me how to use estimateGas for function calls like below:

await (MyContract.methods.addDoc(id,sha256hash).send({from: coinbase[0],gas: 1000000})

  • Replace send with estimateGas and get the return value (e.g., var x = await...). BTW, there's a redundant parenthesis at the beginning of the line (immediately after the await). Dec 17, 2018 at 13:47
  • I know the function usage, the problem is what will be in the data field as addDoc function requires two parameters Dec 17, 2018 at 13:50

1 Answer 1


Try this:

let transaction = MyContract.methods.addDoc(id, sha256hash);
let block = await this.web3.eth.getBlock("latest");
let options = {
    to  : transaction._parent._address,
    data: transaction.encodeABI(),
    gas : block.gasLimit
let gas = await web3.eth.estimateGas(options);
  • It worked. Thank you. Can you tell me what is the significance of using getBlock("latest") here? Dec 18, 2018 at 8:12
  • @AnubhavGupta: I'm not sure that you have to specify it in this case. I know that you need to specify it when you actually execute the transaction, so I kept it here for "best practice". You can try to see if it works without it. Dec 18, 2018 at 8:22
  • And with regards to the significance for transaction execution: you need to specify your limit, in order to avoid the miner spending all your funds. If your limit is lower than the actual gas required, then the transaction will not go through. If your limit is higher than the actual gas required, then the transaction will go through, but only the actual gas required will be deducted from your account. So gas: block.gasLimit yields the highest chances of your transaction being executed. Dec 18, 2018 at 8:26
  • The only problem is that you need to have the entire amount of funds in your account, EVEN THOUGH only the required amount of funds will be deducted from it. For example, suppose that: gasPrice = 10, gasLimit = 20 and gasRequired = 15. So even though you'll end up spending 150 wei, the node first verifies that you have 200 wei in your account. Otherwise, it refrains from executing your transaction. Dec 18, 2018 at 8:26
  • Thank you, do I need to add some extra gas for every transaction, just to be sure that transaction won't decline ? Dec 19, 2018 at 6: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.