Can you act on an integer overflow in Solidity 0.8?

With integer underflow/overflow throwing a panic error in Solidity >=0.8, would it be possible to write a conditional in an instance of that happening?

Example:

I want to add a constant type(uint256).max to the total in the case of an overflow.

uint total = 0;

function addProductToTotal(uint256 a, uint256 b) public returns (uint256 total) {
    uint256 product = a * b;

    // some pseudo-code as conditional
    (if product overflowed) ? total += type(uint256).max : total += product;

}

Or would it always throw a panic error on the transaction - so acting upon an overflow is not possible? If it does, would the best solution be using Solidity 0.7 or an unchecked block in 0.8?

Edit: Changed "revert" to "throw a panic error".

Answers 1

  • In 0.8.0 or better, math overflows revert by default but you can get the old behaviour with unchecked.

    unchecked {
      uint256 p = a * b;
    }
    

    Great. Maybe it overflowed.

    bool didNotOverflow = p / a == b;
    // carry on 
    

    Hope it helps.


Related Questions