{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/Pool/Repayments.sol",
    "Parent Contracts": [
        "node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol",
        "contracts/interfaces/IRepayment.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract Repayments is Initializable, IRepayment, ReentrancyGuard {\n    using SafeERC20 for IERC20;\n    using SafeMath for uint256;\n\n    uint256 constant MAX_INT = 2**256 - 1;\n    uint256 constant YEAR_IN_SECONDS = 365 days;\n\n    IPoolFactory poolFactory;\n\n    enum LoanStatus {\n        COLLECTION, //denotes collection period\n        ACTIVE, // denotes the active loan\n        CLOSED, // Loan is repaid and closed\n        CANCELLED, // Cancelled by borrower\n        DEFAULTED, // Repaymennt defaulted by  borrower\n        TERMINATED // Pool terminated by admin\n    }\n\n    uint256 gracePenaltyRate;\n    uint256 gracePeriodFraction; // fraction of the repayment interval\n\n    struct RepaymentVariables {\n        uint256 repaidAmount;\n        bool isLoanExtensionActive;\n        uint256 loanDurationCovered;\n        uint256 loanExtensionPeriod; // period for which the extension was granted, ie, if loanExtensionPeriod is 7 * 10**30, 7th instalment can be repaid by 8th instalment deadline\n    }\n\n    struct RepaymentConstants {\n        uint256 numberOfTotalRepayments; // using it to check if RepaymentDetails Exists as repayment Interval!=0 in any case\n        uint256 gracePenaltyRate;\n        uint256 gracePeriodFraction;\n        uint256 loanDuration;\n        uint256 repaymentInterval;\n        uint256 borrowRate;\n        uint256 loanStartTime;\n        address repayAsset;\n    }\n\n    /**\n     * @notice used to maintain the variables related to repayment against a pool\n     */\n    mapping(address => RepaymentVariables) public repayVariables;\n\n    /**\n     * @notice used to maintain the constants related to repayment against a pool\n     */\n    mapping(address => RepaymentConstants) public repayConstants;\n\n    /// @notice determines if the pool is active or not based on whether repayments have been started by the\n    ///borrower for this particular pool or not\n    /// @param _poolID address of the pool for which we want to test statu\n    modifier isPoolInitialized(address _poolID) {\n        require(repayConstants[_poolID].numberOfTotalRepayments != 0, 'Pool is not Initiliazed');\n        _;\n    }\n\n    /// @notice modifier used to determine whether the current pool is valid or not\n    /// @dev poolRegistry from IPoolFactory interface returns a bool\n    modifier onlyValidPool() {\n        require(poolFactory.poolRegistry(msg.sender), 'Repayments::onlyValidPool - Invalid Pool');\n        _;\n    }\n\n    /**\n     * @notice modifier used to check if msg.sender is the owner\n     */\n    modifier onlyOwner() {\n        require(msg.sender == poolFactory.owner(), 'Not owner');\n        _;\n    }\n\n    /// @notice Initializes the contract (similar to a constructor)\n    /// @dev Since we cannot use constructors when using OpenZeppelin Upgrades, we use the initialize function\n    ///and the initializer modifier makes sure that this function is called only once\n    /// @param _poolFactory The address of the pool factory\n    /// @param _gracePenaltyRate The penalty rate levied in the grace period\n    /// @param _gracePeriodFraction The fraction of repayment interval that will be allowed as grace period\n    function initialize(\n        address _poolFactory,\n        uint256 _gracePenaltyRate,\n        uint256 _gracePeriodFraction\n    ) external initializer {\n        _updatePoolFactory(_poolFactory);\n        _updateGracePenaltyRate(_gracePenaltyRate);\n        _updateGracePeriodFraction(_gracePeriodFraction);\n    }\n\n    /**\n     * @notice used to update pool factory address\n     * @param _poolFactory address of pool factory contract\n     */\n    function updatePoolFactory(address _poolFactory) external onlyOwner {\n        _updatePoolFactory(_poolFactory);\n    }\n\n    function _updatePoolFactory(address _poolFactory) internal {\n        require(_poolFactory != address(0), '0 address not allowed');\n        poolFactory = IPoolFactory(_poolFactory);\n        emit PoolFactoryUpdated(_poolFactory);\n    }\n\n    /**\n     * @notice used to update grace period as a fraction of repayment interval\n     * @param _gracePeriodFraction updated value of gracePeriodFraction multiplied by 10**30\n     */\n    function updateGracePeriodFraction(uint256 _gracePeriodFraction) external onlyOwner {\n        _updateGracePeriodFraction(_gracePeriodFraction);\n    }\n\n    function _updateGracePeriodFraction(uint256 _gracePeriodFraction) internal {\n        gracePeriodFraction = _gracePeriodFraction;\n        emit GracePeriodFractionUpdated(_gracePeriodFraction);\n    }\n\n    /**\n     * @notice used to update grace penality rate\n     * @param _gracePenaltyRate value of grace penality rate multiplied by 10**30\n     */\n    function updateGracePenaltyRate(uint256 _gracePenaltyRate) external onlyOwner {\n        _updateGracePenaltyRate(_gracePenaltyRate);\n    }\n\n    function _updateGracePenaltyRate(uint256 _gracePenaltyRate) internal {\n        gracePenaltyRate = _gracePenaltyRate;\n        emit GracePenaltyRateUpdated(_gracePenaltyRate);\n    }\n\n    /// @notice For a valid pool, the repayment schedule is being initialized here\n    /// @dev Imported from RepaymentStorage.sol repayConstants is a mapping(address => repayConstants)\n    /// @param numberOfTotalRepayments The total number of repayments that will be required from the borrower\n    /// @param repaymentInterval Intervals after which repayment will be due\n    /// @param borrowRate The rate at which lending took place\n    /// @param loanStartTime The starting time of the loan\n    /// @param lentAsset The address of the asset that was lent (basically a ERC20 token address)\n    function initializeRepayment(\n        uint256 numberOfTotalRepayments,\n        uint256 repaymentInterval,\n        uint256 borrowRate,\n        uint256 loanStartTime,\n        address lentAsset\n    ) external override onlyValidPool {\n        repayConstants[msg.sender].gracePenaltyRate = gracePenaltyRate;\n        repayConstants[msg.sender].gracePeriodFraction = gracePeriodFraction;\n        repayConstants[msg.sender].numberOfTotalRepayments = numberOfTotalRepayments;\n        repayConstants[msg.sender].loanDuration = repaymentInterval.mul(numberOfTotalRepayments).mul(10**30);\n        repayConstants[msg.sender].repaymentInterval = repaymentInterval.mul(10**30);\n        repayConstants[msg.sender].borrowRate = borrowRate;\n        repayConstants[msg.sender].loanStartTime = loanStartTime.mul(10**30);\n        repayConstants[msg.sender].repayAsset = lentAsset;\n    }\n\n    /**\n     * @notice returns the number of repayment intervals that have been repaid,\n     * if repayment interval = 10 secs, loan duration covered = 55 secs, repayment intervals covered = 5\n     * @param _poolID address of the pool\n     * @return scaled interest per second\n     */\n\n    function getInterestPerSecond(address _poolID) public view returns (uint256) {\n        uint256 _activePrincipal = IPool(_poolID).totalSupply();\n        uint256 _interestPerSecond = _activePrincipal.mul(repayConstants[_poolID].borrowRate).div(YEAR_IN_SECONDS);\n        return _interestPerSecond;\n    }\n\n    /// @notice This function determines the number of completed instalments\n    /// @param _poolID The address of the pool for which we want the completed instalments\n    /// @return scaled instalments completed\n    function getInstalmentsCompleted(address _poolID) public view returns (uint256) {\n        uint256 _repaymentInterval = repayConstants[_poolID].repaymentInterval;\n        uint256 _loanDurationCovered = repayVariables[_poolID].loanDurationCovered;\n        uint256 _instalmentsCompleted = _loanDurationCovered.div(_repaymentInterval).mul(10**30); // dividing exponents, returns whole number rounded down\n\n        return _instalmentsCompleted;\n    }\n\n    /// @notice This function determines the interest that is due for the borrower till the current instalment deadline\n    /// @param _poolID The address of the pool for which we want the interest\n    /// @return scaled interest due till instalment deadline\n    function getInterestDueTillInstalmentDeadline(address _poolID) public view returns (uint256) {\n        uint256 _interestPerSecond = getInterestPerSecond(_poolID);\n        uint256 _nextInstalmentDeadline = getNextInstalmentDeadline(_poolID);\n        uint256 _loanDurationCovered = repayVariables[_poolID].loanDurationCovered;\n        uint256 _interestDueTillInstalmentDeadline = (\n            _nextInstalmentDeadline.sub(repayConstants[_poolID].loanStartTime).sub(_loanDurationCovered)\n        ).mul(_interestPerSecond).div(10**30);\n        return _interestDueTillInstalmentDeadline;\n    }\n\n    /// @notice This function determines the timestamp of the next instalment deadline\n    /// @param _poolID The address of the pool for which we want the next instalment deadline\n    /// @return timestamp before which next instalment ends\n    function getNextInstalmentDeadline(address _poolID) public view override returns (uint256) {\n        uint256 _instalmentsCompleted = getInstalmentsCompleted(_poolID);\n        if (_instalmentsCompleted == repayConstants[_poolID].numberOfTotalRepayments.mul(10**30)) {\n            revert('Pool completely repaid');\n        }\n        uint256 _loanExtensionPeriod = repayVariables[_poolID].loanExtensionPeriod;\n        uint256 _repaymentInterval = repayConstants[_poolID].repaymentInterval;\n        uint256 _loanStartTime = repayConstants[_poolID].loanStartTime;\n        uint256 _nextInstalmentDeadline;\n\n        if (_loanExtensionPeriod > _instalmentsCompleted) {\n            _nextInstalmentDeadline = ((_instalmentsCompleted.add(10**30).add(10**30)).mul(_repaymentInterval).div(10**30)).add(\n                _loanStartTime\n            );\n        } else {\n            _nextInstalmentDeadline = ((_instalmentsCompleted.add(10**30)).mul(_repaymentInterval).div(10**30)).add(_loanStartTime);\n        }\n        return _nextInstalmentDeadline;\n    }\n\n    /// @notice This function determine the current instalment interval\n    /// @param _poolID The address of the pool for which we want the current instalment interval\n    /// @return scaled instalment interval\n    function getCurrentInstalmentInterval(address _poolID) public view returns (uint256) {\n        uint256 _instalmentsCompleted = getInstalmentsCompleted(_poolID);\n        return _instalmentsCompleted.add(10**30);\n    }\n\n    /// @notice This function determines the current (loan) interval\n    /// @dev adding 10**30 to add 1. Considering base itself as (10**30)\n    /// @param _poolID The address of the pool for which we want the current loan interval\n    /// @return scaled current loan interval\n    function getCurrentLoanInterval(address _poolID) external view override returns (uint256) {\n        uint256 _loanStartTime = repayConstants[_poolID].loanStartTime;\n        uint256 _currentTime = block.timestamp.mul(10**30);\n        uint256 _repaymentInterval = repayConstants[_poolID].repaymentInterval;\n        uint256 _currentInterval = ((_currentTime.sub(_loanStartTime)).mul(10**30).div(_repaymentInterval)).add(10**30);\n\n        return _currentInterval;\n    }\n\n    /// @notice Check if grace penalty is applicable or not\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool for which we want to inquire if grace penalty is applicable or not\n    /// @return boolean value indicating if applicable or not\n    function isGracePenaltyApplicable(address _poolID) public view returns (bool) {\n        uint256 _repaymentInterval = repayConstants[_poolID].repaymentInterval;\n        uint256 _currentTime = block.timestamp.mul(10**30);\n        uint256 _gracePeriodFraction = repayConstants[_poolID].gracePeriodFraction;\n        uint256 _nextInstalmentDeadline = getNextInstalmentDeadline(_poolID);\n        uint256 _gracePeriodDeadline = _nextInstalmentDeadline.add(_gracePeriodFraction.mul(_repaymentInterval).div(10**30));\n\n        require(_currentTime <= _gracePeriodDeadline, 'Borrower has defaulted');\n\n        if (_currentTime <= _nextInstalmentDeadline) return false;\n        else return true;\n    }\n\n    /// @notice Checks if the borrower has defaulted\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool from which borrower borrowed\n    /// @return bool indicating whether the borrower has defaulted\n    function didBorrowerDefault(address _poolID) external view override returns (bool) {\n        uint256 _repaymentInterval = repayConstants[_poolID].repaymentInterval;\n        uint256 _currentTime = block.timestamp.mul(10**30);\n        uint256 _gracePeriodFraction = repayConstants[_poolID].gracePeriodFraction;\n        uint256 _nextInstalmentDeadline = getNextInstalmentDeadline(_poolID);\n        uint256 _gracePeriodDeadline = _nextInstalmentDeadline.add(_gracePeriodFraction.mul(_repaymentInterval).div(10**30));\n        if (_currentTime > _gracePeriodDeadline) return true;\n        else return false;\n    }\n\n    /// @notice Determines entire interest remaining to be paid for the loan issued to the borrower\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool for which we want to calculate remaining interest\n    /// @return interest remaining\n    function getInterestLeft(address _poolID) public view returns (uint256) {\n        uint256 _interestPerSecond = getInterestPerSecond((_poolID));\n        uint256 _loanDurationLeft = repayConstants[_poolID].loanDuration.sub(repayVariables[_poolID].loanDurationCovered);\n        uint256 _interestLeft = _interestPerSecond.mul(_loanDurationLeft).div(10**30); // multiplying exponents\n\n        return _interestLeft;\n    }\n\n    /// @notice Given there is no loan extension, find the overdue interest after missing the repayment deadline\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool\n    /// @return interest amount that is overdue\n    function getInterestOverdue(address _poolID) public view returns (uint256) {\n        require(repayVariables[_poolID].isLoanExtensionActive, 'No overdue');\n        uint256 _instalmentsCompleted = getInstalmentsCompleted(_poolID);\n        uint256 _interestPerSecond = getInterestPerSecond(_poolID);\n        uint256 _interestOverdue = (\n            (\n                (_instalmentsCompleted.add(10**30)).mul(repayConstants[_poolID].repaymentInterval).div(10**30).sub(\n                    repayVariables[_poolID].loanDurationCovered\n                )\n            )\n        ).mul(_interestPerSecond).div(10**30);\n        return _interestOverdue;\n    }\n\n    /// @notice Used to for your overdues, grace penalty and interest\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool\n    /// @param _amount amount repaid by the borrower\n    function repay(address _poolID, uint256 _amount) external payable nonReentrant isPoolInitialized(_poolID) {\n        address _asset = repayConstants[_poolID].repayAsset;\n        uint256 _amountRepaid = _repay(_poolID, _amount, false);\n\n        _transferTokens(msg.sender, _poolID, _asset, _amountRepaid);\n    }\n\n    function _repayExtension(address _poolID) internal returns (uint256) {\n        if (repayVariables[_poolID].isLoanExtensionActive) {\n            uint256 _interestOverdue = getInterestOverdue(_poolID);\n            repayVariables[_poolID].isLoanExtensionActive = false; // deactivate loan extension flag\n            repayVariables[_poolID].loanDurationCovered = (getInstalmentsCompleted(_poolID).add(10**30))\n                .mul(repayConstants[_poolID].repaymentInterval)\n                .div(10**30);\n            emit ExtensionRepaid(_poolID, _interestOverdue);\n            return _interestOverdue;\n        } else {\n            return 0;\n        }\n    }\n\n    function _repayGracePenalty(address _poolID) internal returns (uint256) {\n        bool _isBorrowerLate = isGracePenaltyApplicable(_poolID);\n\n        if (_isBorrowerLate) {\n            uint256 _penalty = repayConstants[_poolID].gracePenaltyRate.mul(getInterestDueTillInstalmentDeadline(_poolID)).div(10**30);\n            emit GracePenaltyRepaid(_poolID, _penalty);\n            return _penalty;\n        } else {\n            return 0;\n        }\n    }\n\n    function _repayInterest(\n        address _poolID,\n        uint256 _amount,\n        bool _isLastRepayment\n    ) internal returns (uint256) {\n        uint256 _interestLeft = getInterestLeft(_poolID);\n        require((_amount < _interestLeft) != _isLastRepayment, 'Repayments::repay complete interest must be repaid along with principal');\n\n        if (_amount < _interestLeft) {\n            uint256 _interestPerSecond = getInterestPerSecond(_poolID);\n            uint256 _newDurationRepaid = _amount.mul(10**30).div(_interestPerSecond); // dividing exponents\n            repayVariables[_poolID].loanDurationCovered = repayVariables[_poolID].loanDurationCovered.add(_newDurationRepaid);\n            emit InterestRepaid(_poolID, _amount);\n            return _amount;\n        } else {\n            repayVariables[_poolID].loanDurationCovered = repayConstants[_poolID].loanDuration; // full interest repaid\n            emit InterestRepaymentComplete(_poolID, _interestLeft);\n            return _interestLeft;\n        }\n    }\n\n    function _updateRepaidAmount(address _poolID, uint256 _scaledRepaidAmount) internal returns (uint256) {\n        uint256 _toPay = _scaledRepaidAmount.div(10**30);\n        repayVariables[_poolID].repaidAmount = repayVariables[_poolID].repaidAmount.add(_toPay);\n        return _toPay;\n    }\n\n    function _repay(\n        address _poolID,\n        uint256 _amount,\n        bool _isLastRepayment\n    ) internal returns (uint256) {\n        IPool _pool = IPool(_poolID);\n        _amount = _amount * 10**30;\n        uint256 _loanStatus = _pool.getLoanStatus();\n        require(_loanStatus == uint(LoanStatus.ACTIVE) , 'Repayments:repayInterest Pool should be active.');\n\n        uint256 _initialAmount = _amount;\n\n        // pay off grace penality\n        uint256 _gracePenaltyDue = _repayGracePenalty(_poolID);\n        _amount = _amount.sub(_gracePenaltyDue, 'doesnt cover grace penality');\n\n        // pay off the overdue\n        uint256 _interestOverdue = _repayExtension(_poolID);\n        _amount = _amount.sub(_interestOverdue, 'doesnt cover overdue interest');\n\n        // pay interest\n        uint256 _interestRepaid = _repayInterest(_poolID, _amount, _isLastRepayment);\n        _amount = _amount.sub(_interestRepaid);\n\n        return _updateRepaidAmount(_poolID, _initialAmount.sub(_amount));\n    }\n\n    /// @notice Used to pay off the principal of the loan, once the overdues and interests are repaid\n    /// @dev (10**30) is included to maintain the accuracy of the arithmetic operations\n    /// @param _poolID address of the pool\n    function repayPrincipal(address payable _poolID) external payable nonReentrant isPoolInitialized(_poolID) {\n        address _asset = repayConstants[_poolID].repayAsset;\n        uint256 _interestToRepay = _repay(_poolID, MAX_INT, true);\n        IPool _pool = IPool(_poolID);\n\n        require(!repayVariables[_poolID].isLoanExtensionActive, 'Repayments:repayPrincipal Repayment overdue unpaid');\n\n        require(\n            repayConstants[_poolID].loanDuration == repayVariables[_poolID].loanDurationCovered,\n            'Repayments:repayPrincipal Unpaid interest'\n        );\n\n        uint256 _amount = _pool.totalSupply();\n        uint256 _amountToPay = _amount.add(_interestToRepay);\n        _transferTokens(msg.sender, _poolID, _asset, _amountToPay);\n        emit PrincipalRepaid(_poolID, _amount);\n\n        IPool(_poolID).closeLoan();\n    }\n\n    /// @notice Returns the total amount that has been repaid by the borrower till now\n    /// @param _poolID address of the pool\n    /// @return total amount repaid\n    function getTotalRepaidAmount(address _poolID) external view override returns (uint256) {\n        return repayVariables[_poolID].repaidAmount;\n    }\n\n    /// @notice This function activates the instalment deadline\n    /// @param _poolID address of the pool for which deadline is extended\n    function instalmentDeadlineExtended(address _poolID) external override {\n        require(msg.sender == poolFactory.extension(), 'Repayments::repaymentExtended - Invalid caller');\n\n        repayVariables[_poolID].isLoanExtensionActive = true;\n        repayVariables[_poolID].loanExtensionPeriod = getCurrentInstalmentInterval(_poolID);\n    }\n\n    /// @notice Returns the loanDurationCovered till now and the interest per second which will help in interest calculation\n    /// @param _poolID address of the pool for which we want to calculate interest\n    /// @return Loan Duration Covered and the interest per second\n    function getInterestCalculationVars(address _poolID) external view override returns (uint256, uint256) {\n        uint256 _interestPerSecond = getInterestPerSecond(_poolID);\n        return (repayVariables[_poolID].loanDurationCovered, _interestPerSecond);\n    }\n\n    /// @notice Returns the fraction of repayment interval decided as the grace period fraction\n    /// @return grace period fraction\n    function getGracePeriodFraction() external view override returns (uint256) {\n        return gracePeriodFraction;\n    }\n\n    function _transferTokens(\n        address _from,\n        address _to,\n        address _asset,\n        uint256 _amount\n    ) internal {\n        if (_asset == address(0)) {\n            (bool transferSuccess, ) = _to.call{value: _amount}('');\n            require(transferSuccess, '_transferTokens: Transfer failed');\n            if (msg.value != _amount) {\n                (bool refundSuccess, ) = payable(_from).call{value: msg.value.sub(_amount)}('');\n                require(refundSuccess, '_transferTokens: Refund failed');\n            }\n        } else {\n            IERC20(_asset).safeTransferFrom(_from, _to, _amount);\n        }\n    }\n}"
}