[Ethereum] In web3.js, how to accurately find total gas cost to deploy a new contract (including constructor)

gasgas-estimateweb3js

I am using a public node as my web3 privider, so I must sign all transactions manually. This includes transactions that create contracts.

Currently, I use the following method to deploy contracts.

/* I create the contract first. */
var contractAbi = ... (I load this from a file.)
var contractBytecode = ... (I load this from another file.)
var contract = new web3.eth.Contract(contractAbi);

/* Then I get the data encoded with constructor parameters. */
var contractDeployInfo = contract.deploy({
  data: contractBytecode,
  arguments: [constructorParam1, constructorParam2]
});

/* Data field of the transaction. */
var transactionData = contractDeployInfo.encodeABI();

/* Then I estimate the gas, using the provided method. */
contractDeployInfo.estimateGas().then(gas => {
    // Use this gas estimate to create raw transaction, 
    // sign it, send it, and so on.
})

The transaction does go through, and the contract is deployed.

However, the gas estimate returned by contract.deploy().estimateGas() only returns gas that is enough to send the contract through to the miners, but not enough to actually execute the contract's constructor.

As a result, I am left with a blank contract with no data in the contract address that is specified in the transaction receipt.

Should I calculate the gas estimate of the contract's constructor, and add that to the gas limit in my transactions?

This(How to estimate gas at contract creation/deployment to private ethereum blockchain) “duplicate” question uses an older version of Web3 library. Also I was referring to the newly introduced deploy function.

Best Answer

You can deploy the contract in your development testrpc, and check the gas for that transaction.

const tx = await MyContract.new();
const gasUsed = tx.receipt.gasUsed;

Hope this helps.