{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/PoolTemplate.sol",
    "Parent Contracts": [
        "contracts/interfaces/IUniversalMarket.sol",
        "contracts/interfaces/IPoolTemplate.sol",
        "contracts/InsureDAOERC20.sol",
        "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol",
        "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol",
        "node_modules/@openzeppelin/contracts/utils/Context.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract PoolTemplate is InsureDAOERC20, IPoolTemplate, IUniversalMarket {\n    /**\n     * EVENTS\n     */\n    event Deposit(address indexed depositor, uint256 amount, uint256 mint);\n    event WithdrawRequested(\n        address indexed withdrawer,\n        uint256 amount,\n        uint256 time\n    );\n    event Withdraw(address indexed withdrawer, uint256 amount, uint256 retVal);\n    event Unlocked(uint256 indexed id, uint256 amount);\n    event Insured(\n        uint256 indexed id,\n        uint256 amount,\n        bytes32 target,\n        uint256 startTime,\n        uint256 endTime,\n        address insured,\n        uint256 premium\n    );\n    event Redeemed(\n        uint256 indexed id,\n        address insured,\n        bytes32 target,\n        uint256 amount,\n        uint256 payout\n    );\n    event CoverApplied(\n        uint256 pending,\n        uint256 payoutNumerator,\n        uint256 payoutDenominator,\n        uint256 incidentTimestamp,\n        bytes32 merkleRoot,\n        string rawdata,\n        string memo\n    );\n    event TransferInsurance(uint256 indexed id, address from, address to);\n    event CreditIncrease(address indexed depositor, uint256 credit);\n    event CreditDecrease(address indexed withdrawer, uint256 credit);\n    event MarketStatusChanged(MarketStatus statusValue);\n    event Paused(bool paused);\n    event MetadataChanged(string metadata);\n\n    /**\n     * Storage\n     */\n    /// @notice Market setting\n    bool public initialized;\n    bool public override paused;\n    string public metadata;\n\n    /// @notice External contract call addresses\n    IParameters public parameters;\n    IRegistry public registry;\n    IVault public vault;\n\n    /// @notice Market variables\n    uint256 public attributionDebt; //pool's attribution for indices\n    uint256 public override lockedAmount; //Liquidity locked when utilized\n    uint256 public override totalCredit; //Liquidity from index\n    uint256 public rewardPerCredit; //Times MAGIC_SCALE_1E6. To avoid reward decimal truncation *See explanation below.\n    uint256 public pendingEnd; //pending time when paying out\n\n    /// @notice Market variables for margin account\n    struct IndexInfo {\n        uint256 credit; //How many credit (equal to liquidity) the index has allocated\n        uint256 rewardDebt; // Reward debt. *See explanation below.\n        bool exist; //true if the index has allocated credit\n    }\n\n    mapping(address => IndexInfo) public indicies;\n    address[] public indexList;\n\n    //\n    // * We do some fancy math for premium calculation of indicies.\n    // Basically, any point in time, the amount of premium entitled to an index but is pending to be distributed is:\n    //\n    //   pending reward = (index.credit * rewardPerCredit) - index.rewardDebt\n    //\n    // When the pool receives premium, it updates rewardPerCredit\n    //\n    // Whenever an index deposits, withdraws credit to a pool, Here's what happens:\n    //   1. The index receives the pending reward sent to the index vault.\n    //   2. The index's rewardDebt get updated.\n    //\n    // This mechanism is widely used (e.g. SushiSwap: MasterChef.sol)\n    //\n\n    ///@notice Market status transition management\n    enum MarketStatus {\n        Trading,\n        Payingout\n    }\n    MarketStatus public marketStatus;\n\n    ///@notice user's withdrawal status management\n    struct Withdrawal {\n        uint256 timestamp;\n        uint256 amount;\n    }\n    mapping(address => Withdrawal) public withdrawalReq;\n\n    ///@notice insurance status management\n    struct Insurance {\n        uint256 id; //each insuance has their own id\n        uint256 startTime; //timestamp of starttime\n        uint256 endTime; //timestamp of endtime\n        uint256 amount; //insured amount\n        bytes32 target; //target id in bytes32\n        address insured; //the address holds the right to get insured\n        bool status; //true if insurance is not expired or redeemed\n    }\n    mapping(uint256 => Insurance) public insurances;\n    uint256 public allInsuranceCount;\n\n    ///@notice incident status management\n    struct Incident {\n        uint256 payoutNumerator;\n        uint256 payoutDenominator;\n        uint256 incidentTimestamp;\n        bytes32 merkleRoot;\n    }\n    Incident public incident;\n\n    uint256 public constant MAGIC_SCALE_1E6 = 1e6; //internal multiplication scale 1e6 to reduce decimal truncation\n\n    modifier onlyOwner() {\n        require(\n            msg.sender == parameters.getOwner(),\n            \"Restricted: caller is not allowed to operate\"\n        );\n        _;\n    }\n\n    constructor() {\n        initialized = true;\n    }\n\n    /**\n     * Initialize interaction\n     */\n\n    /**\n     * @notice Initialize market\n     * This function registers market conditions.\n     * references[0] = target governance token address\n     * references[1] = underlying token address\n     * references[2] = registry\n     * references[3] = parameter\n     * references[4] = initialDepositor\n     * conditions[0] = minimim deposit amount defined by the factory\n     * conditions[1] = initial deposit amount defined by the creator\n     * @param _metaData arbitrary string to store market information\n     * @param _conditions array of conditions\n     * @param _references array of references\n     */\n    function initialize(\n        string calldata _metaData,\n        uint256[] calldata _conditions,\n        address[] calldata _references\n    ) external override {\n        require(\n            initialized == false &&\n                bytes(_metaData).length > 0 &&\n                _references[0] != address(0) &&\n                _references[1] != address(0) &&\n                _references[2] != address(0) &&\n                _references[3] != address(0) &&\n                _references[4] != address(0) &&\n                _conditions[0] <= _conditions[1],\n            \"ERROR: INITIALIZATION_BAD_CONDITIONS\"\n        );\n        initialized = true;\n\n        string memory _name = string(\n            abi.encodePacked(\n                \"InsureDAO-\",\n                IERC20Metadata(_references[1]).name(),\n                \"-PoolInsurance\"\n            )\n        );\n        string memory _symbol = string(\n            abi.encodePacked(\"i-\", IERC20Metadata(_references[1]).symbol())\n        );\n        uint8 _decimals = IERC20Metadata(_references[0]).decimals();\n\n        initializeToken(_name, _symbol, _decimals);\n\n        registry = IRegistry(_references[2]);\n        parameters = IParameters(_references[3]);\n        vault = IVault(parameters.getVault(_references[1]));\n\n        metadata = _metaData;\n\n        marketStatus = MarketStatus.Trading;\n\n        if (_conditions[1] > 0) {\n            _depositFrom(_conditions[1], _references[4]);\n        }\n    }\n\n    /**\n     * Pool interactions\n     */\n\n    /**\n     * @notice A liquidity provider supplies tokens to the pool and receives iTokens\n     * @param _amount amount of tokens to deposit\n     * @return _mintAmount the amount of iTokens minted from the transaction\n     */\n    function deposit(uint256 _amount) public returns (uint256 _mintAmount) {\n        require(\n            marketStatus == MarketStatus.Trading && paused == false,\n            \"ERROR: DEPOSIT_DISABLED\"\n        );\n        require(_amount > 0, \"ERROR: DEPOSIT_ZERO\");\n\n        _mintAmount = worth(_amount);\n\n        vault.addValue(_amount, msg.sender, address(this));\n\n        emit Deposit(msg.sender, _amount, _mintAmount);\n\n        //mint iToken\n        _mint(msg.sender, _mintAmount);\n    }\n\n    /**\n     * @notice Internal deposit function that allows third party to deposit\n     * @param _amount amount of tokens to deposit\n     * @param _from deposit beneficiary's address\n     * @return _mintAmount the amount of iTokens minted from the transaction\n     */\n    function _depositFrom(uint256 _amount, address _from)\n        internal\n        returns (uint256 _mintAmount)\n    {\n        require(\n            marketStatus == MarketStatus.Trading && paused == false,\n            \"ERROR: DEPOSIT_DISABLED\"\n        );\n        require(_amount > 0, \"ERROR: DEPOSIT_ZERO\");\n\n        _mintAmount = worth(_amount);\n\n        vault.addValue(_amount, _from, address(this));\n\n        emit Deposit(_from, _amount, _mintAmount);\n\n        //mint iToken\n        _mint(_from, _mintAmount);\n    }\n\n    /**\n     * @notice A liquidity provider request withdrawal of collateral\n     * @param _amount amount of iTokens to burn\n     */\n    function requestWithdraw(uint256 _amount) external {\n        uint256 _balance = balanceOf(msg.sender);\n        require(_balance >= _amount, \"ERROR: REQUEST_EXCEED_BALANCE\");\n        require(_amount > 0, \"ERROR: REQUEST_ZERO\");\n        withdrawalReq[msg.sender].timestamp = block.timestamp;\n        withdrawalReq[msg.sender].amount = _amount;\n        emit WithdrawRequested(msg.sender, _amount, block.timestamp);\n    }\n\n    /**\n     * @notice A liquidity provider burns iTokens and receives collateral from the pool\n     * @param _amount amount of iTokens to burn\n     * @return _retVal the amount underlying tokens returned\n     */\n    function withdraw(uint256 _amount) external returns (uint256 _retVal) {\n        uint256 _supply = totalSupply();\n        require(_supply != 0, \"ERROR: NO_AVAILABLE_LIQUIDITY\");\n\n        uint256 _liquidity = originalLiquidity();\n        _retVal = (_amount * _liquidity) / _supply;\n\n        require(\n            marketStatus == MarketStatus.Trading,\n            \"ERROR: WITHDRAWAL_PENDING\"\n        );\n        require(\n            withdrawalReq[msg.sender].timestamp +\n                parameters.getLockup(msg.sender) <\n                block.timestamp,\n            \"ERROR: WITHDRAWAL_QUEUE\"\n        );\n        require(\n            withdrawalReq[msg.sender].timestamp +\n                parameters.getLockup(msg.sender) +\n                parameters.getWithdrawable(msg.sender) >\n                block.timestamp,\n            \"ERROR: WITHDRAWAL_NO_ACTIVE_REQUEST\"\n        );\n        require(\n            withdrawalReq[msg.sender].amount >= _amount,\n            \"ERROR: WITHDRAWAL_EXCEEDED_REQUEST\"\n        );\n        require(_amount > 0, \"ERROR: WITHDRAWAL_ZERO\");\n        require(\n            _retVal <= availableBalance(),\n            \"ERROR: WITHDRAW_INSUFFICIENT_LIQUIDITY\"\n        );\n        //reduce requested amount\n        withdrawalReq[msg.sender].amount -= _amount;\n\n        //Burn iToken\n        _burn(msg.sender, _amount);\n\n        //Withdraw liquidity\n        vault.withdrawValue(_retVal, msg.sender);\n\n        emit Withdraw(msg.sender, _amount, _retVal);\n    }\n\n    /**\n     * @notice Unlocks an array of insurances\n     * @param _ids array of ids to unlock\n     */\n    function unlockBatch(uint256[] calldata _ids) external {\n        for (uint256 i = 0; i < _ids.length; i++) {\n            unlock(_ids[i]);\n        }\n    }\n\n    /**\n     * @notice Unlock funds locked in the expired insurance\n     * @param _id id of the insurance policy to unlock liquidity\n     */\n    function unlock(uint256 _id) public {\n        require(\n            insurances[_id].status == true &&\n                marketStatus == MarketStatus.Trading &&\n                insurances[_id].endTime + parameters.getGrace(msg.sender) <\n                block.timestamp,\n            \"ERROR: UNLOCK_BAD_COINDITIONS\"\n        );\n        insurances[_id].status == false;\n\n        lockedAmount = lockedAmount - insurances[_id].amount;\n\n        emit Unlocked(_id, insurances[_id].amount);\n    }\n\n    /**\n     * Index interactions\n     */\n\n    /**\n     * @notice Allocate credit from an index. Allocated credits are deemed as equivalent liquidity as real token deposits.\n     * @param _credit credit (liquidity amount) to be added to this pool\n     * @return _pending pending preium for the caller index\n     */\n\n    function allocateCredit(uint256 _credit)\n        external\n        override\n        returns (uint256 _pending)\n    {\n        require(\n            IRegistry(registry).isListed(msg.sender),\n            \"ERROR: ALLOCATE_CREDIT_BAD_CONDITIONS\"\n        );\n        IndexInfo storage _index = indicies[msg.sender];\n        uint256 _rewardPerCredit = rewardPerCredit;\n        if (_index.exist == false) {\n            _index.exist = true;\n            indexList.push(msg.sender);\n        } else if (_index.credit > 0) {\n            _pending = _sub(\n                (_index.credit * _rewardPerCredit) / MAGIC_SCALE_1E6,\n                _index.rewardDebt\n            );\n            if (_pending > 0) {\n                vault.transferAttribution(_pending, msg.sender);\n                attributionDebt -= _pending;\n            }\n        }\n        if (_credit > 0) {\n            totalCredit += _credit;\n            _index.credit += _credit;\n            emit CreditIncrease(msg.sender, _credit);\n        }\n        _index.rewardDebt =\n            (_index.credit * _rewardPerCredit) /\n            MAGIC_SCALE_1E6;\n    }\n\n    /**\n     * @notice An index withdraw credit and earn accrued premium\n     * @param _credit credit (liquidity amount) to be withdrawn from this pool\n     * @return _pending pending preium for the caller index\n     */\n    function withdrawCredit(uint256 _credit)\n        external\n        override\n        returns (uint256 _pending)\n    {\n        IndexInfo storage _index = indicies[msg.sender];\n        uint256 _rewardPerCredit = rewardPerCredit;\n        require(\n            IRegistry(registry).isListed(msg.sender) &&\n                _index.credit >= _credit &&\n                _credit <= availableBalance(),\n            \"ERROR: WITHDRAW_CREDIT_BAD_CONDITIONS\"\n        );\n\n        //calculate acrrued premium\n        _pending = _sub(\n            (_index.credit * _rewardPerCredit) / MAGIC_SCALE_1E6,\n            _index.rewardDebt\n        );\n\n        //Withdraw liquidity\n        if (_credit > 0) {\n            totalCredit -= _credit;\n            _index.credit -= _credit;\n            emit CreditDecrease(msg.sender, _credit);\n        }\n\n        //withdraw acrrued premium\n        if (_pending > 0) {\n            vault.transferAttribution(_pending, msg.sender);\n            attributionDebt -= _pending;\n            _index.rewardDebt =\n                (_index.credit * _rewardPerCredit) /\n                MAGIC_SCALE_1E6;\n        }\n    }\n\n    /**\n     * Insurance interactions\n     */\n\n    /**\n     * @notice Get insured for the specified amount for specified span\n     * @param _amount target amount to get covered\n     * @param _maxCost maximum cost to pay for the premium. revert if the premium is higher\n     * @param _span length to get covered(e.g. 7 days)\n     * @param _target target id\n     * @return id of the insurance policy\n     */\n    function insure(\n        uint256 _amount,\n        uint256 _maxCost,\n        uint256 _span,\n        bytes32 _target\n    ) external returns (uint256) {\n        //Distribute premium and fee\n        uint256 _endTime = _span + block.timestamp;\n        uint256 _premium = getPremium(_amount, _span);\n        uint256 _fee = parameters.getFeeRate(msg.sender);\n\n        require(\n            _amount <= availableBalance(),\n            \"ERROR: INSURE_EXCEEDED_AVAILABLE_BALANCE\"\n        );\n        require(_premium <= _maxCost, \"ERROR: INSURE_EXCEEDED_MAX_COST\");\n        require(_span <= 365 days, \"ERROR: INSURE_EXCEEDED_MAX_SPAN\");\n        require(\n            parameters.getMinDate(msg.sender) <= _span,\n            \"ERROR: INSURE_SPAN_BELOW_MIN\"\n        );\n\n        require(\n            marketStatus == MarketStatus.Trading,\n            \"ERROR: INSURE_MARKET_PENDING\"\n        );\n        require(paused == false, \"ERROR: INSURE_MARKET_PAUSED\");\n\n        //current liquidity\n        uint256 _liquidity = totalLiquidity();\n        uint256 _totalCredit = totalCredit;\n\n        //accrue premium/fee\n        uint256[2] memory _newAttribution = vault.addValueBatch(\n            _premium,\n            msg.sender,\n            [address(this), parameters.getOwner()],\n            [MAGIC_SCALE_1E6 - _fee, _fee]\n        );\n\n        //Lock covered amount\n        uint256 _id = allInsuranceCount;\n        lockedAmount += _amount;\n        Insurance memory _insurance = Insurance(\n            _id,\n            block.timestamp,\n            _endTime,\n            _amount,\n            _target,\n            msg.sender,\n            true\n        );\n        insurances[_id] = _insurance;\n        allInsuranceCount += 1;\n\n        //Calculate liquidity for index\n        if (_totalCredit > 0) {\n            uint256 _attributionForIndex = (_newAttribution[0] * _totalCredit) /\n                _liquidity;\n            attributionDebt += _attributionForIndex;\n            rewardPerCredit += ((_attributionForIndex * MAGIC_SCALE_1E6) /\n                _totalCredit);\n        }\n\n        emit Insured(\n            _id,\n            _amount,\n            _target,\n            block.timestamp,\n            _endTime,\n            msg.sender,\n            _premium\n        );\n\n        return _id;\n    }\n\n    /**\n     * @notice Redeem an insurance policy\n     * @param _id the id of the insurance policy\n     * @param _merkleProof merkle proof (similar to \"verify\" function of MerkleProof.sol of OpenZeppelin\n     * Ref: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol\n     */\n    function redeem(uint256 _id, bytes32[] calldata _merkleProof) external {\n        Insurance storage _insurance = insurances[_id];\n        require(_insurance.status == true, \"ERROR: INSURANCE_NOT_ACTIVE\");\n\n        uint256 _payoutNumerator = incident.payoutNumerator;\n        uint256 _payoutDenominator = incident.payoutDenominator;\n        uint256 _incidentTimestamp = incident.incidentTimestamp;\n        bytes32 _targets = incident.merkleRoot;\n\n        require(\n            marketStatus == MarketStatus.Payingout,\n            \"ERROR: NO_APPLICABLE_INCIDENT\"\n        );\n        require(_insurance.insured == msg.sender, \"ERROR: NOT_YOUR_INSURANCE\");\n        require(\n            marketStatus == MarketStatus.Payingout &&\n                _insurance.startTime <= _incidentTimestamp &&\n                _insurance.endTime >= _incidentTimestamp,\n            \"ERROR: INSURANCE_NOT_APPLICABLE\"\n        );\n        require(\n            MerkleProof.verify(\n                _merkleProof,\n                _targets,\n                keccak256(\n                    abi.encodePacked(_insurance.target, _insurance.insured)\n                )\n            ) ||\n                MerkleProof.verify(\n                    _merkleProof,\n                    _targets,\n                    keccak256(abi.encodePacked(_insurance.target, address(0)))\n                ),\n            \"ERROR: INSURANCE_EXEMPTED\"\n        );\n        _insurance.status = false;\n        lockedAmount -= _insurance.amount;\n\n        uint256 _payoutAmount = (_insurance.amount * _payoutNumerator) /\n            _payoutDenominator;\n\n        vault.borrowValue(_payoutAmount, msg.sender);\n\n        emit Redeemed(\n            _id,\n            msg.sender,\n            _insurance.target,\n            _insurance.amount,\n            _payoutAmount\n        );\n    }\n\n    /**\n     * @notice Transfers an active insurance\n     * @param _id id of the insurance policy\n     * @param _to receipient of of the policy\n     */\n    function transferInsurance(uint256 _id, address _to) external {\n        Insurance storage insurance = insurances[_id];\n\n        require(\n            _to != address(0) &&\n                insurance.insured == msg.sender &&\n                insurance.endTime >= block.timestamp &&\n                insurance.status == true,\n            \"ERROR: INSURANCE_TRANSFER_BAD_CONDITIONS\"\n        );\n\n        insurance.insured = _to;\n        emit TransferInsurance(_id, msg.sender, _to);\n    }\n\n    /**\n     * @notice Get how much premium for the specified amount and span\n     * @param _amount amount to get insured\n     * @param _span span to get covered\n     */\n    function getPremium(uint256 _amount, uint256 _span)\n        public\n        view\n        returns (uint256 premium)\n    {\n        return\n            parameters.getPremium(\n                _amount,\n                _span,\n                totalLiquidity(),\n                lockedAmount,\n                address(this)\n            );\n    }\n\n    /**\n     * Reporting interactions\n     */\n\n    /**\n     * @notice Decision to make a payout\n     * @param _pending length of time to allow policyholders to redeem their policy\n     * @param _payoutNumerator Numerator of the payout *See below\n     * @param _payoutDenominator Denominator of the payout *See below\n     * @param _incidentTimestamp Unixtimestamp of the incident\n     * @param _merkleRoot Merkle root of the payout id list\n     * @param _rawdata raw data before the data set is coverted to merkle tree (to be emi\uff54ted within event)\n     * @param _memo additional memo for the payout report (to be emmited within event)\n     * payout ratio is determined by numerator/denominator (e.g. 50/100 = 50% payout\n     */\n    function applyCover(\n        uint256 _pending,\n        uint256 _payoutNumerator,\n        uint256 _payoutDenominator,\n        uint256 _incidentTimestamp,\n        bytes32 _merkleRoot,\n        string calldata _rawdata,\n        string calldata _memo\n    ) external override onlyOwner {\n        require(paused == false, \"ERROR: UNABLE_TO_APPLY\");\n        incident.payoutNumerator = _payoutNumerator;\n        incident.payoutDenominator = _payoutDenominator;\n        incident.incidentTimestamp = _incidentTimestamp;\n        incident.merkleRoot = _merkleRoot;\n        marketStatus = MarketStatus.Payingout;\n        pendingEnd = block.timestamp + _pending;\n        for (uint256 i = 0; i < indexList.length; i++) {\n            if (indicies[indexList[i]].credit > 0) {\n                IIndexTemplate(indexList[i]).lock();\n            }\n        }\n        emit CoverApplied(\n            _pending,\n            _payoutNumerator,\n            _payoutDenominator,\n            _incidentTimestamp,\n            _merkleRoot,\n            _rawdata,\n            _memo\n        );\n        emit MarketStatusChanged(marketStatus);\n    }\n\n    /**\n     * @notice Anyone can resume the market after a pending period ends\n     */\n    function resume() external {\n        require(\n            marketStatus == MarketStatus.Payingout &&\n                pendingEnd < block.timestamp,\n            \"ERROR: UNABLE_TO_RESUME\"\n        );\n\n        uint256 _debt = vault.debts(address(this));\n        uint256 _totalCredit = totalCredit;\n        uint256 _deductionFromIndex = (_debt * _totalCredit * MAGIC_SCALE_1E6) /\n            totalLiquidity();\n        uint256 _actualDeduction;\n        for (uint256 i = 0; i < indexList.length; i++) {\n            address _index = indexList[i];\n            uint256 _credit = indicies[_index].credit;\n            if (_credit > 0) {\n                uint256 _shareOfIndex = (_credit * MAGIC_SCALE_1E6) /\n                    _totalCredit;\n                uint256 _redeemAmount = _divCeil(\n                    _deductionFromIndex,\n                    _shareOfIndex\n                );\n                _actualDeduction += IIndexTemplate(_index).compensate(\n                    _redeemAmount\n                );\n            }\n        }\n\n        uint256 _deductionFromPool = _debt -\n            _deductionFromIndex /\n            MAGIC_SCALE_1E6;\n        uint256 _shortage = _deductionFromIndex /\n            MAGIC_SCALE_1E6 -\n            _actualDeduction;\n\n        if (_deductionFromPool > 0) {\n            vault.offsetDebt(_deductionFromPool, address(this));\n        }\n\n        vault.transferDebt(_shortage);\n\n        marketStatus = MarketStatus.Trading;\n        emit MarketStatusChanged(MarketStatus.Trading);\n    }\n\n    /**\n     * Utilities\n     */\n\n    /**\n     * @notice Get the exchange rate of LP tokens against underlying asset(scaled by MAGIC_SCALE_1E6)\n     * @return The value against the underlying tokens balance.\n     */\n    function rate() external view returns (uint256) {\n        if (totalSupply() > 0) {\n            return (originalLiquidity() * MAGIC_SCALE_1E6) / totalSupply();\n        } else {\n            return 0;\n        }\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @param _owner the target address to look up value\n     * @return The balance of underlying tokens for the specified address\n     */\n    function valueOfUnderlying(address _owner)\n        public\n        view\n        override\n        returns (uint256)\n    {\n        uint256 _balance = balanceOf(_owner);\n        if (_balance == 0) {\n            return 0;\n        } else {\n            return (_balance * originalLiquidity()) / totalSupply();\n        }\n    }\n\n    /**\n     * @notice Get the accrued value for an index\n     * @param _index the address of index\n     * @return The pending premium for the specified index\n     */\n    function pendingPremium(address _index)\n        external\n        view\n        override\n        returns (uint256)\n    {\n        uint256 _credit = indicies[_index].credit;\n        if (_credit == 0) {\n            return 0;\n        } else {\n            return\n                _sub(\n                    (_credit * rewardPerCredit) / MAGIC_SCALE_1E6,\n                    indicies[_index].rewardDebt\n                );\n        }\n    }\n\n    /**\n     * @notice Get token number for the specified underlying value\n     * @param _value amount of iToken\n     * @return _amount The balance of underlying tokens for the specified amount\n     */\n    function worth(uint256 _value) public view returns (uint256 _amount) {\n        uint256 _supply = totalSupply();\n        uint256 _originalLiquidity = originalLiquidity();\n        if (_supply > 0 && _originalLiquidity > 0) {\n            _amount = (_value * _supply) / _originalLiquidity;\n        } else if (_supply > 0 && _originalLiquidity == 0) {\n            _amount = _value * _supply;\n        } else {\n            _amount = _value;\n        }\n    }\n\n    /**\n     * @notice Get allocated credit\n     * @param _index address of an index\n     * @return The balance of credit allocated by the specified index\n     */\n    function allocatedCredit(address _index)\n        public\n        view\n        override\n        returns (uint256)\n    {\n        return indicies[_index].credit;\n    }\n\n    /**\n     * @notice Returns the amount of underlying tokens available for withdrawals\n     * @return _balance available liquidity of this pool\n     */\n    function availableBalance()\n        public\n        view\n        override\n        returns (uint256 _balance)\n    {\n        if (totalLiquidity() > 0) {\n            return totalLiquidity() - lockedAmount;\n        } else {\n            return 0;\n        }\n    }\n\n    /**\n     * @notice Returns the utilization rate for this pool. Scaled by 1e6 (100% = 1e6)\n     * @return _rate utilization rate\n     */\n    function utilizationRate() public view override returns (uint256 _rate) {\n        if (lockedAmount > 0) {\n            return (lockedAmount * MAGIC_SCALE_1E6) / totalLiquidity();\n        } else {\n            return 0;\n        }\n    }\n\n    /**\n     * @notice Pool's Liquidity + Liquidity from Index (how much can the pool sell cover)\n     * @return _balance total liquidity of this pool\n     */\n    function totalLiquidity() public view override returns (uint256 _balance) {\n        return originalLiquidity() + totalCredit;\n    }\n\n    /**\n     * @notice Pool's Liquidity\n     * @return _balance total liquidity of this pool\n     */\n    function originalLiquidity() public view returns (uint256 _balance) {\n        return\n            vault.underlyingValue(address(this)) -\n            vault.attributionValue(attributionDebt);\n    }\n\n    /**\n     * Admin functions\n     */\n\n    /**\n     * @notice Used for changing settlementFeeRecipient\n     * @param _state true to set paused and vice versa\n     */\n    function setPaused(bool _state) external override onlyOwner {\n        if (paused != _state) {\n            paused = _state;\n            emit Paused(_state);\n        }\n    }\n\n    /**\n     * @notice Change metadata string\n     * @param _metadata new metadata string\n     */\n    function changeMetadata(string calldata _metadata)\n        external\n        override\n        onlyOwner\n    {\n        metadata = _metadata;\n        emit MetadataChanged(_metadata);\n    }\n\n    /**\n     * Internal functions\n     */\n\n    /**\n     * @notice Internal function to offset withdraw request and latest balance\n     * @param from the account who send\n     * @param to a\n     * @param amount the amount of tokens to offset\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual override {\n        super._beforeTokenTransfer(from, to, amount);\n\n        if (from != address(0)) {\n            uint256 _after = balanceOf(from) - amount;\n            if (_after < withdrawalReq[from].amount) {\n                withdrawalReq[from].amount = _after;\n            }\n        }\n    }\n\n    /**\n     * @notice Internal function for safe division\n     */\n    function _divCeil(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b > 0);\n        uint256 c = a / b;\n        if (a % b != 0) c = c + 1;\n        return c;\n    }\n\n    /**\n     * @notice Internal function for overflow free subtraction\n     */\n    function _sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (a < b) {\n            return 0;\n        } else {\n            return a - b;\n        }\n    }\n}"
}