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)?

3 Answers 3


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.

  • Is it possible to get the like "startgas" within solidity and without web3 or external calls?
    – dkb
    Commented May 12, 2018 at 18:50
  • 1
    This actually a good idea and this is available in the solidity environment, no need for web3.
    – Jaime
    Commented May 12, 2018 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
    Commented May 12, 2018 at 19:04
  • 1
    @Jaime im working through a similar implementation thats not giving me the expected results: ethereum.stackexchange.com/questions/111741/…
    – lopezdp
    Commented Oct 18, 2021 at 14:48

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.

  • 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
    Commented May 12, 2018 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
    Commented May 12, 2018 at 18:52
  • the answer from @Jesse Busman is what you need
    – Jaime
    Commented May 12, 2018 at 18:59

use getTransactionReceipt: doc

  • Hello, I meant in solidity. Not web3. Is that possible?
    – dkb
    Commented May 12, 2018 at 18:19
  • 2
    This link is not the answer. This is web3js, he asked for solidity Commented May 13, 2018 at 8:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.