[Ethereum] Correct syntax for estimating gas cost of a function in Web3

gas-estimateweb3js

Suppose I have the following function:

function SetMessage (bytes32 _message) returns (bool success) {
    message = _message;
    return true;
    }

Which might be called in Web3 as follows, for example:

MyContract.deployed().then(function (contractInstance) {    
      return contractInstance.SetMessage(_message, { gas: 200000, from: web3.eth.accounts[0] })
    })

What is the correct syntax for using the estimateGas function in Web3 for this function? I have seen the following example for how to use estimateGas (here it's just checking how much gas to transfer ether from one account to another, not checking a function in a contract):

console.log(web3.eth.estimateGas({from: web3.eth.accounts[0], to: "0xEDA8A2E1dfA5B93692D2a9dDF833B6D7DF6D5f93", amount: web3.toWei(1, "ether")}))

However I'm unsure how to use estimateGas to estimate gas for executing a function in a smart contract.

Best Answer

UPDATE:

It is simpler to use contract.methods.methodName.estimateGas with web3 1.0.x:

myContract.methods.SetMessage(_message)
    .estimateGas(
        {
            from: _from,
            gasPrice: _gasPrice
        }, function(error, estimatedGas) {
        }
    )
});

ORIGINAL ANSWER

The common rule is to generate data property for web3.eth.estimateGas.

The generation depends on the number of input parameters and its types.

In case of your function with 1 input of bytes32 type it can be done like this:

function setMessageGasEstimation(web3, message, cb) {
  var func = "SetMessage(bytes32)";
  var methodSignature = web3.eth.abi.encodeFunctionSignature(func);

  var messageHex = web3.fromAscii(message, 32);
  var encodedParameter = web3.eth.abi.encodeParameter('bytes32', messageHex);

  var data = methodSignature //method signature
    + encodedParameter.substring(2); //hex of input string without '0x' prefix

  estimateGas(web3, address, contractAddr, data, function(estimatedGas, err) {
    console.log("estimatedGas: " + estimatedGas);
    //further logic...
  });
}

function estimateGas(web3, acc, contractAddr, data, cb) {
  web3.eth.estimateGas({
      from: acc, 
      data: data,
      to: contractAddr
  }, function(err, estimatedGas) {
    if (err) console.log(err);
    console.log(estimatedGas);
    cb(estimatedGas, err);
  });
}

You can see more examples how to generate data for contract functions with the different set of parameters.

Related Topic