From e91e3595d6c5e82d294e15f3ca2225730ad581f7 Mon Sep 17 00:00:00 2001 From: emilio Date: Wed, 28 Oct 2020 12:39:11 +0100 Subject: [PATCH] Updated PercentageMath --- contracts/libraries/math/PercentageMath.sol | 22 +++++---------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/contracts/libraries/math/PercentageMath.sol b/contracts/libraries/math/PercentageMath.sol index b853f1db..52a38cd4 100644 --- a/contracts/libraries/math/PercentageMath.sol +++ b/contracts/libraries/math/PercentageMath.sol @@ -22,19 +22,13 @@ library PercentageMath { * @return the percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { - if (value == 0) { + if (value == 0 || percentage == 0) { return 0; } - uint256 result = value * percentage; + require(value <= (type(uint256).max - HALF_PERCENT)/percentage, Errors.MULTIPLICATION_OVERFLOW); - require(result / value == percentage, Errors.MULTIPLICATION_OVERFLOW); - - result += HALF_PERCENT; - - require(result >= HALF_PERCENT, Errors.ADDITION_OVERFLOW); - - return result / PERCENTAGE_FACTOR; + return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** @@ -47,14 +41,8 @@ library PercentageMath { require(percentage != 0, Errors.DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; - uint256 result = value * PERCENTAGE_FACTOR; + require(value <= (type(uint256).max - halfPercentage)/PERCENTAGE_FACTOR, Errors.MULTIPLICATION_OVERFLOW); - require(result / PERCENTAGE_FACTOR == value, Errors.MULTIPLICATION_OVERFLOW); - - result += halfPercentage; - - require(result >= halfPercentage, Errors.ADDITION_OVERFLOW); - - return result / percentage; + return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } }