A dangerous way to fix Integer Overflow in Solidity

Surprisingly, a sizable number of submissions for dApp Start Here level was by swapping int32 with uint.

These submission fail for a good reason. The security vulnerability has not been fixed!

Let’s find out why.

uint is an alias for uint256. It has a fixed range, starting from 0 to 115792089237316195423570985008687907853269984665640564039457584007913129639935. It is a big number but it is still fixed. If an arithmetic operation (e.g. adding two number) goes beyond or below this range, integer overflow happens.

So how do we fix integer overflow in Solidity?

Before taking a shortcut (i.e. include Openzeppelin’s SafeMath.sol or upgrade to use Solidity v0.8.0), let’s look at three defensive patterns:

  1. Pre/Post condition testing: check the input before and/or after each arithmetic operation. If safe, proceed with the operation, otherwise throw an exception.
  2. Upcasting: Use a larger datatype and perform the arithmetic. Check if the overflow of smaller datatype before downcasting.
  3. Dynamic datatype: Use a data type that uses a dynamic memory allocation (i.e. BigInteger).

Out of the above three patterns , (3) is the best solution but it is not supported by Solidity and (2) is still dangerous (what if the the input is bigger than the larger data type). So we are left with (1).

function SafeAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
    uint256 c = a + b;
    if (c < a) return (false, 0);
    return (true, c);

In the above example, we used post condition testing. We used one property of addition, that is the result of addition is never smaller than the given numbers.

So let’s stop changing data type to fix integer overflow but use pre or post condition testing. Simple and effective!

Now you can go back to dApp Start Here level and get a score!

:warning: Solidity compiler v0.8.0 and above throws exception when integer overflow happens. Please keep in mind this comes with an additional gas cost and does not protect you against all the 22 causes of integer overflow. Watch this video to find out more: BEC Overflow - SecDim