[Ethereum] Is it possible to log how much gas was used during hardhat/ethers transaction

ethers.jshardhat

I am trying to estimate average gas cost per 10000 transactions i.e.

  const callMany = async () => {
    for (let i = 0; i <= 10000; i++) {
      const tx = await contract.doThing(1, `Val1`, {
        gasLimit: 100000
      });
      await tx.wait();
    }
  };

  await callMany();

But I can't seem to find if its possible / how to log gas used by each transaction in the loop.

Best Answer

You seem to be using ethers.js, while I am not actively using it the documentation states :

If the wait() method on the returned TransactionResponse is called, there will be additional properties on the receipt

The documentation of the full receipt object can be found here.

So you should use something like :

const receipt = tx.wait();
const gasUsed = receipt.getTransactionReceipt().gasUsed;

I don't understand however why you would need such functionality, smart contracts are deterministic and OP_CODES gas weights are fixed, unless some side effect forbids you to proceed with the computation inside the smart contract, I'd expect all of the iteration to consume the same amount of gas.

Related Topic