2

To my understanding, at the beginning of a payable function in a contract, an amount of msg.value ether is added to the contract's balance.

Therefore, the expression address(this).balance >= msg.value is always true.

Therefore, I can compute address(this).balance - msg.value without any risk of underflow.

Is that correct?

Thank you!

1 Answer 1

1

Yes, you are right. When a payable function is invoked the contract balance address(this).balance will be increased by msg.value before any of your code is executed. Therefore both statements of yours are correct:

address(this).balance >= msg.value // Always true in payable function
address(this).balance - msg.value  // Never underflows in payable function

Another answer is confirming it too.

2
  • Just tried it, but I'll try to get some evidence in the docs..
    – Bruno Zell
    Commented Jul 3, 2018 at 8:05
  • Actually if you send ETH to an external address, then later in the same transaction I'm pretty sure address(this).balance will have decreased by the sent amount, while msg.value should have stayed the same (since the incoming message never changed). So yes, this could underflow. (Untested though.) Commented Jul 6, 2022 at 7:21

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.