ETH Price: $3,185.41 (-0.79%)

Contract

0xfC18929d3E511043b89086eA0Fc690e1282B5791

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Advanced mode:
Parent Transaction Hash Block From To
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
EverlongLeverageRouter

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 1 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {LeverageRouter, IPositionManager, ILSTCollateralVault, IERC20, SwappersLib, SafeERC20} from "src/periphery/prop/base/LeverageRouter.sol";
import {IEverlongALM} from "src/interfaces/core/alm/IEverlongALM.sol";
import {IALMPeriphery} from "src/interfaces/periphery/common/IALMPeriphery.sol";

/**
 * @title EverlongLeverageRouter
 * @author Everlong Team
 * @notice This contract enables opening and increasing leveraged CDP positions using DebtToken's flash loans.
 * @dev Whitelisted to not pay flashloan fees, and whitelisted as periphery contract to manage positions on behalf of the user.
 * @dev Assumes the collateral asset is an Everlong Vault ALM
 */
contract EverlongLeverageRouter is LeverageRouter {
    using SafeERC20 for IERC20;

    IALMPeriphery public almPeriphery;

    uint256 constant RAD = 1e27;

    constructor(address _borrowerOperations, address _debtToken, address _priceFeed, address _core, address _everlongCore, address[] memory _initialSwapRouters, address _almPeriphery)
        LeverageRouter(_borrowerOperations, _debtToken, _priceFeed, _core, _everlongCore, _initialSwapRouters)
    {
        almPeriphery = IALMPeriphery(_almPeriphery);
    }

    function _transferFromAsset(address collVaultAsset, address account, uint256 margin) internal override {
        address asset = _nonDebtTokenToken(collVaultAsset);

        IERC20(asset).safeTransferFrom(account, address(this), margin);
    }

    /// @dev Deposit debt token flash loaned and margin deposited to the Alpha Pro Vault, no swap needed
    function _swapAndWrap(
        IPositionManager positionManager,
        address account,
        PositionLoopingParams memory params,
        address collVaultAsset,
        address collVault
    ) internal override returns (uint256 collVaultSharesMinted) {
        (uint256 prevColl, uint256 prevDebt) = positionManager.getPositionCollAndDebt(account);
    
        uint256 tokenOutReceived = _swapAndWrapCore(
            positionManager,
            account,
            collVaultAsset,
            params
        );

        if (tokenOutReceived < params.debtTokenToColl.outputMin) {
            revert InsufficientAssetReceived(tokenOutReceived, params.debtTokenToColl.outputMin);
        }
    
        (uint256 newColl, uint256 newDebt) = positionManager.getPositionCollAndDebt(account);
        if (newColl != prevColl || newDebt != prevDebt) {
            revert DebtOrCollateralChanged(newColl, newDebt, prevColl, prevDebt);
        }
    
        IERC20(collVaultAsset).approve(collVault, tokenOutReceived);
        collVaultSharesMinted = ILSTCollateralVault(collVault).deposit(tokenOutReceived, address(this));
    }

    function _swapAndWrapCore(
        IPositionManager positionManager,
        address account,
        address collVaultAsset,
        PositionLoopingParams memory params
    ) private returns (uint256 tokenOutReceived) {
        /// @dev swapParams must be debtTokenToVolatile if 'predominantVolatileRatio' is true, otherwise margin (volatile) to debtToken
        (DexAggregatorParams memory swapParams, uint256 toSwap, uint256 min0, uint256 min1, bool predominantVolatileRatio) =
            abi.decode(params.debtTokenToColl.dexCalldata, (DexAggregatorParams, uint256, uint256, uint256, bool));

        /// increaseLeverage or user deposit when the BTC ratio is above 50%
        address nonDebtToken = _nonDebtTokenToken(collVaultAsset);
        if (predominantVolatileRatio) {
            params.marginCollAmount += _swap(
                positionManager,
                account,
                swapParams,
                address(debtToken),
                nonDebtToken,
                toSwap
            );
        } else {
            _swap(
                positionManager,
                account,
                swapParams,
                nonDebtToken,
                address(debtToken),
                toSwap
            );
            params.marginCollAmount -= toSwap;
        }

        tokenOutReceived = _wrapALMVault(
            collVaultAsset,
            params.marginCollAmount,
            min0,
            min1
        );
    }

    function _wrapALMVault(
        address collVaultAsset,
        uint256 marginAmount,
        uint256 minToken0Amount,
        uint256 minToken1Amount
    ) internal returns (uint256 tokenOutReceived) {
        uint256 prevTokenOutBalance = IERC20(collVaultAsset).balanceOf(address(this));

        address token0 = IEverlongALM(collVaultAsset).token0();
        address token1 = IEverlongALM(collVaultAsset).token1();

        // token 0 to token 1 ratio
        uint256 ratioRad = almPeriphery.getVaultPositionsRatio(collVaultAsset);
        bool isDebtTokenToken0 = IEverlongALM(collVaultAsset).token0() == address(debtToken);

        // @dev Clamps 'debtTokenAmount' based on volatile token 'marginAmount'
        // Remaining debt token amount can be used to repay part of the debt
        // If the debt token available is not enough, it will revert, means the offchain 'flashloanDebtTokenAmount' calculation is incorrect
        uint256 debtTokenAmount;
        if (isDebtTokenToken0) {
            debtTokenAmount = marginAmount * ratioRad / RAD;
        } else {
            debtTokenAmount = marginAmount * RAD / ratioRad;
        }

        uint256 token0Amount = isDebtTokenToken0 ? debtTokenAmount : marginAmount;
        uint256 token1Amount = isDebtTokenToken0 ? marginAmount : debtTokenAmount;

        address asset = isDebtTokenToken0 ? token1 : token0;
        debtToken.approve(collVaultAsset, debtTokenAmount);
        IERC20(asset).safeIncreaseAllowance(collVaultAsset, marginAmount);
        IEverlongALM(collVaultAsset).deposit(token0Amount, token1Amount, minToken0Amount, minToken1Amount, address(this));

        tokenOutReceived = IERC20(collVaultAsset).balanceOf(address(this)) - prevTokenOutBalance;
    }

    function _nonDebtTokenToken(address collVaultAsset) internal view returns (address) {
        address token0 = address(IEverlongALM(collVaultAsset).token0());
        address token1 = address(IEverlongALM(collVaultAsset).token1());

        return token0 == address(debtToken) ? token1 : token0;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ILSTCollateralVault} from "src/interfaces/utils/ILSTCollateralVault.sol";
import {IBorrowerOperations} from "src/interfaces/utils/IBorrowerOperations.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {ICore} from "src/interfaces/utils/ICore.sol";
import {ILeverageRouter} from "src/interfaces/periphery/prop/base/ILeverageRouter.sol";
import {IDebtToken} from "src/interfaces/utils/IDebtToken.sol";
import {IPositionManager} from "src/interfaces/utils/IPositionManager.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {UtilsLib} from "src/libraries/UtilsLib.sol";
import {SwappersLib} from "src/libraries/SwappersLib.sol";
import {PropMath} from "src/libraries/PropMath.sol";

/**
 * @title LeverageRouter
 * @author Everlong Team
 * @notice This contract enables opening and increasing leveraged CDP positions using DebtToken's flash loans.
 * @dev Whitelisted to not pay flashloan fees, and whitelisted as periphery contract to manage positions on behalf of the user.
 */
contract LeverageRouter is ILeverageRouter {
    using SafeERC20 for IERC20;
    using UtilsLib for bytes;
    using Math for uint256;

    bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
    uint256 constant WAD = 1e18;
    uint256 constant BP = 1e4;

    IBorrowerOperations public immutable borrowerOperations;
    IEverlongCore public immutable everlongCore;
    ICore public immutable core;
    IDebtToken public immutable debtToken;
    IPriceFeed public immutable priceFeed;

    SwappersLib.SwapperData internal swapperData;

    modifier nonReentrant() {
        ReentrancyGuardLib._guard();
        _;
        ReentrancyGuardLib._unlockGuard();
    }

    modifier onlyThis() {
        // Only callable if inside a nonReentrant lock
        ReentrancyGuardLib._internalGuard();
        _;
    }

    modifier onlyOwner() {
        if (msg.sender != everlongCore.owner()) {
            revert NotOwner(msg.sender);
        }
        _;
    }

    constructor(address _borrowerOperations, address _debtToken, address _priceFeed, address _core, address _everlongCore, address[] memory _initialSwapRouters) {
        if (_borrowerOperations == address(0) || _debtToken == address(0) || _priceFeed == address(0) || _core == address(0) || _everlongCore == address(0)) {
            revert ZeroAddress();
        }

        borrowerOperations = IBorrowerOperations(_borrowerOperations);
        everlongCore = IEverlongCore(_everlongCore);
        core = ICore(_core);
        debtToken = IDebtToken(_debtToken);
        priceFeed = IPriceFeed(_priceFeed);

        // add routers on constructor
        for (uint256 i; i < _initialSwapRouters.length; i++) {
            SwappersLib.addWhitelistedSwapper(swapperData, _initialSwapRouters[i], true);
        }
    }

    /// @inheritdoc ILeverageRouter
    function automaticLoopingOpenPosition(IPositionManager positionManager, PositionLoopingParams calldata positionLoopingParams)
        external
        nonReentrant
    {
        bytes memory data = abi.encode(Action.OpenPosition, address(positionManager), positionLoopingParams, msg.sender);

        uint256 flashLoanDebtTokenAmount = _getFlashLoanDebtTokenAmount(positionManager, positionLoopingParams);

        if (
            !debtToken.flashLoan(
                IERC3156FlashBorrower(address(this)), address(debtToken), flashLoanDebtTokenAmount, data
            )
        ) {
            revert FlashLoanFailed();
        }
    }

    /// @inheritdoc ILeverageRouter
    function automaticLoopingAddCollateral(IPositionManager positionManager, PositionLoopingParams calldata positionLoopingParams)
        external
        nonReentrant
    {
        bytes memory data = abi.encode(Action.IncreaseColl, address(positionManager), positionLoopingParams, msg.sender);

        uint256 flashLoanDebtTokenAmount = _getFlashLoanDebtTokenAmount(positionManager, positionLoopingParams);

        if (
            !debtToken.flashLoan(
                IERC3156FlashBorrower(address(this)), address(debtToken), flashLoanDebtTokenAmount, data
            )
        ) {
            revert FlashLoanFailed();
        }
    }

    function _getFlashLoanDebtTokenAmount(IPositionManager, PositionLoopingParams memory positionLoopingParams) internal view virtual returns (uint256) {
        return positionLoopingParams.flashloanDebtTokenAmount;
    }

    function onFlashLoan(address initiator, address, /*token*/ uint256 amount, uint256, /*fee*/ bytes calldata data)
        external
        onlyThis
        returns (bytes32)
    {
        if (msg.sender != address(debtToken) || initiator != address(this)) revert NotDebtToken(msg.sender);

        (Action action, address positionManager, PositionLoopingParams memory params, address account) =
            abi.decode(data, (Action, address, PositionLoopingParams, address));

        _processFlashLoan(action, positionManager, params, account, amount);

        return _RETURN_VALUE;
    }

    /// @inheritdoc ILeverageRouter
    function claimLockedTokens(IERC20[] calldata tokens, uint256[] calldata amounts) external onlyOwner {
        uint256 length = tokens.length;
        for (uint256 i; i < length; ++i) {
            if (address(tokens[i]) == address(0)) {
                (bool success,) = everlongCore.feeReceiver().call{value: amounts[i]}("");
                if (!success) {
                    revert NativeTransferFailed();
                }
            } else {
                tokens[i].safeTransfer(everlongCore.feeReceiver(), amounts[i]);
            }
        }
    }

    /// @inheritdoc ILeverageRouter
    function calculateDebtAmount(
        IPositionManager positionManager,
        address position,
        uint256 marginInAssets,
        uint256 leverage,
        uint256 minimumCR,
        bool isRecoveryMode
    ) external view returns (uint256 debtAmount) {
        if (leverage <= BP) revert("Leverage must be greater than 1");

        LeverageMemory memory m;

        address collVault = positionManager.collateralToken();
        (m.currentColl, m.currentDebt) = positionManager.getPositionCollAndDebt(position);
        m.collVaultPrice = priceFeed.fetchPrice(collVault);
        m.prevICR = (m.currentColl != 0) ? PropMath._computeCR(m.currentColl, m.currentDebt, m.collVaultPrice) : 0;
        m.marginInCollVault = marginInAssets != 0 ? ILSTCollateralVault(collVault).previewDeposit(marginInAssets) : 0;

        {
            uint256 maxLeverage = calculateMaxLeverage(
                m.currentColl,
                m.currentDebt,
                m.marginInCollVault,
                m.collVaultPrice,
                minimumCR
            );
            if (leverage > maxLeverage) revert LeverageExceeded(leverage, maxLeverage);
        }

        m.additionalCollateral = (m.currentColl + m.marginInCollVault) * (leverage - BP) / BP;

        if (m.additionalCollateral == 0) revert ZeroCollateral();

        /// @dev Divided by debt token price to increase precision of debt token needed for the debt token->collateral swap
        debtAmount = m.additionalCollateral * m.collVaultPrice / priceFeed.fetchPrice(address(debtToken));

        _check(positionManager, m, debtAmount, minimumCR, isRecoveryMode);
    }

    /// @inheritdoc ILeverageRouter
    function calculateMaxLeverage(
        uint256 currentColl,
        uint256 currentDebt,
        uint256 margin,
        uint256 price,
        uint256 minimumCR
    ) public pure returns (uint256 maxLeverageInBp) {
        uint256 baseCollValue = (currentColl + margin) * price / WAD;

        if (baseCollValue <= (minimumCR * currentDebt) / WAD) return 0;

        uint256 numerator = (baseCollValue - currentDebt) * minimumCR / WAD;
        uint256 denominator = (minimumCR - WAD) * baseCollValue / WAD;
        maxLeverageInBp = numerator * BP / denominator;
    }

    function _processFlashLoan(
        Action action,
        address positionManager,
        PositionLoopingParams memory params,
        address account,
        uint256 debtTokenFlashLoaned
    ) private {
        uint256 prevStuckedDebtToken = debtToken.balanceOf(address(this)) - debtTokenFlashLoaned;
        address collVault = IPositionManager(positionManager).collateralToken();
        address asset = ILSTCollateralVault(collVault).asset();

        if (params.marginCollAmount != 0) {
            _transferFromAsset(asset, account, params.marginCollAmount);
        }

        uint256 collVaultShares =
            _swapAndWrap(IPositionManager(positionManager), account, params, asset, collVault);

        /// @dev All debt token remaining is because it is stucked, which means we can productively use it to payback part of the flashloan
        uint256 additionalStuckedDebtToken = debtToken.balanceOf(address(this)) - prevStuckedDebtToken;
        uint256 totalDebtTokenToPayback = debtTokenFlashLoaned - additionalStuckedDebtToken;
        if (action == Action.OpenPosition) {
            _openPosition(positionManager, account, collVault, params.positionParams, collVaultShares, totalDebtTokenToPayback);

            emit AutomaticLoopingOpenPosition(
                positionManager,
                account,
                params.marginCollAmount,
                collVaultShares,
                debtTokenFlashLoaned
            );
        } else {
            _increaseCollateral(positionManager, account, collVault, params.positionParams, collVaultShares, totalDebtTokenToPayback);

            emit AutomaticLoopingAddCollateral(
                positionManager,
                account,
                params.marginCollAmount,
                collVaultShares,
                debtTokenFlashLoaned
            );
        }

        debtToken.approve(msg.sender, debtTokenFlashLoaned);
    }

    function _transferFromAsset(address asset, address account, uint256 margin) internal virtual {
        IERC20(asset).safeTransferFrom(account, address(this), margin);
    }

    function _openPosition(
        address positionManager,
        address account,
        address collVault,
        PositionParams memory params,
        uint256 collAmount,
        uint256 debtTokenFlashLoaned
    ) private {
        ILSTCollateralVault(collVault).approve(address(borrowerOperations), collAmount);

        borrowerOperations.openPosition(
            positionManager,
            account,
            params.maxFeePercentage,
            collAmount,
            debtTokenFlashLoaned,
            params.upperHint,
            params.lowerHint
        );
    }

    function _increaseCollateral(
        address positionManager,
        address account,
        address collVault,
        PositionParams memory params,
        uint256 collAmount,
        uint256 debtTokenFlashLoaned
    ) private {
        ILSTCollateralVault(collVault).approve(address(borrowerOperations), collAmount);
        borrowerOperations.adjustPosition(
            positionManager,
            account,
            params.maxFeePercentage,
            collAmount,
            0,
            debtTokenFlashLoaned,
            true,
            params.upperHint,
            params.lowerHint
        );
    }

    function _swap(IPositionManager positionManager, address account, DexAggregatorParams memory params, address tokenIn, address tokenOut, uint256 amount)
        internal
        returns (uint256 tokenOutReceived)
    {
        (uint256 prevColl, uint256 prevDebt) = positionManager.getPositionCollAndDebt(account);

        uint256 prevTokenOutBalance = IERC20(tokenOut).balanceOf(address(this));

        IERC20(tokenIn).safeIncreaseAllowance(params.swapRouter, amount);
        SwappersLib.executeSwap(swapperData, params.swapRouter, params.dexCalldata);

        tokenOutReceived = IERC20(tokenOut).balanceOf(address(this)) - prevTokenOutBalance;

        (uint256 newColl, uint256 newDebt) = positionManager.getPositionCollAndDebt(account);

        if (tokenOutReceived < params.outputMin) {
            revert InsufficientAssetReceived(tokenOutReceived, params.outputMin);
        }
        if (newColl != prevColl || newDebt != prevDebt) {
            revert DebtOrCollateralChanged(newColl, newDebt, prevColl, prevDebt);
        }
    }

    /// @dev Swaps debt token into a collateral asset and deposits the collateral asset into the collVault
    function _swapAndWrap(
        IPositionManager positionManager,
        address account,
        PositionLoopingParams memory params,
        address asset,
        address collVault
    ) internal virtual returns (uint256 collVaultSharesMinted) {
        uint256 collAssetReceived = _swap(positionManager, account, params.debtTokenToColl, address(debtToken), asset, params.flashloanDebtTokenAmount) + params.marginCollAmount;

        IERC20(asset).safeIncreaseAllowance(collVault, collAssetReceived);
        collVaultSharesMinted = ILSTCollateralVault(collVault).deposit(collAssetReceived, address(this));
    }

    function _check(
        IPositionManager positionManager,
        LeverageMemory memory m,
        uint256 debtAmount,
        uint256 minimumCR,
        bool isRecoveryMode
    ) private view {
        uint256 gasCompensation = borrowerOperations.DEBT_GAS_COMPENSATION();
        uint256 debtGasCompensation = m.currentColl == 0 ? gasCompensation : 0;
        uint256 borrowingRate = isRecoveryMode ? 0 : positionManager.getBorrowingRateWithDecay();

        uint256 additionalCompositeDebt = (debtAmount * (borrowingRate + WAD) / WAD);
        uint256 totalNetDebt = m.currentDebt + additionalCompositeDebt;
        uint256 totalCompositeDebt = totalNetDebt + debtGasCompensation;
        uint256 totalCollateral = m.currentColl + m.marginInCollVault + m.additionalCollateral;
        uint256 resultingICR = totalCollateral * m.collVaultPrice / totalCompositeDebt;

        _checkValidCR(positionManager, minimumCR, isRecoveryMode, m, additionalCompositeDebt + debtGasCompensation, resultingICR);

        uint256 minNetDebt = borrowerOperations.minNetDebt();
        if (totalNetDebt - gasCompensation < minNetDebt) revert DebtTooLow(totalNetDebt, minNetDebt);
    }

    /// @dev Validates the minimumCR.
    /// @dev This is  used in the `calculateDebtAmount` function to check if the minimumCR value is valid.
    function _checkValidCR(
        IPositionManager positionManager,
        uint256 minimumCR,
        bool isRecoveryMode,
        LeverageMemory memory m,
        uint256 additionalDebt,
        uint256 resultingICR
    ) private view {
        if (resultingICR < minimumCR) revert PositionBelowMinimumCR(resultingICR, minimumCR);

        if (isRecoveryMode) {
            if (resultingICR < core.CCR()) revert CollateralRatioBelowCCR();
            if (resultingICR < m.prevICR) revert PositionNotImprovedUnderRM(resultingICR, m.prevICR);
        } else {
            if (resultingICR < positionManager.MCR()) revert CollateralRatioBelowMCR();

            (uint256 entireSystemPricedColl, uint256 entireSystemDebt) = borrowerOperations.getGlobalSystemBalances();
            entireSystemPricedColl += (m.additionalCollateral + m.marginInCollVault) * m.collVaultPrice;
            entireSystemDebt += additionalDebt;

            uint256 newTCR = PropMath._computeCR(entireSystemPricedColl, entireSystemDebt);
            uint256 CCR = core.CCR();
            if (newTCR < CCR) revert RecoveryMode(newTCR, CCR);
        }
    }

    function addWhitelistedSwapper(address _swapRouter, bool status) external onlyOwner {
        SwappersLib.addWhitelistedSwapper(swapperData,_swapRouter, status);
    }
}

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.26;

import {IERC20, SafeERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {IALMGetters} from "src/core/alm/getters/ALMGetters.sol";
import {SwappersLib} from "src/libraries/SwappersLib.sol";

interface IEverlongALM {

    /**
     * @param pool Underlying Uniswap V3 pool address
     * @param manager Address of manager who can set parameters and call rebalance
     * @param rebalanceDelegate Address of an additional wallet that can call rebalance
     * @param maxTotalSupply Cap on the total supply of vault shares
     * @param wideRangeWeight Proportion of liquidity in wide range multiplied by 1e6
     * @param wideThreshold Half of the wide order width in ticks
     * @param baseThreshold Half of the base order width in ticks
     * @param limitThreshold Limit order width in ticks
     * @param period Can only rebalance if this length of time (in seconds) has passed
     * @param minTickMove Can only rebalance if price has moved at least this much
     * @param maxTwapDeviation Max deviation (in ticks) from the TWAP during rebalance or deposit
     * @param twapDuration TWAP duration in seconds for maxTwapDeviation check
     * @param protocolFee % Fee charged to cover protocol costs, in BP
     * @param name name of the vault to be created
     * @param symbol symbol of the vault to be created
     */
    struct VaultParams {
        address owner;
        address pool;
        address priceFeed;
        address manager;
        address rebalanceDelegate;
        address depositDelegate;
        uint24 protocolFee; // In 1e6
        uint256 maxTotalSupply;
        uint24 wideRangeWeight; // In 1e6
        int24 wideThreshold;
        int24 baseThreshold;
        int24 limitThreshold;
        uint32 period;
        int24 minTickMove;
        int24 maxTwapDeviation;
        uint32 twapDuration;
        string name;
        string symbol;
        uint24 swapDeviationThreshold; // In 1e6
        uint24 ratioDeviationThreshold; // In 1e6
        uint24 rebalanceDelegateCooldown; // In seconds
        uint24 maxRatioDeviationThresholdIncrease; // In 1e6
        address[] initialWhitelistedSwappers;
        address getters;
    }

    struct EverlongALMStorage {
        address owner;
        IUniswapV3Pool pool;
        IPriceFeed priceFeed;
        IERC20 token0;
        IERC20 token1;

        address manager;
        address pendingManager;
        address rebalanceDelegate;
        address depositDelegate;
        uint256 maxTotalSupply;
        uint128 accruedProtocolFees0;
        uint128 accruedProtocolFees1;

        uint32 period;
        uint24 protocolFee;
        uint24 pendingProtocolFee;
        uint24 wideRangeWeight;
        int24 baseThreshold;
        int24 limitThreshold;
        int24 wideThreshold;
        int24 minTickMove;
        int24 tickSpacing;
        int24 maxTwapDeviation;

        uint32 twapDuration;
        int24 wideLower;
        int24 wideUpper;
        int24 baseLower;
        int24 baseUpper;
        int24 limitLower;
        int24 limitUpper;
        int24 lastTick;
        uint40 lastTimestamp;

        int24 maxTick;
        uint24 swapDeviationThreshold; // In 1e6
        uint24 ratioDeviationThreshold; // In 1e6
        uint24 rebalanceDelegateCooldown; // In seconds
        uint40 lastRatioDeviationThresholdUpdateTimestamp;
        uint24 maxRatioDeviationThresholdIncrease; // In 1e6

        SwappersLib.SwapperData swapperData;
        IALMGetters getters;
    }
    
    struct BurnContext {
        uint256 wideAmount0;
        uint256 wideAmount1;
        uint256 baseAmount0;
        uint256 baseAmount1;
        uint256 limitAmount0;
        uint256 limitAmount1;
    }

    struct ExternalRebalanceParams {
        bool isZeroForOne;
        uint256 sentAmount;
        address swapper;
        bytes payload;
        uint256 minRebalanceOut;
    }

    function deposit(uint256, uint256, uint256, uint256, address) external returns (uint256, uint256, uint256);

    function withdraw(uint256, uint256, uint256, address) external returns (uint256, uint256);

    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory values);

    function getTotalAmounts() external view returns (uint256, uint256);

    function getBalance0() external view returns (uint256);

    function getBalance1() external view returns (uint256);

    function rebalance() external;

    // state variables
    function pool() external view returns (IUniswapV3Pool);

    function protocolFee() external view returns (uint24);

    function getPositions() external view returns (int24[2][3] memory);

    function token0() external view returns (address);

    function token1() external view returns (address);

    function totalSupply() external view returns (uint256);

    function balanceOf(address) external view returns (uint256);

    event Deposit(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event CollectFees(
        uint256 feesToVault0,
        uint256 feesToVault1,
        uint256 feesToProtocol0,
        uint256 feesToProtocol1
    );
    event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
    event CollectProtocol(uint256 amount0, uint256 amount1);

    event UpdateManager(address manager);
    event UpdatePendingManager(address manager);
    event UpdateRebalanceDelegate(address delegate);
    event UpdateDepositDelegate(address delegate);
    event UpdateProtocolFee(uint24 protocolFee);
    event UpdateBaseThreshold(int24 threshold);
    event UpdateLimitThreshold(int24 threshold);
    event UpdateWideRangeWeight(uint24 weight);
    event UpdateWideThreshold(int24 threshold);
    event UpdatePeriod(uint32 period);
    event UpdateMinTickMove(int24 minTickMove);
    event UpdateMaxTwapDeviation(int24 maxTwapDeviation);
    event UpdateTwapDuration(uint32 twapDuration);
    event UpdateMaxTotalSupply(uint256 maxTotalSupply);
    event UpdateSwapDeviationThreshold(uint24 swapDeviationThreshold);
    event UpdateRatioDeviationThreshold(uint24 ratioDeviationThreshold);
    event UpdateRebalanceDelegateCooldown(uint24 rebalanceDelegateCooldown);
    event UpdateMaxRatioDeviationThresholdIncrease(uint24 maxRatioDeviationThresholdIncrease);
    event UpdateGetters(address getters);

    // Errors
    error EV_ZeroAddress();
    error EV_WideRangeWeight();
    error EV_MinTickMove();
    error EV_MaxTwapDeviation();
    error EV_TwapDuration();
    error EV_ThresholdsCannotBeSame();
    error EV_ThresholdNotPositive();
    error EV_ThresholdNotMultipleOfTickSpacing();
    error EV_NotDepositDelegate();
    error EV_ZeroDepositAmount();
    error EV_InvalidRecipient();
    error EV_ZeroShares();
    error EV_Amount0Min();
    error EV_Amount1Min();
    error EV_MaxTotalSupply();
    error EV_NotManagerOrRebalanceDelegate();
    error EV_NotPool();
    error EV_NotGovernance();
    error EV_ProtocolFee();
    error EV_ProtocolFeeTooHigh();
    error EV_NotManager();
    error EV_SweepToken();
    error EV_NotPendingManager();
    error EV_InsufficientBalance(uint256 available, uint256 required);
    error EV_SwapDeviationThreshold();
    error EV_RatioDeviationThreshold();
    error EV_RebalanceDelegateCooldown();
    error EV_MaxRatioDeviationThresholdIncrease();
    error EV_RatioDeviationThresholdIncreaseExceeded(uint24 proposedThreshold, uint256 maxAllowedThreshold);
}

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.26;


interface IALMPeriphery {
    function getVaultPositionsRatio(address vaultAddress) external view returns (uint256 ratioRad);
    function getVaultPositions(address vault) external view returns (uint256 reserves0, uint256 reserves1);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

File 6 of 59 : IERC3156FlashBorrower.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC3156 FlashBorrower, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashBorrower {
    /**
     * @dev Receive a flash loan.
     * @param initiator The initiator of the loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param fee The additional amount of tokens to repay.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     * @return The keccak256 hash of "IERC3156FlashBorrower.onFlashLoan"
     */
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IBaseCollateralVault} from "src/interfaces/utils/IBaseCollateralVault.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";

interface ILSTCollateralVault is IBaseCollateralVault {
    struct LSTCollVaultStorage {
        uint16 minPerformanceFee;
        uint16 maxPerformanceFee;
        uint16 performanceFee; // over yield, in basis points
        /// @dev We currently don't know the lstVault implementation, but if it were to be possible for them to remove tokens from the rewardTokens
        /// There would be no need to remove it from here since the amounts should continue being accounted for in the virtual balance
        EnumerableSet.AddressSet rewardedTokens;

        address _lstVault;
        address mainRewardTokenVault;
        address mainRewardToken;
        address lstWrapper;
        uint96 lastUpdate;

        mapping(address tokenIn => uint) threshold;
    }

    struct LSTInitParams {
        BaseInitParams _baseParams;
        uint16 _minPerformanceFee;
        uint16 _maxPerformanceFee;
        uint16 _performanceFee; // over yield, in basis points
        address _lstVault;
        address _mainRewardTokenVault;
        address _lstWrapper;
    }

    struct RebalanceParams {
        address sentCurrency; 
        uint sentAmount; 
        address swapper;
        bytes payload;
    }

    function rebalance(RebalanceParams calldata p) external;

    function pullRewards() external;

    function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external;

    function internalizeDonations(address[] memory tokens, uint128[] memory amounts) external;

    function setPairThreshold(address tokenIn, uint thresholdInBP) external;

    function setPerformanceFee(uint16 _performanceFee) external;
    function setWithdrawFee(uint16 _withdrawFee) external;

    function getBalance(address token) external view returns (uint);

    function getBalanceOfWithFutureEmissions(address token) external view returns (uint);

    function getFullProfitUnlockTimestamp(address token) external view returns (uint);

    function unlockRatePerSecond(address token) external view returns (uint);

    function getLockedEmissions(address token) external view returns (uint);

    function getPerformanceFee() external view returns (uint16);


    function rewardedTokens() external view returns (address[] memory);

    function lstVault() external view returns (address);

    function mainRewardToken() external view returns (address);

    function mainRewardTokenVault() external view returns (address);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {ICore} from "./ICore.sol";

interface IBorrowerOperations {
    struct Balances {
        uint256[] collaterals;
        uint256[] debts;
        uint256[] prices;
    }

    event BorrowingFeePaid(address indexed borrower, uint256 amount);
    event CollateralConfigured(address positionManager, address collateralToken);
    event PositionCreated(address indexed _borrower, uint256 arrayIndex);
    event PositionManagerRemoved(address positionManager);
    event PositionUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);

    function addColl(
        address positionManager,
        address account,
        uint256 _collateralAmount,
        address _upperHint,
        address _lowerHint
    ) external;

    function adjustPosition(
        address positionManager,
        address account,
        uint256 _maxFeePercentage,
        uint256 _collDeposit,
        uint256 _collWithdrawal,
        uint256 _debtChange,
        bool _isDebtIncrease,
        address _upperHint,
        address _lowerHint
    ) external;

    function closePosition(address positionManager, address account) external;

    function configureCollateral(address positionManager, address collateralToken) external;

    function fetchBalances() external view returns (Balances memory balances);

    function getGlobalSystemBalances() external view returns (uint256 totalPricedCollateral, uint256 totalDebt);

    function getTCR() external view returns (uint256 globalTotalCollateralRatio);

    function openPosition(
        address positionManager,
        address account,
        uint256 _maxFeePercentage,
        uint256 _collateralAmount,
        uint256 _debtAmount,
        address _upperHint,
        address _lowerHint
    ) external;

    function removePositionManager(address positionManager) external;

    function repayDebt(
        address positionManager,
        address account,
        uint256 _debtAmount,
        address _upperHint,
        address _lowerHint
    ) external;

    function setDelegateApproval(address _delegate, bool _isApproved) external;

    function setMinNetDebt(uint256 _minNetDebt) external;

    function withdrawColl(
        address positionManager,
        address account,
        uint256 _collWithdrawal,
        address _upperHint,
        address _lowerHint
    ) external;

    function withdrawDebt(
        address positionManager,
        address account,
        uint256 _maxFeePercentage,
        uint256 _debtAmount,
        address _upperHint,
        address _lowerHint
    ) external;

    function positionManagers(uint256) external view returns (address);

    function checkRecoveryMode(uint256 TCR) external view returns (bool);

    function DEBT_GAS_COMPENSATION() external view returns (uint256);

    function DECIMAL_PRECISION() external view returns (uint256);

    function PERCENT_DIVISOR() external view returns (uint256);

    function CORE() external view returns (ICore);

    function debtToken() external view returns (address);

    function factory() external view returns (address);

    function getCompositeDebt(uint256 _debt) external view returns (uint256);

    function guardian() external view returns (address);

    function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);

    function minNetDebt() external view returns (uint256);

    function owner() external view returns (address);

    function positionManagersData(address) external view returns (address collateralToken, uint16 index);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

/**
 * @title EverlongCore
 * @author Everlong Labs
 * @notice Single source of truth across all Everlong contracts for key administrative data
 */
interface IEverlongCore {
    function owner() external view returns (address);
    function feeReceiver() external view returns (address);
    function priceFeed() external view returns (address);

    function setFeeReceiver(address _feeReceiver) external;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface ICore {

    // --- Public variables ---
    function metaCore() external view returns (address);
    function startTime() external view returns (uint256);
    function CCR() external view returns (uint256);
    function dmBootstrapPeriod() external view returns (uint64);
    function isPeriphery(address peripheryContract) external view returns (bool);

    // --- External functions ---

    function setPeripheryEnabled(address _periphery, bool _enabled) external;
    function setPMBootstrapPeriod(address dm, uint64 _bootstrapPeriod) external;
    function setNewCCR(uint256 _CCR) external;

    function priceFeed() external view returns (address);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function guardian() external view returns (address);
    function feeReceiver() external view returns (address);
    function paused() external view returns (bool);
    function lspBootstrapPeriod() external view returns (uint64);
    function getLspEntryFee(address rebalancer) external view returns (uint16);
    function getLspExitFee(address rebalancer) external view returns (uint16);
    function interestProtocolShare() external view returns (uint16);
    function defaultInterestReceiver() external view returns (address);

    // --- Events ---
    event CCRSet(uint256 initialCCR);
    event PMBootstrapPeriodSet(address dm, uint64 bootstrapPeriod);
    event PeripheryEnabled(address indexed periphery, bool enabled);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPositionManager} from "src/interfaces/utils/IPositionManager.sol";

interface ILeverageRouter is IERC3156FlashBorrower {
    enum Action {
        OpenPosition,
        IncreaseColl,
        RepayDebt
    }

    struct PositionParams {
        uint256 maxFeePercentage;
        address upperHint;
        address lowerHint;
    }

    struct DexAggregatorParams {
        bytes dexCalldata;
        uint256 outputMin;
        address swapRouter;
    }

    struct PositionLoopingParams {
        /// @dev the amount of debt token to be borrowed via flashloan
        uint256 flashloanDebtTokenAmount;
        /// @dev the amount of the underlying asset (of CollVault) to be swapped into DebtToken for repayment, along with debtAmount
        uint256 marginCollAmount;
        PositionParams positionParams;
        DexAggregatorParams debtTokenToColl;
    }

    struct LeverageMemory {
        uint256 currentColl;
        uint256 currentDebt;
        uint256 collVaultPrice;
        uint256 prevICR;
        uint256 marginInCollVault;
        uint256 additionalCollateral;
    }

    error NotOwner(address sender);
    error NotDebtToken(address caller);
    error ZeroCollateral();
    error ZeroAddress();
    error FlashLoanFailed();
    error InvalidDexSelector();
    error CollateralRatioBelowCCR();
    error CollateralRatioBelowMCR();
    error InsufficientAssetReceived(uint256 assetReceived, uint256 outputMin);
    error LeverageExceeded(uint256 leverage, uint256 maxLeverage);
    error DebtTooLow(uint256 debtAmount, uint256 minNetDebt);
    error NativeTransferFailed();
    error InsufficientPayBackAmount(uint256 debtTokenBalance, uint256 payBackAmount);
    error PositionBelowMinimumCR(uint256 resultingCR, uint256 minimumCR);
    error RecoveryMode(uint256 newTCR, uint256 CCR);
    error PositionNotImprovedUnderRM(uint256 resultingICR, uint256 prevICR);
    error DebtOrCollateralChanged(
        uint256 currentColl,
        uint256 currentDebt,
        uint256 newColl,
        uint256 newDebt
    );

    event AutomaticLoopingOpenPosition(
        address indexed positionManager,
        address indexed borrower,
        uint256 marginCollAmount,
        uint256 finalCollAmount, // after swapping debtToken to collateral
        uint256 flashloanDebtTokenAmount
    );

    event AutomaticLoopingAddCollateral(
        address indexed positionManager,
        address indexed borrower,
        uint256 marginCollAmount,
        uint256 finalCollAmount, // after swapping debtToken to collateral
        uint256 flashloanDebtTokenAmount
    );

    /**
     * @dev Opens a leveraged position using flashloan, if internal swap has positive slippage, sends extra debt token to the user
     */
    function automaticLoopingOpenPosition(IPositionManager positionManager, PositionLoopingParams calldata positionLoopingParams) external;

    /**
     * @dev Increases a position by adding collateral using flashloan, if internal swap has positive slippage, sends extra debt token to the user
     */
    function automaticLoopingAddCollateral(IPositionManager positionManager, PositionLoopingParams calldata positionLoopingParams)
        external;

    /**
     * @dev Determines the proper amount of debt tokens that can be borrowed based on the provided margin,
     *      desired collateral ratio (CR), and leverage.
     * @param positionManager the address of PositionManager
     * @param position the address of Borrower
     * @param margin the asset amount to be used for the leveraged position, if the position is already opened, it can be 0
     * @param leverage the leverage factor, representing how much the position is amplified relative to the margin and current collateral
     *                 unit is in BP, where 20000 represents 2x leverage.
     * @param minimumCR collateral Ratio to be applied, will be validated against a threshold tolerance of 50bp
     * @param isRecoveryMode a boolean indicating whether the system is in recovery mode
     * @return debtAmount the calculated amount of debt tokens that will be needed to be borrowed
     */
    function calculateDebtAmount(
        IPositionManager positionManager,
        address position,
        uint256 margin,
        uint256 leverage,
        uint256 minimumCR,
        bool isRecoveryMode
    ) external view returns (uint256 debtAmount);

    /**
     * @dev Based on the minimum ICR a position wants to stay, calculates the maximum leverage that can be applied
     * @param currentColl Amount in Collateral Vault in the position
     * @param currentDebt  Amount in Debt in the position
     * @param margin  Amount of margin to be used for the leveraged position, in the Collateral Vault
     * @param price Dollar value of the collateral vault
     * @param minimumCR WAD precision, e.g. 120% = 1.2e18
     */
    function calculateMaxLeverage(
        uint256 currentColl,
        uint256 currentDebt,
        uint256 margin,
        uint256 price,
        uint256 minimumCR
    ) external pure returns (uint256 maxLeverage);

    /// @dev Allows owner to claim any remaining tokens, including ETH, stored in the router contract.
    function claimLockedTokens(IERC20[] calldata tokens, uint256[] calldata amounts) external;

    /// @dev Allows owner to add or remove a swap router from the whitelist.
    function addWhitelistedSwapper(address _swapRouter, bool status) external;
}

File 14 of 59 : IDebtToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 
import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
interface IDebtToken is IERC20 {
    // --- Events ---
    event FlashLoanFeeUpdated(uint256 newFee);

    // --- Public constants ---
    function version() external view returns (string memory);
    function permitTypeHash() external view returns (bytes32);

    // --- Public immutables ---
    function gasPool() external view returns (address);
    function DEBT_GAS_COMPENSATION() external view returns (uint256);

    // --- Public mappings ---
    function liquidStabilityPools(address) external view returns (bool);
    function borrowerOperations(address) external view returns (bool);
    function factories(address) external view returns (bool);
    function peripheries(address) external view returns (bool);
    function positionManagers(address) external view returns (bool);

    // --- External functions ---

    function enablePositionManager(address _positionManager) external;
    function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);
    function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);
    function mint(address _account, uint256 _amount) external;
    function burn(address _account, uint256 _amount) external;
    function decimals() external view returns (uint8);
    function sendToPeriphery(address _sender, uint256 _amount) external;
    function sendToSP(address _sender, uint256 _amount) external;
    function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function maxFlashLoan(address token) external view returns (uint256);
    function flashFee(address token, uint256 amount) external view returns (uint256);
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
    function whitelistLiquidStabilityPoolAddress(address _liquidStabilityPool, bool active) external;
    function whitelistBorrowerOperationsAddress(address _borrowerOperations, bool active) external;
    function whitelistFactoryAddress(address _factory, bool active) external;
    function whitelistPeripheryAddress(address _periphery, bool active) external;
    function whitelistPSM(address, bool) external;
    function setDebtGasCompensation(uint256 _gasCompensation, bool _isFinalValue) external;
    function setFlashLoanFee(uint256 _fee) external;
    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function permit(
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
    function nonces(address owner) external view returns (uint256);
}

File 15 of 59 : IPositionManager.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IFactory} from "src/interfaces/utils/IFactory.sol";

interface IPositionManager {
    event BaseRateUpdated(uint256 _baseRate);
    event CollateralSent(address _to, uint256 _amount);
    event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);
    event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);
    event Redemption(
        address indexed _redeemer,
        uint256 _attemptedDebtAmount,
        uint256 _actualDebtAmount,
        uint256 _collateralSent,
        uint256 _collateralFee
    );
    event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);
    event TotalStakesUpdated(uint256 _newTotalStakes);
    event PositionIndexUpdated(address _borrower, uint256 _newIndex);
    event PositionSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);
    event PositionUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);

    function addCollateralSurplus(address borrower, uint256 collSurplus) external;

    function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);

    function claimCollateral(address borrower, address _receiver) external;

    function closePosition(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;

    function closePositionByLiquidation(address _borrower) external;

    function setCollVaultRouter(address _collVaultRouter) external;

    function collectInterests() external;

    function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);

    function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;

    function fetchPrice() external view returns (uint256);

    function finalizeLiquidation(
        address _liquidator,
        uint256 _debt,
        uint256 _coll,
        uint256 _collSurplus,
        uint256 _debtGasComp,
        uint256 _collGasComp
    ) external;

    function getEntireSystemBalances() external view returns (uint256, uint256, uint256);

    function movePendingPositionRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;

    function openPosition(
        address _borrower,
        uint256 _collateralAmount,
        uint256 _compositeDebt,
        uint256 NICR,
        address _upperHint,
        address _lowerHint
    ) external returns (uint256 stake, uint256 arrayIndex);

    function redeemCollateral(
        uint256 _debtAmount,
        address _firstRedemptionHint,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint256 _partialRedemptionHintNICR,
        uint256 _maxIterations,
        uint256 _maxFeePercentage
    ) external;

    function setAddresses(address _priceFeedAddress, address _sortedPositionsAddress, address _collateralToken) external;

    function setParameters(
        IFactory.DeploymentParams calldata _params
    ) external;

    function setPaused(bool _paused) external;

    function setPriceFeed(address _priceFeedAddress) external;

    function startSunset() external;

    function updateBalances() external;

    function updatePositionFromAdjustment(
        bool _isDebtIncrease,
        uint256 _debtChange,
        uint256 _netDebtChange,
        bool _isCollIncrease,
        uint256 _collChange,
        address _upperHint,
        address _lowerHint,
        address _borrower,
        address _receiver
    ) external returns (uint256, uint256, uint256);

    function DEBT_GAS_COMPENSATION() external view returns (uint256);

    function DECIMAL_PRECISION() external view returns (uint256);

    function L_collateral() external view returns (uint256);

    function L_debt() external view returns (uint256);

    function MCR() external view returns (uint256);

    function PERCENT_DIVISOR() external view returns (uint256);

    function CORE() external view returns (address);

    function SUNSETTING_INTEREST_RATE() external view returns (uint256);

    function Positions(
        address
    )
        external
        view
        returns (
            uint256 debt,
            uint256 coll,
            uint256 stake,
            uint8 status,
            uint128 arrayIndex,
            uint256 activeInterestIndex
        );

    function activeInterestIndex() external view returns (uint256);

    function baseRate() external view returns (uint256);

    function borrowerOperations() external view returns (address);

    function borrowingFeeFloor() external view returns (uint256);

    function collateralToken() external view returns (address);

    function debtToken() external view returns (address);

    function collVaultRouter() external view returns (address);

    function defaultedCollateral() external view returns (uint256);

    function defaultedDebt() external view returns (uint256);

    function getBorrowingFee(uint256 _debt) external view returns (uint256);

    function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);

    function getBorrowingRate() external view returns (uint256);

    function getBorrowingRateWithDecay() external view returns (uint256);

    function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);

    function getEntireDebtAndColl(
        address _borrower
    ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);

    function getEntireSystemColl() external view returns (uint256);

    function getEntireSystemDebt() external view returns (uint256);

    function getNominalICR(address _borrower) external view returns (uint256);

    function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);

    function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);

    function getRedemptionRate() external view returns (uint256);

    function getRedemptionRateWithDecay() external view returns (uint256);

    function getTotalActiveCollateral() external view returns (uint256);

    function getTotalActiveDebt() external view returns (uint256);

    function getPositionCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);

    function getPositionFromPositionOwnersArray(uint256 _index) external view returns (address);

    function getPositionOwnersCount() external view returns (uint256);

    function getPositionStake(address _borrower) external view returns (uint256);

    function getPositionStatus(address _borrower) external view returns (uint256);

    function guardian() external view returns (address);

    function hasPendingRewards(address _borrower) external view returns (bool);

    function interestPayable() external view returns (uint256);

    function interestRate() external view returns (uint256);

    function lastActiveIndexUpdate() external view returns (uint256);

    function lastCollateralError_Redistribution() external view returns (uint256);

    function lastDebtError_Redistribution() external view returns (uint256);

    function lastFeeOperationTime() external view returns (uint256);

    function liquidationManager() external view returns (address);

    function maxBorrowingFee() external view returns (uint256);

    function maxRedemptionFee() external view returns (uint256);

    function maxSystemDebt() external view returns (uint256);

    function minuteDecayFactor() external view returns (uint256);

    function owner() external view returns (address);

    function paused() external view returns (bool);

    function priceFeed() external view returns (address);

    function redemptionFeeFloor() external view returns (uint256);

    function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);

    function sortedPositions() external view returns (address);

    function sunsetting() external view returns (bool);

    function surplusBalances(address) external view returns (uint256);

    function systemDeploymentTime() external view returns (uint256);

    function totalCollateralSnapshot() external view returns (uint256);

    function totalStakes() external view returns (uint256);

    function totalStakesSnapshot() external view returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPriceFeed {
    struct FeedType {
        address spotOracle;
        bool isCollVault;
    }

    event NewOracleRegistered(address token, address chainlinkAggregator, address underlyingDerivative);
    event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);
    event PriceRecordUpdated(address indexed token, uint256 _price);
    event NewCollVaultRegistered(address collVault, bool enable);
    event NewSpotOracleRegistered(address token, address spotOracle);

    function fetchPrice(address _token) external view returns (uint256);

    function getMultiplePrices(address[] memory _tokens) external view returns (uint256[] memory prices);

    function setOracle(
        address _token,
        address _chainlinkOracle,
        uint32 _heartbeat,
        uint16 _staleThreshold,
        address underlyingDerivative
    ) external;

    function whitelistCollateralVault(address _collateralVaultShareToken, bool enable) external;
    
    function setSpotOracle(address _token, address _spotOracle) external;
    
    function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);

    function CORE() external view returns (address);

    function RESPONSE_TIMEOUT() external view returns (uint256);

    function TARGET_DIGITS() external view returns (uint256);

    function guardian() external view returns (address);

    function oracleRecords(
        address
    )
        external
        view
        returns (
        address chainLinkOracle,
        uint8 decimals,
        uint32 heartbeat,
        uint16 staleThreshold,
        address underlyingDerivative
    );

    function isCollVault(address _collateralVaultShareToken) external view returns (bool);

    function isStableBPT(address _oracle) external view returns (bool);

    function isWeightedBPT(address _oracle) external view returns (bool);

    function getSpotOracle(address _token) external view returns (address);

    function feedType(address _token) external view returns (FeedType memory);

    function owner() external view returns (address);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

