1

Is there a way in the Truffle console to estimate the cost of gas for deploying a contract to mainnet?

I'm attempting to truffle migrate --network main a contract, and it's running out of gas.

I've been tweaking the gas and gasPrice in truffle-config.

// truffle-config.js
main: {
      network_id: 1, // Main's id
      gas: <gas limit>,
      gasPrice: <gas price>

But it would be very helpful to know what the gas would be to deploy a specific contract.

1
  • 1
    Try the following in truffle console: ContractName.new.estimateGas()
    – alberto
    Feb 20, 2021 at 9:06

2 Answers 2

1

@alberto has it correct.

truffle(ropsten)> Migrations.new.estimateGas()
193243
1
  • Welcome to the Ethereum Stack Exchange! :)
    – eth
    Oct 25, 2021 at 14:31
0

you can estimate with Truffle this way bellow:

P.S: You most have the last version of Truffle installed globally that uses Ganache with gas exactimation.

Example of contract

// ./contracts/ContractFactory.sol
pragma solidity ^0.5.0;

contract ContractFactory {
  function createInstance() public {
    new Contract();
  }
}

contract Contract {
  constructor() public {}
}

Test the gas estimate:

// ./test/ContractFactory.js
const ContractFactory = artifacts.require("ContractFactory");

contract("ContractFactory", () => {
  it("...should deploy and successfully call createInstance using the method's provided gas estimate", async () => {
    const contractFactoryInstance = await ContractFactory.new();

    const gasEstimate = await contractFactoryInstance.createInstance.estimateGas();

    const tx = await contractFactoryInstance.createInstance({
      gas: gasEstimate
    });
    assert(tx);
  });
});

Run the test command

$ truffle test
...
...
Contract: ContractFactory

✓ ...should deploy and successfully call createInstance using the method's provided gas estimate (130ms)

1 passing (143ms)

You can to do if gas is exactimation, subtract exactly a single unit of gas from the gasEstimate before sending our test transaction.

// ./test/ContractFactory.js
const ContractFactory = artifacts.require("ContractFactory");

contract("ContractFactory", () => {
  it("...should deploy and successfully call createInstance using the method's provided gas estimate", async () => {
    const contractFactoryInstance = await ContractFactory.new();

const gasEstimate = await contractFactoryInstance.createInstance.estimateGas();

const tx = await contractFactoryInstance.createInstance({
      gas: gasEstimate - 1 // subtract
    });
    assert(tx);
  });
});

Test result

$ truffle test
...
...
Error: Returned error: VM Exception while processing transaction: revert
1
  • 1
    Why do you need all this if you can use Migrations.new.estimateGas()? Mar 6, 2022 at 22:15

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.