Is there a way to get the total GAS provided to a transaction? gasLeft only provides the remaining gas at the time that it's called. Even when called immediately, there is a discrepancy, which I assume is related to the costs of invoking the function.

The objective I'm trying to achieve is to calculate what the balance of the callers address was immediately before the transaction.

I am using the following calculate it, however it seems to be off by a fair few Wei.

uint _gasleft = gasleft();
uint balanceBeforeTx = (_gasleft + 21000 ) * tx.gasprice + block.basefee + msg.value + address(msg.sender).balance;

2 Answers 2


You can take a look at using the estimateGas function to estimate the total gas used before a transaction:

Finding gas to be used by a transaction

  • The question relates to Solidity, calculating it within the function itself. Oct 14, 2022 at 4:43

The question I posted included a misinterpretation of block.basefee, rather than being a fee separate to the gas calculations, it is a per-GAS fee. Meaning it is multiplied by the gas used by a function in the same way that tx.gasprice is.

However, tx.gasprice already includes block.basefee, so including block.basefee in these calculations is not necessary.

This doesn't solve the full problem, but it cause the gas calculated to be predictably different from the actual gas provided. Predictable in the sense that it appears to differ by the same amount each time the function is called.

So the following is a hacky solution which technically solved the problem of calculating the exact amount provided when tested in the wild:

uint balanceBeforeTx = (_gasleft + X) * tx.gasprice + msg.value + address(msg.sender).balance;

Where X is a specific value that I obtained experimentally by deploying a contract with such a function to Goerli and calculating the difference between expected and actual values. I do not guarantee that this will work consistently, or if future EVM changes will break it. If you are reading this answer, please keep that in mind.

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.