5

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

13

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.

3
  • Is it possible to get the like "startgas" within solidity and without web3 or external calls?
    – dkb
    May 12 '18 at 18:50
  • 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
3

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.

3
  • 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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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