library ReentrancyGuardLib {
    error Reentrant();
    error ReentrantInternal();

    function _guard() internal {
        bytes4 selector = Reentrant.selector;

        assembly ("memory-safe") {
            if tload(0) {
                mstore(0, selector)
                revert(0, 0x04)
            }
            tstore(0, 1)
        }
    }

    function _unlockGuard() internal {
        // Unlocks the guard, making the pattern composable.
        // After the function exits, it can be called again, even in the same transaction.
        assembly ("memory-safe") {
            tstore(0, 0)
        }
    }

    function _internalGuard() internal {
        bytes4 selector = ReentrantInternal.selector;

        assembly ("memory-safe") {
            switch tload(0) // Reentrancy guard slot
            case 1 { tstore(0, 2) } // Disable internal reentrancies
            default {
                mstore(0, selector)
                revert(0, 0x04)
            }
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

library UtilsLib {

    error DexCalldataTooShort();

    function getSelector(bytes memory data) internal pure returns (bytes4 selector) {
        if (data.length < 4) {
            revert DexCalldataTooShort();
        }
        selector = bytes4(data);
    }

    function bubbleUpRevert(bytes memory reason) internal pure {
        assembly {
            revert(add(reason, 0x20), mload(reason))
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;
import {UtilsLib} from "./UtilsLib.sol";


library SwappersLib {
    using UtilsLib for bytes;

    error SwapperNotWhitelisted();

    event SwapperAdded(address indexed swapRouter, bool status);

    struct SwapperData {
        mapping(address => bool) whitelistedSwappers;
    }

    function addWhitelistedSwapper(SwapperData storage self, address _swapRouter, bool status) internal {
        self.whitelistedSwappers[_swapRouter] = status;

        emit SwapperAdded(_swapRouter, status);
    }

    function executeSwap(SwapperData storage self, address swapRouter, bytes memory dexCalldata) internal {
        if (!self.whitelistedSwappers[swapRouter]) revert SwapperNotWhitelisted();
        
        (bool success, bytes memory retData) = swapRouter.call(dexCalldata);
        if (!success) {
            retData.bubbleUpRevert();
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

library PropMath {
    uint256 internal constant DECIMAL_PRECISION = 1e18;

    /* Precision for Nominal ICR (independent of price). Rationale for the value:
     *
     * - Making it “too high” could lead to overflows.
     * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
     *
     * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,
     * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
     *
     */
    uint256 internal constant NICR_PRECISION = 1e20;

    function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a < _b) ? _a : _b;
    }

    function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a : _b;
    }

    /*
     * Multiply two decimal numbers and use normal rounding rules:
     * -round product up if 19'th mantissa digit >= 5
     * -round product down if 19'th mantissa digit < 5
     *
     * Used only inside the exponentiation, _decPow().
     */
    function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
        uint256 prod_xy = x * y;

        decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;
    }

    /*
     * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
     *
     * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
     *
     * Called by two functions that represent time in units of minutes:
     * 1) PositionManager._calcDecayedBaseRate
     * 2) CommunityIssuance._getCumulativeIssuanceFraction
     *
     * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
     * "minutes in 1000 years": 60 * 24 * 365 * 1000
     *
     * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
     * negligibly different from just passing the cap, since:
     *
     * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
     * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
     */
    function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {
        if (_minutes > 525600000) {
            _minutes = 525600000;
        } // cap to avoid overflow

        if (_minutes == 0) {
            return DECIMAL_PRECISION;
        }

        uint256 y = DECIMAL_PRECISION;
        uint256 x = _base;
        uint256 n = _minutes;

        // Exponentiation-by-squaring
        while (n > 1) {
            if (n % 2 == 0) {
                x = decMul(x, x);
                n = n / 2;
            } else {
                // if (n % 2 != 0)
                y = decMul(x, y);
                x = decMul(x, x);
                n = (n - 1) / 2;
            }
        }

        return decMul(x, y);
    }

    function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a - _b : _b - _a;
    }

    function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
        if (_debt > 0) {
            return (_coll * NICR_PRECISION) / _debt;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
        if (_debt > 0) {
            uint256 newCollRatio = (_coll * _price) / _debt;

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
        if (_debt > 0) {
            uint256 newCollRatio = (_coll) / _debt;

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _isApproxEqAbs(uint256 a, uint256 b, uint256 tolerance) internal pure returns (bool) {
        return a > b ? (a - b) <= tolerance : (b - a) <= tolerance;
    }

    function _isWithinToleranceAbove(
        uint256 a,
        uint256 b,
        uint256 tolerance
    ) internal pure returns (bool) {
        if (a < b) return false;
        return (a - b) <= tolerance;
    }

    function _isWithinToleranceBelow(
        uint256 a,
        uint256 b,
        uint256 tolerance
    ) internal pure returns (bool) {
        if (a > b) return false;
        return (b - a) <= tolerance;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

File 22 of 59 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{

}

File 23 of 59 : ALMGetters.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.26;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {PositionKey} from "@uniswap/v3-periphery/contracts/libraries/PositionKey.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {PropMath} from "src/libraries/PropMath.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";
import {IEverlongALM} from "src/interfaces/core/alm/IEverlongALM.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {ALMLib} from "src/core/alm/library/ALMLib.sol";

library EverlongALMStorageLib {
    // keccak256(abi.encode(uint(keccak256("openzeppelin.storage.EverlongALM")) - 1)) & ~bytes32(uint(0xff))
    bytes32 internal constant EVERLONG_ALM_STORAGE_LOC = 0xb4801203179a1f53d2a89513756c4fddeb24d0f949ce9fc7cf03114c341dc500;

    uint256 internal constant MANAGER_SLOT = 5;
    uint256 internal constant PENDING_MANAGER_SLOT = 6;
    uint256 internal constant REBALANCE_DELEGATE_SLOT = 7;
    uint256 internal constant DEPOSIT_DELEGATE_SLOT = 8;
    uint256 internal constant MAX_TOTAL_SUPPLY_SLOT = 9;
    uint256 internal constant ACCRUED_PROTOCOL_FEES_SLOT = 10;
    uint256 internal constant PARAMS_SLOT = 11;
    uint256 internal constant RANGE_SLOT = 12;
    uint256 internal constant RATIO_SLOT = 13;
    uint256 internal constant SWAPPER_DATA_SLOT = 14;
    uint256 internal constant GETTERS_SLOT = 15;

    // PARAMS_SLOT bit offsets
    uint256 internal constant PROTOCOL_FEE_OFFSET = 32;
    uint256 internal constant PENDING_PROTOCOL_FEE_OFFSET = 56;
    uint256 internal constant WIDE_RANGE_WEIGHT_OFFSET = 80;
    uint256 internal constant BASE_THRESHOLD_OFFSET = 104;
    uint256 internal constant LIMIT_THRESHOLD_OFFSET = 128;
    uint256 internal constant WIDE_THRESHOLD_OFFSET = 152;
    uint256 internal constant MIN_TICK_MOVE_OFFSET = 176;
    uint256 internal constant TICK_SPACING_OFFSET = 200;
    uint256 internal constant MAX_TWAP_DEVIATION_OFFSET = 224;

    // RANGE_SLOT bit offsets
    uint256 internal constant TWAP_DURATION_OFFSET = 0;
    uint256 internal constant WIDE_LOWER_OFFSET = 32;
    uint256 internal constant WIDE_UPPER_OFFSET = 56;
    uint256 internal constant BASE_LOWER_OFFSET = 80;
    uint256 internal constant BASE_UPPER_OFFSET = 104;
    uint256 internal constant LIMIT_LOWER_OFFSET = 128;
    uint256 internal constant LIMIT_UPPER_OFFSET = 152;
    uint256 internal constant LAST_TICK_OFFSET = 176;
    uint256 internal constant LAST_TIMESTAMP_OFFSET = 200;

    // RATIO_SLOT bit offsets
    uint256 internal constant MAX_TICK_OFFSET = 0;
    uint256 internal constant SWAP_DEVIATION_THRESHOLD_OFFSET = 24;
    uint256 internal constant RATIO_DEVIATION_THRESHOLD_OFFSET = 48;
    uint256 internal constant REBALANCE_DELEGATE_COOLDOWN_OFFSET = 72;
    uint256 internal constant LAST_RATIO_DEV_UPDATE_TIMESTAMP_OFFSET = 96;
    uint256 internal constant MAX_RATIO_DEV_THRESHOLD_INCREASE_OFFSET = 136;

    function managerSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + MANAGER_SLOT);
    }

    function pendingManagerSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + PENDING_MANAGER_SLOT);
    }

    function rebalanceDelegateSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + REBALANCE_DELEGATE_SLOT);
    }

    function depositDelegateSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + DEPOSIT_DELEGATE_SLOT);
    }

    function maxTotalSupplySlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + MAX_TOTAL_SUPPLY_SLOT);
    }

    function accruedProtocolFeesSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + ACCRUED_PROTOCOL_FEES_SLOT);
    }

    function paramsSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + PARAMS_SLOT);
    }

    function rangeSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + RANGE_SLOT);
    }

    function ratioSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + RATIO_SLOT);
    }

    function swapperDataSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + SWAPPER_DATA_SLOT);
    }

    function gettersSlot() internal pure returns (bytes32) {
        return bytes32(uint256(EVERLONG_ALM_STORAGE_LOC) + GETTERS_SLOT);
    }
}

