1

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".

4
  • it wont revert unless you put a require() statement
    – Nulik
    Jul 7, 2021 at 4:54
  • too much hype with this overflow thing. Assembly language developers have been dealing with this since 1960s, since the invention of a computer.
    – Nulik
    Jul 7, 2021 at 4:56
  • @Nulik It'll throw a panic error in Solidity 0.8 though, compared to 0.7 where SafeMath was used. So I'm wondering if I can avoid this panic error in this version.
    – Pottedtree
    Jul 7, 2021 at 5:02
  • well, SafeMath will produce panic on purpose because overflow shouldn't happen. But if your App is perfectly fine with topping out at max value then go for it. In assembly language this is called saturation, for example all Intel X86 processors have a vector instruction like VADDSB where in case of overflow maximum values are kept. modoocode.com/paddsb-paddsw Overflow is handled with signed saturation, as described in the following paragraphs.
    – Nulik
    Jul 7, 2021 at 5:11

1 Answer 1

7

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.

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.