Solidity – How To Estimate Gas Costs

I’ve been working on optimizing the gas cost for deploying a smart contract. Turns out truffle has some pretty useful ways of estimating gas used.

Good Old Migrate

The most obvious way is to just run $ truffle migrate and see what the output says. When the project has quite a large build this can take some time so it’s not that efficient for seeing the difference some code changes make. I do find it useful to run this every now and again though just to confirm the estimates are correct.

estimateGas()

The other way I found useful is to use the estimateGas function. As is pretty self explanatory it is just an estimate and could change depending on the contract state. I found this was nice and quick to use on a truffle cli and I found two useful estimations to look at:

Contract deployment

Start the local ganache with a large gas limit:

$ ganache-cli --gasLimit 10000000 --allowUnlimitedContractSize

Start a truffle cli that connects to above chain:

$ truffle console

Estimate gas for deploying your contract:

truffle(develop)> YourContract.new.estimateGas()

Calling Contract Method

Start with the same set-up steps as above. Then:

truffle(develop)>  YourContract.testMethod.estimateGas()

And that’s it – another useful trick!

Leave a Reply

Your email address will not be published. Required fields are marked *