interface IALMGetters {
    error EV_PeriodNotElapsed();
    error EV_TickNotMoved();
    error EV_PriceOutOfBounds();
    error EV_TwapPriceDeviation();
    error EV_SwapSlippageExceeded(uint256 receivedValue, uint256 sentValue);
    error EV_InsufficientSwapOutput(uint256 actual, uint256 required);
    error EV_RatioDeviationExceeded(uint256 tokenInValue, uint256 tokenOutValue);

    function getTotalAmounts(bool roundUp) external view returns (uint256 total0, uint256 total1);
    function getPositionAmounts(int24 tickLower, int24 tickUpper, bool roundUp) external view returns (uint256 amount0, uint256 amount1);
    function checkCanRebalance() external view;
    function checkPriceNearTwap() external view;
    function getTwap() external view returns (int24);
    function checkMaxSlippageAndRatioDeviation(
        IEverlongALM.ExternalRebalanceParams memory params,
        uint256 tokenOutBalanceBefore,
        address tokenIn,
        address tokenOut,
        uint256 sentPrice,
        uint256 receivedPrice
    ) external view;
}

contract ALMGetters is IALMGetters {
    using PriceLib for uint256;

    IEverlongALM immutable public alm;
    IUniswapV3Pool immutable public pool;

    uint24 constant HUNDRED_PERCENT = 1e6;

    constructor (address _alm, address _pool) {
        alm = IEverlongALM(_alm);
        /// @dev Assumes pool never changes
        pool = IUniswapV3Pool(_pool);
    }

    // ─── extSloads helpers ───────────────────────────────────────────
    function _loadSlot(bytes32 slot) private view returns (uint256 word) {
        bytes32[] memory slots = new bytes32[](1);
        slots[0] = slot;
        word = uint256(alm.extSloads(slots)[0]);
    }

    function _loadCoreSlots() private view returns (uint256 params, uint256 ranges, uint256 ratios) {
        bytes32[] memory slots = new bytes32[](3);
        slots[0] = EverlongALMStorageLib.paramsSlot();
        slots[1] = EverlongALMStorageLib.rangeSlot();
        slots[2] = EverlongALMStorageLib.ratioSlot();

        bytes32[] memory r = alm.extSloads(slots);
        params = uint256(r[0]);
        ranges = uint256(r[1]);
        ratios = uint256(r[2]);
    }

    function _loadParams() private view returns (uint256) {
        return _loadSlot(EverlongALMStorageLib.paramsSlot());
    }

    function _loadRange() private view returns (uint256) {
        return _loadSlot(EverlongALMStorageLib.rangeSlot());
    }

    function _loadRatios() private view returns (uint256) {
        return _loadSlot(EverlongALMStorageLib.ratioSlot());
    }

    function _decodeUint24(uint256 word, uint256 offset) private pure returns (uint24) {
        return uint24(word >> offset);
    }

    function _decodeInt24(uint256 word, uint256 offset) private pure returns (int24) {
        return int24(uint24(word >> offset));
    }

    function getters() public view returns (address) {
        return address(uint160(_loadSlot(EverlongALMStorageLib.gettersSlot())));
    }

    function isSwapperWhitelisted(address swapper) public view returns (bool) {
        bytes32[] memory slots = new bytes32[](1);
        slots[0] = keccak256(abi.encode(swapper, EverlongALMStorageLib.swapperDataSlot()));
        return uint256(alm.extSloads(slots)[0]) != 0;
    }

    // ─── extSloads-backed getters ─────────────────────────────────────
    function manager() public view returns (address) {
        return address(uint160(_loadSlot(EverlongALMStorageLib.managerSlot())));
    }

    function pendingManager() public view returns (address) {
        return address(uint160(_loadSlot(EverlongALMStorageLib.pendingManagerSlot())));
    }

    function rebalanceDelegate() public view returns (address) {
        return address(uint160(_loadSlot(EverlongALMStorageLib.rebalanceDelegateSlot())));
    }

    function depositDelegate() public view returns (address) {
        return address(uint160(_loadSlot(EverlongALMStorageLib.depositDelegateSlot())));
    }

    function maxTotalSupply() public view returns (uint256) {
        return _loadSlot(EverlongALMStorageLib.maxTotalSupplySlot());
    }

    function accruedProtocolFees0() public view returns (uint128) {
        uint256 word = _loadSlot(EverlongALMStorageLib.accruedProtocolFeesSlot());
        return uint128(word);
    }

    function accruedProtocolFees1() public view returns (uint128) {
        uint256 word = _loadSlot(EverlongALMStorageLib.accruedProtocolFeesSlot());
        return uint128(word >> 128);
    }

    function period() public view returns (uint32) {
        return uint32(_loadParams());
    }

    function protocolFee() public view returns (uint24) {
        return _decodeUint24(_loadParams(), EverlongALMStorageLib.PROTOCOL_FEE_OFFSET);
    }

    function pendingProtocolFee() public view returns (uint24) {
        uint24 pendingProtocolFeePlusOne = _decodeUint24(_loadParams(), EverlongALMStorageLib.PENDING_PROTOCOL_FEE_OFFSET);
        return pendingProtocolFeePlusOne == 0 ? 0 : pendingProtocolFeePlusOne - 1;
    }

    function wideRangeWeight() public view returns (uint24) {
        return _decodeUint24(_loadParams(), EverlongALMStorageLib.WIDE_RANGE_WEIGHT_OFFSET);
    }

    function baseThreshold() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.BASE_THRESHOLD_OFFSET);
    }

    function limitThreshold() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.LIMIT_THRESHOLD_OFFSET);
    }

    function wideThreshold() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.WIDE_THRESHOLD_OFFSET);
    }

    function minTickMove() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.MIN_TICK_MOVE_OFFSET);
    }

    function tickSpacing() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.TICK_SPACING_OFFSET);
    }

    function maxTwapDeviation() public view returns (int24) {
        return _decodeInt24(_loadParams(), EverlongALMStorageLib.MAX_TWAP_DEVIATION_OFFSET);
    }

    function twapDuration() public view returns (uint32) {
        return uint32(_loadRange() >> EverlongALMStorageLib.TWAP_DURATION_OFFSET);
    }

    function lastTick() public view returns (int24) {
        return _decodeInt24(_loadRange(), EverlongALMStorageLib.LAST_TICK_OFFSET);
    }

    function lastTimestamp() public view returns (uint40) {
        return uint40(_loadRange() >> EverlongALMStorageLib.LAST_TIMESTAMP_OFFSET);
    }

    function swapDeviationThreshold() public view returns (uint24) {
        return _decodeUint24(_loadRatios(), EverlongALMStorageLib.SWAP_DEVIATION_THRESHOLD_OFFSET);
    }

    function ratioDeviationThreshold() public view returns (uint24) {
        return _decodeUint24(_loadRatios(), EverlongALMStorageLib.RATIO_DEVIATION_THRESHOLD_OFFSET);
    }

    function rebalanceDelegateCooldown() public view returns (uint24) {
        return _decodeUint24(_loadRatios(), EverlongALMStorageLib.REBALANCE_DELEGATE_COOLDOWN_OFFSET);
    }

    function lastRatioDeviationThresholdUpdateTimestamp() public view returns (uint40) {
        return uint40(_loadRatios() >> EverlongALMStorageLib.LAST_RATIO_DEV_UPDATE_TIMESTAMP_OFFSET);
    }

    function maxRatioDeviationThresholdIncrease() public view returns (uint24) {
        return _decodeUint24(_loadRatios(), EverlongALMStorageLib.MAX_RATIO_DEV_THRESHOLD_INCREASE_OFFSET);
    }

    function getTotalAmounts(bool roundUp) public view override returns (uint256 total0, uint256 total1) {
        int24[2][3] memory positions = alm.getPositions();
        (uint256 wideAmount0, uint256 wideAmount1) = getPositionAmounts(positions[0][0], positions[0][1], roundUp);
        (uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(positions[1][0], positions[1][1], roundUp);
        (uint256 limitAmount0, uint256 limitAmount1) = getPositionAmounts(positions[2][0], positions[2][1], roundUp);
        total0 = alm.getBalance0() + wideAmount0 + baseAmount0 + limitAmount0;
        total1 = alm.getBalance1() + wideAmount1 + baseAmount1 + limitAmount1;
    }

    /**
     * @notice Amounts of token0 and token1 held in vault's position. Includes
     * owed fees but excludes the proportion of fees that will be paid to the
     * protocol. Doesn't include fees accrued since last poke.
     */
    function getPositionAmounts(int24 tickLower, int24 tickUpper, bool roundUp)
        public
        view
        returns (uint256 amount0, uint256 amount1)
    {
        (uint128 liquidity,,, uint128 tokensOwed0, uint128 tokensOwed1) = _position(tickLower, tickUpper);
        (amount0, amount1) = ALMLib._amountsForLiquidity(address(pool), tickLower, tickUpper, liquidity, roundUp);

        // Subtract protocol and manager fees
        uint256 paramsWord = _loadParams();
        uint24 _protocolFee = _decodeUint24(paramsWord, EverlongALMStorageLib.PROTOCOL_FEE_OFFSET);
        uint128 protocolFees0 = tokensOwed0 * _protocolFee / HUNDRED_PERCENT;
        uint128 protocolFees1 = tokensOwed1 * _protocolFee / HUNDRED_PERCENT;

        amount0 += tokensOwed0 - protocolFees0;
        amount1 += tokensOwed1 - protocolFees1;
    }

    function checkCanRebalance() public view {
        checkPriceNearTwap();
        (uint256 paramsWord, uint256 rangesWord, uint256 ratiosWord) = _loadCoreSlots();

        uint40 _lastTimestamp = uint40(rangesWord >> EverlongALMStorageLib.LAST_TIMESTAMP_OFFSET);
        int24 lastTick = _decodeInt24(rangesWord, EverlongALMStorageLib.LAST_TICK_OFFSET);
        int24 baseThreshold = _decodeInt24(paramsWord, EverlongALMStorageLib.BASE_THRESHOLD_OFFSET);
        int24 limitThreshold = _decodeInt24(paramsWord, EverlongALMStorageLib.LIMIT_THRESHOLD_OFFSET);
        int24 tickSpacing = _decodeInt24(paramsWord, EverlongALMStorageLib.TICK_SPACING_OFFSET);
        uint32 _period = uint32(paramsWord);
        int24 minTickMove_ = _decodeInt24(paramsWord, EverlongALMStorageLib.MIN_TICK_MOVE_OFFSET);

        // check enough time has passed
        if (block.timestamp < (_lastTimestamp + _period)) revert EV_PeriodNotElapsed();

        // check price has moved enough
        (, int24 tick,,,,,) = pool.slot0();
        int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
        if (_lastTimestamp != 0 && tickMove < minTickMove_) revert EV_TickNotMoved();
        // check price not too close to boundary
        int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
        if (
            !(
                tick >= TickMath.MIN_TICK + maxThreshold + tickSpacing
                    && tick <= TickMath.MAX_TICK - maxThreshold - tickSpacing
            )
        ) revert EV_PriceOutOfBounds();
    }

    function checkPriceNearTwap() public view {
        (, int24 tick,,,,,) = pool.slot0();
        int24 twap = getTwap();
        int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
        if (twapDeviation > maxTwapDeviation()) revert EV_TwapPriceDeviation();
    }

    /// @dev Fetches time-weighted average price in ticks from Uniswap pool.
    function getTwap() public view returns (int24) {
        uint32 _twapDuration = twapDuration();
        uint32[] memory secondsAgo = new uint32[](2);
        secondsAgo[0] = _twapDuration;
        secondsAgo[1] = 0;

        (int56[] memory tickCumulatives,) = pool.observe(secondsAgo);
        return int24((tickCumulatives[1] - tickCumulatives[0]) / int56(uint56((_twapDuration))));
    }

    function checkMaxSlippageAndRatioDeviation(
        IEverlongALM.ExternalRebalanceParams memory params,
        uint256 tokenOutBalanceBefore,
        address tokenIn,
        address tokenOut,
        uint256 sentPrice,
        uint256 receivedPrice
    ) external view {
        uint256 tokenOutBalanceAfter = params.isZeroForOne ? alm.getBalance1() : alm.getBalance0();
        uint8 tokenInDecimals = IAsset(tokenIn).decimals();
        uint8 tokenOutDecimals = IAsset(tokenOut).decimals();
        uint256 ratiosWord = _loadRatios();
        uint24 _swapDeviationThreshold = _decodeUint24(ratiosWord, EverlongALMStorageLib.SWAP_DEVIATION_THRESHOLD_OFFSET);
        uint24 _ratioDeviationThreshold = _decodeUint24(ratiosWord, EverlongALMStorageLib.RATIO_DEVIATION_THRESHOLD_OFFSET);

        {
            uint256 amountOut = tokenOutBalanceAfter - tokenOutBalanceBefore;
            uint256 sentValue = _assetValue(params.sentAmount, sentPrice, tokenInDecimals);

            {
                uint256 receivedValue = _assetValue(amountOut, receivedPrice, tokenOutDecimals);
                if (receivedValue < sentValue * (HUNDRED_PERCENT - _swapDeviationThreshold) / HUNDRED_PERCENT) {
                    revert EV_SwapSlippageExceeded(receivedValue, sentValue);
                }
            }

            if (amountOut < params.minRebalanceOut) {
                revert EV_InsufficientSwapOutput(amountOut, params.minRebalanceOut);
            }
        }

        (uint256 total0, uint256 total1) = alm.getTotalAmounts();
        uint256 totalTokenIn =  params.isZeroForOne ? total0 : total1;
        uint256 totalTokenOut = params.isZeroForOne ? total1 : total0;
        uint256 tokenInBalanceValue = _assetValue(totalTokenIn, sentPrice, tokenInDecimals);
        uint256 tokenOutBalanceValue = _assetValue(totalTokenOut, receivedPrice, tokenOutDecimals);
        uint256 maxDelta = Math.min(tokenInBalanceValue, tokenOutBalanceValue) * _ratioDeviationThreshold / HUNDRED_PERCENT;

        if (!PropMath._isApproxEqAbs(tokenInBalanceValue, tokenOutBalanceValue, maxDelta)) {
            revert EV_RatioDeviationExceeded(tokenInBalanceValue, tokenOutBalanceValue);
        }
    }

    /// @dev Wrapper around `IUniswapV3Pool.positions()`.
    function _position(int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint128, uint256, uint256, uint128, uint128)
    {
        bytes32 positionKey = PositionKey.compute(address(alm), tickLower, tickUpper);
        return pool.positions(positionKey);
    }

    /// @dev Returned in WAD
    function _assetValue(uint256 amount, uint256 price, uint8 decimals) internal pure returns (uint256) {
        return amount.convertToValue(price, decimals);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 26 of 59 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC4626, IERC20} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";

interface IBaseCollateralVault is IERC4626, IERC1822Proxiable {
    struct BaseInitParams {
        uint16 _minWithdrawFee;
        uint16 _maxWithdrawFee;
        uint16 _withdrawFee;
        address _metaCore;
        // ERC4626
        IERC20 _asset;
        // ERC20
        string _sharesName;
        string _sharesSymbol;
    }

    struct BaseCollVaultStorage {
        uint16 minWithdrawFee;
        uint16 maxWithdrawFee;
        uint16 withdrawFee; // over rewarded tokens, in basis points
        uint8 assetDecimals;

        address _metaCore;

        // Second mapping of this struct is usless, but it's for retrocompatibility with LSTCollateralVault
        EmissionsLib.BalanceData balanceData;
    }

    function initialize(BaseInitParams calldata params) external;

    function totalAssets() external view returns (uint);

    function fetchPrice() external view returns (uint);

    function getPrice(address token) external view returns (uint);

    function receiveDonations(address[] memory tokens, uint[] memory amounts, address receiver) external;

    function setWithdrawFee(uint16 _withdrawFee) external;

    function getBalance(address token) external view returns (uint);

    function getWithdrawFee() external view returns (uint16);

    function getEverlongCore() external view returns (address);

    function getPriceFeed() external view returns (address);

    function assetDecimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";

library EmissionsLib {
    using SafeCast for uint256;
    uint64 constant internal DEFAULT_UNLOCK_RATE = 1e11; // 10% per second
    uint64 constant internal MAX_UNLOCK_RATE = 1e12; // 100%

    struct BalanceData {
        mapping(address token => uint) balance;
        mapping(address token => EmissionSchedule) emissionSchedule;
    }

    struct EmissionSchedule {
        uint128 emissions;
        uint64 lockTimestamp;
        uint64 _unlockRatePerSecond; // rate points
    }

    error AmountCannotBeZero();
    error EmissionRateExceedsMax();
    // error UnsupportedEmissionConfig();

    event EmissionsAdded(address indexed token, uint128 amount);
    event EmissionsSub(address indexed token, uint128 amount);
    event NewUnlockRatePerSecond(address indexed token, uint64 unlockRatePerSecond);

    /// @dev zero _unlockRatePerSecond parameter resets rate back to DEFAULT_UNLOCK_RATE
    function setUnlockRatePerSecond(BalanceData storage $, address token, uint64 _unlockRatePerSecond) internal {
        if (_unlockRatePerSecond > MAX_UNLOCK_RATE) revert EmissionRateExceedsMax();
        _addEmissions($, token, 0); // update lockTimestamp and emissions
        $.emissionSchedule[token]._unlockRatePerSecond = _unlockRatePerSecond;

        emit NewUnlockRatePerSecond(token, _unlockRatePerSecond);
    }

    function addEmissions(BalanceData storage $, address token, uint128 amount) internal {
        if (amount == 0) revert AmountCannotBeZero();
        _addEmissions($, token, amount);

        emit EmissionsAdded(token, amount);
    }

    function _addEmissions(BalanceData storage $, address token, uint128 amount) private {        
        EmissionSchedule memory schedule = $.emissionSchedule[token];

        uint256 _unlockTimestamp = unlockTimestamp(schedule);
        uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) + amount).toUint128();

        schedule.emissions = nextEmissions;
        schedule.lockTimestamp = block.timestamp.toUint64();
        $.balance[token] += amount;

        $.emissionSchedule[token] = schedule;
    }

    function subEmissions(BalanceData storage $, address token, uint128 amount) internal {
        if (amount == 0) revert AmountCannotBeZero();
        _subEmissions($, token, amount);

        emit EmissionsSub(token, amount);
    }

    function _subEmissions(BalanceData storage $, address token, uint128 amount) private {
        EmissionSchedule memory schedule = $.emissionSchedule[token];

        uint256 _unlockTimestamp = unlockTimestamp(schedule);
        uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) - amount).toUint128();

        schedule.emissions = nextEmissions;
        schedule.lockTimestamp = block.timestamp.toUint64();
        $.balance[token] -= amount;

        $.emissionSchedule[token] = schedule;
    }

    /// @dev Doesn't include locked emissions
    function unlockedEmissions(EmissionSchedule memory schedule) internal view returns (uint256) {
        return schedule.emissions - lockedEmissions(schedule, unlockTimestamp(schedule));
    }

    function balanceOfWithFutureEmissions(BalanceData storage $, address token) internal view returns (uint256) {
        return $.balance[token];
    }

    /**
     * @notice Returns the unlocked token emissions
     */
    function balanceOf(BalanceData storage $, address token) internal view returns (uint256) {
        EmissionSchedule memory schedule = $.emissionSchedule[token];
        return $.balance[token] - lockedEmissions(schedule, unlockTimestamp(schedule));
    }

    /**
     * @notice Returns locked emissions
     */
    function lockedEmissions(EmissionSchedule memory schedule, uint256 _unlockTimestamp) internal view returns (uint256) {
        if (block.timestamp >= _unlockTimestamp) {
            // all emissions were unlocked 
            return 0;
        } else {
            // emissions are still unlocking, calculate the amount of already unlocked emissions
            uint256 secondsSinceLockup = block.timestamp - schedule.lockTimestamp;
            // design decision - use dimensionless 'unlock rate units' to unlock emissions over a fixed time window 
            uint256 ratePointsUnlocked = unlockRatePerSecond(schedule) * secondsSinceLockup;
            // emissions remainder is designed to be added to balance in unlockTimestamp
            return schedule.emissions - ratePointsUnlocked * schedule.emissions / MAX_UNLOCK_RATE;
        }
    } 

    // timestamp at which all emissions are fully unlocked
    function unlockTimestamp(EmissionSchedule memory schedule) internal pure returns (uint256) {
        // ceil to account for remainder seconds left after integer division
        return divRoundUp(MAX_UNLOCK_RATE, unlockRatePerSecond(schedule)) + schedule.lockTimestamp; 
    }

    function unlockRatePerSecond(EmissionSchedule memory schedule) internal pure returns (uint256) {
        return schedule._unlockRatePerSecond == 0 ? DEFAULT_UNLOCK_RATE : schedule._unlockRatePerSecond;
    }

    function divRoundUp(uint256 dividend, uint256 divisor) internal pure returns (uint256) {
        return (dividend + divisor - 1) / divisor;
    }
}

