14

I want to return the gas used to the user when he uses a payable function. I used tx.gasprice but it always returns 1.

How can I get the actual gas used value (not the maximum or user set values, but really the gas used value for the transaction, in my case, a function call)?

dkb
  • 723
  • 1
  • 5
  • 20

3 Answers3

32

You can measure the gas used in a block of code by calculating the difference between gasleft() at the start and gasleft() at the end:

function test() returns (uint256 gasUsed)
{
    uint256 startGas = gasleft();

    // ...some code here...

    gasUsed = startGas - gasleft();
}

This does not yet take into account the constant cost of a transaction, which as far as I know is usually approximately 21000.

Jesbus
  • 10,478
  • 6
  • 35
  • 62
  • Is it possible to get the like "startgas" within solidity and without web3 or external calls? – dkb May 12 '18 at 18:50
  • 1
    This actually a good idea and this is available in the solidity environment, no need for web3. – Jaime May 12 '18 at 18:58
  • @Jaime what I wrote was just an example. For sure I had some other functions that should work with gas. But I didn't want to talk detailed about it. – dkb May 12 '18 at 19:04
  • 1
    @Jaime im working through a similar implementation thats not giving me the expected results: https://ethereum.stackexchange.com/questions/111741/how-can-i-measure-gas-in-solidity-to-increment-a-users-balance-according-to-the – lopezdp Oct 18 '21 at 14:48
6

tx.gasPrice is the price per 1 gas, not the gas paid. There is no way to get this information from the variables in the environment in solidity. The solution is to have a frontend app that sends this info to your contract.

Hope this help.

Jaime
  • 8,340
  • 1
  • 12
  • 20
  • It helps but the problem is, I want to work with that value within solidity itself, so use it in functions. Is that in no way possible? – dkb May 12 '18 at 18:27
  • No, as far as I know. The only option is to use web3 and send this info to your contract. Then you can read the value it as any other variable. – Jaime May 12 '18 at 18:52
  • the answer from @Jesse Busman is what you need – Jaime May 12 '18 at 18:59
1

use getTransactionReceipt: doc

Itération 122442
  • 2,052
  • 1
  • 12
  • 33