3

When running truffle migrate or truffle test, how can I get the gas usage (for example, see below the log from testrpc)?

Transaction: 0x19d38e8d8418db2bcc569068ad756adf10edd77c39c2da1afd4639b30efdbe31  
Contract created: 0x7589cbcd1d32fb4b6bac489453c58395c4cea3ff
Gas usage: 4308473 // <=== HOW DO I ACCESS THIS IN TRUFFLE?
Block Number: 14
Block Time: Sun Jan 14 2018 16:11:54 GMT-0800 (PST)

For example, if I had the transactionHash, I could just use web3.eth.getTransactionReceipt and check receipt.gasUsed.

I can not access the receipt since the instance of the Contract.deployed() does not have a transactionHash.

Is there a way to access the equivalent of receipt.gasUsed for a contract deployed by Truffle?

2
  • Are you migrating on a testnet? If so then you should be able to check the gas used by each transaction on Etherscan, like for example if you deployed on Rinkeby, you can check it on rinkeby.etherscan.io
    – Julien
    Jan 15, 2018 at 0:44
  • Thanks. I’m trying to access the gas cost programmatically in my truffle deployment or test files, and not have to scroll through the testrpc logs or go to etherscan. Typically you can just get this from transaction receipts, but I also don’t know how to access the transaction hash (again without having to check the testrpc logs or etherscan) when the contract is created in my deployments script in migrations.
    – carlolm
    Jan 15, 2018 at 0:53

1 Answer 1

10

This is based off what I learned here: https://ethereum.stackexchange.com/a/43004/27157

it("Should deploy with less than 4.7 mil gas", async () => {
  let someInstance = await SomeContract.new();
  let receipt = await web3.eth.getTransactionReceipt(someInstance.transactionHash);
  assert.isBelow(receipt.gasUsed, 4700000);
});
2
  • Thanks. Yes I had been doing something similar. I create contract constructors and call them, check ETH balance before and after. I can apply the same pattern for function calls, if I want to test how much those cost also. This is helpful for stress testing, cost optimization, and checking contract limitations.
    – carlolm
    Mar 22, 2018 at 20:34
  • Checking difference in balance will show you what was the cost of trasaction. This is not the same as gas used since cost = gasUsed * gasPrice
    – Rob Magier
    Dec 9, 2018 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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