{
    "Function": "slitherConstructorVariables",
    "File": "src/V3Vault.sol",
    "Parent Contracts": [
        "src/interfaces/IErrors.sol",
        "lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol",
        "src/interfaces/IVault.sol",
        "lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol",
        "lib/openzeppelin-contracts/contracts/access/Ownable.sol",
        "lib/openzeppelin-contracts/contracts/utils/Multicall.sol",
        "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol",
        "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol",
        "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol",
        "lib/openzeppelin-contracts/contracts/utils/Context.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract V3Vault is ERC20, Multicall, Ownable, IVault, IERC721Receiver, IErrors {\n    using Math for uint256;\n\n    uint256 private constant Q32 = 2 ** 32;\n    uint256 private constant Q96 = 2 ** 96;\n\n    uint32 public constant MAX_COLLATERAL_FACTOR_X32 = uint32(Q32 * 90 / 100); // 90%\n\n    uint32 public constant MIN_LIQUIDATION_PENALTY_X32 = uint32(Q32 * 2 / 100); // 2%\n    uint32 public constant MAX_LIQUIDATION_PENALTY_X32 = uint32(Q32 * 10 / 100); // 10%\n\n    uint32 public constant MIN_RESERVE_PROTECTION_FACTOR_X32 = uint32(Q32 / 100); //1%\n\n    uint32 public constant MAX_DAILY_LEND_INCREASE_X32 = uint32(Q32 / 10); //10%\n    uint32 public constant MAX_DAILY_DEBT_INCREASE_X32 = uint32(Q32 / 10); //10%\n\n    /// @notice Uniswap v3 position manager\n    INonfungiblePositionManager public immutable nonfungiblePositionManager;\n\n    /// @notice Uniswap v3 factory\n    IUniswapV3Factory public immutable factory;\n\n    /// @notice interest rate model implementation\n    IInterestRateModel public immutable interestRateModel;\n\n    /// @notice oracle implementation\n    IV3Oracle public immutable oracle;\n\n    /// @notice permit2 contract\n    IPermit2 public immutable permit2;\n\n    /// @notice underlying asset for lending / borrowing\n    address public immutable override asset;\n\n    /// @notice decimals of underlying token (are the same as ERC20 share token)\n    uint8 private immutable assetDecimals;\n\n    // events\n    event ApprovedTransform(uint256 indexed tokenId, address owner, address target, bool isActive);\n\n    event Add(uint256 indexed tokenId, address owner, uint256 oldTokenId); // when a token is added replacing another token - oldTokenId > 0\n    event Remove(uint256 indexed tokenId, address recipient);\n\n    event ExchangeRateUpdate(uint256 debtExchangeRateX96, uint256 lendExchangeRateX96);\n    // Deposit and Withdraw events are defined in IERC4626\n    event WithdrawCollateral(\n        uint256 indexed tokenId, address owner, address recipient, uint128 liquidity, uint256 amount0, uint256 amount1\n    );\n    event Borrow(uint256 indexed tokenId, address owner, uint256 assets, uint256 shares);\n    event Repay(uint256 indexed tokenId, address repayer, address owner, uint256 assets, uint256 shares);\n    event Liquidate(\n        uint256 indexed tokenId,\n        address liquidator,\n        address owner,\n        uint256 value,\n        uint256 cost,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 reserve,\n        uint256 missing\n    ); // shows exactly how liquidation amounts were divided\n\n    // admin events\n    event WithdrawReserves(uint256 amount, address receiver);\n    event SetTransformer(address transformer, bool active);\n    event SetLimits(\n        uint256 minLoanSize,\n        uint256 globalLendLimit,\n        uint256 globalDebtLimit,\n        uint256 dailyLendIncreaseLimitMin,\n        uint256 dailyDebtIncreaseLimitMin\n    );\n    event SetReserveFactor(uint32 reserveFactorX32);\n    event SetReserveProtectionFactor(uint32 reserveProtectionFactorX32);\n    event SetTokenConfig(address token, uint32 collateralFactorX32, uint32 collateralValueLimitFactorX32);\n\n    event SetEmergencyAdmin(address emergencyAdmin);\n\n    // configured tokens\n    struct TokenConfig {\n        uint32 collateralFactorX32; // how much this token is valued as collateral\n        uint32 collateralValueLimitFactorX32; // how much asset equivalent may be lent out given this collateral\n        uint192 totalDebtShares; // how much debt shares are theoretically backed by this collateral\n    }\n\n    mapping(address => TokenConfig) public tokenConfigs;\n\n    // percentage of interest which is kept in the protocol for reserves\n    uint32 public reserveFactorX32 = 0;\n\n    // percentage of lend amount which needs to be in reserves before withdrawn\n    uint32 public reserveProtectionFactorX32 = MIN_RESERVE_PROTECTION_FACTOR_X32;\n\n    // total of debt shares - increases when borrow - decreases when repay\n    uint256 public debtSharesTotal = 0;\n\n    // exchange rates are Q96 at the beginning - 1 share token per 1 asset token\n    uint256 public lastExchangeRateUpdate = 0;\n    uint256 public lastDebtExchangeRateX96 = Q96;\n    uint256 public lastLendExchangeRateX96 = Q96;\n\n    uint256 public globalDebtLimit = 0;\n    uint256 public globalLendLimit = 0;\n\n    // minimal size of loan (to protect from non-liquidatable positions because of gas-cost)\n    uint256 public minLoanSize = 0;\n\n    // daily lend increase limit handling\n    uint256 public dailyLendIncreaseLimitMin = 0;\n    uint256 public dailyLendIncreaseLimitLeft = 0;\n    uint256 public dailyLendIncreaseLimitLastReset = 0;\n\n    // daily debt increase limit handling\n    uint256 public dailyDebtIncreaseLimitMin = 0;\n    uint256 public dailyDebtIncreaseLimitLeft = 0;\n    uint256 public dailyDebtIncreaseLimitLastReset = 0;\n\n    // lender balances are handled with ERC-20 mint/burn\n\n    // loans are handled with this struct\n    struct Loan {\n        uint256 debtShares;\n    }\n\n    mapping(uint256 => Loan) public loans; // tokenID -> loan mapping\n\n    // storage variables to handle enumerable token ownership\n    mapping(address => uint256[]) private ownedTokens; // Mapping from owner address to list of owned token IDs\n    mapping(uint256 => uint256) private ownedTokensIndex; // Mapping from token ID to index of the owner tokens list (for removal without loop)\n    mapping(uint256 => address) private tokenOwner; // Mapping from token ID to owner\n\n    uint256 private transformedTokenId = 0; // transient storage (when available in dencun)\n\n    mapping(address => bool) public transformerAllowList; // contracts allowed to transform positions (selected audited contracts e.g. V3Utils)\n    mapping(address => mapping(uint256 => mapping(address => bool))) public transformApprovals; // owners permissions for other addresses to call transform on owners behalf (e.g. AutoRange contract)\n\n    // address which can call special emergency actions without timelock\n    address public emergencyAdmin;\n\n    constructor(\n        string memory name,\n        string memory symbol,\n        address _asset,\n        INonfungiblePositionManager _nonfungiblePositionManager,\n        IInterestRateModel _interestRateModel,\n        IV3Oracle _oracle,\n        IPermit2 _permit2\n    ) ERC20(name, symbol) {\n        asset = _asset;\n        assetDecimals = IERC20Metadata(_asset).decimals();\n        nonfungiblePositionManager = _nonfungiblePositionManager;\n        factory = IUniswapV3Factory(_nonfungiblePositionManager.factory());\n        interestRateModel = _interestRateModel;\n        oracle = _oracle;\n        permit2 = _permit2;\n    }\n\n    ////////////////// EXTERNAL VIEW FUNCTIONS\n\n    /// @notice Retrieves global information about the vault\n    /// @return debt Total amount of debt asset tokens\n    /// @return lent Total amount of lent asset tokens\n    /// @return balance Balance of asset token in contract\n    /// @return available Available balance of asset token in contract (balance - reserves)\n    /// @return reserves Amount of reserves\n    function vaultInfo()\n        external\n        view\n        override\n        returns (\n            uint256 debt,\n            uint256 lent,\n            uint256 balance,\n            uint256 available,\n            uint256 reserves,\n            uint256 debtExchangeRateX96,\n            uint256 lendExchangeRateX96\n        )\n    {\n        (debtExchangeRateX96, lendExchangeRateX96) = _calculateGlobalInterest();\n        (balance, available, reserves) = _getAvailableBalance(debtExchangeRateX96, lendExchangeRateX96);\n\n        debt = _convertToAssets(debtSharesTotal, debtExchangeRateX96, Math.Rounding.Up);\n        lent = _convertToAssets(totalSupply(), lendExchangeRateX96, Math.Rounding.Up);\n    }\n\n    /// @notice Retrieves lending information for a specified account.\n    /// @param account The address of the account for which lending info is requested.\n    /// @return amount Amount of lent assets for the account\n    function lendInfo(address account) external view override returns (uint256 amount) {\n        (, uint256 newLendExchangeRateX96) = _calculateGlobalInterest();\n        amount = _convertToAssets(balanceOf(account), newLendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    /// @notice Retrieves details of a loan identified by its token ID.\n    /// @param tokenId The unique identifier of the loan - which is the corresponding UniV3 Position\n    /// @return debt Amount of debt for this position\n    /// @return fullValue Current value of the position priced as asset token\n    /// @return collateralValue Current collateral value of the position priced as asset token\n    /// @return liquidationCost If position is liquidatable - cost to liquidate position - otherwise 0\n    /// @return liquidationValue If position is liquidatable - the value of the (partial) position which the liquidator recieves - otherwise 0\n    function loanInfo(uint256 tokenId)\n        external\n        view\n        override\n        returns (\n            uint256 debt,\n            uint256 fullValue,\n            uint256 collateralValue,\n            uint256 liquidationCost,\n            uint256 liquidationValue\n        )\n    {\n        (uint256 newDebtExchangeRateX96,) = _calculateGlobalInterest();\n\n        debt = _convertToAssets(loans[tokenId].debtShares, newDebtExchangeRateX96, Math.Rounding.Up);\n\n        bool isHealthy;\n        (isHealthy, fullValue, collateralValue,) = _checkLoanIsHealthy(tokenId, debt);\n\n        if (!isHealthy) {\n            (liquidationValue, liquidationCost,) = _calculateLiquidation(debt, fullValue, collateralValue);\n        }\n    }\n\n    /// @notice Retrieves owner of a loan\n    /// @param tokenId The unique identifier of the loan - which is the corresponding UniV3 Position\n    /// @return owner Owner of the loan\n    function ownerOf(uint256 tokenId) external view override returns (address owner) {\n        return tokenOwner[tokenId];\n    }\n\n    /// @notice Retrieves count of loans for owner (for enumerating owners loans)\n    /// @param owner Owner address\n    function loanCount(address owner) external view override returns (uint256) {\n        return ownedTokens[owner].length;\n    }\n\n    /// @notice Retrieves tokenid of loan at given index for owner (for enumerating owners loans)\n    /// @param owner Owner address\n    /// @param index Index\n    function loanAtIndex(address owner, uint256 index) external view override returns (uint256) {\n        return ownedTokens[owner][index];\n    }\n\n    ////////////////// OVERRIDDEN EXTERNAL VIEW FUNCTIONS FROM ERC20\n    /// @inheritdoc IERC20Metadata\n    function decimals() public view override(IERC20Metadata, ERC20) returns (uint8) {\n        return assetDecimals;\n    }\n\n    ////////////////// OVERRIDDEN EXTERNAL VIEW FUNCTIONS FROM ERC4626\n\n    /// @inheritdoc IERC4626\n    function totalAssets() public view override returns (uint256) {\n        return IERC20(asset).balanceOf(address(this));\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToShares(uint256 assets) external view override returns (uint256 shares) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToShares(assets, lendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToAssets(uint256 shares) external view override returns (uint256 assets) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToAssets(shares, lendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    /// @inheritdoc IERC4626\n    function maxDeposit(address) external view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        uint256 value = _convertToAssets(totalSupply(), lendExchangeRateX96, Math.Rounding.Up);\n        if (value >= globalLendLimit) {\n            return 0;\n        } else {\n            return globalLendLimit - value;\n        }\n    }\n\n    /// @inheritdoc IERC4626\n    function maxMint(address) external view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        uint256 value = _convertToAssets(totalSupply(), lendExchangeRateX96, Math.Rounding.Up);\n        if (value >= globalLendLimit) {\n            return 0;\n        } else {\n            return _convertToShares(globalLendLimit - value, lendExchangeRateX96, Math.Rounding.Down);\n        }\n    }\n\n    /// @inheritdoc IERC4626\n    function maxWithdraw(address owner) external view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToAssets(balanceOf(owner), lendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    /// @inheritdoc IERC4626\n    function maxRedeem(address owner) external view override returns (uint256) {\n        return balanceOf(owner);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewDeposit(uint256 assets) public view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToShares(assets, lendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewMint(uint256 shares) public view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToAssets(shares, lendExchangeRateX96, Math.Rounding.Up);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewWithdraw(uint256 assets) public view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToShares(assets, lendExchangeRateX96, Math.Rounding.Up);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewRedeem(uint256 shares) public view override returns (uint256) {\n        (, uint256 lendExchangeRateX96) = _calculateGlobalInterest();\n        return _convertToAssets(shares, lendExchangeRateX96, Math.Rounding.Down);\n    }\n\n    ////////////////// OVERRIDDEN EXTERNAL FUNCTIONS FROM ERC4626\n\n    /// @inheritdoc IERC4626\n    function deposit(uint256 assets, address receiver) external override returns (uint256) {\n        (, uint256 shares) = _deposit(receiver, assets, false, \"\");\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function mint(uint256 shares, address receiver) external override returns (uint256) {\n        (uint256 assets,) = _deposit(receiver, shares, true, \"\");\n        return assets;\n    }\n\n    /// @inheritdoc IERC4626\n    function withdraw(uint256 assets, address receiver, address owner) external override returns (uint256) {\n        (, uint256 shares) = _withdraw(receiver, owner, assets, false);\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function redeem(uint256 shares, address receiver, address owner) external override returns (uint256) {\n        (uint256 assets,) = _withdraw(receiver, owner, shares, true);\n        return assets;\n    }\n\n    // deposit using permit2 data\n    function deposit(uint256 assets, address receiver, bytes calldata permitData) external override returns (uint256) {\n        (, uint256 shares) = _deposit(receiver, assets, false, permitData);\n        return shares;\n    }\n\n    // mint using permit2 data\n    function mint(uint256 shares, address receiver, bytes calldata permitData) external override returns (uint256) {\n        (uint256 assets,) = _deposit(receiver, shares, true, permitData);\n        return assets;\n    }\n\n    ////////////////// EXTERNAL FUNCTIONS\n\n    /// @notice Creates a new collateralized position (transfer approved position)\n    /// @param tokenId The token ID associated with the new position.\n    /// @param recipient Address to recieve the position in the vault\n    function create(uint256 tokenId, address recipient) external override {\n        nonfungiblePositionManager.safeTransferFrom(msg.sender, address(this), tokenId, abi.encode(recipient));\n    }\n\n    /// @notice Creates a new collateralized position with a permit for token spending (transfer position with permit)\n    /// @param tokenId The token ID associated with the new position.\n    /// @param owner Current owner of the position (signature owner)\n    /// @param recipient Address to recieve the position in the vault\n    /// @param deadline Timestamp until which the permit is valid.\n    /// @param v, r, s Components of the signature for the permit.\n    function createWithPermit(\n        uint256 tokenId,\n        address owner,\n        address recipient,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external override {\n        if (msg.sender != owner) {\n            revert Unauthorized();\n        }\n\n        nonfungiblePositionManager.permit(address(this), tokenId, deadline, v, r, s);\n        nonfungiblePositionManager.safeTransferFrom(owner, address(this), tokenId, abi.encode(recipient));\n    }\n\n    /// @notice Whenever a token is recieved it either creates a new loan, or modifies an existing one when in transform mode.\n    /// @inheritdoc IERC721Receiver\n    function onERC721Received(address, address from, uint256 tokenId, bytes calldata data)\n        external\n        override\n        returns (bytes4)\n    {\n        // only Uniswap v3 NFTs allowed - sent from other contract\n        if (msg.sender != address(nonfungiblePositionManager) || from == address(this)) {\n            revert WrongContract();\n        }\n\n        (uint256 debtExchangeRateX96, uint256 lendExchangeRateX96) = _updateGlobalInterest();\n\n        if (transformedTokenId == 0) {\n            address owner = from;\n            if (data.length > 0) {\n                owner = abi.decode(data, (address));\n            }\n            loans[tokenId] = Loan(0);\n\n            _addTokenToOwner(owner, tokenId);\n            emit Add(tokenId, owner, 0);\n        } else {\n            uint256 oldTokenId = transformedTokenId;\n\n            // if in transform mode - and a new position is sent - current position is replaced and returned\n            if (tokenId != oldTokenId) {\n                address owner = tokenOwner[oldTokenId];\n\n                // set transformed token to new one\n                transformedTokenId = tokenId;\n\n                // copy debt to new token\n                loans[tokenId] = Loan(loans[oldTokenId].debtShares);\n\n                _addTokenToOwner(owner, tokenId);\n                emit Add(tokenId, owner, oldTokenId);\n\n                // clears data of old loan\n                _cleanupLoan(oldTokenId, debtExchangeRateX96, lendExchangeRateX96, owner);\n\n                // sets data of new loan\n                _updateAndCheckCollateral(\n                    tokenId, debtExchangeRateX96, lendExchangeRateX96, 0, loans[tokenId].debtShares\n                );\n            }\n        }\n\n        return IERC721Receiver.onERC721Received.selector;\n    }\n\n    /// @notice Allows another address to call transform on behalf of owner (on a given token)\n    /// @param tokenId The token to be permitted\n    /// @param target The address to be allowed\n    /// @param isActive If it allowed or not\n    function approveTransform(uint256 tokenId, address target, bool isActive) external override {\n        if (tokenOwner[tokenId] != msg.sender) {\n            revert Unauthorized();\n        }\n        transformApprovals[msg.sender][tokenId][target] = isActive;\n\n        emit ApprovedTransform(tokenId, msg.sender, target, isActive);\n    }\n\n    /// @notice Method which allows a contract to transform a loan by changing it (and only at the end checking collateral)\n    /// @param tokenId The token ID to be processed\n    /// @param transformer The address of a whitelisted transformer contract\n    /// @param data Encoded transformation params\n    /// @return newTokenId Final token ID (may be different than input token ID when the position was replaced by transformation)\n    function transform(uint256 tokenId, address transformer, bytes calldata data)\n        external\n        override\n        returns (uint256 newTokenId)\n    {\n        if (tokenId == 0 || !transformerAllowList[transformer]) {\n            revert TransformNotAllowed();\n        }\n        if (transformedTokenId > 0) {\n            revert Reentrancy();\n        }\n        transformedTokenId = tokenId;\n\n        (uint256 newDebtExchangeRateX96,) = _updateGlobalInterest();\n\n        address loanOwner = tokenOwner[tokenId];\n\n        // only the owner of the loan, the vault itself or any approved caller can call this\n        if (loanOwner != msg.sender && !transformApprovals[loanOwner][tokenId][msg.sender]) {\n            revert Unauthorized();\n        }\n\n        // give access to transformer\n        nonfungiblePositionManager.approve(transformer, tokenId);\n\n        (bool success,) = transformer.call(data);\n        if (!success) {\n            revert TransformFailed();\n        }\n\n        // may have changed in the meantime\n        tokenId = transformedTokenId;\n\n        // check owner not changed (NEEDED because token could have been moved somewhere else in the meantime)\n        address owner = nonfungiblePositionManager.ownerOf(tokenId);\n        if (owner != address(this)) {\n            revert Unauthorized();\n        }\n\n        // remove access for transformer\n        nonfungiblePositionManager.approve(address(0), tokenId);\n\n        uint256 debt = _convertToAssets(loans[tokenId].debtShares, newDebtExchangeRateX96, Math.Rounding.Up);\n        _requireLoanIsHealthy(tokenId, debt);\n\n        transformedTokenId = 0;\n\n        return tokenId;\n    }\n\n    /// @notice Borrows specified amount using token as collateral\n    /// @param tokenId The token ID to use as collateral\n    /// @param assets How much assets to borrow\n    function borrow(uint256 tokenId, uint256 assets) external override {\n        bool isTransformMode =\n            transformedTokenId > 0 && transformedTokenId == tokenId && transformerAllowList[msg.sender];\n\n        (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        _resetDailyDebtIncreaseLimit(newLendExchangeRateX96, false);\n\n        Loan storage loan = loans[tokenId];\n\n        // if not in transfer mode - must be called from owner or the vault itself\n        if (!isTransformMode && tokenOwner[tokenId] != msg.sender && address(this) != msg.sender) {\n            revert Unauthorized();\n        }\n\n        uint256 shares = _convertToShares(assets, newDebtExchangeRateX96, Math.Rounding.Up);\n\n        uint256 loanDebtShares = loan.debtShares + shares;\n        loan.debtShares = loanDebtShares;\n        debtSharesTotal += shares;\n\n        if (debtSharesTotal > _convertToShares(globalDebtLimit, newDebtExchangeRateX96, Math.Rounding.Down)) {\n            revert GlobalDebtLimit();\n        }\n        if (assets > dailyDebtIncreaseLimitLeft) {\n            revert DailyDebtIncreaseLimit();\n        } else {\n            dailyDebtIncreaseLimitLeft -= assets;\n        }\n\n        _updateAndCheckCollateral(\n            tokenId, newDebtExchangeRateX96, newLendExchangeRateX96, loanDebtShares - shares, loanDebtShares\n        );\n\n        uint256 debt = _convertToAssets(loanDebtShares, newDebtExchangeRateX96, Math.Rounding.Up);\n\n        if (debt < minLoanSize) {\n            revert MinLoanSize();\n        }\n\n        // only does check health here if not in transform mode\n        if (!isTransformMode) {\n            _requireLoanIsHealthy(tokenId, debt);\n        }\n\n        address owner = tokenOwner[tokenId];\n\n        // fails if not enough asset available\n        // if called from transform mode - send funds to transformer contract\n        SafeERC20.safeTransfer(IERC20(asset), isTransformMode ? msg.sender : owner, assets);\n\n        emit Borrow(tokenId, owner, assets, shares);\n    }\n\n    /// @dev Decreases the liquidity of a given position and collects the resultant assets (and possibly additional fees)\n    /// This function is not allowed during transformation (if a transformer wants to decreaseLiquidity he can call the methods directly on the NonfungiblePositionManager)\n    /// @param params Struct containing various parameters for the operation. Includes tokenId, liquidity amount, minimum asset amounts, and deadline.\n    /// @return amount0 The amount of the first type of asset collected.\n    /// @return amount1 The amount of the second type of asset collected.\n    function decreaseLiquidityAndCollect(DecreaseLiquidityAndCollectParams calldata params)\n        external\n        override\n        returns (uint256 amount0, uint256 amount1)\n    {\n        // this method is not allowed during transform - can be called directly on nftmanager if needed from transform contract\n        if (transformedTokenId > 0) {\n            revert TransformNotAllowed();\n        }\n\n        address owner = tokenOwner[params.tokenId];\n\n        if (owner != msg.sender) {\n            revert Unauthorized();\n        }\n\n        (uint256 newDebtExchangeRateX96,) = _updateGlobalInterest();\n\n        (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(\n            INonfungiblePositionManager.DecreaseLiquidityParams(\n                params.tokenId, params.liquidity, params.amount0Min, params.amount1Min, params.deadline\n            )\n        );\n\n        INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams(\n            params.tokenId,\n            params.recipient,\n            params.feeAmount0 == type(uint128).max ? type(uint128).max : SafeCast.toUint128(amount0 + params.feeAmount0),\n            params.feeAmount1 == type(uint128).max ? type(uint128).max : SafeCast.toUint128(amount1 + params.feeAmount1)\n        );\n\n        (amount0, amount1) = nonfungiblePositionManager.collect(collectParams);\n\n        uint256 debt = _convertToAssets(loans[params.tokenId].debtShares, newDebtExchangeRateX96, Math.Rounding.Up);\n        _requireLoanIsHealthy(params.tokenId, debt);\n\n        emit WithdrawCollateral(params.tokenId, owner, params.recipient, params.liquidity, amount0, amount1);\n    }\n\n    /// @notice Repays borrowed tokens. Can be denominated in assets or debt share amount\n    /// @param tokenId The token ID to use as collateral\n    /// @param amount How many assets/debt shares to repay\n    /// @param isShare Is amount specified in assets or debt shares.\n    function repay(uint256 tokenId, uint256 amount, bool isShare) external override {\n        _repay(tokenId, amount, isShare, \"\");\n    }\n\n    /// @notice Repays borrowed tokens. Can be denominated in assets or debt share amount\n    /// @param tokenId The token ID to use as collateral\n    /// @param amount How many assets/debt shares to repay\n    /// @param isShare Is amount specified in assets or debt shares.\n    /// @param permitData Permit2 data and signature\n    function repay(uint256 tokenId, uint256 amount, bool isShare, bytes calldata permitData) external override {\n        _repay(tokenId, amount, isShare, permitData);\n    }\n\n    // state used in liquidation function to avoid stack too deep errors\n    struct LiquidateState {\n        uint256 newDebtExchangeRateX96;\n        uint256 newLendExchangeRateX96;\n        uint256 debt;\n        bool isHealthy;\n        uint256 liquidationValue;\n        uint256 liquidatorCost;\n        uint256 reserveCost;\n        uint256 missing;\n        uint256 fullValue;\n        uint256 collateralValue;\n        uint256 feeValue;\n    }\n\n    /// @notice Liquidates position - needed assets are depending on current price.\n    /// Sufficient assets need to be approved to the contract for the liquidation to succeed.\n    /// @param params The params defining liquidation\n    /// @return amount0 The amount of the first type of asset collected.\n    /// @return amount1 The amount of the second type of asset collected.\n    function liquidate(LiquidateParams calldata params) external override returns (uint256 amount0, uint256 amount1) {\n        // liquidation is not allowed during transformer mode\n        if (transformedTokenId > 0) {\n            revert TransformNotAllowed();\n        }\n\n        LiquidateState memory state;\n\n        (state.newDebtExchangeRateX96, state.newLendExchangeRateX96) = _updateGlobalInterest();\n\n        uint256 debtShares = loans[params.tokenId].debtShares;\n        if (debtShares != params.debtShares) {\n            revert DebtChanged();\n        }\n\n        state.debt = _convertToAssets(debtShares, state.newDebtExchangeRateX96, Math.Rounding.Up);\n\n        (state.isHealthy, state.fullValue, state.collateralValue, state.feeValue) =\n            _checkLoanIsHealthy(params.tokenId, state.debt);\n        if (state.isHealthy) {\n            revert NotLiquidatable();\n        }\n\n        (state.liquidationValue, state.liquidatorCost, state.reserveCost) =\n            _calculateLiquidation(state.debt, state.fullValue, state.collateralValue);\n\n        // calculate reserve (before transfering liquidation money - otherwise calculation is off)\n        if (state.reserveCost > 0) {\n            state.missing =\n                _handleReserveLiquidation(state.reserveCost, state.newDebtExchangeRateX96, state.newLendExchangeRateX96);\n        }\n\n        if (params.permitData.length > 0) {\n            (ISignatureTransfer.PermitTransferFrom memory permit, bytes memory signature) =\n                abi.decode(params.permitData, (ISignatureTransfer.PermitTransferFrom, bytes));\n            permit2.permitTransferFrom(\n                permit,\n                ISignatureTransfer.SignatureTransferDetails(address(this), state.liquidatorCost),\n                msg.sender,\n                signature\n            );\n        } else {\n            // take value from liquidator\n            SafeERC20.safeTransferFrom(IERC20(asset), msg.sender, address(this), state.liquidatorCost);\n        }\n\n        debtSharesTotal -= debtShares;\n\n        // send promised collateral tokens to liquidator\n        (amount0, amount1) =\n            _sendPositionValue(params.tokenId, state.liquidationValue, state.fullValue, state.feeValue, msg.sender);\n\n        if (amount0 < params.amount0Min || amount1 < params.amount1Min) {\n            revert SlippageError();\n        }\n\n        address owner = tokenOwner[params.tokenId];\n\n        // disarm loan and send remaining position to owner\n        _cleanupLoan(params.tokenId, state.newDebtExchangeRateX96, state.newLendExchangeRateX96, owner);\n\n        emit Liquidate(\n            params.tokenId,\n            msg.sender,\n            owner,\n            state.fullValue,\n            state.liquidatorCost,\n            amount0,\n            amount1,\n            state.reserveCost,\n            state.missing\n        );\n    }\n\n    ////////////////// ADMIN FUNCTIONS only callable by owner\n\n    /// @notice withdraw protocol reserves (onlyOwner)\n    /// only allows to withdraw excess reserves (> globalLendAmount * reserveProtectionFactor)\n    /// @param amount amount to withdraw\n    /// @param receiver receiver address\n    function withdrawReserves(uint256 amount, address receiver) external onlyOwner {\n        (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        uint256 protected =\n            _convertToAssets(totalSupply(), newLendExchangeRateX96, Math.Rounding.Up) * reserveProtectionFactorX32 / Q32;\n        (uint256 balance,, uint256 reserves) = _getAvailableBalance(newDebtExchangeRateX96, newLendExchangeRateX96);\n        uint256 unprotected = reserves > protected ? reserves - protected : 0;\n        uint256 available = balance > unprotected ? unprotected : balance;\n\n        if (amount > available) {\n            revert InsufficientLiquidity();\n        }\n\n        if (amount > 0) {\n            SafeERC20.safeTransfer(IERC20(asset), receiver, amount);\n        }\n\n        emit WithdrawReserves(amount, receiver);\n    }\n\n    /// @notice configure transformer contract (onlyOwner)\n    /// @param transformer address of transformer contract\n    /// @param active should the transformer be active?\n    function setTransformer(address transformer, bool active) external onlyOwner {\n        // protects protocol from owner trying to set dangerous transformer\n        if (\n            transformer == address(0) || transformer == address(this) || transformer == asset\n                || transformer == address(nonfungiblePositionManager)\n        ) {\n            revert InvalidConfig();\n        }\n\n        transformerAllowList[transformer] = active;\n        emit SetTransformer(transformer, active);\n    }\n\n    /// @notice set limits (this doesnt affect existing loans) - this method can be called by owner OR emergencyAdmin\n    /// @param _minLoanSize min size of a loan - trying to create smaller loans will revert\n    /// @param _globalLendLimit global limit of lent amount\n    /// @param _globalDebtLimit global limit of debt amount\n    /// @param _dailyLendIncreaseLimitMin min daily increasable amount of lent amount\n    /// @param _dailyDebtIncreaseLimitMin min daily increasable amount of debt amount\n    function setLimits(\n        uint256 _minLoanSize,\n        uint256 _globalLendLimit,\n        uint256 _globalDebtLimit,\n        uint256 _dailyLendIncreaseLimitMin,\n        uint256 _dailyDebtIncreaseLimitMin\n    ) external {\n        if (msg.sender != emergencyAdmin && msg.sender != owner()) {\n            revert Unauthorized();\n        }\n\n        minLoanSize = _minLoanSize;\n        globalLendLimit = _globalLendLimit;\n        globalDebtLimit = _globalDebtLimit;\n        dailyLendIncreaseLimitMin = _dailyLendIncreaseLimitMin;\n        dailyDebtIncreaseLimitMin = _dailyDebtIncreaseLimitMin;\n\n        (, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        // force reset daily limits with new values\n        _resetDailyLendIncreaseLimit(newLendExchangeRateX96, true);\n        _resetDailyDebtIncreaseLimit(newLendExchangeRateX96, true);\n\n        emit SetLimits(\n            _minLoanSize, _globalLendLimit, _globalDebtLimit, _dailyLendIncreaseLimitMin, _dailyDebtIncreaseLimitMin\n        );\n    }\n\n    /// @notice sets reserve factor - percentage difference between debt and lend interest (onlyOwner)\n    /// @param _reserveFactorX32 reserve factor multiplied by Q32\n    function setReserveFactor(uint32 _reserveFactorX32) external onlyOwner {\n        reserveFactorX32 = _reserveFactorX32;\n        emit SetReserveFactor(_reserveFactorX32);\n    }\n\n    /// @notice sets reserve protection factor - percentage of globalLendAmount which can't be withdrawn by owner (onlyOwner)\n    /// @param _reserveProtectionFactorX32 reserve protection factor multiplied by Q32\n    function setReserveProtectionFactor(uint32 _reserveProtectionFactorX32) external onlyOwner {\n        if (_reserveProtectionFactorX32 < MIN_RESERVE_PROTECTION_FACTOR_X32) {\n            revert InvalidConfig();\n        }\n        reserveProtectionFactorX32 = _reserveProtectionFactorX32;\n        emit SetReserveProtectionFactor(_reserveProtectionFactorX32);\n    }\n\n    /// @notice Sets or updates the configuration for a token (onlyOwner)\n    /// @param token Token to configure\n    /// @param collateralFactorX32 collateral factor for this token mutiplied by Q32\n    /// @param collateralValueLimitFactorX32 how much of it maybe used as collateral measured as percentage of total lent assets mutiplied by Q32\n    function setTokenConfig(address token, uint32 collateralFactorX32, uint32 collateralValueLimitFactorX32)\n        external\n        onlyOwner\n    {\n        if (collateralFactorX32 > MAX_COLLATERAL_FACTOR_X32) {\n            revert CollateralFactorExceedsMax();\n        }\n        tokenConfigs[token].collateralFactorX32 = collateralFactorX32;\n        tokenConfigs[token].collateralValueLimitFactorX32 = collateralValueLimitFactorX32;\n        emit SetTokenConfig(token, collateralFactorX32, collateralValueLimitFactorX32);\n    }\n\n    /// @notice Updates emergency admin address (onlyOwner)\n    /// @param admin Emergency admin address\n    function setEmergencyAdmin(address admin) external onlyOwner {\n        emergencyAdmin = admin;\n        emit SetEmergencyAdmin(admin);\n    }\n\n    ////////////////// INTERNAL FUNCTIONS\n\n    function _deposit(address receiver, uint256 amount, bool isShare, bytes memory permitData)\n        internal\n        returns (uint256 assets, uint256 shares)\n    {\n        (, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        _resetDailyLendIncreaseLimit(newLendExchangeRateX96, false);\n\n        if (isShare) {\n            shares = amount;\n            assets = _convertToAssets(shares, newLendExchangeRateX96, Math.Rounding.Up);\n        } else {\n            assets = amount;\n            shares = _convertToShares(assets, newLendExchangeRateX96, Math.Rounding.Down);\n        }\n\n        if (permitData.length > 0) {\n            (ISignatureTransfer.PermitTransferFrom memory permit, bytes memory signature) =\n                abi.decode(permitData, (ISignatureTransfer.PermitTransferFrom, bytes));\n            permit2.permitTransferFrom(\n                permit, ISignatureTransfer.SignatureTransferDetails(address(this), assets), msg.sender, signature\n            );\n        } else {\n            // fails if not enough token approved\n            SafeERC20.safeTransferFrom(IERC20(asset), msg.sender, address(this), assets);\n        }\n\n        _mint(receiver, shares);\n\n        if (totalSupply() > globalLendLimit) {\n            revert GlobalLendLimit();\n        }\n\n        if (assets > dailyLendIncreaseLimitLeft) {\n            revert DailyLendIncreaseLimit();\n        } else {\n            dailyLendIncreaseLimitLeft -= assets;\n        }\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n    }\n\n    // withdraws lent tokens. can be denominated in token or share amount\n    function _withdraw(address receiver, address owner, uint256 amount, bool isShare)\n        internal\n        returns (uint256 assets, uint256 shares)\n    {\n        (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        if (isShare) {\n            shares = amount;\n            assets = _convertToAssets(amount, newLendExchangeRateX96, Math.Rounding.Down);\n        } else {\n            assets = amount;\n            shares = _convertToShares(amount, newLendExchangeRateX96, Math.Rounding.Up);\n        }\n\n        // if caller has allowance for owners shares - may call withdraw\n        if (msg.sender != owner) {\n            _spendAllowance(owner, msg.sender, shares);\n        }\n\n        (, uint256 available,) = _getAvailableBalance(newDebtExchangeRateX96, newLendExchangeRateX96);\n        if (available < assets) {\n            revert InsufficientLiquidity();\n        }\n\n        // fails if not enough shares\n        _burn(owner, shares);\n        SafeERC20.safeTransfer(IERC20(asset), receiver, assets);\n\n        // when amounts are withdrawn - they may be deposited again\n        dailyLendIncreaseLimitLeft += assets;\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n    }\n\n    function _repay(uint256 tokenId, uint256 amount, bool isShare, bytes memory permitData) internal {\n        (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96) = _updateGlobalInterest();\n\n        Loan storage loan = loans[tokenId];\n\n        uint256 currentShares = loan.debtShares;\n\n        uint256 shares;\n        uint256 assets;\n\n        if (isShare) {\n            shares = amount;\n            assets = _convertToAssets(amount, newDebtExchangeRateX96, Math.Rounding.Up);\n        } else {\n            assets = amount;\n            shares = _convertToShares(amount, newDebtExchangeRateX96, Math.Rounding.Down);\n        }\n\n        // fails if too much repayed\n        if (shares > currentShares) {\n            revert RepayExceedsDebt();\n        }\n\n        if (assets > 0) {\n            if (permitData.length > 0) {\n                (ISignatureTransfer.PermitTransferFrom memory permit, bytes memory signature) =\n                    abi.decode(permitData, (ISignatureTransfer.PermitTransferFrom, bytes));\n                permit2.permitTransferFrom(\n                    permit, ISignatureTransfer.SignatureTransferDetails(address(this), assets), msg.sender, signature\n                );\n            } else {\n                // fails if not enough token approved\n                SafeERC20.safeTransferFrom(IERC20(asset), msg.sender, address(this), assets);\n            }\n        }\n\n        uint256 loanDebtShares = loan.debtShares - shares;\n        loan.debtShares = loanDebtShares;\n        debtSharesTotal -= shares;\n\n        // when amounts are repayed - they maybe borrowed again\n        dailyDebtIncreaseLimitLeft += assets;\n\n        _updateAndCheckCollateral(\n            tokenId, newDebtExchangeRateX96, newLendExchangeRateX96, loanDebtShares + shares, loanDebtShares\n        );\n\n        address owner = tokenOwner[tokenId];\n\n        // if fully repayed\n        if (currentShares == shares) {\n            _cleanupLoan(tokenId, newDebtExchangeRateX96, newLendExchangeRateX96, owner);\n        } else {\n            // if resulting loan is too small - revert\n            if (_convertToAssets(loanDebtShares, newDebtExchangeRateX96, Math.Rounding.Up) < minLoanSize) {\n                revert MinLoanSize();\n            }\n        }\n\n        emit Repay(tokenId, msg.sender, owner, assets, shares);\n    }\n\n    // checks how much balance is available - excluding reserves\n    function _getAvailableBalance(uint256 debtExchangeRateX96, uint256 lendExchangeRateX96)\n        internal\n        view\n        returns (uint256 balance, uint256 available, uint256 reserves)\n    {\n        balance = totalAssets();\n\n        uint256 debt = _convertToAssets(debtSharesTotal, debtExchangeRateX96, Math.Rounding.Up);\n        uint256 lent = _convertToAssets(totalSupply(), lendExchangeRateX96, Math.Rounding.Down);\n\n        reserves = balance + debt > lent ? balance + debt - lent : 0;\n        available = balance > reserves ? balance - reserves : 0;\n    }\n\n    // removes correct amount from position to send to liquidator\n    function _sendPositionValue(\n        uint256 tokenId,\n        uint256 liquidationValue,\n        uint256 fullValue,\n        uint256 feeValue,\n        address recipient\n    ) internal returns (uint256 amount0, uint256 amount1) {\n        uint128 liquidity;\n        uint128 fees0;\n        uint128 fees1;\n\n        // if full position is liquidated - no analysis needed\n        if (liquidationValue == fullValue) {\n            (,,,,,,, liquidity,,,,) = nonfungiblePositionManager.positions(tokenId);\n            fees0 = type(uint128).max;\n            fees1 = type(uint128).max;\n        } else {\n            (,,, liquidity,,, fees0, fees1) = oracle.getPositionBreakdown(tokenId);\n\n            // only take needed fees\n            if (liquidationValue < feeValue) {\n                liquidity = 0;\n                fees0 = uint128(liquidationValue * fees0 / feeValue);\n                fees1 = uint128(liquidationValue * fees1 / feeValue);\n            } else {\n                // take all fees and needed liquidity\n                fees0 = type(uint128).max;\n                fees1 = type(uint128).max;\n                liquidity = uint128((liquidationValue - feeValue) * liquidity / (fullValue - feeValue));\n            }\n        }\n\n        if (liquidity > 0) {\n            nonfungiblePositionManager.decreaseLiquidity(\n                INonfungiblePositionManager.DecreaseLiquidityParams(tokenId, liquidity, 0, 0, block.timestamp)\n            );\n        }\n\n        (amount0, amount1) = nonfungiblePositionManager.collect(\n            INonfungiblePositionManager.CollectParams(tokenId, recipient, fees0, fees1)\n        );\n    }\n\n    // cleans up loan when it is closed because of replacement, repayment or liquidation\n    // send the position in its current state to owner\n    function _cleanupLoan(uint256 tokenId, uint256 debtExchangeRateX96, uint256 lendExchangeRateX96, address owner)\n        internal\n    {\n        _removeTokenFromOwner(owner, tokenId);\n        _updateAndCheckCollateral(tokenId, debtExchangeRateX96, lendExchangeRateX96, loans[tokenId].debtShares, 0);\n        delete loans[tokenId];\n        nonfungiblePositionManager.safeTransferFrom(address(this), owner, tokenId);\n        emit Remove(tokenId, owner);\n    }\n\n    // calculates amount which needs to be payed to liquidate position\n    //  if position is too valuable - not all of the position is liquididated - only needed amount\n    //  if position is not valuable enough - missing part is covered by reserves - if not enough reserves - collectively by other borrowers\n    function _calculateLiquidation(uint256 debt, uint256 fullValue, uint256 collateralValue)\n        internal\n        pure\n        returns (uint256 liquidationValue, uint256 liquidatorCost, uint256 reserveCost)\n    {\n        // in a standard liquidation - liquidator pays complete debt (and get part or all of position)\n        // if position has less than enough value - liquidation cost maybe less - rest is payed by protocol or lenders collectively\n        liquidatorCost = debt;\n\n        // position value needed to pay debt at max penalty\n        uint256 maxPenaltyValue = debt * (Q32 + MAX_LIQUIDATION_PENALTY_X32) / Q32;\n\n        // if position is more valuable than debt with max penalty\n        if (fullValue >= maxPenaltyValue) {\n            // position value when position started to be liquidatable\n            uint256 startLiquidationValue = debt * fullValue / collateralValue;\n            uint256 penaltyFractionX96 =\n                (Q96 - ((fullValue - maxPenaltyValue) * Q96 / (startLiquidationValue - maxPenaltyValue)));\n            uint256 penaltyX32 = MIN_LIQUIDATION_PENALTY_X32\n                + (MAX_LIQUIDATION_PENALTY_X32 - MIN_LIQUIDATION_PENALTY_X32) * penaltyFractionX96 / Q96;\n\n            liquidationValue = debt * (Q32 + penaltyX32) / Q32;\n        } else {\n            // all position value\n            liquidationValue = fullValue;\n\n            uint256 penaltyValue = fullValue * (Q32 - MAX_LIQUIDATION_PENALTY_X32) / Q32;\n            liquidatorCost = penaltyValue;\n            reserveCost = debt - penaltyValue;\n        }\n    }\n\n    // calculates if there are enough reserves to cover liquidaton - if not its shared between lenders\n    function _handleReserveLiquidation(\n        uint256 reserveCost,\n        uint256 newDebtExchangeRateX96,\n        uint256 newLendExchangeRateX96\n    ) internal returns (uint256 missing) {\n        (,, uint256 reserves) = _getAvailableBalance(newDebtExchangeRateX96, newLendExchangeRateX96);\n\n        // if not enough - democratize debt\n        if (reserveCost > reserves) {\n            missing = reserveCost - reserves;\n\n            uint256 totalLent = _convertToAssets(totalSupply(), newLendExchangeRateX96, Math.Rounding.Up);\n\n            // this lines distribute missing amount and remove it from all lent amount proportionally\n            newLendExchangeRateX96 = (totalLent - missing) * newLendExchangeRateX96 / totalLent;\n            lastLendExchangeRateX96 = newLendExchangeRateX96;\n            emit ExchangeRateUpdate(newDebtExchangeRateX96, newLendExchangeRateX96);\n        }\n    }\n\n    function _calculateTokenCollateralFactorX32(uint256 tokenId) internal view returns (uint32) {\n        (,, address token0, address token1,,,,,,,,) = nonfungiblePositionManager.positions(tokenId);\n        uint32 factor0X32 = tokenConfigs[token0].collateralFactorX32;\n        uint32 factor1X32 = tokenConfigs[token1].collateralFactorX32;\n        return factor0X32 > factor1X32 ? factor1X32 : factor0X32;\n    }\n\n    function _updateGlobalInterest()\n        internal\n        returns (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96)\n    {\n        // only needs to be updated once per block (when needed)\n        if (block.timestamp > lastExchangeRateUpdate) {\n            (newDebtExchangeRateX96, newLendExchangeRateX96) = _calculateGlobalInterest();\n            lastDebtExchangeRateX96 = newDebtExchangeRateX96;\n            lastLendExchangeRateX96 = newLendExchangeRateX96;\n            lastExchangeRateUpdate = block.timestamp;\n            emit ExchangeRateUpdate(newDebtExchangeRateX96, newLendExchangeRateX96);\n        } else {\n            newDebtExchangeRateX96 = lastDebtExchangeRateX96;\n            newLendExchangeRateX96 = lastLendExchangeRateX96;\n        }\n    }\n\n    function _calculateGlobalInterest()\n        internal\n        view\n        returns (uint256 newDebtExchangeRateX96, uint256 newLendExchangeRateX96)\n    {\n        uint256 oldDebtExchangeRateX96 = lastDebtExchangeRateX96;\n        uint256 oldLendExchangeRateX96 = lastLendExchangeRateX96;\n\n        (, uint256 available,) = _getAvailableBalance(oldDebtExchangeRateX96, oldLendExchangeRateX96);\n\n        uint256 debt = _convertToAssets(debtSharesTotal, oldDebtExchangeRateX96, Math.Rounding.Up);\n\n        (uint256 borrowRateX96, uint256 supplyRateX96) = interestRateModel.getRatesPerSecondX96(available, debt);\n\n        supplyRateX96 = supplyRateX96.mulDiv(Q32 - reserveFactorX32, Q32);\n\n        // always growing or equal\n        uint256 lastRateUpdate = lastExchangeRateUpdate;\n\n        if (lastRateUpdate > 0) {\n            newDebtExchangeRateX96 = oldDebtExchangeRateX96\n                + oldDebtExchangeRateX96 * (block.timestamp - lastRateUpdate) * borrowRateX96 / Q96;\n            newLendExchangeRateX96 = oldLendExchangeRateX96\n                + oldLendExchangeRateX96 * (block.timestamp - lastRateUpdate) * supplyRateX96 / Q96;\n        } else {\n            newDebtExchangeRateX96 = oldDebtExchangeRateX96;\n            newLendExchangeRateX96 = oldLendExchangeRateX96;\n        }\n    }\n\n    function _requireLoanIsHealthy(uint256 tokenId, uint256 debt) internal view {\n        (bool isHealthy,,,) = _checkLoanIsHealthy(tokenId, debt);\n        if (!isHealthy) {\n            revert CollateralFail();\n        }\n    }\n\n    // updates collateral token configs - and check if limit is not surpassed (check is only done on increasing debt shares)\n    function _updateAndCheckCollateral(\n        uint256 tokenId,\n        uint256 debtExchangeRateX96,\n        uint256 lendExchangeRateX96,\n        uint256 oldShares,\n        uint256 newShares\n    ) internal {\n        if (oldShares != newShares) {\n            (,, address token0, address token1,,,,,,,,) = nonfungiblePositionManager.positions(tokenId);\n\n            // remove previous collateral - add new collateral\n            if (oldShares > newShares) {\n                tokenConfigs[token0].totalDebtShares -= SafeCast.toUint192(oldShares - newShares);\n                tokenConfigs[token1].totalDebtShares -= SafeCast.toUint192(oldShares - newShares);\n            } else {\n                tokenConfigs[token0].totalDebtShares += SafeCast.toUint192(newShares - oldShares);\n                tokenConfigs[token1].totalDebtShares += SafeCast.toUint192(newShares - oldShares);\n\n                // check if current value of used collateral is more than allowed limit\n                // if collateral is decreased - never revert\n                uint256 lentAssets = _convertToAssets(totalSupply(), lendExchangeRateX96, Math.Rounding.Up);\n                uint256 collateralValueLimitFactorX32 = tokenConfigs[token0].collateralValueLimitFactorX32;\n                if (\n                    collateralValueLimitFactorX32 < type(uint32).max\n                        && _convertToAssets(tokenConfigs[token0].totalDebtShares, debtExchangeRateX96, Math.Rounding.Up)\n                            > lentAssets * collateralValueLimitFactorX32 / Q32\n                ) {\n                    revert CollateralValueLimit();\n                }\n                collateralValueLimitFactorX32 = tokenConfigs[token1].collateralValueLimitFactorX32;\n                if (\n                    collateralValueLimitFactorX32 < type(uint32).max\n                        && _convertToAssets(tokenConfigs[token1].totalDebtShares, debtExchangeRateX96, Math.Rounding.Up)\n                            > lentAssets * collateralValueLimitFactorX32 / Q32\n                ) {\n                    revert CollateralValueLimit();\n                }\n            }\n        }\n    }\n\n    function _resetDailyLendIncreaseLimit(uint256 newLendExchangeRateX96, bool force) internal {\n        // daily lend limit reset handling\n        uint256 time = block.timestamp / 1 days;\n        if (force || time > dailyLendIncreaseLimitLastReset) {\n            uint256 lendIncreaseLimit = _convertToAssets(totalSupply(), newLendExchangeRateX96, Math.Rounding.Up)\n                * (Q32 + MAX_DAILY_LEND_INCREASE_X32) / Q32;\n            dailyLendIncreaseLimitLeft =\n                dailyLendIncreaseLimitMin > lendIncreaseLimit ? dailyLendIncreaseLimitMin : lendIncreaseLimit;\n            dailyLendIncreaseLimitLastReset = time;\n        }\n    }\n\n    function _resetDailyDebtIncreaseLimit(uint256 newLendExchangeRateX96, bool force) internal {\n        // daily debt limit reset handling\n        uint256 time = block.timestamp / 1 days;\n        if (force || time > dailyDebtIncreaseLimitLastReset) {\n            uint256 debtIncreaseLimit = _convertToAssets(totalSupply(), newLendExchangeRateX96, Math.Rounding.Up)\n                * (Q32 + MAX_DAILY_DEBT_INCREASE_X32) / Q32;\n            dailyDebtIncreaseLimitLeft =\n                dailyDebtIncreaseLimitMin > debtIncreaseLimit ? dailyDebtIncreaseLimitMin : debtIncreaseLimit;\n            dailyDebtIncreaseLimitLastReset = time;\n        }\n    }\n\n    function _checkLoanIsHealthy(uint256 tokenId, uint256 debt)\n        internal\n        view\n        returns (bool isHealthy, uint256 fullValue, uint256 collateralValue, uint256 feeValue)\n    {\n        (fullValue, feeValue,,) = oracle.getValue(tokenId, address(asset));\n        uint256 collateralFactorX32 = _calculateTokenCollateralFactorX32(tokenId);\n        collateralValue = fullValue.mulDiv(collateralFactorX32, Q32);\n        isHealthy = collateralValue >= debt;\n    }\n\n    function _convertToShares(uint256 amount, uint256 exchangeRateX96, Math.Rounding rounding)\n        internal\n        pure\n        returns (uint256)\n    {\n        return amount.mulDiv(Q96, exchangeRateX96, rounding);\n    }\n\n    function _convertToAssets(uint256 shares, uint256 exchangeRateX96, Math.Rounding rounding)\n        internal\n        pure\n        returns (uint256)\n    {\n        return shares.mulDiv(exchangeRateX96, Q96, rounding);\n    }\n\n    function _addTokenToOwner(address to, uint256 tokenId) internal {\n        ownedTokensIndex[tokenId] = ownedTokens[to].length;\n        ownedTokens[to].push(tokenId);\n        tokenOwner[tokenId] = to;\n    }\n\n    function _removeTokenFromOwner(address from, uint256 tokenId) internal {\n        uint256 lastTokenIndex = ownedTokens[from].length - 1;\n        uint256 tokenIndex = ownedTokensIndex[tokenId];\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = ownedTokens[from][lastTokenIndex];\n            ownedTokens[from][tokenIndex] = lastTokenId;\n            ownedTokensIndex[lastTokenId] = tokenIndex;\n        }\n        ownedTokens[from].pop();\n        // Note that ownedTokensIndex[tokenId] is not deleted. There is no need to delete it - gas optimization\n        delete tokenOwner[tokenId]; // Remove the token from the token owner mapping\n    }\n}"
}