{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/vaults/NFTVault.sol",
    "Parent Contracts": [
        "node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol",
        "node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [
        "keccak256(bytes)",
        "keccak256(bytes)",
        "keccak256(bytes)"
    ],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract NFTVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable {\n    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;\n\n    event PositionOpened(address indexed owner, uint256 indexed index);\n    event Borrowed(\n        address indexed owner,\n        uint256 indexed index,\n        uint256 amount\n    );\n    event Repaid(address indexed owner, uint256 indexed index, uint256 amount);\n    event PositionClosed(address indexed owner, uint256 indexed index);\n    event Liquidated(\n        address indexed liquidator,\n        address indexed owner,\n        uint256 indexed index,\n        bool insured\n    );\n    event Repurchased(address indexed owner, uint256 indexed index);\n    event InsuranceExpired(address indexed owner, uint256 indexed index);\n\n    enum BorrowType {\n        NOT_CONFIRMED,\n        NON_INSURANCE,\n        USE_INSURANCE\n    }\n\n    struct Position {\n        BorrowType borrowType;\n        uint256 debtPrincipal;\n        uint256 debtPortion;\n        uint256 debtAmountForRepurchase;\n        uint256 liquidatedAt;\n        address liquidator;\n    }\n\n    struct Rate {\n        uint128 numerator;\n        uint128 denominator;\n    }\n\n    struct VaultSettings {\n        Rate debtInterestApr;\n        Rate creditLimitRate;\n        Rate liquidationLimitRate;\n        Rate valueIncreaseLockRate;\n        Rate organizationFeeRate;\n        Rate insurancePurchaseRate;\n        Rate insuranceLiquidationPenaltyRate;\n        uint256 insuraceRepurchaseTimeLimit;\n        uint256 borrowAmountCap;\n    }\n\n    bytes32 public constant DAO_ROLE = keccak256(\"DAO_ROLE\");\n    bytes32 public constant LIQUIDATOR_ROLE = keccak256(\"LIQUIDATOR_ROLE\");\n\n    bytes32 public constant CUSTOM_NFT_HASH = keccak256(\"CUSTOM\");\n\n    IStableCoin public stablecoin;\n    /// @notice Chainlink ETH/USD price feed\n    IAggregatorV3Interface public ethAggregator;\n    /// @notice Chainlink JPEG/USD price feed\n    IAggregatorV3Interface public jpegAggregator;\n    /// @notice Chainlink NFT floor oracle\n    IAggregatorV3Interface public floorOracle;\n    /// @notice Chainlink NFT fallback floor oracle\n    IAggregatorV3Interface public fallbackOracle;\n    /// @notice JPEGLocker, used by this contract to lock JPEG and increase the value of an NFT\n    IJPEGLock public jpegLocker;\n    IERC721Upgradeable public nftContract;\n\n    /// @notice If true, the floor price won't be fetched using the Chainlink oracle but\n    /// a value set by the DAO will be used instead\n    bool public daoFloorOverride;\n    // @notice If true, the floor price will be fetched using the fallback oracle\n    bool public useFallbackOracle;\n    /// @notice Total outstanding debt\n    uint256 public totalDebtAmount;\n    /// @dev Last time debt was accrued. See {accrue} for more info\n    uint256 public totalDebtAccruedAt;\n    uint256 public totalFeeCollected;\n    uint256 internal totalDebtPortion;\n\n    VaultSettings public settings;\n\n    /// @dev Keeps track of all the NFTs used as collateral for positions\n    EnumerableSetUpgradeable.UintSet private positionIndexes;\n\n    mapping(uint256 => Position) private positions;\n    mapping(uint256 => address) public positionOwner;\n    mapping(bytes32 => uint256) public nftTypeValueETH;\n    mapping(uint256 => uint256) public nftValueETH;\n    //bytes32(0) is floor\n    mapping(uint256 => bytes32) public nftTypes;\n    mapping(uint256 => uint256) public pendingNFTValueETH;\n\n    /// @dev Checks if the provided NFT index is valid\n    /// @param nftIndex The index to check\n    modifier validNFTIndex(uint256 nftIndex) {\n        //The standard OZ ERC721 implementation of ownerOf reverts on a non existing nft isntead of returning address(0)\n        require(nftContract.ownerOf(nftIndex) != address(0), \"invalid_nft\");\n        _;\n    }\n\n    struct NFTCategoryInitializer {\n        bytes32 hash;\n        uint256 valueETH;\n        uint256[] nfts;\n    }\n\n    /// @param _stablecoin PUSD address\n    /// @param _nftContract The NFT contrat address. It could also be the address of an helper contract\n    /// if the target NFT isn't an ERC721 (CryptoPunks as an example)\n    /// @param _ethAggregator Chainlink ETH/USD price feed address\n    /// @param _jpegAggregator Chainlink JPEG/USD price feed address\n    /// @param _floorOracle Chainlink floor oracle address\n    /// @param _fallbackOracle Chainlink fallback floor oracle address\n    /// @param _typeInitializers Used to initialize NFT categories with their value and NFT indexes.\n    /// Floor NFT shouldn't be initialized this way\n    /// @param _jpegLocker JPEGLock address\n    /// @param _settings Initial settings used by the contract\n    function initialize(\n        IStableCoin _stablecoin,\n        IERC721Upgradeable _nftContract,\n        IAggregatorV3Interface _ethAggregator,\n        IAggregatorV3Interface _jpegAggregator,\n        IAggregatorV3Interface _floorOracle,\n        IAggregatorV3Interface _fallbackOracle,\n        NFTCategoryInitializer[] memory _typeInitializers,\n        IJPEGLock _jpegLocker,\n        VaultSettings memory _settings\n    ) external initializer {\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        _setupRole(DAO_ROLE, msg.sender);\n        _setRoleAdmin(LIQUIDATOR_ROLE, DAO_ROLE);\n        _setRoleAdmin(DAO_ROLE, DAO_ROLE);\n\n        _validateRate(_settings.debtInterestApr);\n        _validateRate(_settings.creditLimitRate);\n        _validateRate(_settings.liquidationLimitRate);\n        _validateRate(_settings.valueIncreaseLockRate);\n        _validateRate(_settings.organizationFeeRate);\n        _validateRate(_settings.insurancePurchaseRate);\n        _validateRate(_settings.insuranceLiquidationPenaltyRate);\n\n        _validateCreditLimitAndLiquidationRate(\n            _settings.creditLimitRate,\n            _settings.liquidationLimitRate\n        );\n\n        stablecoin = _stablecoin;\n        jpegLocker = _jpegLocker;\n        ethAggregator = _ethAggregator;\n        jpegAggregator = _jpegAggregator;\n        floorOracle = _floorOracle;\n        fallbackOracle = _fallbackOracle;\n        nftContract = _nftContract;\n\n        settings = _settings;\n\n        //initializing the categories\n        for (uint256 i = 0; i < _typeInitializers.length; i++) {\n            NFTCategoryInitializer memory initializer = _typeInitializers[i];\n            nftTypeValueETH[initializer.hash] = initializer.valueETH;\n            for (uint256 j = 0; j < initializer.nfts.length; j++) {\n                nftTypes[initializer.nfts[j]] = initializer.hash;\n            }\n        }\n    }\n\n    /// @dev The {accrue} function updates the contract's state by calculating\n    /// the additional interest accrued since the last state update\n    function accrue() public {\n        uint256 additionalInterest = _calculateAdditionalInterest();\n\n        totalDebtAccruedAt = block.timestamp;\n\n        totalDebtAmount += additionalInterest;\n        totalFeeCollected += additionalInterest;\n    }\n\n    /// @notice Allows the DAO to change the total debt cap\n    /// @param _borrowAmountCap New total debt cap\n    function setBorrowAmountCap(uint256 _borrowAmountCap)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        settings.borrowAmountCap = _borrowAmountCap;\n    }\n\n    /// @notice Allows the DAO to change the interest APR on borrows\n    /// @param _debtInterestApr The new interest rate\n    function setDebtInterestApr(Rate memory _debtInterestApr)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_debtInterestApr);\n        settings.debtInterestApr = _debtInterestApr;\n    }\n\n    /// @notice Allows the DAO to change the amount of JPEG needed to increase the value of an NFT relative to the desired value\n    /// @param _valueIncreaseLockRate The new rate\n    function setValueIncreaseLockRate(Rate memory _valueIncreaseLockRate)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_valueIncreaseLockRate);\n        settings.valueIncreaseLockRate = _valueIncreaseLockRate;\n    }\n\n    /// @notice Allows the DAO to change the max debt to collateral rate for a position\n    /// @param _creditLimitRate The new rate\n    function setCreditLimitRate(Rate memory _creditLimitRate)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_creditLimitRate);\n        _validateCreditLimitAndLiquidationRate(\n            _creditLimitRate,\n            settings.liquidationLimitRate\n        );\n\n        settings.creditLimitRate = _creditLimitRate;\n    }\n\n    /// @notice Allows the DAO to change the minimum debt to collateral rate for a position to be market as liquidatable\n    /// @param _liquidationLimitRate The new rate\n    function setLiquidationLimitRate(Rate memory _liquidationLimitRate)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_liquidationLimitRate);\n        _validateCreditLimitAndLiquidationRate(\n            settings.creditLimitRate,\n            _liquidationLimitRate\n        );\n\n        settings.liquidationLimitRate = _liquidationLimitRate;\n    }\n\n    /// @notice Allows the DAO to toggle the fallback oracle\n    /// @param _useFallback Whether to use the fallback oracle\n    function toggleFallbackOracle(bool _useFallback)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        useFallbackOracle = _useFallback;\n    }\n\n    /// @notice Allows the DAO to change the amount of time JPEG tokens need to be locked to change the value of an NFT\n    /// @param _newLockTime The amount new lock time amount\n    function setJPEGLockTime(uint256 _newLockTime) external onlyRole(DAO_ROLE) {\n        jpegLocker.setLockTime(_newLockTime);\n    }\n\n    /// @notice Allows the DAO to bypass the floor oracle and override the NFT floor value\n    /// @param _newFloor The new floor\n    function overrideFloor(uint256 _newFloor) external onlyRole(DAO_ROLE) {\n        require(_newFloor > 0, \"Invalid floor\");\n        nftTypeValueETH[bytes32(0)] = _newFloor;\n        daoFloorOverride = true;\n    }\n\n    /// @notice Allows the DAO to stop overriding floor\n    function disableFloorOverride() external onlyRole(DAO_ROLE) {\n        daoFloorOverride = false;\n    }\n\n    /// @notice Allows the DAO to change the static borrow fee\n    /// @param _organizationFeeRate The new fee rate\n    function setOrganizationFeeRate(Rate memory _organizationFeeRate)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_organizationFeeRate);\n        settings.organizationFeeRate = _organizationFeeRate;\n    }\n\n    /// @notice Allows the DAO to change the cost of insurance\n    /// @param _insurancePurchaseRate The new insurance fee rate\n    function setInsurancePurchaseRate(Rate memory _insurancePurchaseRate)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        _validateRate(_insurancePurchaseRate);\n        settings.insurancePurchaseRate = _insurancePurchaseRate;\n    }\n\n    /// @notice Allows the DAO to change the repurchase penalty rate in case of liquidation of an insured NFT\n    /// @param _insuranceLiquidationPenaltyRate The new rate\n    function setInsuranceLiquidationPenaltyRate(\n        Rate memory _insuranceLiquidationPenaltyRate\n    ) external onlyRole(DAO_ROLE) {\n        _validateRate(_insuranceLiquidationPenaltyRate);\n        settings\n            .insuranceLiquidationPenaltyRate = _insuranceLiquidationPenaltyRate;\n    }\n\n    /// @notice Allows the DAO to add an NFT to a specific price category\n    /// @param _nftIndex The index to add to the category\n    /// @param _type The category hash\n    function setNFTType(uint256 _nftIndex, bytes32 _type)\n        external\n        validNFTIndex(_nftIndex)\n        onlyRole(DAO_ROLE)\n    {\n        require(\n            _type == bytes32(0) || nftTypeValueETH[_type] > 0,\n            \"invalid_nftType\"\n        );\n        nftTypes[_nftIndex] = _type;\n    }\n\n    /// @notice Allows the DAO to change the value of an NFT category\n    /// @param _type The category hash\n    /// @param _amountETH The new value, in ETH\n    function setNFTTypeValueETH(bytes32 _type, uint256 _amountETH)\n        external\n        onlyRole(DAO_ROLE)\n    {\n        nftTypeValueETH[_type] = _amountETH;\n    }\n\n    /// @notice Allows the DAO to set the value in ETH of the NFT at index `_nftIndex`.\n    /// A JPEG deposit by a user is required afterwards. See {finalizePendingNFTValueETH} for more details\n    /// @param _nftIndex The index of the NFT to change the value of\n    /// @param _amountETH The new desired ETH value\n    function setPendingNFTValueETH(uint256 _nftIndex, uint256 _amountETH)\n        external\n        validNFTIndex(_nftIndex)\n        onlyRole(DAO_ROLE)\n    {\n        pendingNFTValueETH[_nftIndex] = _amountETH;\n    }\n\n    /// @notice Allows a user to lock up JPEG to make the change in value of an NFT effective.\n    /// Can only be called after {setPendingNFTValueETH}, which requires a governance vote.\n    /// @dev The amount of JPEG that needs to be locked is calculated by applying `valueIncreaseLockRate`\n    /// to the new credit limit of the NFT\n    /// @param _nftIndex The index of the NFT\n    function finalizePendingNFTValueETH(uint256 _nftIndex)\n        external\n        validNFTIndex(_nftIndex)\n    {\n        uint256 pendingValue = pendingNFTValueETH[_nftIndex];\n        require(pendingValue > 0, \"no_pending_value\");\n        uint256 toLockJpeg = (((pendingValue *\n            _ethPriceUSD() *\n            settings.creditLimitRate.numerator) /\n            settings.creditLimitRate.denominator) *\n            settings.valueIncreaseLockRate.numerator) /\n            settings.valueIncreaseLockRate.denominator /\n            _jpegPriceUSD();\n\n        //lock JPEG using JPEGLock\n        jpegLocker.lockFor(msg.sender, _nftIndex, toLockJpeg);\n\n        nftTypes[_nftIndex] = CUSTOM_NFT_HASH;\n        nftValueETH[_nftIndex] = pendingValue;\n        //clear pending value\n        pendingNFTValueETH[_nftIndex] = 0;\n    }\n\n    /// @dev Validates the credit limit rate and the liquidation limit rate.\n    /// The credit limit rate must be less than the liquidation rate\n    /// @param _creditLimitRate The credit limit rate to validate\n    /// @param _liquidationLimitRate The liquidation limit rate\n    function _validateCreditLimitAndLiquidationRate(\n        Rate memory _creditLimitRate,\n        Rate memory _liquidationLimitRate\n    ) internal pure {\n        require(\n            _liquidationLimitRate.numerator * _creditLimitRate.denominator >\n                _creditLimitRate.numerator * _liquidationLimitRate.denominator,\n            \"credit_rate_exceeds_or_equals_liquidation_rate\"\n        );\n    }\n\n    /// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator.\n    /// @param rate The rate to validate\n    function _validateRate(Rate memory rate) internal pure {\n        require(\n            rate.denominator > 0 && rate.denominator >= rate.numerator,\n            \"invalid_rate\"\n        );\n    }\n\n    /// @dev Returns the value in ETH of the NFT at index `_nftIndex`\n    /// @param _nftIndex The NFT to return the value of\n    /// @return The value of the NFT, 18 decimals\n    function _getNFTValueETH(uint256 _nftIndex)\n        internal\n        view\n        returns (uint256)\n    {\n        bytes32 nftType = nftTypes[_nftIndex];\n\n        if (nftType == bytes32(0) && !daoFloorOverride) {\n            return\n                _normalizeAggregatorAnswer(\n                    useFallbackOracle ? fallbackOracle : floorOracle\n                );\n        } else if (nftType == CUSTOM_NFT_HASH) return nftValueETH[_nftIndex];\n\n        return nftTypeValueETH[nftType];\n    }\n\n    /// @dev Returns the value in USD of the NFT at index `_nftIndex`\n    /// @param _nftIndex The NFT to return the value of\n    /// @return The value of the NFT in USD, 18 decimals\n    function _getNFTValueUSD(uint256 _nftIndex)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 nft_value = _getNFTValueETH(_nftIndex);\n        return (nft_value * _ethPriceUSD()) / 1 ether;\n    }\n\n    /// @dev Returns the current ETH price in USD\n    /// @return The current ETH price, 18 decimals\n    function _ethPriceUSD() internal view returns (uint256) {\n        return _normalizeAggregatorAnswer(ethAggregator);\n    }\n\n    /// @dev Returns the current JPEG price in USD\n    /// @return The current JPEG price, 18 decimals\n    function _jpegPriceUSD() internal view returns (uint256) {\n        return _normalizeAggregatorAnswer(jpegAggregator);\n    }\n\n    /// @dev Fetches and converts to 18 decimals precision the latest answer of a Chainlink aggregator\n    /// @param aggregator The aggregator to fetch the answer from\n    /// @return The latest aggregator answer, normalized\n    function _normalizeAggregatorAnswer(IAggregatorV3Interface aggregator)\n        internal\n        view\n        returns (uint256)\n    {\n        int256 answer = aggregator.latestAnswer();\n        uint8 decimals = aggregator.decimals();\n\n        require(answer > 0, \"invalid_oracle_answer\");\n        //converts the answer to have 18 decimals\n        return\n            decimals > 18\n                ? uint256(answer) / 10**(decimals - 18)\n                : uint256(answer) * 10**(18 - decimals);\n    }\n\n    struct NFTInfo {\n        uint256 index;\n        bytes32 nftType;\n        address owner;\n        uint256 nftValueETH;\n        uint256 nftValueUSD;\n    }\n\n    /// @notice Returns data relative to the NFT at index `_nftIndex`\n    /// @param _nftIndex The NFT index\n    /// @return nftInfo The data relative to the NFT\n    function getNFTInfo(uint256 _nftIndex)\n        external\n        view\n        returns (NFTInfo memory nftInfo)\n    {\n        nftInfo = NFTInfo(\n            _nftIndex,\n            nftTypes[_nftIndex],\n            nftContract.ownerOf(_nftIndex),\n            _getNFTValueETH(_nftIndex),\n            _getNFTValueUSD(_nftIndex)\n        );\n    }\n\n    /// @dev Returns the credit limit of an NFT\n    /// @param _nftIndex The NFT to return credit limit of\n    /// @return The NFT credit limit\n    function _getCreditLimit(uint256 _nftIndex)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 asset_value = _getNFTValueUSD(_nftIndex);\n        return\n            (asset_value * settings.creditLimitRate.numerator) /\n            settings.creditLimitRate.denominator;\n    }\n\n    /// @dev Returns the minimum amount of debt necessary to liquidate an NFT\n    /// @param _nftIndex The index of the NFT\n    /// @return The minimum amount of debt to liquidate the NFT\n    function _getLiquidationLimit(uint256 _nftIndex)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 asset_value = _getNFTValueUSD(_nftIndex);\n        return\n            (asset_value * settings.liquidationLimitRate.numerator) /\n            settings.liquidationLimitRate.denominator;\n    }\n\n    /// @dev Calculates current outstanding debt of an NFT\n    /// @param _nftIndex The NFT to calculate the outstanding debt of\n    /// @return The outstanding debt value\n    function _getDebtAmount(uint256 _nftIndex) internal view returns (uint256) {\n        uint256 calculatedDebt = _calculateDebt(\n            totalDebtAmount,\n            positions[_nftIndex].debtPortion,\n            totalDebtPortion\n        );\n\n        uint256 principal = positions[_nftIndex].debtPrincipal;\n\n        //_calculateDebt is prone to rounding errors that may cause\n        //the calculated debt amount to be 1 or 2 units less than\n        //the debt principal when the accrue() function isn't called\n        //in between the first borrow and the _calculateDebt call.\n        return principal > calculatedDebt ? principal : calculatedDebt;\n    }\n\n    /// @dev Calculates the total debt of a position given the global debt, the user's portion of the debt and the total user portions\n    /// @param total The global outstanding debt\n    /// @param userPortion The user's portion of debt\n    /// @param totalPortion The total user portions of debt\n    /// @return The outstanding debt of the position\n    function _calculateDebt(\n        uint256 total,\n        uint256 userPortion,\n        uint256 totalPortion\n    ) internal pure returns (uint256) {\n        return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion;\n    }\n\n    /// @dev Opens a position\n    /// Emits a {PositionOpened} event\n    /// @param _owner The owner of the position to open\n    /// @param _nftIndex The NFT used as collateral for the position\n    function _openPosition(address _owner, uint256 _nftIndex) internal {\n        nftContract.transferFrom(_owner, address(this), _nftIndex);\n\n        positions[_nftIndex] = Position({\n            borrowType: BorrowType.NOT_CONFIRMED,\n            debtPrincipal: 0,\n            debtPortion: 0,\n            debtAmountForRepurchase: 0,\n            liquidatedAt: 0,\n            liquidator: address(0)\n        });\n        positionOwner[_nftIndex] = _owner;\n        positionIndexes.add(_nftIndex);\n\n        emit PositionOpened(_owner, _nftIndex);\n    }\n\n    /// @dev Calculates the additional global interest since last time the contract's state was updated by calling {accrue}\n    /// @return The additional interest value\n    function _calculateAdditionalInterest() internal view returns (uint256) {\n        // Number of seconds since {accrue} was called\n        uint256 elapsedTime = block.timestamp - totalDebtAccruedAt;\n        if (elapsedTime == 0) {\n            return 0;\n        }\n\n        if (totalDebtAmount == 0) {\n            return 0;\n        }\n\n        // Accrue interest\n        uint256 interestPerYear = (totalDebtAmount *\n            settings.debtInterestApr.numerator) /\n            settings.debtInterestApr.denominator;\n        uint256 interestPerSec = interestPerYear / 365 days;\n\n        return elapsedTime * interestPerSec;\n    }\n\n    /// @notice Returns the number of open positions\n    /// @return The number of open positions\n    function totalPositions() external view returns (uint256) {\n        return positionIndexes.length();\n    }\n\n    /// @notice Returns all open position NFT indexes\n    /// @return The open position NFT indexes\n    function openPositionsIndexes() external view returns (uint256[] memory) {\n        return positionIndexes.values();\n    }\n\n    struct PositionPreview {\n        address owner;\n        uint256 nftIndex;\n        bytes32 nftType;\n        uint256 nftValueUSD;\n        VaultSettings vaultSettings;\n        uint256 creditLimit;\n        uint256 debtPrincipal;\n        uint256 debtInterest;\n        BorrowType borrowType;\n        bool liquidatable;\n        uint256 liquidatedAt;\n        address liquidator;\n    }\n\n    /// @notice Returns data relative to a postition, existing or not\n    /// @param _nftIndex The index of the NFT used as collateral for the position\n    /// @return preview See assignment below\n    function showPosition(uint256 _nftIndex)\n        external\n        view\n        validNFTIndex(_nftIndex)\n        returns (PositionPreview memory preview)\n    {\n        address posOwner = positionOwner[_nftIndex];\n\n        uint256 debtPrincipal = positions[_nftIndex].debtPrincipal;\n        uint256 debtAmount = positions[_nftIndex].liquidatedAt > 0\n            ? positions[_nftIndex].debtAmountForRepurchase //calculate updated debt\n            : _calculateDebt(\n                totalDebtAmount + _calculateAdditionalInterest(),\n                positions[_nftIndex].debtPortion,\n                totalDebtPortion\n            );\n\n        //_calculateDebt is prone to rounding errors that may cause\n        //the calculated debt amount to be 1 or 2 units less than\n        //the debt principal if no time has elapsed in between the first borrow\n        //and the _calculateDebt call.\n        if (debtPrincipal > debtAmount) debtAmount = debtPrincipal;\n\n        preview = PositionPreview({\n            owner: posOwner, //the owner of the position, `address(0)` if the position doesn't exists\n            nftIndex: _nftIndex, //the NFT used as collateral for the position\n            nftType: nftTypes[_nftIndex], //the type of the NFT\n            nftValueUSD: _getNFTValueUSD(_nftIndex), //the value in USD of the NFT\n            vaultSettings: settings, //the current vault's settings\n            creditLimit: _getCreditLimit(_nftIndex), //the NFT's credit limit\n            debtPrincipal: debtPrincipal, //the debt principal for the position, `0` if the position doesn't exists\n            debtInterest: debtAmount - debtPrincipal, //the interest of the position\n            borrowType: positions[_nftIndex].borrowType, //the insurance type of the position, `NOT_CONFIRMED` if it doesn't exist\n            liquidatable: positions[_nftIndex].liquidatedAt == 0 &&\n                debtAmount >= _getLiquidationLimit(_nftIndex), //if the position can be liquidated\n            liquidatedAt: positions[_nftIndex].liquidatedAt, //if the position has been liquidated and it had insurance, the timestamp at which the liquidation happened\n            liquidator: positions[_nftIndex].liquidator //if the position has been liquidated and it had insurance, the address of the liquidator\n        });\n    }\n\n    /// @notice Allows users to open positions and borrow using an NFT\n    /// @dev emits a {Borrowed} event\n    /// @param _nftIndex The index of the NFT to be used as collateral\n    /// @param _amount The amount of PUSD to be borrowed. Note that the user will receive less than the amount requested,\n    /// the borrow fee and insurance automatically get removed from the amount borrowed\n    /// @param _useInsurance Whereter to open an insured position. In case the position has already been opened previously,\n    /// this parameter needs to match the previous insurance mode. To change insurance mode, a user needs to close and reopen the position\n    function borrow(\n        uint256 _nftIndex,\n        uint256 _amount,\n        bool _useInsurance\n    ) external validNFTIndex(_nftIndex) nonReentrant {\n        accrue();\n\n        require(\n            msg.sender == positionOwner[_nftIndex] ||\n                address(0) == positionOwner[_nftIndex],\n            \"unauthorized\"\n        );\n        require(_amount > 0, \"invalid_amount\");\n        require(\n            totalDebtAmount + _amount <= settings.borrowAmountCap,\n            \"debt_cap\"\n        );\n\n        if (positionOwner[_nftIndex] == address(0)) {\n            _openPosition(msg.sender, _nftIndex);\n        }\n\n        Position storage position = positions[_nftIndex];\n        require(position.liquidatedAt == 0, \"liquidated\");\n        require(\n            position.borrowType == BorrowType.NOT_CONFIRMED ||\n                (position.borrowType == BorrowType.USE_INSURANCE &&\n                    _useInsurance) ||\n                (position.borrowType == BorrowType.NON_INSURANCE &&\n                    !_useInsurance),\n            \"invalid_insurance_mode\"\n        );\n\n        uint256 creditLimit = _getCreditLimit(_nftIndex);\n        uint256 debtAmount = _getDebtAmount(_nftIndex);\n        require(debtAmount + _amount <= creditLimit, \"insufficient_credit\");\n\n        //calculate the borrow fee\n        uint256 organizationFee = (_amount *\n            settings.organizationFeeRate.numerator) /\n            settings.organizationFeeRate.denominator;\n\n        uint256 feeAmount = organizationFee;\n        //if the position is insured, calculate the insurance fee\n        if (position.borrowType == BorrowType.USE_INSURANCE || _useInsurance) {\n            feeAmount +=\n                (_amount * settings.insurancePurchaseRate.numerator) /\n                settings.insurancePurchaseRate.denominator;\n        }\n        totalFeeCollected += feeAmount;\n        //subtract the fee from the amount borrowed\n        stablecoin.mint(msg.sender, _amount - feeAmount);\n\n        if (position.borrowType == BorrowType.NOT_CONFIRMED) {\n            position.borrowType = _useInsurance\n                ? BorrowType.USE_INSURANCE\n                : BorrowType.NON_INSURANCE;\n        }\n\n        // update debt portion\n        if (totalDebtPortion == 0) {\n            totalDebtPortion = _amount;\n            position.debtPortion = _amount;\n        } else {\n            uint256 plusPortion = (totalDebtPortion * _amount) /\n                totalDebtAmount;\n            totalDebtPortion += plusPortion;\n            position.debtPortion += plusPortion;\n        }\n        position.debtPrincipal += _amount;\n        totalDebtAmount += _amount;\n\n        emit Borrowed(msg.sender, _nftIndex, _amount);\n    }\n\n    /// @notice Allows users to repay a portion/all of their debt. Note that since interest increases every second,\n    /// a user wanting to repay all of their debt should repay for an amount greater than their current debt to account for the\n    /// additional interest while the repay transaction is pending, the contract will only take what's necessary to repay all the debt\n    /// @dev Emits a {Repaid} event\n    /// @param _nftIndex The NFT used as collateral for the position\n    /// @param _amount The amount of debt to repay. If greater than the position's outstanding debt, only the amount necessary to repay all the debt will be taken\n    function repay(uint256 _nftIndex, uint256 _amount)\n        external\n        validNFTIndex(_nftIndex)\n        nonReentrant\n    {\n        accrue();\n\n        require(msg.sender == positionOwner[_nftIndex], \"unauthorized\");\n        require(_amount > 0, \"invalid_amount\");\n\n        Position storage position = positions[_nftIndex];\n        require(position.liquidatedAt == 0, \"liquidated\");\n\n        uint256 debtAmount = _getDebtAmount(_nftIndex);\n        require(debtAmount > 0, \"position_not_borrowed\");\n\n        uint256 debtPrincipal = position.debtPrincipal;\n        uint256 debtInterest = debtAmount - debtPrincipal;\n\n        _amount = _amount > debtAmount ? debtAmount : _amount;\n\n        // burn all payment, the interest is sent to the DAO using the {collect} function\n        stablecoin.burnFrom(msg.sender, _amount);\n\n        uint256 paidPrincipal = _amount > debtInterest\n            ? _amount - debtInterest\n            : 0;\n\n        uint256 minusPortion = paidPrincipal == debtPrincipal\n            ? position.debtPortion\n            : (totalDebtPortion * _amount) / totalDebtAmount;\n\n        totalDebtPortion -= minusPortion;\n        position.debtPortion -= minusPortion;\n        position.debtPrincipal -= paidPrincipal;\n        totalDebtAmount -= _amount;\n\n        emit Repaid(msg.sender, _nftIndex, _amount);\n    }\n\n    /// @notice Allows a user to close a position and get their collateral back, if the position's outstanding debt is 0\n    /// @dev Emits a {PositionClosed} event\n    /// @param _nftIndex The index of the NFT used as collateral\n    function closePosition(uint256 _nftIndex)\n        external\n        validNFTIndex(_nftIndex)\n    {\n        accrue();\n\n        require(msg.sender == positionOwner[_nftIndex], \"unauthorized\");\n        require(_getDebtAmount(_nftIndex) == 0, \"position_not_repaid\");\n\n        positionOwner[_nftIndex] = address(0);\n        delete positions[_nftIndex];\n        positionIndexes.remove(_nftIndex);\n\n        // transfer nft back to owner if nft was deposited\n        if (nftContract.ownerOf(_nftIndex) == address(this)) {\n            nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);\n        }\n\n        emit PositionClosed(msg.sender, _nftIndex);\n    }\n\n    /// @notice Allows members of the `LIQUIDATOR_ROLE` to liquidate a position. Positions can only be liquidated\n    /// once their debt amount exceeds the minimum liquidation debt to collateral value rate.\n    /// In order to liquidate a position, the liquidator needs to repay the user's outstanding debt.\n    /// If the position is not insured, it's closed immediately and the collateral is sent to the liquidator.\n    /// If the position is insured, the position remains open (interest doesn't increase) and the owner of the position has a certain amount of time\n    /// (`insuranceRepurchaseTimeLimit`) to fully repay the liquidator and pay an additional liquidation fee (`insuranceLiquidationPenaltyRate`), if this\n    /// is done in time the user gets back their collateral and their position is automatically closed. If the user doesn't repurchase their collateral\n    /// before the time limit passes, the liquidator can claim the liquidated NFT and the position is closed\n    /// @dev Emits a {Liquidated} event\n    /// @param _nftIndex The NFT to liquidate\n    function liquidate(uint256 _nftIndex)\n        external\n        onlyRole(LIQUIDATOR_ROLE)\n        validNFTIndex(_nftIndex)\n        nonReentrant\n    {\n        accrue();\n\n        address posOwner = positionOwner[_nftIndex];\n        require(posOwner != address(0), \"position_not_exist\");\n\n        Position storage position = positions[_nftIndex];\n        require(position.liquidatedAt == 0, \"liquidated\");\n\n        uint256 debtAmount = _getDebtAmount(_nftIndex);\n        require(\n            debtAmount >= _getLiquidationLimit(_nftIndex),\n            \"position_not_liquidatable\"\n        );\n\n        // burn all payment\n        stablecoin.burnFrom(msg.sender, debtAmount);\n\n        // update debt portion\n        totalDebtPortion -= position.debtPortion;\n        totalDebtAmount -= debtAmount;\n        position.debtPortion = 0;\n\n        bool insured = position.borrowType == BorrowType.USE_INSURANCE;\n        if (insured) {\n            position.debtAmountForRepurchase = debtAmount;\n            position.liquidatedAt = block.timestamp;\n            position.liquidator = msg.sender;\n        } else {\n            // transfer nft to liquidator\n            positionOwner[_nftIndex] = address(0);\n            delete positions[_nftIndex];\n            positionIndexes.remove(_nftIndex);\n            nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);\n        }\n\n        emit Liquidated(msg.sender, posOwner, _nftIndex, insured);\n    }\n\n    /// @notice Allows liquidated users who purchased insurance to repurchase their collateral within the time limit\n    /// defined with the `insuranceRepurchaseTimeLimit`. The user needs to pay the liquidator the total amount of debt\n    /// the position had at the time of liquidation, plus an insurance liquidation fee defined with `insuranceLiquidationPenaltyRate`\n    /// @dev Emits a {Repurchased} event\n    /// @param _nftIndex The NFT to repurchase\n    function repurchase(uint256 _nftIndex) external validNFTIndex(_nftIndex) {\n        Position memory position = positions[_nftIndex];\n        require(msg.sender == positionOwner[_nftIndex], \"unauthorized\");\n        require(position.liquidatedAt > 0, \"not_liquidated\");\n        require(\n            position.borrowType == BorrowType.USE_INSURANCE,\n            \"non_insurance\"\n        );\n        require(\n            position.liquidatedAt + settings.insuraceRepurchaseTimeLimit >=\n                block.timestamp,\n            \"insurance_expired\"\n        );\n\n        uint256 debtAmount = position.debtAmountForRepurchase;\n        uint256 penalty = (debtAmount *\n            settings.insuranceLiquidationPenaltyRate.numerator) /\n            settings.insuranceLiquidationPenaltyRate.denominator;\n\n        // transfer payment to liquidator\n        stablecoin.transferFrom(\n            msg.sender,\n            position.liquidator,\n            debtAmount + penalty\n        );\n\n        // transfer nft to user\n        positionOwner[_nftIndex] = address(0);\n        delete positions[_nftIndex];\n        positionIndexes.remove(_nftIndex);\n\n        nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);\n\n        emit Repurchased(msg.sender, _nftIndex);\n    }\n\n    /// @notice Allows the liquidator who liquidated the insured position with NFT at index `_nftIndex` to claim the position's collateral\n    /// after the time period defined with `insuranceRepurchaseTimeLimit` has expired and the position owner has not repurchased the collateral.\n    /// @dev Emits an {InsuranceExpired} event\n    /// @param _nftIndex The NFT to claim\n    function claimExpiredInsuranceNFT(uint256 _nftIndex)\n        external\n        validNFTIndex(_nftIndex)\n    {\n        Position memory position = positions[_nftIndex];\n        address owner = positionOwner[_nftIndex];\n        require(address(0) != owner, \"no_position\");\n        require(position.liquidatedAt > 0, \"not_liquidated\");\n        require(\n            position.liquidatedAt + settings.insuraceRepurchaseTimeLimit <\n                block.timestamp,\n            \"insurance_not_expired\"\n        );\n        require(position.liquidator == msg.sender, \"unauthorized\");\n\n        positionOwner[_nftIndex] = address(0);\n        delete positions[_nftIndex];\n        positionIndexes.remove(_nftIndex);\n\n        nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);\n\n        emit InsuranceExpired(owner, _nftIndex);\n    }\n\n    /// @notice Allows the DAO to collect interest and fees before they are repaid\n    function collect() external nonReentrant onlyRole(DAO_ROLE) {\n        accrue();\n        stablecoin.mint(msg.sender, totalFeeCollected);\n        totalFeeCollected = 0;\n    }\n\n    uint256[50] private __gap;\n}"
}