If a contract is payable and requires some amount of Ether is it possible to take the gas cost out of the sent value instead of directly from the user. Although both these values are coming from the user I would want a user to only be charged the value they are trying to send.

Lets just say for example a lottery contract. Each user would pay, for the sake of the example, 1 Ether to enter the lottery. However I would want to take off of that 1 Ether the gas cost, adding only the difference to the lottery contract and having my user pay the exact amount they wished to pay.

1 Answer 1


Since the gas cost depends on the contract execution and is only finally known after the transaction completes, you can't know the exact cost inside the contract.

However, you can make pretty good estimates with the available gasleft() and tx.gasprice variables. And even if those estimates are a bit off, it might be ok since they are probably a bit off in a similar way for all users.

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.