I have an expensive function I am calling in my smart contract, and I need to keep track of the approximate amount of gas its consuming, so I measure gas remaining at the beginning of the function and end of function and subtract to get gas consumed.

I have set it up like this:

 event ReportCost(
      uint gasCost
 function doSomethingExpensive() public {
      uint startGas = gasleft();
      //do expensive thing
      uint endGas = gasleft()
      emit ReportGas(startGas-endGas)

On the client, when I make this call contract like so:

 let result = await contract.doSomethingExpensive();
 let receipt await result.wait();
 let events = receipt.events?filter(x) == "ReportCost"});
 let gasCost = events[0].args["gasCost"];

This gives the result gasCost 4642815

I thought this would be the cost in wei, but if that's true, its way too cheap. I am running the hard gas reporter which reports the cost at 4680474 gwei not wei, which makes more sense. I just don't understand why appear to be getting cost in gwei gwei since the gasleft function seems like it suppposed to return wei not gwei.

  • Well, mystery solved. Apparently gasleft() reports gas in gwei.
    – GGizmos
    Oct 13, 2021 at 0:28
  • No, it doesn't. I think you are mixing up concepts. gasleft() will give you the amount of gas units consumed. Then you multiply that by the gas price to get how much eth was consumed. The reason the gas reporter tells you that value is (probably) because it's using a gas price of 1 gwei. Oct 13, 2021 at 18:09


Your Answer

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

Browse other questions tagged or ask your own question.