4

Does anyone know how to get the gas costs of a reversed transaction when testing with Hardhat / Chai?

I found out I can get the receipt object of a transaction, which holds the required data to calculate the total gas costs, like so:

const transaction = contract.connect(account).withdraw(); 
const receipt = await transaction.wait();
const transactionCosts = receipt.gasUsed.mul(
  receipt.effectiveGasPrice
);

But now I have a transaction that gets reverted, for which I am also testing. Code:

await expect(
  contract.connect(account).withdraw()
).to.be.revertedWith("Ownable: caller is not the owner");

Does anyone know how I get the gas costs (like in the first example) of the transaction in the second example?

1 Answer 1

2

I've figured out a way to do this, althought I wonder if there isn't an easier way.

    // Get latest transaction hash
    const latestBlock = await ethers.provider.getBlock("latest");
    const latestTXHash = latestBlock.transactions.at(-1);
    // Get latest transaction receipt object
    const latestTXReceipt = await ethers.provider.getTransactionReceipt(
      latestTXHash
    );
    // Determine latest transaction gas costs
    const latestTXGasUsage = latestTXReceipt.gasUsed;
    const latestTXGasPrice = latestTXReceipt.effectiveGasPrice;
    const latestTXGasCosts = latestTXGasUsage.mul(latestTXGasPrice);

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.