// File: /C/dev/repos/coti-cvix-contracts/contracts/FeesModel.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./utils/SafeMath80.sol";
import "./utils/SafeMath8.sol";

import "./interfaces/ICVIOracle.sol";
import "./interfaces/IFeesCalculator.sol";
import "./interfaces/IFeesModel.sol";

contract FeesModel is IFeesModel, Ownable {

    using SafeMath for uint256;
    using SafeMath8 for uint8;
    using SafeMath80 for uint80;

    uint256 private constant PRECISION_DECIMALS = 1e10;
    uint80 private constant ROUND_JUMPS_PRECISION = 1000;

    IFeesCalculator private feesCalculator;
    ICVIOracle private cviOracle;

    uint80 public maxOracleValuesUsed = 10;

    uint80 private latestOracleRoundId;
    uint256 private latestSnapshotTimestamp;
    
    mapping(uint256 => uint256) private cviSnapshots;

    constructor(IFeesCalculator _feesCalculator, ICVIOracle _cviOracle) public {
        feesCalculator = _feesCalculator;
        cviOracle = _cviOracle;
    }

    function updateSnapshots() external override returns (uint256) {
        if (cviSnapshots[block.timestamp] != 0) { // Block was already updated
            return 0;
        }

        if (latestSnapshotTimestamp == 0) { // For first recorded block
            cviSnapshots[block.timestamp] = PRECISION_DECIMALS;
            (,latestOracleRoundId) = cviOracle.getCVILatestRoundData();
            latestSnapshotTimestamp = block.timestamp;
            return 0;
        }

        uint80 periodStartRoundId = latestOracleRoundId;
        (uint16 lastCVIValue, uint256 latestCVITimestamp) = cviOracle.getCVIRoundData(periodStartRoundId);
        (,latestOracleRoundId) = cviOracle.getCVILatestRoundData();

        require(latestOracleRoundId >= periodStartRoundId, "Bad round id");

        uint80 cviValuesNumLeft = latestOracleRoundId.sub(periodStartRoundId).add(1);
        uint80 roundsJump = ROUND_JUMPS_PRECISION;

        if (cviValuesNumLeft > maxOracleValuesUsed) {
            roundsJump = cviValuesNumLeft.mul(ROUND_JUMPS_PRECISION).div(maxOracleValuesUsed.sub(1));
            cviValuesNumLeft = maxOracleValuesUsed;
        }

        uint80 currRoundId = latestOracleRoundId;
        if (cviValuesNumLeft > 2) {
            currRoundId = periodStartRoundId.add(roundsJump / ROUND_JUMPS_PRECISION);
        }

        uint256 lastCVITimestamp = latestSnapshotTimestamp;
        uint8 currCVIValueIndex = 0;

        IFeesCalculator.CVIValue[] memory cviValues = new IFeesCalculator.CVIValue[](cviValuesNumLeft);
        cviValuesNumLeft = cviValuesNumLeft.sub(1);

        // Note: this line is valid even when cviValuesNumLeft == 0
        uint256[] memory cviPeriods = new uint256[](cviValuesNumLeft);

        bool shouldUpdateTurbulence = false;

        while (cviValuesNumLeft > 0) {
            shouldUpdateTurbulence = true;

            (uint16 currCVIValue, uint256 currCVITimestamp) = cviOracle.getCVIRoundData(currRoundId);
            
            if (currCVIValueIndex == 0) {
                cviPeriods[currCVIValueIndex] = currCVITimestamp.sub(latestCVITimestamp);
            } else {
                cviPeriods[currCVIValueIndex] = currCVITimestamp.sub(lastCVITimestamp);
            }

            cviValues[currCVIValueIndex] = IFeesCalculator.CVIValue(currCVITimestamp.sub(lastCVITimestamp), lastCVIValue);
            currCVIValueIndex = currCVIValueIndex.add(1);

            lastCVITimestamp = currCVITimestamp;
            lastCVIValue = currCVIValue;

            cviValuesNumLeft = cviValuesNumLeft - 1;

            if (cviValuesNumLeft == 1) {
                currRoundId = latestOracleRoundId; // Always round to latest round on last jump
            } else if (cviValuesNumLeft > 1) {
                currRoundId = periodStartRoundId.add(roundsJump.mul(currCVIValueIndex) / ROUND_JUMPS_PRECISION);
            }
        }

        cviValues[currCVIValueIndex] = IFeesCalculator.CVIValue(block.timestamp.sub(lastCVITimestamp), lastCVIValue);
        uint256 singleUnitFundingFee = feesCalculator.calculateSingleUnitFundingFee(cviValues);
        
        if (shouldUpdateTurbulence) {
            feesCalculator.updateTurbulenceIndicatorPercent(cviPeriods);
        }        

        cviSnapshots[block.timestamp] = cviSnapshots[latestSnapshotTimestamp].add(singleUnitFundingFee);
        latestSnapshotTimestamp = block.timestamp;

        return singleUnitFundingFee;
    }

    function setCVIOracle(ICVIOracle _newOracle) external override onlyOwner {
        cviOracle = _newOracle;
    }

    function setFeesCalculator(IFeesCalculator _newCalculator) external override onlyOwner {
        feesCalculator = _newCalculator;
    }

    function setLatestOracleRoundId(uint80 _newOracleRoundId) external override onlyOwner {
        latestOracleRoundId = _newOracleRoundId;
    }

    function setMaxOracleValuesUsed(uint80 _newMaxOracleValuesUsed) external override onlyOwner {
        maxOracleValuesUsed = _newMaxOracleValuesUsed;
    }
    
    function calculateFundingFees(uint256 startTime, uint256 endTime, uint256 positionUnitsAmount) external view override returns (uint256) {
        return _calculateFundingFees(startTime, endTime, positionUnitsAmount);
    }

    function calculateFundingFees(uint256 startTime, uint256 positionUnitsAmount) external view override returns (uint256) {
        return _calculateFundingFees(startTime, latestSnapshotTimestamp, positionUnitsAmount);
    }

    function calculateFundingFeesAddendum(uint256 positionUnitsAmount) external view override returns (uint256) {
        if (positionUnitsAmount == 0 || latestSnapshotTimestamp == 0 || latestSnapshotTimestamp == block.timestamp) {
            return 0;
        }

        uint80 currRoundId = latestOracleRoundId;
        (uint16 latestCVIValue ,uint80 updatedLatestOracleRoundId) = cviOracle.getCVILatestRoundData();
        (uint16 lastCVIValue,) = cviOracle.getCVIRoundData(currRoundId);
        uint256 lastCVITimestamp = latestSnapshotTimestamp;

        IFeesCalculator.CVIValue[] memory cviValues = new IFeesCalculator.CVIValue[](updatedLatestOracleRoundId.sub(latestOracleRoundId).add(1));

        while (currRoundId < updatedLatestOracleRoundId) {
            currRoundId = currRoundId.add(1);
            (uint16 currCVIValue, uint256 currCVITimestamp) = cviOracle.getCVIRoundData(currRoundId);
            cviValues[currRoundId.sub(latestOracleRoundId).sub(1)] = IFeesCalculator.CVIValue(currCVITimestamp.sub(lastCVITimestamp), lastCVIValue);
            
            lastCVITimestamp = currCVITimestamp;
            lastCVIValue = currCVIValue;
       }

       cviValues[currRoundId.sub(latestOracleRoundId)] = IFeesCalculator.CVIValue(block.timestamp.sub(lastCVITimestamp), latestCVIValue);
       return positionUnitsAmount.mul(feesCalculator.calculateSingleUnitFundingFee(cviValues)).div(PRECISION_DECIMALS);
    }

    function _calculateFundingFees(uint256 startTime, uint256 endTime, uint256 positionUnitsAmount) private view returns (uint256) {
        return cviSnapshots[endTime].sub(cviSnapshots[startTime]).mul(positionUnitsAmount).div(PRECISION_DECIMALS);
    }
}

