From 4baf17d9e6a90befc07642419cbaeafcaf176f96 Mon Sep 17 00:00:00 2001 From: The3D Date: Mon, 27 Jul 2020 12:32:54 +0200 Subject: [PATCH] added percentMath --- contracts/libraries/PercentageMath.sol | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 contracts/libraries/PercentageMath.sol diff --git a/contracts/libraries/PercentageMath.sol b/contracts/libraries/PercentageMath.sol new file mode 100644 index 00000000..7ce7c076 --- /dev/null +++ b/contracts/libraries/PercentageMath.sol @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: agpl-3.0 +pragma solidity ^0.6.8; + +import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; + +/** + * @title PercentageMath library + * @author Aave + * @notice Provides functions to calculate percentages. Percentages needs to be defined by default with 2 decimals of precision (100.00) + * @dev Operations are rounded up + **/ + +library PercentageMath { + using SafeMath for uint256; + + uint256 constant PERCENTAGE_FACTOR = 1e2; //percentage plus two decimals + uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; + + function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { + return HALF_PERCENT.add(value.mul(percentage)).div(PERCENTAGE_FACTOR); + } + + function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { + uint256 halfPercentage = percentage / 2; + + return halfPercentage.add(value.mul(PERCENTAGE_FACTOR)).div(halfPercentage); + } +}