File 30 of 59 : IFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface IFactory {
    // commented values are suggested default parameters
    struct DeploymentParams {
        uint256 minuteDecayFactor; // 999037758833783000  (half life of 12 hours)
        uint256 redemptionFeeFloor; // 1e18 / 1000 * 5  (0.5%)
        uint256 maxRedemptionFee; // 1e18  (100%)
        uint256 borrowingFeeFloor; // 1e18 / 1000 * 5  (0.5%)
        uint256 maxBorrowingFee; // 1e18 / 100 * 5  (5%)
        uint256 interestRateInBps; // 100 (1%)
        uint256 maxDebt;
        uint256 MCR; // 12 * 1e17  (120%)
        address collVaultRouter; // set to address(0) if DenManager coll is not CollateralVault
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 39 of 59 : IUniswapV3PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
}

File 40 of 59 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 41 of 59 : PositionKey.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

library PositionKey {
    /// @dev Returns the key of the position in the core library
    function compute(
        address owner,
        int24 tickLower,
        int24 tickUpper
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio = absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

library PriceLib {
    using Math for uint;

    // WAD adjusted result
    function convertToValue(uint amount, uint price, uint8 decimals) internal pure returns (uint) {
        return amount * price / 10 ** decimals;
    }

    function convertToAmount(uint amountInUsd, uint collPrice, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
        if (collPrice == 0 || amountInUsd == 0) {
            return 0;
        }

        return amountInUsd.mulDiv(10 ** collDecimals, collPrice, rounding);
    }

    // Coll decimal adjust amount result
    function convertAssetsToCollAmount(uint assets, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
        uint assetsUsdValue = assets.mulDiv(debtTokenPrice, 10 ** vaultDecimals, rounding);

        if (collPrice != 0) {
            return convertToAmount(assetsUsdValue, collPrice, collDecimals, rounding);
        } else {
            return 0;
        }
    }

    function convertCollAmountToAssets(uint collAmount, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals) internal pure returns (uint) {
        uint collUsdValue = collAmount * collPrice / 10 ** collDecimals;
        
        if (debtTokenPrice != 0) {
            return collUsdValue * 10 ** vaultDecimals / debtTokenPrice;
        } else {
            return 0;
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";

interface IAsset is IERC20 {
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.26;

import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {SqrtPriceMath} from "@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

library ALMLib {
    uint24 constant MINIMUM_LIQUIDITY = 1e3;

    error EV_ZeroCross();

    /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
    function _liquidityForAmounts(
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtRatioX96
    ) external pure returns (uint128) {
        return LiquidityAmounts.getLiquidityForAmounts(
            sqrtRatioX96,
            TickMath.getSqrtRatioAtTick(tickLower),
            TickMath.getSqrtRatioAtTick(tickUpper),
            amount0,
            amount1
        );
    }

    /**
     * @notice Computes the token0 and token1 value for a given amount of liquidity,
     * respecting rounding for deposit/withdraw to align with uniswap's approach when providing/removing liquidity.
     */
    function _amountsForLiquidity(address pool, int24 tickLower, int24 tickUpper, uint128 liquidity, bool roundUp)
        external
        view
        returns (uint256 amount0, uint256 amount1)
    {
        (uint160 sqrtRatioX96,,,,,,) = IUniswapV3Pool(pool).slot0();
        uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
        uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);

        if (sqrtRatioAX96 > sqrtRatioBX96) {
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        }

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, liquidity, roundUp);
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, liquidity, roundUp);
        } else {
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp);
        }
    }

    /// @dev Calculates the largest possible `amount0` and `amount1` such that
    /// they're in the same proportion as total amounts, but not greater than
    /// `amount0Desired` and `amount1Desired` respectively.
    function _calcSharesAndAmounts(
        uint256 _totalSupply,
        uint256 total0,
        uint256 total1,
        uint256 amount0Desired,
        uint256 amount1Desired
    )
        external
        view
        returns (uint256 shares, uint256 amount0, uint256 amount1)
    {
        // If total supply > 0, vault can't be empty
        assert(_totalSupply == 0 || total0 > 0 || total1 > 0);

        if (_totalSupply == 0) {
            // For first deposit, just use the amounts desired
            amount0 = amount0Desired;
            amount1 = amount1Desired;
            shares = (amount0 > amount1 ? amount0 : amount1) - MINIMUM_LIQUIDITY;
        } else if (total0 == 0) {
            amount1 = amount1Desired;
            shares = amount1 * _totalSupply / total1;
        } else if (total1 == 0) {
            amount0 = amount0Desired;
            shares = amount0 * _totalSupply / total0;
        } else {
            uint256 cross0 = amount0Desired * total1;
            uint256 cross1 = amount1Desired * total0;
            uint256 cross = cross0 > cross1 ? cross1 : cross0;
            if (cross == 0) revert EV_ZeroCross();

            // Round up amounts
            amount0 = (cross - 1) / total1 + 1;
            amount1 = (cross - 1) / total0 + 1;
            shares = cross * _totalSupply / total0 / total1;
        }
    }

    /// @dev Ensures tick is within the maximum range boundaries
    function _boundTick(int24 tick, int24 _maxTick) external pure returns (int24) {
        if (tick < -_maxTick) {
            return -_maxTick;
        }
        if (tick > _maxTick) {
            return _maxTick;
        }
        return tick;
    }

    /// @dev Rounds tick down towards negative infinity so that it's a multiple
    /// of `tickSpacing`.
    function _floor(int24 tick, int24 tickSpacing) external pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--;
        return compressed * tickSpacing;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);
}

File 47 of 59 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

File 48 of 59 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 49 of 59 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

File 50 of 59 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 51 of 59 : Errors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
        unchecked {
            return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
        }
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        unchecked {
            return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
        }
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0) {
        unchecked {
            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

            return
                FullMath.mulDiv(
                    uint256(liquidity) << FixedPoint96.RESOLUTION,
                    sqrtRatioBX96 - sqrtRatioAX96,
                    sqrtRatioBX96
                ) / sqrtRatioAX96;
        }
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        unchecked {
            return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
        }
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import {SafeCast} from './SafeCast.sol';

import {FullMath} from './FullMath.sol';
import {UnsafeMath} from './UnsafeMath.sol';
import {FixedPoint96} from './FixedPoint96.sol';

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

    /// @notice Gets the next sqrt price given a delta of token0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of token0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of token0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amount,
        bool add
    ) internal pure returns (uint160) {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            unchecked {
                uint256 product;
                if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1)
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product;
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
                uint256 denominator = numerator1 - product;
                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
            }
        }
    }

    /// @notice Gets the next sqrt price given a delta of token1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of token1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of token1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amount,
        bool add
    ) internal pure returns (uint160) {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            require(sqrtPX96 > quotient);
            // always fits 160 bits
            unchecked {
                return uint160(sqrtPX96 - quotient);
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of token0 or token1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of token0, or token1, is being swapped in
    /// @param zeroForOne Whether the amount in is token0 or token1
    /// @return sqrtQX96 The price after adding the input amount to token0 or token1
    function getNextSqrtPriceFromInput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountIn,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        require(sqrtPX96 > 0);
        require(liquidity > 0);

        // round to make sure that we don't pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
                : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of token0 or token1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of token0, or token1, is being swapped out
    /// @param zeroForOne Whether the amount out is token0 or token1
    /// @return sqrtQX96 The price after removing the output amount of token0 or token1
    function getNextSqrtPriceFromOutput(
        uint160 sqrtPX96,
        uint128 liquidity,
        uint256 amountOut,
        bool zeroForOne
    ) internal pure returns (uint160 sqrtQX96) {
        require(sqrtPX96 > 0);
        require(liquidity > 0);

        // round to make sure that we pass the target price
        return
            zeroForOne
                ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
                : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount0) {
        unchecked {
            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;

            require(sqrtRatioAX96 > 0);

            return
                roundUp
                    ? UnsafeMath.divRoundingUp(
                        FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
                        sqrtRatioAX96
                    )
                    : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity,
        bool roundUp
    ) internal pure returns (uint256 amount1) {
        unchecked {
            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

            return
                roundUp
                    ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
                    : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
        }
    }

    /// @notice Helper that gets signed token0 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount0) {
        unchecked {
            return
                liquidity < 0
                    ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                    : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
        }
    }

    /// @notice Helper that gets signed token1 delta
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        int128 liquidity
    ) internal pure returns (int256 amount1) {
        unchecked {
            return
                liquidity < 0
                    ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                    : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the precoditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}

File 57 of 59 : FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint160
    function toUint160(uint256 y) internal pure returns (uint160 z) {
        require((z = uint160(y)) == y);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param y The int256 to be downcasted
    /// @return z The downcasted integer, now type int128
    function toInt128(int256 y) internal pure returns (int128 z) {
        require((z = int128(y)) == y);
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param y The uint256 to be casted
    /// @return z The casted integer, now type int256
    function toInt256(uint256 y) internal pure returns (int256 z) {
        require(y < 2**255);
        z = int256(y);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @notice Returns ceil(x / y)
    /// @dev division by 0 has unspecified behavior, and must be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin-upgradeable/contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "v3-core/=lib/v3-core/contracts/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_borrowerOperations","type":"address"},{"internalType":"address","name":"_debtToken","type":"address"},{"internalType":"address","name":"_priceFeed","type":"address"},{"internalType":"address","name":"_core","type":"address"},{"internalType":"address","name":"_everlongCore","type":"address"},{"internalType":"address[]","name":"_initialSwapRouters","type":"address[]"},{"internalType":"address","name":"_almPeriphery","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CollateralRatioBelowCCR","type":"error"},{"inputs":[],"name":"CollateralRatioBelowMCR","type":"error"},{"inputs":[{"internalType":"uint256","name":"currentColl","type":"uint256"},{"internalType":"uint256","name":"currentDebt","type":"uint256"},{"internalType":"uint256","name":"newColl","type":"uint256"},{"internalType":"uint256","name":"newDebt","type":"uint256"}],"name":"DebtOrCollateralChanged","type":"error"},{"inputs":[{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"minNetDebt","type":"uint256"}],"name":"DebtTooLow","type":"error"},{"inputs":[],"name":"FlashLoanFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"assetReceived","type":"uint256"},{"internalType":"uint256","name":"outputMin","type":"uint256"}],"name":"InsufficientAssetReceived","type":"error"},{"inputs":[{"internalType":"uint256","name":"debtTokenBalance","type":"uint256"},{"internalType":"uint256","name":"payBackAmount","type":"uint256"}],"name":"InsufficientPayBackAmount","type":"error"},{"inputs":[],"name":"InvalidDexSelector","type":"error"},{"inputs":[{"internalType":"uint256","name":"leverage","type":"uint256"},{"internalType":"uint256","name":"maxLeverage","type":"uint256"}],"name":"LeverageExceeded","type":"error"},{"inputs":[],"name":"NativeTransferFailed","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"NotDebtToken","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"NotOwner","type":"error"},{"inputs":[{"internalType":"uint256","name":"resultingCR","type":"uint256"},{"internalType":"uint256","name":"minimumCR","type":"uint256"}],"name":"PositionBelowMinimumCR","type":"error"},{"inputs":[{"internalType":"uint256","name":"resultingICR","type":"uint256"},{"internalType":"uint256","name":"prevICR","type":"uint256"}],"name":"PositionNotImprovedUnderRM","type":"error"},{"inputs":[{"internalType":"uint256","name":"newTCR","type":"uint256"},{"internalType":"uint256","name":"CCR","type":"uint256"}],"name":"RecoveryMode","type":"error"},{"inputs":[],"name":"SwapperNotWhitelisted","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroCollateral","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"positionManager","type":"address"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginCollAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"finalCollAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"flashloanDebtTokenAmount","type":"uint256"}],"name":"AutomaticLoopingAddCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"positionManager","type":"address"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginCollAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"finalCollAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"flashloanDebtTokenAmount","type":"uint256"}],"name":"AutomaticLoopingOpenPosition","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"swapRouter","type":"address"},{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"SwapperAdded","type":"event"},{"inputs":[{"internalType":"address","name":"_swapRouter","type":"address"},{"internalType":"bool","name":"status","type":"bool"}],"name":"addWhitelistedSwapper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"almPeriphery","outputs":[{"internalType":"contract IALMPeriphery","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IPositionManager","name":"positionManager","type":"address"},{"components":[{"internalType":"uint256","name":"flashloanDebtTokenAmount","type":"uint256"},{"internalType":"uint256","name":"marginCollAmount","type":"uint256"},{"components":[{"internalType":"uint256","name":"maxFeePercentage","type":"uint256"},{"internalType":"address","name":"upperHint","type":"address"},{"internalType":"address","name":"lowerHint","type":"address"}],"internalType":"struct ILeverageRouter.PositionParams","name":"positionParams","type":"tuple"},{"components":[{"internalType":"bytes","name":"dexCalldata","type":"bytes"},{"internalType":"uint256","name":"outputMin","type":"uint256"},{"internalType":"address","name":"swapRouter","type":"address"}],"internalType":"struct ILeverageRouter.DexAggregatorParams","name":"debtTokenToColl","type":"tuple"}],"internalType":"struct ILeverageRouter.PositionLoopingParams","name":"positionLoopingParams","type":"tuple"}],"name":"automaticLoopingAddCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IPositionManager","name":"positionManager","type":"address"},{"components":[{"internalType":"uint256","name":"flashloanDebtTokenAmount","type":"uint256"},{"internalType":"uint256","name":"marginCollAmount","type":"uint256"},{"components":[{"internalType":"uint256","name":"maxFeePercentage","type":"uint256"},{"internalType":"address","name":"upperHint","type":"address"},{"internalType":"address","name":"lowerHint","type":"address"}],"internalType":"struct ILeverageRouter.PositionParams","name":"positionParams","type":"tuple"},{"components":[{"internalType":"bytes","name":"dexCalldata","type":"bytes"},{"internalType":"uint256","name":"outputMin","type":"uint256"},{"internalType":"address","name":"swapRouter","type":"address"}],"internalType":"struct ILeverageRouter.DexAggregatorParams","name":"debtTokenToColl","type":"tuple"}],"internalType":"struct ILeverageRouter.PositionLoopingParams","name":"positionLoopingParams","type":"tuple"}],"name":"automaticLoopingOpenPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowerOperations","outputs":[{"internalType":"contract IBorrowerOperations","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IPositionManager","name":"positionManager","type":"address"},{"internalType":"address","name":"position","type":"address"},{"internalType":"uint256","name":"marginInAssets","type":"uint256"},{"internalType":"uint256","name":"leverage","type":"uint256"},{"internalType":"uint256","name":"minimumCR","type":"uint256"},{"internalType":"bool","name":"isRecoveryMode","type":"bool"}],"name":"calculateDebtAmount","outputs":[{"internalType":"uint256","name":"debtAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"currentColl","type":"uint256"},{"internalType":"uint256","name":"currentDebt","type":"uint256"},{"internalType":"uint256","name":"margin","type":"uint256"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"minimumCR","type":"uint256"}],"name":"calculateMaxLeverage","outputs":[{"internalType":"uint256","name":"maxLeverageInBp","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"claimLockedTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"core","outputs":[{"internalType":"contract ICore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"debtToken","outputs":[{"internalType":"contract IDebtToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"everlongCore","outputs":[{"internalType":"contract IEverlongCore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"initiator","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onFlashLoan","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"priceFeed","outputs":[{"internalType":"contract IPriceFeed","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

610120604052348015610010575f80fd5b506040516136b33803806136b383398101604081905261002f916101ca565b8686868686866001600160a01b038616158061005257506001600160a01b038516155b8061006457506001600160a01b038416155b8061007657506001600160a01b038316155b8061008857506001600160a01b038216155b156100a65760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0380871660805282811660a05283811660c05285811660e0528416610100525f5b815181101561010a576101025f8383815181106100ed576100ed6102f7565b6020026020010151600161013e60201b60201c565b6001016100ce565b5050600180546001600160a01b0319166001600160a01b0397909716969096179095555061030b9950505050505050505050565b6001600160a01b0382165f8181526020858152604091829020805460ff191685151590811790915591519182527f7dc49220c17ba736a5a8f465c46784ed2262884e4ea605ae95e6fd117a77a421910160405180910390a2505050565b80516001600160a01b03811681146101b1575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b5f805f805f805f60e0888a0312156101e0575f80fd5b6101e98861019b565b96506101f76020890161019b565b95506102056040890161019b565b94506102136060890161019b565b93506102216080890161019b565b60a08901519093506001600160401b0381111561023c575f80fd5b8801601f81018a1361024c575f80fd5b80516001600160401b03811115610265576102656101b6565b604051600582901b90603f8201601f191681016001600160401b0381118282101715610293576102936101b6565b60405291825260208184018101929081018d8411156102b0575f80fd5b6020850194505b838510156102d6576102c88561019b565b8152602094850194016102b7565b5094506102e99250505060c0890161019b565b905092959891949750929550565b634e487b7160e01b5f52603260045260245ffd5b60805160a05160c05160e051610100516132af6104045f395f818161013c0152818161058f015261075e01525f81816102100152818161027b015281816102ab0152818161036a0152818161078b01528181610d1401528181610e9d0152818161103e01528181611d7e01528181611e4201528181611e8a01528181612318015261242f01525f81816101d6015281816119200152611b3f01525f818160b60152818161082d015281816109bf01528181610ab40152610bc301525f8181610163015281816110f7015281816112a1015281816116a70152818161176a015281816117f0015281816118c10152611a7301526132af5ff3fe608060405234801561000f575f80fd5b50600436106100ad575f3560e01c806321216ba3146100b157806323adce5f146100ee57806323e30c8b1461010357806368ea904714610124578063741bef1a1461013757806377553ad41461015e5780638ca67ac9146101855780639573ea2514610198578063a6b50585146101ab578063c11f5d5d146101be578063f2f4eb26146101d1578063f6038b67146101f8578063f8d898981461020b575b5f80fd5b6100d87f000000000000000000000000000000000000000000000000000000000000000081565b6040516100e591906128a6565b60405180910390f35b6101016100fc3660046128d1565b610232565b005b610116610111366004612933565b610356565b6040519081526020016100e5565b6001546100d8906001600160a01b031681565b6100d87f000000000000000000000000000000000000000000000000000000000000000081565b6100d87f000000000000000000000000000000000000000000000000000000000000000081565b6101166101933660046129e3565b61041e565b6101016101a6366004612a46565b61082b565b6101166101b9366004612a72565b6108e9565b6101016101cc366004612af0565b6109bd565b6100d87f000000000000000000000000000000000000000000000000000000000000000081565b6101016102063660046128d1565b610ca1565b6100d87f000000000000000000000000000000000000000000000000000000000000000081565b61023a610cc2565b5f808383336040516020016102529493929190612c0f565b60405160208183030381529060405290505f610277848461027290612ed4565b610ce0565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635cffe9de307f000000000000000000000000000000000000000000000000000000000000000084866040518563ffffffff1660e01b81526004016102eb9493929190612f0d565b6020604051808303815f875af1158015610307573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061032b9190612f54565b610348576040516349088f5960e11b815260040160405180910390fd5b5050610352610ce9565b5050565b5f61035f610cee565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161415806103a057506001600160a01b0387163014155b156103c9573360405163ef04520760e01b81526004016103c091906128a6565b60405180910390fd5b5f8080806103d986880188612f6f565b93509350935093506103ee848484848d610d10565b507f439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd99a9950505050505050505050565b5f61271084116104705760405162461bcd60e51b815260206004820152601f60248201527f4c65766572616765206d7573742062652067726561746572207468616e20310060448201526064016103c0565b6104a36040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f886001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104e0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105049190612fed565b6040516375bd3fbf60e11b81529091506001600160a01b038a169063eb7a7f7e90610533908b906004016128a6565b6040805180830381865afa15801561054d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105719190613008565b60208401528252604051635670bcc760e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063ace1798e906105c49084906004016128a6565b602060405180830381865afa1580156105df573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610603919061302a565b604083015281515f03610616575f61062c565b61062c825f0151836020015184604001516110c3565b60608301525f87900361063f575f6106a6565b60405163ef8b30f760e01b8152600481018890526001600160a01b0382169063ef8b30f790602401602060405180830381865afa158015610682573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a6919061302a565b608083018190528251602084015160408501515f936106c79392918a6108e9565b9050808711156106ee578681604051636881ba1f60e01b81526004016103c0929190613041565b506127106106fc8188613063565b6080840151845161070d9190613076565b6107179190613089565b61072191906130a0565b60a083018190525f03610747576040516375d8f05d60e11b815260040160405180910390fd5b604051635670bcc760e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063ace1798e906107b3907f0000000000000000000000000000000000000000000000000000000000000000906004016128a6565b602060405180830381865afa1580156107ce573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107f2919061302a565b82604001518360a001516108069190613089565b61081091906130a0565b925061081f89838588886110f4565b50509695505050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610887573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ab9190612fed565b6001600160a01b0316336001600160a01b0316146108de573360405163245aecd360e01b81526004016103c091906128a6565b6103525f838361135f565b5f80670de0b6b3a7640000846108ff878a613076565b6109099190613089565b61091391906130a0565b9050670de0b6b3a76400006109288785613089565b61093291906130a0565b8111610941575f9150506109b4565b5f670de0b6b3a7640000846109568985613063565b6109609190613089565b61096a91906130a0565b90505f670de0b6b3a7640000836109818288613063565b61098b9190613089565b61099591906130a0565b9050806109a461271084613089565b6109ae91906130a0565b93505050505b95945050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a19573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a3d9190612fed565b6001600160a01b0316336001600160a01b031614610a70573360405163245aecd360e01b81526004016103c091906128a6565b825f5b81811015610c99575f868683818110610a8e57610a8e6130bf565b9050602002016020810190610aa391906130d3565b6001600160a01b031603610bbe575f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b3f006746040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b0e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b329190612fed565b6001600160a01b0316858584818110610b4d57610b4d6130bf565b905060200201356040515f6040518083038185875af1925050503d805f8114610b91576040519150601f19603f3d011682016040523d82523d5f602084013e610b96565b606091505b5050905080610bb857604051633d2cec6f60e21b815260040160405180910390fd5b50610c91565b610c917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b3f006746040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c1d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c419190612fed565b858584818110610c5357610c536130bf565b90506020020135888885818110610c6c57610c6c6130bf565b9050602002016020810190610c8191906130d3565b6001600160a01b031691906113bc565b600101610a73565b505050505050565b610ca9610cc2565b5f60018383336040516020016102529493929190612c0f565b63769dd35360e11b5f5c15610cd957805f5260045ffd5b60015f5d50565b80515b92915050565b5f805d565b631e12bc8b60e11b5f5c60018114610d0857815f5260045ffd5b60025f5d5050565b5f817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610d5e91906128a6565b602060405180830381865afa158015610d79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d9d919061302a565b610da79190613063565b90505f856001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610de6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0a9190612fed565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e6d9190612fed565b905085602001515f14610e8957610e8981868860200151611417565b5f610e97888789858761143e565b90505f847f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610ee791906128a6565b602060405180830381865afa158015610f02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f26919061302a565b610f309190613063565b90505f610f3d8288613063565b90505f8b6002811115610f5257610f52612b5a565b03610fc157610f698a89878c604001518786611683565b876001600160a01b03168a6001600160a01b03167fceb7fc8aae017c84c14d3757032afb8d320f723f5d8f1a3274f2de722cb3f68c8b60200151868b604051610fb4939291906130ee565b60405180910390a3611027565b610fd38a89878c6040015187866117cc565b876001600160a01b03168a6001600160a01b03167f7accea18c2c31aaa0e983d88efaa9ad7accf703abe513c864ef11835808611f48b60200151868b60405161101e939291906130ee565b60405180910390a35b60405163095ea7b360e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063095ea7b3906110759033908b90600401613104565b6020604051808303815f875af1158015611091573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110b59190612f54565b505050505050505050505050565b5f82156110e9575f836110d68487613089565b6110e091906130a0565b91506110ed9050565b505f195b9392505050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316634ba4a28b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611151573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611175919061302a565b85519091505f9015611187575f611189565b815b90505f836111f657876001600160a01b03166366ca4a216040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111f1919061302a565b6111f8565b5f5b90505f670de0b6b3a764000061120e8184613076565b6112189089613089565b61122291906130a0565b90505f8189602001516112359190613076565b90505f6112428583613076565b90505f8a60a001518b608001518c5f015161125d9190613076565b6112679190613076565b90505f828c604001518361127b9190613089565b61128591906130a0565b905061129e8d8b8b8f6112988c8b613076565b866118f3565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663969c24526040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112fb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061131f919061302a565b90508061132c8a87613063565b101561134f57848160405163b9f105d760e01b81526004016103c0929190613041565b5050505050505050505050505050565b6001600160a01b0382165f8181526020858152604091829020805460ff191685151590811790915591519182527f7dc49220c17ba736a5a8f465c46784ed2262884e4ea605ae95e6fd117a77a421910160405180910390a2505050565b6114128363a9059cbb60e01b84846040516024016113db929190613104565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611be4565b505050565b5f61142184611cb5565b90506114386001600160a01b038216843085611dc5565b50505050565b5f805f876001600160a01b031663eb7a7f7e886040518263ffffffff1660e01b815260040161146d91906128a6565b6040805180830381865afa158015611487573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114ab9190613008565b915091505f6114bc8989888a611dfd565b90508660600151602001518110156114f25760608701516020015160405163c88d2ec760e01b81526103c0918391600401613041565b5f808a6001600160a01b031663eb7a7f7e8b6040518263ffffffff1660e01b815260040161152091906128a6565b6040805180830381865afa15801561153a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061155e9190613008565b9150915084821415806115715750838114155b15611597578181868660405163f02b7d5760e01b81526004016103c0949392919061311d565b60405163095ea7b360e01b81526001600160a01b0389169063095ea7b3906115c5908a908790600401613104565b6020604051808303815f875af11580156115e1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116059190612f54565b50604051636e553f6560e01b8152600481018490523060248201526001600160a01b03881690636e553f65906044016020604051808303815f875af1158015611650573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611674919061302a565b9b9a5050505050505050505050565b60405163095ea7b360e01b81526001600160a01b0385169063095ea7b3906116d1907f0000000000000000000000000000000000000000000000000000000000000000908690600401613104565b6020604051808303815f875af11580156116ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117119190612f54565b508251602084015160408086015190516326caa39d60e01b81526001600160a01b038a8116600483015289811660248301526044820194909452606481018690526084810185905291831660a4830152821660c48201527f0000000000000000000000000000000000000000000000000000000000000000909116906326caa39d9060e4015b5f604051808303815f87803b1580156117ae575f80fd5b505af11580156117c0573d5f803e3d5ffd5b50505050505050505050565b60405163095ea7b360e01b81526001600160a01b0385169063095ea7b39061181a907f0000000000000000000000000000000000000000000000000000000000000000908690600401613104565b6020604051808303815f875af1158015611836573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061185a9190612f54565b50825160208401516040808601519051634f7f575960e11b81526001600160a01b038a8116600483015289811660248301526044820194909452606481018690525f608482015260a48101859052600160c482015291831660e483015282166101048201527f000000000000000000000000000000000000000000000000000000000000000090911690639efeaeb29061012401611797565b8481101561191857808560405163f6abf60f60e01b81526004016103c0929190613041565b83156119ef577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561197a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199e919061302a565b8110156119be576040516322157deb60e11b815260040160405180910390fd5b82606001518110156119ea57606083015160405163039505ed60e41b81526103c0918391600401613041565b610c99565b856001600160a01b031663794e57246040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a2b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a4f919061302a565b811015611a6f57604051637b6065eb60e11b815260040160405180910390fd5b5f807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663716c53c26040518163ffffffff1660e01b81526004016040805180830381865afa158015611acc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611af09190613008565b91509150846040015185608001518660a00151611b0d9190613076565b611b179190613089565b611b219083613076565b9150611b2d8482613076565b90505f611b3a8383611ed6565b90505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b99573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bbd919061302a565b9050808210156117c0578181604051632b00928d60e21b81526004016103c0929190613041565b5f611c38826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611ef99092919063ffffffff16565b8051909150156114125780806020019051810190611c569190612f54565b6114125760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016103c0565b5f80826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cf3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d179190612fed565b90505f836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d56573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d7a9190612fed565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826001600160a01b031614611dbb5781611dbd565b805b949350505050565b6040516001600160a01b03808516602483015283166044820152606481018290526114389085906323b872dd60e01b906084016113db565b5f805f805f8086606001515f0151806020019051810190611e1e9190613138565b945094509450945094505f611e3289611cb5565b90508115611e8157611e688b8b887f0000000000000000000000000000000000000000000000000000000000000000858a611f07565b88602001818151611e799190613076565b905250611ec6565b611eaf8b8b88847f00000000000000000000000000000000000000000000000000000000000000008a611f07565b508488602001818151611ec29190613063565b9052505b611674898960200151868661216c565b5f8115611ef1575f611ee883856130a0565b9150610ce39050565b505f19610ce3565b6060611dbd84845f856125de565b5f805f886001600160a01b031663eb7a7f7e896040518263ffffffff1660e01b8152600401611f3691906128a6565b6040805180830381865afa158015611f50573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f749190613008565b915091505f856001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611fa591906128a6565b602060405180830381865afa158015611fc0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fe4919061302a565b6040890151909150612001906001600160a01b03891690876126b5565b6120135f89604001518a5f0151612752565b6040516370a0823160e01b815281906001600160a01b038816906370a08231906120419030906004016128a6565b602060405180830381865afa15801561205c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612080919061302a565b61208a9190613063565b93505f808b6001600160a01b031663eb7a7f7e8c6040518263ffffffff1660e01b81526004016120ba91906128a6565b6040805180830381865afa1580156120d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120f89190613008565b9150915089602001518610156121285760208a015160405163c88d2ec760e01b81526103c0918891600401613041565b84821415806121375750838114155b1561215d578181868660405163f02b7d5760e01b81526004016103c0949392919061311d565b50505050509695505050505050565b5f80856001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161219a91906128a6565b602060405180830381865afa1580156121b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121d9919061302a565b90505f866001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015612218573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061223c9190612fed565b90505f876001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561227b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061229f9190612fed565b600154604051631d210ce760e01b81529192505f916001600160a01b0390911690631d210ce7906122d4908c906004016128a6565b602060405180830381865afa1580156122ef573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612313919061302a565b90505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168a6001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561237c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123a09190612fed565b6001600160a01b03161490505f81156123da57676765c793fa10079d601b1b6123c9848c613089565b6123d391906130a0565b90506123fd565b826123f0676765c793fa10079d601b1b8c613089565b6123fa91906130a0565b90505b5f82612409578a61240b565b815b90505f83612419578261241b565b8b5b90505f84612429578761242b565b865b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663095ea7b38f866040518363ffffffff1660e01b815260040161247b929190613104565b6020604051808303815f875af1158015612497573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124bb9190612f54565b506124d06001600160a01b0382168f8f6126b5565b60405163365d0ed760e01b81526004810184905260248101839052604481018d9052606481018c90523060848201526001600160a01b038f169063365d0ed79060a4016060604051808303815f875af115801561252f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125539190613226565b505050888e6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161258391906128a6565b602060405180830381865afa15801561259e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125c2919061302a565b6125cc9190613063565b9e9d5050505050505050505050505050565b60608247101561263f5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016103c0565b5f80866001600160a01b0316858760405161265a9190613251565b5f6040518083038185875af1925050503d805f8114612694576040519150601f19603f3d011682016040523d82523d5f602084013e612699565b606091505b50915091506126aa878383876127fc565b979650505050505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301525f91839186169063dd62ed3e90604401602060405180830381865afa158015612703573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612727919061302a565b6127319190613076565b90506114388463095ea7b360e01b85846040516024016113db929190613104565b6001600160a01b0382165f9081526020849052604090205460ff1661278a57604051635d7763a160e11b815260040160405180910390fd5b5f80836001600160a01b0316836040516127a49190613251565b5f604051808303815f865af19150503d805f81146127dd576040519150601f19603f3d011682016040523d82523d5f602084013e6127e2565b606091505b5091509150816127f5576127f581612874565b5050505050565b6060831561286a5782515f03612863576001600160a01b0385163b6128635760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016103c0565b5081611dbd565b611dbd838361287c565b805160208201fd5b81511561288c5781518083602001fd5b8060405162461bcd60e51b81526004016103c09190613267565b6001600160a01b0391909116815260200190565b6001600160a01b03811681146128ce575f80fd5b50565b5f80604083850312156128e2575f80fd5b82356128ed816128ba565b915060208301356001600160401b03811115612907575f80fd5b830160c08186031215612918575f80fd5b809150509250929050565b803561292e816128ba565b919050565b5f805f805f8060a08789031215612948575f80fd5b8635612953816128ba565b95506020870135612963816128ba565b9450604087013593506060870135925060808701356001600160401b0381111561298b575f80fd5b8701601f8101891361299b575f80fd5b80356001600160401b038111156129b0575f80fd5b8960208284010111156129c1575f80fd5b60208201935080925050509295509295509295565b80151581146128ce575f80fd5b5f805f805f8060c087890312156129f8575f80fd5b8635612a03816128ba565b95506020870135612a13816128ba565b945060408701359350606087013592506080870135915060a0870135612a38816129d6565b809150509295509295509295565b5f8060408385031215612a57575f80fd5b8235612a62816128ba565b91506020830135612918816129d6565b5f805f805f60a08688031215612a86575f80fd5b505083359560208501359550604085013594606081013594506080013592509050565b5f8083601f840112612ab9575f80fd5b5081356001600160401b03811115612acf575f80fd5b6020830191508360208260051b8501011115612ae9575f80fd5b9250929050565b5f805f8060408587031215612b03575f80fd5b84356001600160401b03811115612b18575f80fd5b612b2487828801612aa9565b90955093505060208501356001600160401b03811115612b42575f80fd5b612b4e87828801612aa9565b95989497509550505050565b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b03169052565b5f8135601e19833603018112612b8f575f80fd5b82016020810190356001600160401b03811115612baa575f80fd5b803603821315612bb8575f80fd5b60608552806060860152808260808701375f858201608001526020848101359086018190529150612beb60408501612923565b9150612bfa6040860183612b6e565b601f01601f1916939093016080019392505050565b5f60038610612c2c57634e487b7160e01b5f52602160045260245ffd5b8582526001600160a01b038516602080840191909152608060408085018290528635918501919091529085013560a084015284013560c08301526060840135612c74816128ba565b6001600160a01b031660e08301526080840135612c90816128ba565b6001600160a01b031661010083015260a084013536859003605e19018112612cb6575f80fd5b60c0610120840152612cce6101408401868301612b7b565b9150506109b46060830184612b6e565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b0381118282101715612d1457612d14612cde565b60405290565b604051608081016001600160401b0381118282101715612d1457612d14612cde565b604051601f8201601f191681016001600160401b0381118282101715612d6457612d64612cde565b604052919050565b5f6001600160401b03821115612d8457612d84612cde565b50601f01601f191660200190565b5f60608284031215612da2575f80fd5b612daa612cf2565b905081356001600160401b03811115612dc1575f80fd5b8201601f81018413612dd1575f80fd5b8035612de4612ddf82612d6c565b612d3c565b818152856020838501011115612df8575f80fd5b816020840160208301375f60209282018301528352838101359083015250612e2260408301612923565b604082015292915050565b5f81830360c0811215612e3e575f80fd5b612e46612d1a565b833581526020808501359082015291506060603f1982011215612e67575f80fd5b50612e70612cf2565b604083013581526060830135612e85816128ba565b60208201526080830135612e98816128ba565b60408281019190915282015260a08201356001600160401b03811115612ebc575f80fd5b612ec884828501612d92565b60608301525092915050565b5f610ce33683612e2d565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b03858116825284166020820152604081018390526080606082018190525f90612f3f90830184612edf565b9695505050505050565b805161292e816129d6565b5f60208284031215612f64575f80fd5b81516110ed816129d6565b5f805f8060808587031215612f82575f80fd5b843560038110612f90575f80fd5b93506020850135612fa0816128ba565b925060408501356001600160401b03811115612fba575f80fd5b612fc687828801612e2d565b9250506060850135612fd7816128ba565b939692955090935050565b805161292e816128ba565b5f60208284031215612ffd575f80fd5b81516110ed816128ba565b5f8060408385031215613019575f80fd5b505080516020909101519092909150565b5f6020828403121561303a575f80fd5b5051919050565b918252602082015260400190565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610ce357610ce361304f565b80820180821115610ce357610ce361304f565b8082028115828204841417610ce357610ce361304f565b5f826130ba57634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156130e3575f80fd5b81356110ed816128ba565b9283526020830191909152604082015260600190565b6001600160a01b03929092168252602082015260400190565b93845260208401929092526040830152606082015260800190565b5f805f805f60a0868803121561314c575f80fd5b85516001600160401b03811115613161575f80fd5b860160608189031215613172575f80fd5b61317a612cf2565b81516001600160401b0381111561318f575f80fd5b8201601f81018a1361319f575f80fd5b80516131ad612ddf82612d6c565b8181528b60208385010111156131c1575f80fd5b8160208401602083015e5f602092820183015283528381015190830152506131eb60408301612fe2565b60408281019190915260208901519089015160608a01519298509096509450925061321a905060808701612f49565b90509295509295909350565b5f805f60608486031215613238575f80fd5b5050815160208301516040909301519094929350919050565b5f82518060208501845e5f920191825250919050565b602081525f6110ed6020830184612edf56fea2646970667358221220d4d9b2640a30db3b1d76b4d853b9c3236d2bef53277168f836c592428f940fd164736f6c634300081a003300000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd40000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d57000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca500000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000fc30a70c19b201e67e60c14c6b36031d961f96f00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000ac4c6e212a361c968f1725b4d055b47e63f80b75

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106100ad575f3560e01c806321216ba3146100b157806323adce5f146100ee57806323e30c8b1461010357806368ea904714610124578063741bef1a1461013757806377553ad41461015e5780638ca67ac9146101855780639573ea2514610198578063a6b50585146101ab578063c11f5d5d146101be578063f2f4eb26146101d1578063f6038b67146101f8578063f8d898981461020b575b5f80fd5b6100d87f000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca581565b6040516100e591906128a6565b60405180910390f35b6101016100fc3660046128d1565b610232565b005b610116610111366004612933565b610356565b6040519081526020016100e5565b6001546100d8906001600160a01b031681565b6100d87f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a81565b6100d87f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd481565b6101166101933660046129e3565b61041e565b6101016101a6366004612a46565b61082b565b6101166101b9366004612a72565b6108e9565b6101016101cc366004612af0565b6109bd565b6100d87f000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d5781565b6101016102063660046128d1565b610ca1565b6100d87f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f81565b61023a610cc2565b5f808383336040516020016102529493929190612c0f565b60405160208183030381529060405290505f610277848461027290612ed4565b610ce0565b90507f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b0316635cffe9de307f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f84866040518563ffffffff1660e01b81526004016102eb9493929190612f0d565b6020604051808303815f875af1158015610307573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061032b9190612f54565b610348576040516349088f5960e11b815260040160405180910390fd5b5050610352610ce9565b5050565b5f61035f610cee565b336001600160a01b037f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f161415806103a057506001600160a01b0387163014155b156103c9573360405163ef04520760e01b81526004016103c091906128a6565b60405180910390fd5b5f8080806103d986880188612f6f565b93509350935093506103ee848484848d610d10565b507f439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd99a9950505050505050505050565b5f61271084116104705760405162461bcd60e51b815260206004820152601f60248201527f4c65766572616765206d7573742062652067726561746572207468616e20310060448201526064016103c0565b6104a36040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f886001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104e0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105049190612fed565b6040516375bd3fbf60e11b81529091506001600160a01b038a169063eb7a7f7e90610533908b906004016128a6565b6040805180830381865afa15801561054d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105719190613008565b60208401528252604051635670bcc760e11b81526001600160a01b037f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a169063ace1798e906105c49084906004016128a6565b602060405180830381865afa1580156105df573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610603919061302a565b604083015281515f03610616575f61062c565b61062c825f0151836020015184604001516110c3565b60608301525f87900361063f575f6106a6565b60405163ef8b30f760e01b8152600481018890526001600160a01b0382169063ef8b30f790602401602060405180830381865afa158015610682573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a6919061302a565b608083018190528251602084015160408501515f936106c79392918a6108e9565b9050808711156106ee578681604051636881ba1f60e01b81526004016103c0929190613041565b506127106106fc8188613063565b6080840151845161070d9190613076565b6107179190613089565b61072191906130a0565b60a083018190525f03610747576040516375d8f05d60e11b815260040160405180910390fd5b604051635670bcc760e11b81526001600160a01b037f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a169063ace1798e906107b3907f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f906004016128a6565b602060405180830381865afa1580156107ce573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107f2919061302a565b82604001518360a001516108069190613089565b61081091906130a0565b925061081f89838588886110f4565b50509695505050505050565b7f000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca56001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610887573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ab9190612fed565b6001600160a01b0316336001600160a01b0316146108de573360405163245aecd360e01b81526004016103c091906128a6565b6103525f838361135f565b5f80670de0b6b3a7640000846108ff878a613076565b6109099190613089565b61091391906130a0565b9050670de0b6b3a76400006109288785613089565b61093291906130a0565b8111610941575f9150506109b4565b5f670de0b6b3a7640000846109568985613063565b6109609190613089565b61096a91906130a0565b90505f670de0b6b3a7640000836109818288613063565b61098b9190613089565b61099591906130a0565b9050806109a461271084613089565b6109ae91906130a0565b93505050505b95945050505050565b7f000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca56001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a19573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a3d9190612fed565b6001600160a01b0316336001600160a01b031614610a70573360405163245aecd360e01b81526004016103c091906128a6565b825f5b81811015610c99575f868683818110610a8e57610a8e6130bf565b9050602002016020810190610aa391906130d3565b6001600160a01b031603610bbe575f7f000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca56001600160a01b031663b3f006746040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b0e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b329190612fed565b6001600160a01b0316858584818110610b4d57610b4d6130bf565b905060200201356040515f6040518083038185875af1925050503d805f8114610b91576040519150601f19603f3d011682016040523d82523d5f602084013e610b96565b606091505b5050905080610bb857604051633d2cec6f60e21b815260040160405180910390fd5b50610c91565b610c917f000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca56001600160a01b031663b3f006746040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c1d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c419190612fed565b858584818110610c5357610c536130bf565b90506020020135888885818110610c6c57610c6c6130bf565b9050602002016020810190610c8191906130d3565b6001600160a01b031691906113bc565b600101610a73565b505050505050565b610ca9610cc2565b5f60018383336040516020016102529493929190612c0f565b63769dd35360e11b5f5c15610cd957805f5260045ffd5b60015f5d50565b80515b92915050565b5f805d565b631e12bc8b60e11b5f5c60018114610d0857815f5260045ffd5b60025f5d5050565b5f817f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610d5e91906128a6565b602060405180830381865afa158015610d79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d9d919061302a565b610da79190613063565b90505f856001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610de6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0a9190612fed565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e6d9190612fed565b905085602001515f14610e8957610e8981868860200151611417565b5f610e97888789858761143e565b90505f847f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610ee791906128a6565b602060405180830381865afa158015610f02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f26919061302a565b610f309190613063565b90505f610f3d8288613063565b90505f8b6002811115610f5257610f52612b5a565b03610fc157610f698a89878c604001518786611683565b876001600160a01b03168a6001600160a01b03167fceb7fc8aae017c84c14d3757032afb8d320f723f5d8f1a3274f2de722cb3f68c8b60200151868b604051610fb4939291906130ee565b60405180910390a3611027565b610fd38a89878c6040015187866117cc565b876001600160a01b03168a6001600160a01b03167f7accea18c2c31aaa0e983d88efaa9ad7accf703abe513c864ef11835808611f48b60200151868b60405161101e939291906130ee565b60405180910390a35b60405163095ea7b360e01b81526001600160a01b037f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f169063095ea7b3906110759033908b90600401613104565b6020604051808303815f875af1158015611091573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110b59190612f54565b505050505050505050505050565b5f82156110e9575f836110d68487613089565b6110e091906130a0565b91506110ed9050565b505f195b9392505050565b5f7f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd46001600160a01b0316634ba4a28b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611151573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611175919061302a565b85519091505f9015611187575f611189565b815b90505f836111f657876001600160a01b03166366ca4a216040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111f1919061302a565b6111f8565b5f5b90505f670de0b6b3a764000061120e8184613076565b6112189089613089565b61122291906130a0565b90505f8189602001516112359190613076565b90505f6112428583613076565b90505f8a60a001518b608001518c5f015161125d9190613076565b6112679190613076565b90505f828c604001518361127b9190613089565b61128591906130a0565b905061129e8d8b8b8f6112988c8b613076565b866118f3565b5f7f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd46001600160a01b031663969c24526040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112fb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061131f919061302a565b90508061132c8a87613063565b101561134f57848160405163b9f105d760e01b81526004016103c0929190613041565b5050505050505050505050505050565b6001600160a01b0382165f8181526020858152604091829020805460ff191685151590811790915591519182527f7dc49220c17ba736a5a8f465c46784ed2262884e4ea605ae95e6fd117a77a421910160405180910390a2505050565b6114128363a9059cbb60e01b84846040516024016113db929190613104565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611be4565b505050565b5f61142184611cb5565b90506114386001600160a01b038216843085611dc5565b50505050565b5f805f876001600160a01b031663eb7a7f7e886040518263ffffffff1660e01b815260040161146d91906128a6565b6040805180830381865afa158015611487573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114ab9190613008565b915091505f6114bc8989888a611dfd565b90508660600151602001518110156114f25760608701516020015160405163c88d2ec760e01b81526103c0918391600401613041565b5f808a6001600160a01b031663eb7a7f7e8b6040518263ffffffff1660e01b815260040161152091906128a6565b6040805180830381865afa15801561153a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061155e9190613008565b9150915084821415806115715750838114155b15611597578181868660405163f02b7d5760e01b81526004016103c0949392919061311d565b60405163095ea7b360e01b81526001600160a01b0389169063095ea7b3906115c5908a908790600401613104565b6020604051808303815f875af11580156115e1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116059190612f54565b50604051636e553f6560e01b8152600481018490523060248201526001600160a01b03881690636e553f65906044016020604051808303815f875af1158015611650573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611674919061302a565b9b9a5050505050505050505050565b60405163095ea7b360e01b81526001600160a01b0385169063095ea7b3906116d1907f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd4908690600401613104565b6020604051808303815f875af11580156116ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117119190612f54565b508251602084015160408086015190516326caa39d60e01b81526001600160a01b038a8116600483015289811660248301526044820194909452606481018690526084810185905291831660a4830152821660c48201527f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd4909116906326caa39d9060e4015b5f604051808303815f87803b1580156117ae575f80fd5b505af11580156117c0573d5f803e3d5ffd5b50505050505050505050565b60405163095ea7b360e01b81526001600160a01b0385169063095ea7b39061181a907f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd4908690600401613104565b6020604051808303815f875af1158015611836573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061185a9190612f54565b50825160208401516040808601519051634f7f575960e11b81526001600160a01b038a8116600483015289811660248301526044820194909452606481018690525f608482015260a48101859052600160c482015291831660e483015282166101048201527f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd490911690639efeaeb29061012401611797565b8481101561191857808560405163f6abf60f60e01b81526004016103c0929190613041565b83156119ef577f000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d576001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561197a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199e919061302a565b8110156119be576040516322157deb60e11b815260040160405180910390fd5b82606001518110156119ea57606083015160405163039505ed60e41b81526103c0918391600401613041565b610c99565b856001600160a01b031663794e57246040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a2b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a4f919061302a565b811015611a6f57604051637b6065eb60e11b815260040160405180910390fd5b5f807f00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd46001600160a01b031663716c53c26040518163ffffffff1660e01b81526004016040805180830381865afa158015611acc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611af09190613008565b91509150846040015185608001518660a00151611b0d9190613076565b611b179190613089565b611b219083613076565b9150611b2d8482613076565b90505f611b3a8383611ed6565b90505f7f000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d576001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b99573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bbd919061302a565b9050808210156117c0578181604051632b00928d60e21b81526004016103c0929190613041565b5f611c38826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611ef99092919063ffffffff16565b8051909150156114125780806020019051810190611c569190612f54565b6114125760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016103c0565b5f80826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cf3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d179190612fed565b90505f836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d56573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d7a9190612fed565b90507f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b0316826001600160a01b031614611dbb5781611dbd565b805b949350505050565b6040516001600160a01b03808516602483015283166044820152606481018290526114389085906323b872dd60e01b906084016113db565b5f805f805f8086606001515f0151806020019051810190611e1e9190613138565b945094509450945094505f611e3289611cb5565b90508115611e8157611e688b8b887f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f858a611f07565b88602001818151611e799190613076565b905250611ec6565b611eaf8b8b88847f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f8a611f07565b508488602001818151611ec29190613063565b9052505b611674898960200151868661216c565b5f8115611ef1575f611ee883856130a0565b9150610ce39050565b505f19610ce3565b6060611dbd84845f856125de565b5f805f886001600160a01b031663eb7a7f7e896040518263ffffffff1660e01b8152600401611f3691906128a6565b6040805180830381865afa158015611f50573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f749190613008565b915091505f856001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611fa591906128a6565b602060405180830381865afa158015611fc0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fe4919061302a565b6040890151909150612001906001600160a01b03891690876126b5565b6120135f89604001518a5f0151612752565b6040516370a0823160e01b815281906001600160a01b038816906370a08231906120419030906004016128a6565b602060405180830381865afa15801561205c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612080919061302a565b61208a9190613063565b93505f808b6001600160a01b031663eb7a7f7e8c6040518263ffffffff1660e01b81526004016120ba91906128a6565b6040805180830381865afa1580156120d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120f89190613008565b9150915089602001518610156121285760208a015160405163c88d2ec760e01b81526103c0918891600401613041565b84821415806121375750838114155b1561215d578181868660405163f02b7d5760e01b81526004016103c0949392919061311d565b50505050509695505050505050565b5f80856001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161219a91906128a6565b602060405180830381865afa1580156121b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121d9919061302a565b90505f866001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015612218573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061223c9190612fed565b90505f876001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561227b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061229f9190612fed565b600154604051631d210ce760e01b81529192505f916001600160a01b0390911690631d210ce7906122d4908c906004016128a6565b602060405180830381865afa1580156122ef573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612313919061302a565b90505f7f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b03168a6001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561237c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123a09190612fed565b6001600160a01b03161490505f81156123da57676765c793fa10079d601b1b6123c9848c613089565b6123d391906130a0565b90506123fd565b826123f0676765c793fa10079d601b1b8c613089565b6123fa91906130a0565b90505b5f82612409578a61240b565b815b90505f83612419578261241b565b8b5b90505f84612429578761242b565b865b90507f0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f6001600160a01b031663095ea7b38f866040518363ffffffff1660e01b815260040161247b929190613104565b6020604051808303815f875af1158015612497573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124bb9190612f54565b506124d06001600160a01b0382168f8f6126b5565b60405163365d0ed760e01b81526004810184905260248101839052604481018d9052606481018c90523060848201526001600160a01b038f169063365d0ed79060a4016060604051808303815f875af115801561252f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125539190613226565b505050888e6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161258391906128a6565b602060405180830381865afa15801561259e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125c2919061302a565b6125cc9190613063565b9e9d5050505050505050505050505050565b60608247101561263f5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016103c0565b5f80866001600160a01b0316858760405161265a9190613251565b5f6040518083038185875af1925050503d805f8114612694576040519150601f19603f3d011682016040523d82523d5f602084013e612699565b606091505b50915091506126aa878383876127fc565b979650505050505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301525f91839186169063dd62ed3e90604401602060405180830381865afa158015612703573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612727919061302a565b6127319190613076565b90506114388463095ea7b360e01b85846040516024016113db929190613104565b6001600160a01b0382165f9081526020849052604090205460ff1661278a57604051635d7763a160e11b815260040160405180910390fd5b5f80836001600160a01b0316836040516127a49190613251565b5f604051808303815f865af19150503d805f81146127dd576040519150601f19603f3d011682016040523d82523d5f602084013e6127e2565b606091505b5091509150816127f5576127f581612874565b5050505050565b6060831561286a5782515f03612863576001600160a01b0385163b6128635760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016103c0565b5081611dbd565b611dbd838361287c565b805160208201fd5b81511561288c5781518083602001fd5b8060405162461bcd60e51b81526004016103c09190613267565b6001600160a01b0391909116815260200190565b6001600160a01b03811681146128ce575f80fd5b50565b5f80604083850312156128e2575f80fd5b82356128ed816128ba565b915060208301356001600160401b03811115612907575f80fd5b830160c08186031215612918575f80fd5b809150509250929050565b803561292e816128ba565b919050565b5f805f805f8060a08789031215612948575f80fd5b8635612953816128ba565b95506020870135612963816128ba565b9450604087013593506060870135925060808701356001600160401b0381111561298b575f80fd5b8701601f8101891361299b575f80fd5b80356001600160401b038111156129b0575f80fd5b8960208284010111156129c1575f80fd5b60208201935080925050509295509295509295565b80151581146128ce575f80fd5b5f805f805f8060c087890312156129f8575f80fd5b8635612a03816128ba565b95506020870135612a13816128ba565b945060408701359350606087013592506080870135915060a0870135612a38816129d6565b809150509295509295509295565b5f8060408385031215612a57575f80fd5b8235612a62816128ba565b91506020830135612918816129d6565b5f805f805f60a08688031215612a86575f80fd5b505083359560208501359550604085013594606081013594506080013592509050565b5f8083601f840112612ab9575f80fd5b5081356001600160401b03811115612acf575f80fd5b6020830191508360208260051b8501011115612ae9575f80fd5b9250929050565b5f805f8060408587031215612b03575f80fd5b84356001600160401b03811115612b18575f80fd5b612b2487828801612aa9565b90955093505060208501356001600160401b03811115612b42575f80fd5b612b4e87828801612aa9565b95989497509550505050565b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b03169052565b5f8135601e19833603018112612b8f575f80fd5b82016020810190356001600160401b03811115612baa575f80fd5b803603821315612bb8575f80fd5b60608552806060860152808260808701375f858201608001526020848101359086018190529150612beb60408501612923565b9150612bfa6040860183612b6e565b601f01601f1916939093016080019392505050565b5f60038610612c2c57634e487b7160e01b5f52602160045260245ffd5b8582526001600160a01b038516602080840191909152608060408085018290528635918501919091529085013560a084015284013560c08301526060840135612c74816128ba565b6001600160a01b031660e08301526080840135612c90816128ba565b6001600160a01b031661010083015260a084013536859003605e19018112612cb6575f80fd5b60c0610120840152612cce6101408401868301612b7b565b9150506109b46060830184612b6e565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b0381118282101715612d1457612d14612cde565b60405290565b604051608081016001600160401b0381118282101715612d1457612d14612cde565b604051601f8201601f191681016001600160401b0381118282101715612d6457612d64612cde565b604052919050565b5f6001600160401b03821115612d8457612d84612cde565b50601f01601f191660200190565b5f60608284031215612da2575f80fd5b612daa612cf2565b905081356001600160401b03811115612dc1575f80fd5b8201601f81018413612dd1575f80fd5b8035612de4612ddf82612d6c565b612d3c565b818152856020838501011115612df8575f80fd5b816020840160208301375f60209282018301528352838101359083015250612e2260408301612923565b604082015292915050565b5f81830360c0811215612e3e575f80fd5b612e46612d1a565b833581526020808501359082015291506060603f1982011215612e67575f80fd5b50612e70612cf2565b604083013581526060830135612e85816128ba565b60208201526080830135612e98816128ba565b60408281019190915282015260a08201356001600160401b03811115612ebc575f80fd5b612ec884828501612d92565b60608301525092915050565b5f610ce33683612e2d565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b03858116825284166020820152604081018390526080606082018190525f90612f3f90830184612edf565b9695505050505050565b805161292e816129d6565b5f60208284031215612f64575f80fd5b81516110ed816129d6565b5f805f8060808587031215612f82575f80fd5b843560038110612f90575f80fd5b93506020850135612fa0816128ba565b925060408501356001600160401b03811115612fba575f80fd5b612fc687828801612e2d565b9250506060850135612fd7816128ba565b939692955090935050565b805161292e816128ba565b5f60208284031215612ffd575f80fd5b81516110ed816128ba565b5f8060408385031215613019575f80fd5b505080516020909101519092909150565b5f6020828403121561303a575f80fd5b5051919050565b918252602082015260400190565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610ce357610ce361304f565b80820180821115610ce357610ce361304f565b8082028115828204841417610ce357610ce361304f565b5f826130ba57634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156130e3575f80fd5b81356110ed816128ba565b9283526020830191909152604082015260600190565b6001600160a01b03929092168252602082015260400190565b93845260208401929092526040830152606082015260800190565b5f805f805f60a0868803121561314c575f80fd5b85516001600160401b03811115613161575f80fd5b860160608189031215613172575f80fd5b61317a612cf2565b81516001600160401b0381111561318f575f80fd5b8201601f81018a1361319f575f80fd5b80516131ad612ddf82612d6c565b8181528b60208385010111156131c1575f80fd5b8160208401602083015e5f602092820183015283528381015190830152506131eb60408301612fe2565b60408281019190915260208901519089015160608a01519298509096509450925061321a905060808701612f49565b90509295509295909350565b5f805f60608486031215613238575f80fd5b5050815160208301516040909301519094929350919050565b5f82518060208501845e5f920191825250919050565b602081525f6110ed6020830184612edf56fea2646970667358221220d4d9b2640a30db3b1d76b4d853b9c3236d2bef53277168f836c592428f940fd164736f6c634300081a0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd40000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d57000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca500000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000fc30a70c19b201e67e60c14c6b36031d961f96f00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000ac4c6e212a361c968f1725b4d055b47e63f80b75

-----Decoded View---------------
Arg [0] : _borrowerOperations (address): 0x49FD0C4fb5172b20b7636b13c49fb15dA52D5bd4
Arg [1] : _debtToken (address): 0x0F26bBb8962d73bC891327F14dB5162D5279899F
Arg [2] : _priceFeed (address): 0xD9069E3F3EEb45d4E05b765142ba28f3BeB96F7a
Arg [3] : _core (address): 0xF6ec524105548C37D3C2eB482BA197AE19740d57
Arg [4] : _everlongCore (address): 0x776D3a1591E3F8b466B9Cee9DD1D849C92B30Ca5
Arg [5] : _initialSwapRouters (address[]): 0xAC4c6e212A361c968F1725b4d055b47E63F80b75
Arg [6] : _almPeriphery (address): 0xFc30A70C19B201e67e60C14C6b36031D961F96f0

-----Encoded View---------------
9 Constructor Arguments found :
Arg [0] : 00000000000000000000000049fd0c4fb5172b20b7636b13c49fb15da52d5bd4
Arg [1] : 0000000000000000000000000f26bbb8962d73bc891327f14db5162d5279899f
Arg [2] : 000000000000000000000000d9069e3f3eeb45d4e05b765142ba28f3beb96f7a
Arg [3] : 000000000000000000000000f6ec524105548c37d3c2eb482ba197ae19740d57
Arg [4] : 000000000000000000000000776d3a1591e3f8b466b9cee9dd1d849c92b30ca5
Arg [5] : 00000000000000000000000000000000000000000000000000000000000000e0
Arg [6] : 000000000000000000000000fc30a70c19b201e67e60c14c6b36031d961f96f0
Arg [7] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [8] : 000000000000000000000000ac4c6e212a361c968f1725b4d055b47e63f80b75


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.