0

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). – goodvibration Dec 17 '18 at 13:47
  • I know the function usage, the problem is what will be in the data field as addDoc function requires two parameters – Anubhav Gupta Dec 17 '18 at 13:50
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);
console.log(gas);
  • It worked. Thank you. Can you tell me what is the significance of using getBlock("latest") here? – Anubhav Gupta Dec 18 '18 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. – goodvibration Dec 18 '18 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. – goodvibration Dec 18 '18 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. – goodvibration Dec 18 '18 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 ? – Anubhav Gupta Dec 19 '18 at 6:55

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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