// File: /C/dev/repos/coti-cvix-contracts/contracts/interfaces/ICVIOracle.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;

interface ICVIOracle {
    function getCVIRoundData(uint80 roundId) external view returns (uint16 cviValue, uint256 cviTimestamp);
    function getCVILatestRoundData() external view returns (uint16 cviValue, uint80 cviRoundId);
}

// File: /C/dev/repos/coti-cvix-contracts/contracts/interfaces/IFeesCalculator.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;

interface IFeesCalculator {

    struct CVIValue {
        uint256 period;
        uint16 cviValue;
    }

    function updateTurbulenceIndicatorPercent(uint256[] calldata periods) external returns (uint16);

    function setTurbulenceUpdator(address newUpdator) external;

    function setDepositFee(uint16 newDepositFeePercentage) external;
    function setWithdrawFee(uint16 newWithdrawFeePercentage) external;
    function setOpenPositionFee(uint16 newOpenPositionFeePercentage) external;
    function setClosePositionFee(uint16 newClosePositionFeePercentage) external;
    function setClosePositionMaxFee(uint16 newClosePositionMaxFeePercentage) external;
    function setClosePositionFeeDecay(uint256 newClosePositionFeeDecayPeriod) external;
    
    function setOracleHeartbeatPeriod(uint256 newOracleHeartbeatPeriod) external;
    function setBuyingPremiumFeeMax(uint16 newBuyingPremiumFeeMaxPercentage) external;
    function setBuyingPremiumThreshold(uint16 newBuyingPremiumThreshold) external;
    function setTurbulenceStep(uint16 newTurbulenceStepPercentage) external;
    function setTurbulenceFeeMinPercentThreshold(uint16 _newTurbulenceFeeMinPercentThreshold) external;

