In Remix IDE, it's straightforward to deploy a smart contract and then execute a function call to see the debug log for gas usage. How may we see the gas consumption for function calls in hardhat? Assume that npx hardhat node
is run on a different tab while contract is also deployed npx hardhat run --network localhost scripts/deploy.js
3 Answers
After a lot of trial and error, the following worked for me. First, we have to add web3
to hardhat. To do this run the following command in the terminal.
$ npm install --save-dev @nomiclabs/hardhat-web3 web3
Then open hardhat.config.js
file and add dependency.
require("@nomiclabs/hardhat-web3");
Finally we can estimate gas with web3 in our tests.
var methodSignature = web3.eth.abi.encodeFunctionSignature(func);
var encodedParameter = web3.eth.abi.encodeParameter("string", "ABCDEFGH");
var data = methodSignature //method signature
+ encodedParameter.substring(2); //hex of input string without '0x' prefix
let gas = await provider.estimateGas({
from: owner.address,
to: addr2.address,
data: data,
value: 1000000000000000,
function(estimatedGas, err) {
console.log("estimatedGas: " + estimatedGas);
console.log("Err:" + err);
}
});
console.log("Gas: " + gas);
You can use ethers
imported from 'hardhat' to estimateGas if it's in the test environment.
I haven't checked on the hardhat console, but it may be better to check the gas cost using hardhat-gas-reporter and methods like the one below along side with your tests. (hardhat-gas-reporter does not report for the cost of receive
)
import { ethers } from "hardhat";
const ethAmount = ethers.utils.parseEther('0.5');
const gas = await ethers.provider.estimateGas({
from: from.address,
to: to.address,
value: ethAmount,
});
console.log('gas', gas.toNumber())
If you're running a script, you can console.log a function call and access the estimateGas property.
const [owner, addr1, addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory("Token");
const hardhatToken = await Token.deploy();
console.log("Gas: ", await hardhatToken.estimateGas.balanceOf(addr1.address);