2

Imagine you have a function like this:

function compute(uint256 a, uint256 b) external pure returns (uint256) {
  return a % b;
}

Does it revert when b is 0?

1

2 Answers 2

5

This is answered in the Solidity documentation.

From https://docs.soliditylang.org/en/v0.8.17/types.html#modulo:

Modulo with zero causes a Panic error. This check can not be disabled through unchecked { ... }.

2

It reverts, but with INVALID opcode (similar to assert) rather than REVERT opcode (similar to require).

In order to impose the latter, you can add require(b != 0) prior to return a % b.

If b is a user-input value, then you should add this require statement.

If b is an internally-generated value in your system and you know that it is never supposed to be 0, then you can add assert(b != 0) prior to return a % b, or you can leave it as is (since, as mentioned above, a % b will yield the exact same behavior).

4
  • Just discovered an important implication of this. If you let Solidity handle mod 0, the contract call will consume all remaining gas. If you preemptively require the divisor not to be zero, which leaves remaining gas untouched. Commented Jun 13, 2020 at 9:01
  • This is why OpenZeppelin added a mod function in SafeMath. Commented Jun 13, 2020 at 9:01
  • 1
    @PaulRazvanBerg: This implication is obvious from the answer, because it is well known that require (and more generally, the REVERT opcode) returns the remaining gas to the user, while assert (and more generally, the INVALID opcode) does not. Thus, as explained in my answer, you should use require (OZ function if you will), when dealing with user-input. That's also explained in my answer IMO (or at least implied by it). Commented Jun 13, 2020 at 9:54
  • For sure, but you're a seasoned Solidity engineer. Now the gas consumption implications are obvious to anyone stumbling upon this StackExchange thread. Commented Jun 13, 2020 at 10:00

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.