7

Can a contract have a method that, does something, and if there is gas left over, performs an extra task?

Something like:

function doSomething() {
  performCheapTask();
  if(thereIsGasLeftOver) {
    performExtraTask();
  }
}
8

Yes, you can check gasleft() to get the remaining gas and only proceed if you think you'll have enough. This assumes you can make a reasonable estimate of how much gas you'll need, though: If you undershoot and spend too much, the whole transaction will be reverted.

There's some related discussion under this EIP: https://github.com/ethereum/EIPs/issues/90

Also note that there are proposals to change the gas requirements in a future fork, so even if you estimate the gas you need correctly now, it may break in future.

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.