Solidity Overflow – How to Intentionally Allow Overflow in Solidity

overflowsolidity

I'm working on an application that handles percents of a whole.

1. By definition the total percentage will never exceed 100%

I do not want to leave a bug in the application in which could leave a user in an unsolvable state.

Imagine the following scenario.

  1. I'm a token owner I've created a token with the max supply of Uint256.Max.
  2. I put the full supply into a contract
  3. I would like to move 30% of the supply somewhere.

I have an operation to obtain the percent:

function _getAmountFromPercent(uint256 amount, uint256 percentBips) internal pure returns(uint256) {
    return (amount * percentBips) / BASIS_POINTS_FACTOR;
}

This operation will cause an overflow, however the following operation will normalize it since the percentage will always be below 100.

Swaping the operations, wont work either, if your amount is less than the Denomintor you will always result int having 0.

How can I allow overflow operations?

Best Answer

Using the lib gnosis/solidity-arithmetic:

import "./path/to/Arithmetic.sol";
...        

function _getAmountFromPercent(uint256 amount, uint256 percentBips) internal pure returns(uint256) {
        return Arithmetic.overflowResistantFraction(amount , percentBips, BASIS_POINTS_FACTOR);
    }
Related Topic