    function calculateBuyingPremiumFee(uint256 tokenAmount, uint256 collateralRatio) external view returns (uint256 buyingPremiumFee);
    function calculateSingleUnitFundingFee(CVIValue[] calldata cviValues) external pure returns (uint256 fundingFee);
    function calculateClosePositionFeePercent(uint256 creationTimestamp) external view returns (uint16);
    function calculateWithdrawFeePercent(uint256 lastDepositTimestamp) external view returns (uint16);

    function depositFeePercent() external returns (uint16);
    function withdrawFeePercent() external returns (uint16);
    function openPositionFeePercent() external returns (uint16);
    function closePositionFeePercent() external returns (uint16);
    function buyingPremiumFeeMaxPercent() external returns (uint16);
}

// File: /C/dev/repos/coti-cvix-contracts/contracts/interfaces/IFeesModel.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;

import "./ICVIOracle.sol";
import "./IFeesCalculator.sol";

interface IFeesModel {
    function updateSnapshots() external returns (uint256);

    function setCVIOracle(ICVIOracle newOracle) external;
    function setFeesCalculator(IFeesCalculator newCalculator) external;
    function setLatestOracleRoundId(uint80 newOracleRoundId) external;
    function setMaxOracleValuesUsed(uint80 newMaxOracleValuesUsed) external;

    function calculateFundingFees(uint256 startTime, uint256 positionUnitsAmount) external view returns (uint256);
    function calculateFundingFees(uint256 startTime, uint256 endTime, uint256 positionUnitsAmount) external view returns (uint256);
    function calculateFundingFeesAddendum(uint256 positionUnitsAmount) external view returns (uint256);
}

// File: /C/dev/repos/coti-cvix-contracts/contracts/utils/SafeMath8.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath8 {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint8 a, uint8 b) internal pure returns (uint8) {
        uint8 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint8 a, uint8 b) internal pure returns (uint8) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
        require(b <= a, errorMessage);
        uint8 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint8 a, uint8 b) internal pure returns (uint8) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint8 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint8 a, uint8 b) internal pure returns (uint8) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
        require(b > 0, errorMessage);
        uint8 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint8 a, uint8 b) internal pure returns (uint8) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
// File: /C/dev/repos/coti-cvix-contracts/contracts/utils/SafeMath80.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath80 {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint80 a, uint80 b) internal pure returns (uint80) {
        uint80 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint80 a, uint80 b) internal pure returns (uint80) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint80 a, uint80 b, string memory errorMessage) internal pure returns (uint80) {
        require(b <= a, errorMessage);
        uint80 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint80 a, uint80 b) internal pure returns (uint80) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint80 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint80 a, uint80 b) internal pure returns (uint80) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint80 a, uint80 b, string memory errorMessage) internal pure returns (uint80) {
        require(b > 0, errorMessage);
        uint80 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint80 a, uint80 b) internal pure returns (uint80) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint80 a, uint80 b, string memory errorMessage) internal pure returns (uint80) {
        require(b != 0, errorMessage);
        return a % b;
    }
}
// File: @openzeppelin/contracts/GSN/Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import "../GSN/Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () internal {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: @openzeppelin/contracts/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}