ETH Price: $2,944.80 (-0.77%)

Contract

0xa9855658eC2e5766a9f73E056A0bF55Af7135fE0

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
YariEverlongManagedLeveragedVault

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 1 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EverlongManagedLeveragedVault} from "src/core/mlv/protocol/v1/prop/everlong/EverlongManagedLeveragedVault.sol";
import {IDeleverageRouter} from "src/interfaces/periphery/prop/base/IDeleverageRouter.sol";
import {IRedSnwapper} from "src/interfaces/utils/chains/katana/IRedSnwapper.sol";
import {IPositionManager} from "src/interfaces/utils/IPositionManager.sol";

/**
 * @title EverlongManagedLeveragedVault
 * @author Everlong team
 * @notice Vault version. See parent contracts for details.
 * @dev Responsible for interfacing with the DEX aggregator
 * @dev Tolerance on leverage/deleverage is set to BOTH, since it's key to keep the ICR at 2x at real prices, not just oracle prices
 */
contract YariEverlongManagedLeveragedVault is EverlongManagedLeveragedVault {
    using SafeERC20 for IERC20;

    IRedSnwapper public constant swapper = IRedSnwapper(0xAC4c6e212A361c968F1725b4d055b47E63F80b75);

    function forceNewPositionManager() external onlyOwnerOrKeeper {
        _getPropManagedLeveragedVaultStorage().positionManager = IPositionManager(0xeeA27dE7B45d1c7C98E89aC248F7a9b894fabA84);
        address oldImpl = 0x0Fa53F1b5f1b9552ed6b6d10C89CD9ec7B7E34A1;
        upgradeToAndCall(oldImpl, hex"");
    }

    function _afterRedeemEffects(uint256 coll, address receiver, bytes memory deleveragePayload) internal override virtual returns (uint256 assets) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();
        DeleverageParams memory p;
        (, p.minToken0Amount, p.minToken1Amount, p.outputMin, p.pathDefinition, p.executor) =
            abi.decode(deleveragePayload, (IDeleverageRouter.PositionLoopingParams, uint256, uint256, uint256, bytes, address));

        address _asset = asset();
        address debtToken = address($.v1.base.debtToken);

        (
            uint256 amountIn,
            uint256 assetBalance
        ) = _unwrapEverlongALM(_asset, coll, p.minToken0Amount, p.minToken1Amount);

        // Approve router to spend input tokens
        IERC20(debtToken).safeIncreaseAllowance(address(swapper), amountIn);
        /// @dev Since we are on Katana we use Sushiswaps DEX Aggregator, since it enables us to dynamically pass the inputAmount
        assets = swapper.snwap(
            debtToken,
            amountIn,
            address(this),
            _asset,
            p.outputMin,
            p.executor,
            p.pathDefinition
        ) + assetBalance;

        if (assets != 0) {
            IERC20(_asset).safeTransfer(receiver, assets);
        }
    }
}

// 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: BUSL-1.1

pragma solidity 0.8.26;

import {PropManagedLeveragedVault, IERC20} from "src/core/mlv/protocol/v1/prop/PropManagedLeveragedVault.sol";
import {ILSTCollateralVault} from "src/interfaces/utils/ILSTCollateralVault.sol";
import {IDebtToken} from "src/interfaces/utils/IDebtToken.sol";
import {IEverlongALM} from "src/interfaces/core/alm/IEverlongALM.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";

/**
 * @title EverlongManagedLeveragedVault
 * @author Everlong team
 * @notice Vault version. See parent contracts for details.
 * @dev Modified to support collVault to MLV asset unwrapping
 * @dev Tolerance on leverage/deleverage is set to BOTH, since it's key to keep the ICR at 2x at real prices, not just oracle prices
 */
abstract contract EverlongManagedLeveragedVault is PropManagedLeveragedVault {
    /**
     * @notice Increase exposure by borrowing debt and swapping it for collateral
     * @dev Won't work during RecoveryMode
     * @dev Keeper has to cap debtAmount to available debt, after accounting borrowingFee, since of maxSystemDebt
     */
    function increaseLeverage(
        bytes calldata leveragePayload
    ) external onlyOwnerOrKeeper override nonReentrant maxOperationCost(address(_getBaseManagedLeveragedVaultStorage().debtToken), leveragePayload) {
        _leverage(0, leveragePayload);

        _checkInvariantICR(_getCurrentPositionICR(), _getTargetICR(), Tolerance.BOTH);
    }

    /**
     * @notice Decrease exposure by swapping collateral for debt
     */
    function decreaseLeverage(
        bytes calldata deleveragePayload
    ) external onlyOwnerOrKeeper override nonReentrant maxOperationCost(address(_getBaseManagedLeveragedVaultStorage().collateral), deleveragePayload) {
        _deleverage(0, deleveragePayload);

        _checkInvariantICR(_getCurrentPositionICR(), _getTargetICR(), Tolerance.BOTH);
    }

    struct DeleverageParams {
        uint256 minToken0Amount;
        uint256 minToken1Amount;
        uint256 outputQuote;
        uint256 outputMin;
        bytes   pathDefinition;
        address executor;
        uint32  referralCode;
    }

    function _unwrapEverlongALM(
        address _asset,
        uint256 collVaultAmount,
        uint256 minToken0Amount,
        uint256 minToken1Amount
    ) internal returns (uint256 amountIn, uint256 assetBalance) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        IDebtToken debtToken = IDebtToken(address($.v1.base.debtToken));
        ILSTCollateralVault collVault = ILSTCollateralVault(address($.v1.base.collateral));
        IEverlongALM collVaultAsset = IEverlongALM(collVault.asset());
        uint256 prevDebtTokenBalance = debtToken.balanceOf(address(this));
        uint256 prevAssetBalance = IERC20(_asset).balanceOf(address(this));
        
        uint256 everlongVaultAmount = super._afterRedeemEffects(collVaultAmount, address(this), hex"");
        collVaultAsset.withdraw(everlongVaultAmount, minToken0Amount, minToken1Amount, address(this));

        amountIn = debtToken.balanceOf(address(this)) - prevDebtTokenBalance;
        assetBalance = IERC20(_asset).balanceOf(address(this)) - prevAssetBalance;
    }

    /// @dev Everlong vaults break the previous invariant in which the vault asset was as well the asset of the collateral vault
    function _collConversion(uint256 assets) internal view override returns (uint256 coll) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        address collVaultAsset = ILSTCollateralVault(address($.v1.base.collateral)).asset();

        uint256 collVaultAssetPrice = getPrice(collVaultAsset);
        uint256 assetPrice = getPrice(asset());
        uint256 collVaultAssetScaling = 10 ** uint256(IAsset(collVaultAsset).decimals());
        uint256 assetDecimalsScaling = 10 ** uint256(IAsset(asset()).decimals());

        // An overflow would require a very high decimal coll vault asset, or really high price
        uint256 collVaultAssetAmount = assets * assetPrice * collVaultAssetScaling / (collVaultAssetPrice * assetDecimalsScaling);

        coll = super._collConversion(collVaultAssetAmount);
    }
}

// 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 IDeleverageRouter is IERC3156FlashBorrower {
    enum Operation {
        ClosePosition,
        RepayDebt
    }

    struct PositionParams {
        uint256 collVaultAmount; // To withdraw
        address upperHint;
        address lowerHint;
    }

    struct RedeemToOnePartialParams {
        uint256 minTargetTokenAmount;
        uint256 collAmountToSwap;
        address swapRouter;
        bytes[] swapCalldatas;
    }

    struct PositionLoopingParams {
        uint256 debtToRepay;
        uint256 debtTokenProvidedByUser;
        PositionParams positionParams;
        RedeemToOnePartialParams collVaultParams;
    }

    error NotOwner(address sender);
    error NotDebtToken(address caller);
    error ZeroAddress();
    error FlashLoanFailed();
    error NativeTransferFailed();
    error InsufficientCollateral(uint256 collAmount, uint256 minCollAmount);
    error InsufficientDebtTokenReceived(uint256 debtTokenReceived, uint256 minDebtTokenAmount);
    error InsufficientDebtToClose(uint256 provided, uint256 actual);
    error NoPositionToClose();
    error NoNeedToLoop();
    error DebtOrCollateralChanged(
        uint256 currentColl,
        uint256 currentDebt,
        uint256 newColl,
        uint256 newDebt
    );

    event Deleverage(
        address indexed positionManager,
        address indexed account,
        uint256 collAmountWithdrawn, // in collateral vault denominated amount
        uint256 collAmountToSwap, // in collateral vault denominated amount, if parameter overriden, can be less than collAmountWithdrawn
        uint256 debtTokenReceived, // after collVault to debtToken swap
        uint256 debtAmount,
        Operation operation
    );

    /// @dev Allows the user to repay debt for position using flashloan, if internal swap has positive slippage, sends extra debt token to the user
    /// @dev Ensure it leaves minNetDebt, margin slippage check is done in the debt token approval step
    function automaticLoopingRepayDebt(IPositionManager positionManager, PositionLoopingParams calldata positionLoopingParams) external;

    /// @dev Allows the user to close a position using flashloan, if internal swap has positive slippage, sends extra debt token or collateral to the user
    /// @dev Margin slippage check is done in the debt token approval step
    function closePosition(IPositionManager positionManager, PositionLoopingParams calldata closePositionWithFlashLoanParams) external;
    /// @dev Allows owner to claim any remaining tokens, including ETH, stored in the router contract.
    function claimLockedTokens(IERC20[] calldata tokens, uint256[] calldata amounts) external;
}

// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.26;

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

interface IRedSnwapper {
    struct InputToken {
      address token;
      uint amountIn;
      address transferTo;
    }

    struct OutputToken {
      address token;
      address recipient;
      uint amountOutMin;
    }

    struct Executor {
      address executor;
      uint value;
      bytes data;
    }

    function snwap(
        address tokenIn,
        uint amountIn, // if amountIn == 0 then amountIn = tokenIn.balance(this) - 1
        address recipient,
        address tokenOut,
        uint amountOutMin,
        address executor,
        bytes calldata executorData
    ) external payable returns (uint amountOut);

    function snwapMultiple(
        InputToken[] calldata inputTokens,
        OutputToken[] calldata outputTokens,
        Executor[] calldata executors
    ) external payable returns (uint[] memory amountOut);
}

File 6 of 84 : 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
// 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);
}

// 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);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {IERC20, SafeERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ManagedLeveragedVaultV1} from "src/core/mlv/base/v1/ManagedLeveragedVault.sol";
import {IPropManagedLeveragedVault} from "src/interfaces/core/mlv/protocol/v1/prop/IPropManagedLeveragedVault.sol";
import {IBorrowerOperations} from "src/interfaces/utils/IBorrowerOperations.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {IPositionManager} from "src/interfaces/utils/IPositionManager.sol";
import {ILeverageRouter} from "src/interfaces/periphery/prop/base/ILeverageRouter.sol";
import {IDeleverageRouter} from "src/interfaces/periphery/prop/base/IDeleverageRouter.sol";
import {PropMath} from "src/libraries/PropMath.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {BaseManagedLeveragedVault, IBaseManagedLeveragedVault} from "src/core/mlv/base/BaseManagedLeveragedVault.sol";
import {PropLib} from "src/core/mlv/base/lib/PropLib.sol";
    
/**
 * @title PropManagedLeveragedVault
 * @author Everlong team
 * @notice This contract implements a managed leveraged vault for the CDP protocol.
 * @dev `$.collateral` is different that `asset()`, the first is a CDP CollateralVault, the former is also the asset of the CollateralVault.
 */
contract PropManagedLeveragedVault is ManagedLeveragedVaultV1, IPropManagedLeveragedVault {
    using PropLib for PropLib.Context;
    using SafeERC20 for IERC20;
    using Math for uint256;

    /// @custom:storage-location erc7201:openzeppelin.storage.ManagedLeveragedVault
    struct PropManagedLeveragedVaultStorage {
        ManagedLeveragedVaultV1Storage v1;
        IBorrowerOperations borrowerOperations;
        IPositionManager positionManager;
        ILeverageRouter leverageRouter;
        IDeleverageRouter deleverageRouter;
    }

    function _getPropManagedLeveragedVaultStorage()
        internal
        pure
        returns (PropManagedLeveragedVaultStorage storage store)
    {
        assembly {
            store.slot := ManagedLeveragedVaultStorageLocation
        }
    }

    function initialize(BaseInitParams calldata baseParams, ProtocolInitParams calldata protocolParams) external initializer {
        _baseInitialize(baseParams);
        _protocolInitialize(protocolParams);
    }

    function _protocolInitialize(ProtocolInitParams memory params) internal {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        if (
            params.borrowerOperations == address(0)
            || params.positionManager == address(0)
            || params.leverageRouter == address(0)
            || params.deleverageRouter == address(0)
        ) revert ZeroAddress();

        $.borrowerOperations = IBorrowerOperations(params.borrowerOperations);
        $.positionManager = IPositionManager(params.positionManager);
    
        $.leverageRouter = ILeverageRouter(params.leverageRouter);
        $.deleverageRouter = IDeleverageRouter(params.deleverageRouter);

        /// @dev Both routers are permissioned for the MLV
        _setDelegateApproval(params.leverageRouter, true);
        _setDelegateApproval(params.deleverageRouter, true);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CORE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _totalAssets(Math.Rounding rounding) internal view override returns (uint256) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();
        
        IPositionManager positionManager = IPositionManager($.positionManager);
        (uint256 collateral, uint256 debt) = _getPositionCollAndDebt();
        collateral += positionManager.surplusBalances(address(this));
        uint256 collateralValue = $.v1.base.getters.getCollateralValue(collateral);
        uint256 debtValue = $.v1.base.getters.getDebtValue(debt);
        
        if (debtValue > collateralValue) {
            revert BadDebt(debtValue - collateralValue);
        }

        uint256 netValue = collateralValue - debtValue;
        address _asset = asset();
        uint256 assetPrice = getPrice(_asset);
        uint8 assetDecimals = IAsset(_asset).decimals();
        
        uint256 assets = netValue.mulDiv(10 ** assetDecimals, assetPrice, rounding);
        
        return assets;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           SETTERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function setLeverageRouter(address _leverageRouter) external onlyOwner {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        if (_leverageRouter == address(0)) revert ZeroAddress();

        $.leverageRouter = ILeverageRouter(_leverageRouter);

        emit NewLeverageRouter(_leverageRouter);
    }

    function setDeleverageRouter(address _deleverageRouter) external onlyOwner {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        if (_deleverageRouter == address(0)) revert ZeroAddress();

        $.deleverageRouter = IDeleverageRouter(_deleverageRouter);

        emit NewDeleverageRouter(_deleverageRouter);
    }

    function setDelegateApproval(address user, bool isDelegated) external onlyOwner {
        _setDelegateApproval(user, isDelegated);
    }

    function _setDelegateApproval(address user, bool isDelegated) internal {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        $.borrowerOperations.setDelegateApproval(user, isDelegated);

        emit NewDelegation(user, isDelegated);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         INTERNALS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _leverage(uint256 margin, bytes calldata levPayload) internal override {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        VaultState memory vs;
        IPositionManager positionManager = IPositionManager($.positionManager);
        ILeverageRouter.PositionLoopingParams memory levP = abi.decode(levPayload, (ILeverageRouter.PositionLoopingParams));

        if (margin == 0) {
            _getPropContext()._checkMaxFeePercentage(levP.positionParams.maxFeePercentage);
        }

        levP.marginCollAmount = margin;

        (vs.prevColl, vs.prevDebt) = _getPositionCollAndDebt();

        // Perform the leverage using the rebalancer contract
        IERC20(asset()).forceApprove(address($.leverageRouter), levP.marginCollAmount);
        $.leverageRouter.automaticLoopingAddCollateral(
            positionManager,
            levP
        );

        (vs.newColl, vs.newDebt) = _getPositionCollAndDebt();

        // should be at least higher with margin addition 
        if (vs.newColl <= vs.prevColl + _collConversion(levP.marginCollAmount)) revert CollateralNotIncreased(vs.newColl, vs.prevColl);
        if (vs.newDebt <= vs.prevDebt) revert DebtNotIncreased(vs.newDebt, vs.prevDebt);
        if (levP.marginCollAmount != 0) {
            uint256 collDeposit = vs.newColl - vs.prevColl;
            uint256 debtMinted = vs.newDebt - vs.prevDebt;

            uint256 targetCR = _getTargetICR();
            uint256 collPrice = positionManager.fetchPrice();

            // assert CR within deviation range
            // don't check it if the position is being initialized
            if (totalSupply() != 0) {
                uint256 operationCR = PropMath._computeCR(collDeposit, debtMinted, collPrice);
                _checkInvariantICR(operationCR, targetCR, Tolerance.BOTH);
            }
        }
    }

    function _deleverage(uint256 collToReceive, bytes calldata delevPayload) internal override returns (uint256 collVaultToRedeem) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();

        VaultState memory vs;
        IPositionManager positionManager = IPositionManager($.positionManager);
        IDeleverageRouter.PositionLoopingParams memory delevP = abi.decode(delevPayload, (IDeleverageRouter.PositionLoopingParams));

        (vs.prevColl, vs.prevDebt) = _getPositionCollAndDebt();

        (vs.prevDebtBalance, vs.prevCollateralBalance) = _debtAndCollateralBalance();

        if (delevP.collVaultParams.collAmountToSwap == 0) revert ZeroAmount();
        delevP.positionParams.collVaultAmount = collToReceive + delevP.collVaultParams.collAmountToSwap;
        delevP.debtTokenProvidedByUser = 0;

        uint256 prevTotalAssets = collToReceive != 0 ? _totalAssets(Math.Rounding.Up) : 0;

        $.deleverageRouter.automaticLoopingRepayDebt(
            positionManager,
            delevP
        );

        (vs.debtBalance, vs.collateralBalance) = _debtAndCollateralBalance();

        /// @dev If debt token received in collateral swap ends up being more than flash loaned, it's sent to this contract
        uint256 debtTokenSurplus = vs.debtBalance - vs.prevDebtBalance;
        if (collToReceive != 0) {
            collVaultToRedeem = _computeNetCollWithDebtSurplus(
                debtTokenSurplus,
                collToReceive,
                prevTotalAssets
            );
        }

        /// @dev Hints may be slightly off after deleveraging
        /// @dev If more exposure was used, it is substracted to his withdrawable assets, and redeposited
        /// @dev If less exposure was needed, it is added to his withdrawable assets
        /// @dev DebtToken refunded due to surpassing flash loan repayment is position-repayed
        _modifyCollAndRepayDebt(
            abi.encode(
                delevP.positionParams.upperHint,
                delevP.positionParams.lowerHint
            ),
            int256(vs.collateralBalance) - int256(vs.prevCollateralBalance) - int256(collVaultToRedeem),
            debtTokenSurplus
        );

        (vs.newColl, vs.newDebt) = _getPositionCollAndDebt();

        if (collToReceive != 0) {
            uint256 operationCR = PropMath._computeCR(vs.prevColl - vs.newColl, vs.prevDebt - vs.newDebt, positionManager.fetchPrice());
            _checkInvariantICR(operationCR, _getTargetICR(), Tolerance.BOTH);
        }

        // should be at least lower with margin substraction
        if (vs.newColl >= vs.prevColl) revert CollateralNotDecreased(vs.newColl, vs.prevColl);
        if (vs.newDebt > vs.prevDebt) revert DebtNotDecreased(vs.newDebt, vs.prevDebt);
    }

    function _modifyCollAndRepayDebt(
        bytes memory modifyPositionPayload,
        int256 missingExposure,
        uint256 debt
    ) internal override {
        _getPropContext()._modifyCollAndRepayDebt(
            modifyPositionPayload,
            missingExposure,
            debt
        );
    }

    function _openPosition(
        bytes calldata openPositionPayload
    ) internal override {
        _getPropContext()._openPosition(openPositionPayload);
    }

    function _preRedeemEffects() internal view override {
        _getPropContext()._preRedeemEffects();
    }

    /// @dev Caution with `assets`, it can be reward tokens denominated in 'asset()' units
    function _afterRedeemEffects(uint256 coll, address receiver, bytes memory deleveragePayload) internal override virtual returns (uint256 assets) {
        address collVaultAsset = IERC4626(address(_getBaseManagedLeveragedVaultStorage().collateral)).asset();  
        assets = _getPropContext()._afterRedeemEffects(collVaultAsset, coll, receiver, deleveragePayload);
    }

    function _collConversion(uint256 assets) internal view override virtual returns (uint256 coll) {
        coll = _getPropContext()._collConversion(assets);
    }

    function _decodeSwapAmount(address inputToken, bytes memory payload) internal view override returns (uint256 amountToSwap) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (inputToken == address($.collateral)) {
            amountToSwap = abi.decode(payload, (IDeleverageRouter.PositionLoopingParams)).collVaultParams.collAmountToSwap;
        } else {
            amountToSwap = abi.decode(payload, (ILeverageRouter.PositionLoopingParams)).flashloanDebtTokenAmount;
        }
    }

    function _collateralDecimals() internal pure override returns (uint8) {
        return PropLib._collateralDecimals();
    }

    function _getPositionCollAndDebt() internal view override returns (uint256 coll, uint256 debt) {
        return _getPropContext()._getPositionCollAndDebt();
    }

    function _pullRewards() internal override {
        _getPropContext()._pullRewards();
    }

    function _getPropContext() private view returns (PropLib.Context memory) {
        PropManagedLeveragedVaultStorage storage $ = _getPropManagedLeveragedVaultStorage();
        return PropLib.Context({
            asset: asset(),
            positionManager: $.positionManager,
            borrowerOperations: $.borrowerOperations,
            collateral: $.v1.base.collateral,
            everlongCore: $.v1.base.everlongCore,
            getters: $.v1.base.getters
        });
    }
}

// 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);
}

File 12 of 84 : 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);
}

// 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: MIT
pragma solidity 0.8.26;

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

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

File 15 of 84 : 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);
}

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

pragma solidity ^0.8.0;

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

File 17 of 84 : 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/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);
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
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);
}

// 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: BUSL-1.1

pragma solidity 0.8.26;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20, IERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IManagedLeveragedVaultV1} from "src/interfaces/core/mlv/base/v1/IManagedLeveragedVaultV1.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";
import {UtilsLib} from "src/libraries/UtilsLib.sol";
import {BaseManagedLeveragedVault, IBaseManagedLeveragedVault} from "src/core/mlv/base/BaseManagedLeveragedVault.sol";

/**
 * @title ManagedLeveragedVaultV1
 * @author Everlong team
 * @notice Managed leverage token with the set leverage/CR target.
 * @dev Exposure token is the same asset.
 * @dev Breaks ERC4626 standard.
 */
abstract contract ManagedLeveragedVaultV1 is BaseManagedLeveragedVault, IManagedLeveragedVaultV1 {
    using Math for uint256;
    using PriceLib for uint256;
    using SafeERC20 for IERC20;
    using UtilsLib for bytes;

    /// @custom:storage-location erc7201:openzeppelin.storage.ManagedLeveragedVault
    struct ManagedLeveragedVaultV1Storage {
        BaseManagedLeveragedVaultStorage base;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CORE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /**
     * @notice Positionominated in `asset()`, tracks collVaultShares (coll and margin) and substracts PnL of the exposure token, minus position debt
     * @dev Breaks ERC4626 since it can revert on BadDebt
     */
    function totalAssets() public view override(BaseManagedLeveragedVault, IBaseManagedLeveragedVault) returns (uint256) {
        return _totalAssets(Math.Rounding.Down);
    }

    /**
     * @notice Increase exposure by borrowing debt and swapping it for collateral
     * @dev Won't work during RecoveryMode
     * @dev Keeper has to cap debtAmount to available debt, after accounting borrowingFee, since of maxSystemDebt
     */
    function increaseLeverage(
        bytes calldata leveragePayload
    ) external onlyOwnerOrKeeper virtual nonReentrant maxOperationCost(address(_getBaseManagedLeveragedVaultStorage().debtToken), leveragePayload) {
        _leverage(0, leveragePayload);

        _checkInvariantICR(_getCurrentPositionICR(), _getTargetICR(), Tolerance.ABOVE);
    }

    /**
     * @notice Decrease exposure by swapping collateral for debt
     */
    function decreaseLeverage(
        bytes calldata deleveragePayload
    ) external onlyOwnerOrKeeper virtual nonReentrant maxOperationCost(address(_getBaseManagedLeveragedVaultStorage().collateral), deleveragePayload) {
        _deleverage(0, deleveragePayload);

        _checkInvariantICR(_getCurrentPositionICR(), _getTargetICR(), Tolerance.ABOVE);
    }

    /// @notice Open a new position with targetCR and all availabe collateral, occurs in the case of a migration (closedByOwner), or liquidation/redemption
    /// @dev If it's a liquidation/redemption, if there's collSurplus it will be claimed
    function openPosition(
        bytes calldata openPositionPayload,
        address swapRouter,
        bytes memory dexPayload,
        bytes calldata leveragePayload
    ) external onlyOwnerOrKeeper {
        _openPosition(openPositionPayload);

        _mintOnce(swapRouter, dexPayload, leveragePayload);

        _checkInvariantICR(_getCurrentPositionICR(), _getTargetICR(), Tolerance.ABOVE);
    }

    function _mintOnce(
        address swapRouter,
        bytes memory dexPayload,
        bytes calldata leveragePayload
    ) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        uint256 debtBalance = IERC20($.debtToken).balanceOf(address(this));
        $.debtToken.forceApprove(swapRouter, debtBalance);
        (bool success, bytes memory retData) = swapRouter.call(dexPayload);
        if (!success) {
            retData.bubbleUpRevert();
        }

        uint256 margin = IERC20(asset()).balanceOf(address(this));

        if (margin == 0) revert ZeroAmount();

        _leverage(margin, leveragePayload);

        if (totalSupply() == 0) {
            _mint($.everlongCore.owner(), totalAssets());
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          GETTERS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function getMarginBalance() public view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        uint256 debtValue = $.getters.getDebtValue();
        uint256 debtInCollateral = debtValue.convertToAmount(
            getPrice(address($.collateral)),
            _collateralDecimals(),
            Math.Rounding.Down
        );

        return $.getters.getCollateralBalance() - debtInCollateral;
    }

    function getExposureBalance() public view returns (uint256) {
        (uint256 coll,) = _getPositionCollAndDebt();

        return coll - getMarginBalance();
    }

    function getExposureValue() public view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return getExposureBalance().mulDiv(getPrice(address($.collateral)), WAD);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         INTERNALS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _computeNetCollWithDebtSurplus(
        uint256 debtSurplus,
        uint256 collToReceive,
        uint256 prevTotalAssets
    ) internal view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        uint256 debtSurplusInUsd = debtSurplus.mulDiv(getPrice(address($.debtToken)), WAD);
        uint256 debtSurplusInAssets = debtSurplusInUsd.mulDiv(10 ** IAsset(asset()).decimals(), getPrice(asset()));

        return _computeNetColl(debtSurplusInAssets, collToReceive, prevTotalAssets);
    }

    function _debtAndCollateralBalance() internal view returns (uint256 debtBalance, uint256 collateralBalance) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        debtBalance = $.debtToken.balanceOf(address(this));
        collateralBalance = $.collateral.balanceOf(address(this));
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IBaseManagedLeveragedVault} from "src/interfaces/core/mlv/base/IBaseManagedLeveragedVault.sol";

interface IPropManagedLeveragedVault {
    // --- Enums ------------------------------------------------
    enum PositionStatus { nonExistent, active, closedByOwner, closedByLiquidation, closedByRedemption }

    struct ProtocolInitParams {
        address borrowerOperations;
        address positionManager;
        address leverageRouter;
        address deleverageRouter;
    }

    struct VaultState {
        uint256 prevColl;
        uint256 prevDebt;
        uint256 newColl;
        uint256 newDebt;
        uint256 prevDebtBalance;
        uint256 prevCollateralBalance;
        uint256 debtBalance;
        uint256 collateralBalance;
        uint256 targetCR;
        uint256 collPrice;
    }

    // --- Errors -----------------------------------------------
    error BadDebt(uint256 debt);
    error CollateralNotIncreased(uint256 actual, uint256 previous);
    error DebtNotIncreased(uint256 actual, uint256 previous);
    error CollateralNotDecreased(uint256 actual, uint256 previous);
    error DebtNotDecreased(uint256 actual, uint256 previous);

    // --- Events -----------------------------------------------
    event NewLeverageRouter(address leverageRouter);
    event NewDeleverageRouter(address deleverageRouter);
    event NewDelegation(address delegation, bool enabled);

    // --- Functions ---------------------------------------------
    function initialize(IBaseManagedLeveragedVault.BaseInitParams calldata baseParams, ProtocolInitParams calldata protocolParams) external;
    function setLeverageRouter(address _leverageRouter) external;
    function setDeleverageRouter(address _deleverageRouter) external;
    function setDelegateApproval(address user, bool isDelegated) external;
}

// 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.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;

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;
}

// 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;
    }
}

File 27 of 84 : BaseManagedLeveragedVault.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {
    ERC4626Upgradeable,
    ERC20Upgradeable,
    IERC4626,
    Math
} from "@openzeppelin-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20, IERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IBaseManagedLeveragedVault} from "src/interfaces/core/mlv/base/IBaseManagedLeveragedVault.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";
import {FeeLib} from "src/libraries/FeeLib.sol";
import {ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {IFeeHook} from "src/interfaces/utils/IFeeHook.sol";
import {ITargetICRHook} from "src/interfaces/utils/ITargetICRHook.sol";
import {IBaseManagedLeveragedVaultGetters} from "src/interfaces/core/mlv/helpers/base/IBaseManagedLeveragedVaultGetters.sol";

abstract contract BaseManagedLeveragedVault is ERC4626Upgradeable, UUPSUpgradeable, IBaseManagedLeveragedVault {
    using Math for uint256;
    using PriceLib for uint256;
    using SafeERC20 for IERC20;
    using FeeLib for uint256;

    uint256 constant WAD = 1e18;
    uint16 constant BP = 1e4;
    uint16 constant MAX_DEVIATION_ICR = 500; // 5%
    uint16 constant MAX_DEVIATION_TA = 250; // 2.5%
    uint16 constant MAX_SLIPPAGE_SWAP = 300; // 3%

    struct BaseManagedLeveragedVaultStorage {
        IEverlongCore everlongCore;
        IERC20 debtToken; // Debt token used for leverage
        IERC20 collateral; // In case it's different from the asset
        uint16 maxDeviationICRinBP; // BP
        uint16 maxDeviationTotalAssetsInBP; // BP
        uint16 maxSlippageSwapInBP; // BP
        address keeper;
        ITargetICRHook targetICRHook;
        IFeeHook feeHook; // Hook to charge fees on deposit/withdraw
        IBaseManagedLeveragedVaultGetters getters;
    }

    // keccak256(abi.encode(uint(keccak256("openzeppelin.storage.ManagedLeveragedVault")) - 1)) & ~bytes32(uint(0xff))
    bytes32 internal constant ManagedLeveragedVaultStorageLocation =
        0x12ca37b393c412d053690654fb6d504d2a16c55c2bd10941af581f2221d9c100;

    function _getBaseManagedLeveragedVaultStorage()
        internal
        pure
        returns (BaseManagedLeveragedVaultStorage storage store)
    {
        assembly {
            store.slot := ManagedLeveragedVaultStorageLocation
        }
    }

    constructor() {
        _disableInitializers();
    }

    function _baseInitialize(BaseInitParams memory params) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (
            params.everlongCore == address(0)
        ) revert ZeroAddress();

        __ERC4626_init(params.asset);
        __ERC20_init(params.name, params.symbol);

        $.everlongCore = IEverlongCore(params.everlongCore);
        $.debtToken = IERC20(params.debtToken);
        $.collateral = IERC20(params.collateral);
        _setTargetICRHook(params.targetICRHook);
        _setMaxDeviationICRinBP(params.maxDeviationICRinBP);
        _setMaxDeviationTotalAssetsInBP(params.maxDeviationTotalAssetsInBP);
        _setMaxSlippageSwapInBP(params.maxSlippageSwapInBP);
        _setKeeper(params.keeper);
        _setFeeHook(params.feeHook);
        _setGetters(params.getters);
    }

    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    modifier onlyOwner() {
        _onlyOwner();
        _;
    }

    modifier onlyOwnerOrKeeper() {
        _onlyOwnerOrKeeper();
        _;
    }

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

    modifier pullRewards() {
        _pullRewards();
        _;
    }

    /// @dev Checks if the operation is within the max deviation in totalAssets, and swap slippage limits
    modifier maxOperationCost(address inputToken, bytes memory payload) {
        _pullRewards();
        uint256 prevTotalAssets = totalAssets();
        _;
        uint256 amountToSwap = _decodeSwapAmount(inputToken, payload);
        _getBaseManagedLeveragedVaultStorage().getters.checkMaxOperationCost(inputToken, amountToSwap, prevTotalAssets);
    }

    function deposit(uint256, address) public pure override returns (uint256) { revert NotSupportedMethod(); }
    function mint(uint256, address) public pure override returns (uint256) { revert NotSupportedMethod(); }
    function withdraw(uint256, address, address) public pure override returns (uint256) { revert NotSupportedMethod(); }
    function redeem(uint256, address, address) public pure override returns (uint256) { revert NotSupportedMethod(); }

    function totalAssets() public view override(ERC4626Upgradeable, IBaseManagedLeveragedVault) virtual returns (uint256) {
        return _totalAssets(Math.Rounding.Down);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      CORE INTERNALS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Make sure to override in child implementation
    function _totalAssets(Math.Rounding rounding) internal view virtual returns (uint256) {}


    // totalAssets > totalSupply, shareholders are making a profit, 
    // totalSupply



    /**
     * @notice Accepts `asset()`, wraps into into a collateral (if needed) and deposits it into the position as margin
     * @notice There's an entryFeeInBP which is charged in this vault shares
     * @dev Position is incentivized to be opened with a CR close to target, with only a small deviation accepted
     * @dev Any operation cost in internalized to the user (e.g.negative slippage, borrowing fees...) lead to fewer shares, positive slippage can lead to more
     * @param assets Amount of `asset()` to deposit
     * @param receiver Address to receive shares
     * @param leveragePayload Encoded parameters for the leverage rebalance operation
     * @param minSharesOut Minimum amount of shares to be minted, after applying entry fee and potential slippage
     */
    function deposit(uint256 assets, address receiver, bytes calldata leveragePayload, uint256 minSharesOut)
        public
        nonReentrant
        pullRewards
        returns (uint256 shares)
    {
        uint256 prevTotalAssets = _depositCheckInteraction(assets, receiver);

        _leverage(assets, leveragePayload);

        shares = _depositEffects(prevTotalAssets, minSharesOut, receiver);
    }

    /**
     * @notice Redeems shares for `asset()`
     * @dev Internally deleverages, by repaying the corresponding debt of the position, using its exposure
     * @dev Slippage costs of the deleveraging are applied to the user, resulting in fewer assets, to not socialize costs
     * @dev The exit fee is charged in shares
     * @param shares Amount of shares to burn
     * @param receiver Address to receive assets
     * @param owner Address that owns the shares, if different from the sender needs an approval
     * @param deleveragePayload Struct with parameters for the deleverage rebalance operation
     * @param minAssetsOut Minimum amount of assets to be redeemed, after applying exit fee and potential slippage
     */
    function redeem(uint256 shares, address receiver, address owner, bytes calldata deleveragePayload, uint256 minAssetsOut)
        public
        nonReentrant
        pullRewards
        returns (uint256 assets)
    {
        uint256 coll = _redeemChecksInteractions(shares, owner);

        uint256 collToRedeem = _deleverage(coll, deleveragePayload);

        assets = _redeemEffects(receiver, owner, shares, collToRedeem, minAssetsOut, deleveragePayload);
    }

    function _depositCheckInteraction(uint256 assets, address receiver) internal returns (uint256 prevTotalAssets) {
        uint256 maxAssets = maxDeposit(receiver);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
        }

        if (assets == 0) revert ZeroAmount();

        prevTotalAssets = _totalAssets(Math.Rounding.Up);

        IERC20(asset()).safeTransferFrom(msg.sender, address(this), assets);
    }

    function _depositEffects(uint256 prevTotalAssets, uint256 minSharesOut, address receiver) internal returns (uint256 shares) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        uint256 currTotalAssets = totalAssets();
        uint256 newAssets = currTotalAssets - prevTotalAssets;

        (uint256 rawShares, uint256 feeShares) = _previewDeposit(newAssets, prevTotalAssets);
        shares = rawShares - feeShares;

        if (shares < minSharesOut) revert VaultSlippage(minSharesOut, shares);

        if (feeShares != 0) {
            _mint($.everlongCore.feeReceiver(), feeShares);
        }

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, newAssets, shares);
    }

    function _redeemChecksInteractions(uint256 shares, address owner) internal returns (uint256 coll) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        uint256 maxShares = maxRedeem(owner);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
        }

        if (shares == 0) revert ZeroAmount();

        (uint256 assets, uint256 shareFee) = _previewRedeem(shares);

        if (shareFee != 0) {
            _mint($.everlongCore.feeReceiver(), shareFee);
        }

        _burn(owner, shares);

        coll = _collConversion(assets);

        if (coll == 0) revert ZeroAmount();
    }

    function _redeemEffects(address receiver, address owner, uint256 shares, uint256 collToRedeem, uint256 minAssetsOut, bytes memory deleveragePayload) internal returns (uint256 assets) {
        _preRedeemEffects();

        if (msg.sender != owner) {
            _spendAllowance(owner, msg.sender, shares);
        }
        /// @dev assets returned are the main asset, doesn't include reward tokens
        assets = _afterRedeemEffects(collToRedeem, receiver, deleveragePayload);

        if (assets < minAssetsOut) revert VaultSlippage(minAssetsOut, assets);

        emit Withdraw(msg.sender, receiver, owner, assets, shares);
    }

    /**
     * @dev Implementation has to check for the following invariants:
     * - Collateral increased by at least the margin amount
     * - Debt increased by any amount
     * - If swaps, and can be passed offchain, check for no donations to swapper or address(this)
     * - If user called, check for operation CR within deviation range of target CR
     * - If keeper called, should have a 'maxOperationCost' wrapping this internal
     * @param margin Amount of margin to use for leverage, if 0, indicates it's keeper leverage
     * @param levPayload Payload with parameters for the leverage rebalance operation
     */
    function _leverage(uint256 margin, bytes calldata levPayload) internal virtual {}

    /**
     * @dev Implementation has to check for the following invariants:
     * - Collateral and debt decreases
     * - If swaps are used, and can be passed offchain, check for no donations to swapper or address(this)
     * - If user called, check for operation CR within deviation range of target CR
     * - If keeper called, should have a 'maxOperationCost' wrapping this internal
     * @param collToReceive Amount of collateral expected to receive after deleveraging, if 0, indicates its keeper deleverage
     *                      It can decrease/increase if the slippage is negative/positive
     * @param delevPayload Payload with parameters for the deleverage rebalance operation
     * @return collToRedeem Definite of collateral to redeem
    */
    function _deleverage(uint256 collToReceive, bytes calldata delevPayload) internal virtual returns (uint256 collToRedeem) {}

    function _computeNetColl(
        uint256 debtSurplusInAssets,
        uint256 collToReceive,
        uint256 prevTotalAssets
    ) internal view returns (uint256 netColl) {
        return _getBaseManagedLeveragedVaultStorage().getters.computeNetColl(
            debtSurplusInAssets,
            collToReceive,
            prevTotalAssets
        );
    }

    function _getCurrentPositionICR() internal view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return $.getters.getCurrentPositionICR();
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           SETTERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function setMaxDeviationICRinBP(uint16 _maxDeviationICRinBP) external onlyOwner {
        _setMaxDeviationICRinBP(_maxDeviationICRinBP);
    }

    function setMaxDeviationTotalAssetsInBP(uint16 _maxDeviationTotalAssetsInBP) external onlyOwner {
        _setMaxDeviationTotalAssetsInBP(_maxDeviationTotalAssetsInBP);
    }

    function setMaxSlippageSwapInBP(uint16 _maxSlippageSwapInBP) external onlyOwner {
        _setMaxSlippageSwapInBP(_maxSlippageSwapInBP);
    }

    function setKeeper(address _keeper) external onlyOwner {
        _setKeeper(_keeper);
    }

    function setTargetICRHook(address _targetICRHook) external onlyOwner {
        _setTargetICRHook(_targetICRHook);
    }

    function setFeeHook(address _feeHook) external onlyOwner {
        _setFeeHook(_feeHook);
    }

    function setGetters(address _getters) external onlyOwner {
        _setGetters(_getters);
    }

    function _setMaxDeviationICRinBP(uint16 _maxDeviationICRinBP) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_maxDeviationICRinBP > MAX_DEVIATION_ICR) revert SurpassedPrecision(MAX_DEVIATION_ICR);

        $.maxDeviationICRinBP = _maxDeviationICRinBP;

        emit NewMaxDeviationICRInBP(_maxDeviationICRinBP);
    }

    function _setMaxDeviationTotalAssetsInBP(uint16 _maxDeviationTotalAssetsInBP) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_maxDeviationTotalAssetsInBP > MAX_DEVIATION_TA) revert SurpassedPrecision(MAX_DEVIATION_TA);

        $.maxDeviationTotalAssetsInBP = _maxDeviationTotalAssetsInBP;

        emit NewMaxDeviationTotalAssetsInBP(_maxDeviationTotalAssetsInBP);
    }

    function _setMaxSlippageSwapInBP(uint16 _maxSlippageSwapInBP) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_maxSlippageSwapInBP > MAX_SLIPPAGE_SWAP) revert SurpassedPrecision(MAX_SLIPPAGE_SWAP);

        $.maxSlippageSwapInBP = _maxSlippageSwapInBP;

        emit NewMaxSlippageSwapInBP(_maxSlippageSwapInBP);
    }

    function _setKeeper(address _keeper) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_keeper == address(0)) revert ZeroAddress();

        $.keeper = _keeper;

        emit NewKeeper(_keeper);
    }

    function _setTargetICRHook(address _targetICRHook) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_targetICRHook == address(0)) revert ZeroAddress();

        $.targetICRHook = ITargetICRHook(_targetICRHook);

        emit NewTargetICRHook(_targetICRHook);
    }

    function _setFeeHook(address _feeHook) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        if (_feeHook == address(0)) revert ZeroAddress();

        $.feeHook = IFeeHook(_feeHook);

        emit NewFeeHook(_feeHook);
    }

    function _setGetters(address _getters) internal {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        // Save bytecode size with same custom error
        if (_getters == address(0) || address(IBaseManagedLeveragedVaultGetters(_getters).vault()) != address(this)) revert ZeroAddress();

        $.getters = IBaseManagedLeveragedVaultGetters(_getters);

        emit NewGetters(_getters);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          GETTERS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /* STORAGE VIEW */

    function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory res) {
        uint nSlots = slots.length;

        res = new bytes32[](nSlots);

        for (uint i; i < nSlots;) {
            bytes32 slot = slots[i++];

            assembly ("memory-safe") {
                mstore(add(res, mul(i, 32)), sload(slot))
            }
        }
    }

    function getPrice(
        address token
    ) public view returns (uint256 scaledPriceInUsdWad) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return $.getters.getPrice(token);
    }

    // Preview ERC4626 functions applying entry/exit fees
    function previewDeposit(uint256 assets) public view override returns (uint) {
        (uint256 rawShares, uint256 feeShares) = _previewDeposit(assets);
        return rawShares - feeShares;
    }

    /// @dev Preview taking an exit fee on redeem. See {IERC4626-previewRedeem}.
    /// @dev Doesn't account intra-operation slippage losses which may decrease assets withdrawn
    function previewRedeem(
        uint256 shares
    ) public view override returns (uint) {
        (uint256 assets,) = _previewRedeem(shares);
        return assets;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         INTERNALS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _modifyCollAndRepayDebt(
        bytes memory modifyPositionPayload,
        int256 missingExposure,
        uint256 debt
    ) internal virtual {}

    function _openPosition(
        bytes calldata openPositionPayload
    ) internal virtual {}

    function _preRedeemEffects() internal virtual {}

    function _afterRedeemEffects(uint256 collToRedeem, address receiver, bytes memory deleveragePayload) internal virtual returns (uint256 assets) {}

    function _collConversion(uint256 assets) internal view virtual returns (uint256 coll) {}

    function _decodeSwapAmount(address inputToken, bytes memory payload) internal virtual returns (uint256 amountToSwap) {}

    function _collateralDecimals() internal view virtual returns (uint8) {}

    function _getPositionCollAndDebt() internal view virtual returns (uint256 coll, uint256 debt) {}

    function _previewDeposit(uint256 assets) internal view returns (uint256 rawShares, uint256 feeShares) {
        rawShares = super.previewDeposit(assets);
        feeShares = rawShares.feeOnRaw(_entryFeeInBP(assets));
    }

    function _previewDeposit(uint256 _assets, uint256 _totalAssets) internal view returns (uint256 rawShares, uint256 feeShares) {
        rawShares = _assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), _totalAssets + 1, Math.Rounding.Down);
        feeShares = rawShares.feeOnRaw(_entryFeeInBP(_assets));
    }

    function _previewRedeem(uint256 shares) internal view returns (uint, uint) {
        uint256 shareFee = shares.feeOnRaw(_exitFeeInBP(shares));
        uint256 assets = super.previewRedeem(shares - shareFee);
        return (assets, shareFee);
    }

    function _getTargetICR() internal view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return $.getters.getTargetICR();
    }

    function _checkInvariantICR(uint256 currentICR, uint256 targetICR, Tolerance tolerance) internal view {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        $.getters.checkInvariantICR(currentICR, targetICR, tolerance);
    }

    function _entryFeeInBP(uint256 amount) private view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return $.getters.entryFeeInBP(amount, msg.sender);
    }

    function _exitFeeInBP(uint256 amount) private view returns (uint256) {
        BaseManagedLeveragedVaultStorage storage $ = _getBaseManagedLeveragedVaultStorage();

        return $.getters.exitFeeInBP(amount, msg.sender);
    }

    function _onlyOwner() private view {
        if (msg.sender != _getBaseManagedLeveragedVaultStorage().everlongCore.owner()) revert NotOwner(msg.sender);
    }

    function _onlyOwnerOrKeeper() private view {
        if (msg.sender != _getBaseManagedLeveragedVaultStorage().everlongCore.owner() && msg.sender != _getBaseManagedLeveragedVaultStorage().keeper) revert NotOwner(msg.sender);
    }

    function _pullRewards() internal virtual {}
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC20, SafeERC20} from "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
import {IPositionManager} from "src/interfaces/utils/IPositionManager.sol";
import {IBorrowerOperations} from "src/interfaces/utils/IBorrowerOperations.sol";
import {ILSTCollateralVault} from "src/interfaces/utils/ILSTCollateralVault.sol";
import {IEverlongCore} from "src/interfaces/core/IEverlongCore.sol";
import {IPriceFeed} from "src/interfaces/core/oracles/IPriceFeed.sol";
import {IBaseManagedLeveragedVaultGetters} from "src/interfaces/core/mlv/helpers/base/IBaseManagedLeveragedVaultGetters.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";

/**
 * @title PropLib
 * @notice This contract implements a managed leveraged vault for the CDP protocol.
 * @dev `$.collateral` is different that `asset()`, the first is a CDP CollateralVault, the former is also the asset of the CollateralVault.
 */
library PropLib {
    using SafeERC20 for IERC20;
    using PriceLib for uint256;

    enum PositionStatus { nonExistent, active, closedByOwner, closedByLiquidation, closedByRedemption }
    enum Tolerance { ABOVE, BOTH }

    uint8 constant MAX_BORROWING_FEE_MULTIPLIER = 5; // x5
    uint256 constant MIN_OPERATION_ICR = 0.2e18; // 20% above CCR (relative)
    uint256 constant WAD = 1e18;

    error AlreadyOpened();
    error BelowCR(uint256 currentICR);
    error SurpassedMaxFeePercentage(uint256 maxFeePercentage, uint256 constrainedMaxFeePercentage);
    error VaultSlippage(uint256 minCollVaultShares, uint256 mintedShares);

    event NewBorrowerOperations(address borrowerOperations);
    event NewPositionManager(address positionManager);

    struct Context {
        address asset;
        IPositionManager positionManager;
        IBorrowerOperations borrowerOperations;
        IERC20 collateral;
        IEverlongCore everlongCore;
        IBaseManagedLeveragedVaultGetters getters;
    }

    function _withdrawDebt(Context memory $, bytes memory withdrawDebtPayload, uint256 _debtTokenAmount) external {
        (
            uint256 _maxFeePercentage,
            address _upperHint,
            address _lowerHint
        ) = abi.decode(
            withdrawDebtPayload,
            (uint256, address, address)
        );

        _checkMaxFeePercentage($, _maxFeePercentage);

        $.borrowerOperations.withdrawDebt(
            address($.positionManager),
            address(this),
            _maxFeePercentage,
            _debtTokenAmount,
            _upperHint,
            _lowerHint
        );
    }

    function _repayDebt(
        Context memory $,
        bytes memory repayDebtPayload,
        uint256 debtTokenAmount
    ) external {
        (
            address _upperHint,
            address _lowerHint
        ) = abi.decode(
            repayDebtPayload,
            (address, address)
        );

        $.borrowerOperations.repayDebt(
            address($.positionManager),
            address(this),
            debtTokenAmount,
            _upperHint,
            _lowerHint
        );
    }

    function _addColl(
        Context memory $,
        bytes memory addCollateralPayload,
        uint256 coll
    ) external {
        (
            address upperHint,
            address lowerHint
        ) = abi.decode(
            addCollateralPayload,
            (address, address)
        );

        $.collateral.forceApprove(address($.borrowerOperations), coll);
        $.borrowerOperations.addColl(
            address($.positionManager),
            address(this),
            coll,
            upperHint,
            lowerHint
        );
    }

    function _modifyCollAndRepayDebt(
        Context memory $,
        bytes memory modifyPositionPayload,
        int256 missingExposure,
        uint256 debt
    ) external {
        (
            address upperHint,
            address lowerHint
        ) = abi.decode(modifyPositionPayload, (address, address));

        bool isCollDeposit = missingExposure >= 0;

        uint256 collDeposit = isCollDeposit ? uint256(missingExposure) : 0;
        uint256 collWithdrawal = isCollDeposit ? 0 : uint256(-missingExposure);
        
        if (missingExposure != 0 || debt != 0) {
            $.collateral.forceApprove(address($.borrowerOperations), collDeposit);
            $.borrowerOperations.adjustPosition({
                positionManager: address($.positionManager),
                account: address(this),
                _maxFeePercentage: 0,
                _collDeposit: collDeposit,
                _collWithdrawal: collWithdrawal,
                _debtChange: debt,
                _isDebtIncrease: false,
                _upperHint: upperHint,
                _lowerHint: lowerHint
            });
        }
    }

    function _repayDebtAndWithdrawCollateral(
        Context memory $,
        bytes memory modifyPositionPayload,
        uint256 collToReceive,
        uint256 receivedDebtToken
    ) external {
        (
            address upperHint,
            address lowerHint
        ) = abi.decode(modifyPositionPayload, (address, address));

        $.borrowerOperations.adjustPosition({
            positionManager: address($.positionManager),
            account: address(this),
            _maxFeePercentage: 0,
            _collDeposit: 0,
            _collWithdrawal: collToReceive,
            _debtChange: receivedDebtToken,
            _isDebtIncrease: false,
            _upperHint: upperHint,
            _lowerHint: lowerHint
        });
    }

    function _addCollAndWithdrawDebt(
        Context memory $,
        bytes memory depositPayload,
        uint256 collVaultShares,
        uint256 debtTokenToReceive
    ) external {
        (
            uint256 maxFeePercentage,
            address upperHint,
            address lowerHint
        ) = abi.decode(
            depositPayload,
            (uint256, address, address)
        );

        IERC20(address($.collateral)).forceApprove(address($.borrowerOperations), collVaultShares);
        $.borrowerOperations.adjustPosition({
            positionManager: address($.positionManager),
            account: address(this),
            _maxFeePercentage: maxFeePercentage,
            _collDeposit: collVaultShares,
            _collWithdrawal: 0,
            _debtChange: debtTokenToReceive,
            _isDebtIncrease: true,
            _upperHint: upperHint,
            _lowerHint: lowerHint
        });
    }

    function _openPosition(
        Context memory $,
        bytes memory openPositionPayload
    ) external {
        (
            uint256 _maxFeePercentage,
            uint256 _debtMinted,
            address _upperHint,
            address _lowerHint
        ) = abi.decode(openPositionPayload, (uint256, uint256, address, address));

        uint256 status = $.positionManager.getPositionStatus(address(this));
        if (PositionStatus(status) == PositionStatus.active) revert AlreadyOpened();

        uint256 collVaultShares = $.collateral.balanceOf(address(this));
        collVaultShares += _claimCollateral($);

        $.collateral.forceApprove(address($.borrowerOperations), collVaultShares);
        $.borrowerOperations.openPosition(
            address($.positionManager),
            address(this),
            _maxFeePercentage,
            collVaultShares,
            _debtMinted,
            _upperHint,
            _lowerHint
        );
    }

    function _claimCollateral(Context memory $) private returns (uint256 collVaultAmount) {
        IPositionManager positionManager = $.positionManager;

        collVaultAmount = positionManager.surplusBalances(address(this));

        if (collVaultAmount != 0) {
            positionManager.claimCollateral(address(this), address(this));
        }
    }

    function _preDeposit(Context memory $, uint256 assetsAmount) external returns (uint256 coll) {
        IERC20($.asset).forceApprove(address($.collateral), assetsAmount);
        coll = ILSTCollateralVault(address($.collateral)).deposit(assetsAmount, address(this));
    }

    function _preRedeemEffects(Context memory $) external view {
        // Position should be above a certain threshold (MIN_OPERATION_ICR) over closest possible liquidation CR (CCR or MCR)
        uint256 CCR = $.borrowerOperations.CORE().CCR();
        uint256 minICROverCCR = CCR + (MIN_OPERATION_ICR * (CCR - WAD) / WAD); // Relative
        uint256 mincICROverMCR = $.positionManager.MCR() + MIN_OPERATION_ICR; // Absolute

        uint256 minICR = Math.max(minICROverCCR, mincICROverMCR);
        uint256 currentICR = $.getters.getCurrentPositionICR();
        if (currentICR < minICR) revert BelowCR(currentICR);
    }

    function _afterRedeemEffects(Context memory $, address collVaultAsset, uint256 coll, address receiver, bytes memory) external returns (uint256 assets) {
        uint256 prevIdleAssets = IERC20(collVaultAsset).balanceOf(receiver);
        ILSTCollateralVault(address($.collateral)).redeem(coll, receiver, address(this));
        assets = IERC20(collVaultAsset).balanceOf(receiver) - prevIdleAssets;
    }

    function _collConversion(Context memory $, uint256 assets) external view returns (uint256 coll) {
        coll = ILSTCollateralVault(address($.collateral)).convertToShares(assets);
    }

    function _getPositionCollAndDebt(Context memory $) external view returns (uint256 coll, uint256 debt) {
        (coll, debt) = $.positionManager.getPositionCollAndDebt(address(this));
    }

    function _pullRewards(Context memory $) external {
        ILSTCollateralVault(address($.collateral)).pullRewards();
    }

    function _collateralDecimals() external pure returns (uint8) {
        return 18; // COLL_VAULT_DECIMALS
    }

    function _checkMaxFeePercentage(
        Context memory $,
        uint256 maxFeePercentage
    ) public view {
        uint256 constrainedMaxFeePercentage = $.positionManager.borrowingFeeFloor() * MAX_BORROWING_FEE_MULTIPLIER;

        if (maxFeePercentage > constrainedMaxFeePercentage) {
            revert SurpassedMaxFeePercentage(maxFeePercentage, constrainedMaxFeePercentage);
        }
    }
}

// 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 32 of 84 : 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 33 of 84 : 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

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
// 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: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
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
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IBaseManagedLeveragedVault} from "src/interfaces/core/mlv/base/IBaseManagedLeveragedVault.sol";

interface IManagedLeveragedVaultV1 is IBaseManagedLeveragedVault {
    // --- Core Actions ----------------------------------------
    function increaseLeverage(bytes calldata leveragePayload) external;

    function decreaseLeverage(bytes calldata deleveragePayload) external;

    function openPosition(
        bytes calldata openPositionPayload,
        address swapRouter,
        bytes memory dexPayload,
        bytes calldata leveragePayload
    ) external;

    // --- View Getters ----------------------------------------
    function getMarginBalance() external view returns (uint256);
    function getExposureBalance() external view returns (uint256);
    function getExposureValue() external view returns (uint256);
}

// 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;

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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IBaseManagedLeveragedVault {
    // --- Enums ------------------------------------------------
    enum Tolerance { ABOVE, BOTH }
    enum Operation { LEVERAGE, DELEVERAGE}

    struct BaseInitParams {
        IERC20 asset;
        string name;
        string symbol;
        address everlongCore;
        address debtToken;
        address collateral;
        uint16 maxDeviationICRinBP;
        uint16 maxDeviationTotalAssetsInBP;
        uint16 maxSlippageSwapInBP;
        address keeper;
        address targetICRHook;
        address feeHook;
        address getters;
    }

    // --- Errors ------------------------------------------------
    error ZeroAmount();
    error ZeroAddress();
    error SurpassedPrecision(uint256 precision);
    error AlreadyOpened();
    error NotOwner(address caller);
    error NotSupportedMethod();
    error VaultSlippage(uint256 expected, uint256 actual);

    // --- Events -----------------------------------------------
    event NewTargetICRHook(address targetICRHook);
    event NewKeeper(address keeper);
    event NewMaxDeviationICRInBP(uint16 maxDeviationICRInBP);
    event NewMaxDeviationTotalAssetsInBP(uint16 maxDeviationTotalAssetsInBP);
    event NewMaxSlippageSwapInBP(uint16 maxSlippageSwapInBP);
    event NewFeeHook(address feeHook);
    event NewGetters(address getters);

    // --- Functions ---------------------------------------------
    function totalAssets() external view returns (uint256);
    function setMaxDeviationICRinBP(uint16 _maxDeviationICRinBP) external;
    function setMaxDeviationTotalAssetsInBP(uint16 _maxDeviationTotalAssetsInBP) external;
    function setMaxSlippageSwapInBP(uint16 _maxSlippageSwapInBP) external;
    function setKeeper(address _keeper) external;
    function setTargetICRHook(address _targetICRHook) external;
    function setFeeHook(address _feeHook) external;
    function setGetters(address _getters) external;
    function getPrice(address token) external view returns (uint256 scaledPriceInUsdWad);
    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory values);
}

// 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
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * [CAUTION]
 * ====
 * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
 * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
 * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
 * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
 * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
 * verifying the amount received is as expected, using a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
 * The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
 * and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
 * itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
 * offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
 * of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
 * With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
 * underlying math can be found xref:erc4626.adoc#inflation-attack[here].
 *
 * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
 * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
 * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
 * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
 * `_convertToShares` and `_convertToAssets` functions.
 *
 * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
 * ====
 */
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
    using Math for uint256;

    /// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
    struct ERC4626Storage {
        IERC20 _asset;
        uint8 _underlyingDecimals;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;

    function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
        assembly {
            $.slot := ERC4626StorageLocation
        }
    }

    /**
     * @dev Attempted to deposit more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);

    /**
     * @dev Attempted to mint more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);

    /**
     * @dev Attempted to withdraw more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);

    /**
     * @dev Attempted to redeem more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
     */
    function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
        __ERC4626_init_unchained(asset_);
    }

    function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
        ERC4626Storage storage $ = _getERC4626Storage();
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        $._underlyingDecimals = success ? assetDecimals : 18;
        $._asset = asset_;
    }

    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
        (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
            abi.encodeCall(IERC20Metadata.decimals, ())
        );
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /**
     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
     * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
     *
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return $._underlyingDecimals + _decimalsOffset();
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual returns (address) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return address($._asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual returns (uint256) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return $._asset.balanceOf(address(this));
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
        uint256 maxAssets = maxDeposit(receiver);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
        }

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}. */
    function mint(uint256 shares, address receiver) public virtual returns (uint256) {
        uint256 maxShares = maxMint(receiver);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
        }

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxAssets = maxWithdraw(owner);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
        }

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxShares = maxRedeem(owner);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
        }

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
        ERC4626Storage storage $ = _getERC4626Storage();
        // If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom($._asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        ERC4626Storage storage $ = _getERC4626Storage();
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer($._asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _decimalsOffset() internal view virtual returns (uint8) {
        return 0;
    }
}

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

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../../lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * 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. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

File 46 of 84 : 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);
    }
}

// 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;

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

library FeeLib {
    using Math for uint;

    uint private constant BP = 1e4;

    /// @dev Calculates the fees that should be added to an amount `shares` that does already include fees.
    /// Used in {IERC4626-deposit}, {IERC4626-mint}, {IERC4626-withdraw} and {IERC4626-previewRedeem} operations.
    function feeOnRaw(
        uint shares,
        uint feeBP
    ) internal pure returns (uint) {
        return shares.mulDiv(feeBP, BP, Math.Rounding.Up);
    }

    /// @dev Calculates the fee part of an amount `shares` that deoes not includes fees.
    /// Used in {IERC4626-previewDeposit} and {IERC4626-previewRedeem} operations.
    function feeOnTotal(
        uint shares,
        uint feeBP
    ) internal pure returns (uint) {
        return shares.mulDiv(feeBP, feeBP + BP, Math.Rounding.Up);
    }
}

// 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;

interface IFeeHook {
    enum Action {
        DEPOSIT,
        MINT,
        WITHDRAW,
        REDEEM
    }

    function calcFee(address caller, address token, uint amount, Action action) external view returns (uint feeInBP);
}

File 51 of 84 : ITargetICRHook.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface ITargetICRHook {
    function calcTargetICR()
        external
        view
        returns (uint256 targetICR);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IBaseManagedLeveragedVault} from "src/interfaces/core/mlv/base/IBaseManagedLeveragedVault.sol";

interface IBaseManagedLeveragedVaultGetters {
    error PositionOutOfTargetCR(uint256 currentICR, uint256 targetICR, uint256 maxDelta);
    error TotalAssetsDeviation(uint256 prevTotalAssets, uint256 newTotalAssets, uint256 maxDelta);
    error VaultSlippage(uint256 expected, uint256 actual);

    function getPrice(address token) external view returns (uint256);
    function vault() external view returns (IBaseManagedLeveragedVault);
    function getCollateralBalance() external view returns (uint256);
    function getCollateralValue() external view returns (uint256);
    function getCollateralValue(uint256 amount) external view returns (uint256);
    function getDebtBalance() external view returns (uint256);
    function getDebtValue() external view returns (uint256);
    function getDebtValue(uint256 amount) external view returns (uint256);
    function getCurrentPositionICR() external view returns (uint256);
    function getTargetICR() external view returns (uint256);
    function entryFeeInBP(uint256 amount, address caller) external view returns (uint256);
    function exitFeeInBP(uint256 amount, address caller) external view returns (uint256);
    function checkInvariantICR(uint256 currentICR, uint256 targetICR, IBaseManagedLeveragedVault.Tolerance tolerance) external view;
    function checkMaxOperationCost(address inputToken, uint256 amountToSwap, uint256 prevTotalAssets) external view;
    function computeNetColl(uint256 nectSurplusInAssets, uint256 collToReceive, uint256 prevTotalAssets) external view returns (uint256 netColl);
}

// 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 54 of 84 : 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);
}

// 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 60 of 84 : 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 61 of 84 : 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 62 of 84 : 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: 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;
    }
}

File 65 of 84 : 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 66 of 84 : 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 67 of 84 : 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: 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) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "../../lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

// 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 (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
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

File 78 of 84 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

// 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);
        }
    }
}

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

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
}

// 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 82 of 84 : 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,
  "libraries": {
    "src/core/mlv/protocol/v1/prop/everlong/yari/YariEverlongManagedLeveragedVault.sol": {
      "PropLib": "0x5a91f87c9e72240bc1b780be0557a61164fd9ffd"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"AlreadyOpened","type":"error"},{"inputs":[{"internalType":"uint256","name":"debt","type":"uint256"}],"name":"BadDebt","type":"error"},{"inputs":[{"internalType":"uint256","name":"actual","type":"uint256"},{"internalType":"uint256","name":"previous","type":"uint256"}],"name":"CollateralNotDecreased","type":"error"},{"inputs":[{"internalType":"uint256","name":"actual","type":"uint256"},{"internalType":"uint256","name":"previous","type":"uint256"}],"name":"CollateralNotIncreased","type":"error"},{"inputs":[{"internalType":"uint256","name":"actual","type":"uint256"},{"internalType":"uint256","name":"previous","type":"uint256"}],"name":"DebtNotDecreased","type":"error"},{"inputs":[{"internalType":"uint256","name":"actual","type":"uint256"},{"internalType":"uint256","name":"previous","type":"uint256"}],"name":"DebtNotIncreased","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxMint","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxRedeem","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxWithdraw","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"NotOwner","type":"error"},{"inputs":[],"name":"NotSupportedMethod","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"precision","type":"uint256"}],"name":"SurpassedPrecision","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"VaultSlippage","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"delegation","type":"address"},{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"NewDelegation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"deleverageRouter","type":"address"}],"name":"NewDeleverageRouter","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"feeHook","type":"address"}],"name":"NewFeeHook","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"getters","type":"address"}],"name":"NewGetters","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"keeper","type":"address"}],"name":"NewKeeper","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"leverageRouter","type":"address"}],"name":"NewLeverageRouter","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"maxDeviationICRInBP","type":"uint16"}],"name":"NewMaxDeviationICRInBP","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"maxDeviationTotalAssetsInBP","type":"uint16"}],"name":"NewMaxDeviationTotalAssetsInBP","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"maxSlippageSwapInBP","type":"uint16"}],"name":"NewMaxSlippageSwapInBP","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"targetICRHook","type":"address"}],"name":"NewTargetICRHook","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"deleveragePayload","type":"bytes"}],"name":"decreaseLeverage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes","name":"leveragePayload","type":"bytes"},{"internalType":"uint256","name":"minSharesOut","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"extSloads","outputs":[{"internalType":"bytes32[]","name":"res","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"forceNewPositionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getExposureBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExposureValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMarginBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getPrice","outputs":[{"internalType":"uint256","name":"scaledPriceInUsdWad","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"leveragePayload","type":"bytes"}],"name":"increaseLeverage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"asset","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address","name":"everlongCore","type":"address"},{"internalType":"address","name":"debtToken","type":"address"},{"internalType":"address","name":"collateral","type":"address"},{"internalType":"uint16","name":"maxDeviationICRinBP","type":"uint16"},{"internalType":"uint16","name":"maxDeviationTotalAssetsInBP","type":"uint16"},{"internalType":"uint16","name":"maxSlippageSwapInBP","type":"uint16"},{"internalType":"address","name":"keeper","type":"address"},{"internalType":"address","name":"targetICRHook","type":"address"},{"internalType":"address","name":"feeHook","type":"address"},{"internalType":"address","name":"getters","type":"address"}],"internalType":"struct IBaseManagedLeveragedVault.BaseInitParams","name":"baseParams","type":"tuple"},{"components":[{"internalType":"address","name":"borrowerOperations","type":"address"},{"internalType":"address","name":"positionManager","type":"address"},{"internalType":"address","name":"leverageRouter","type":"address"},{"internalType":"address","name":"deleverageRouter","type":"address"}],"internalType":"struct IPropManagedLeveragedVault.ProtocolInitParams","name":"protocolParams","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"openPositionPayload","type":"bytes"},{"internalType":"address","name":"swapRouter","type":"address"},{"internalType":"bytes","name":"dexPayload","type":"bytes"},{"internalType":"bytes","name":"leveragePayload","type":"bytes"}],"name":"openPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"bytes","name":"deleveragePayload","type":"bytes"},{"internalType":"uint256","name":"minAssetsOut","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"bool","name":"isDelegated","type":"bool"}],"name":"setDelegateApproval","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_deleverageRouter","type":"address"}],"name":"setDeleverageRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeHook","type":"address"}],"name":"setFeeHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_getters","type":"address"}],"name":"setGetters","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_keeper","type":"address"}],"name":"setKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_leverageRouter","type":"address"}],"name":"setLeverageRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_maxDeviationICRinBP","type":"uint16"}],"name":"setMaxDeviationICRinBP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_maxDeviationTotalAssetsInBP","type":"uint16"}],"name":"setMaxDeviationTotalAssetsInBP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_maxSlippageSwapInBP","type":"uint16"}],"name":"setMaxSlippageSwapInBP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_targetICRHook","type":"address"}],"name":"setTargetICRHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"swapper","outputs":[{"internalType":"contract IRedSnwapper","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"}]

60a060405230608052348015610013575f80fd5b5061001c610021565b6100d3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156100715760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100d05780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051615f306100f95f395f8181611fd101528181611ffa01526121300152615f305ff3fe608060405260043610610243575f3560e01c806301e1d1141461024757806306fdde031461026e57806307a2d13a1461028f57806308476e6e146102ae578063095ea7b3146102c45780630a28a477146102f3578063161a141c1461031257806318160ddd146103315780631e47b7d21461034557806323ab46941461035957806323b872dd146103785780632ab09d5a146103975780632b3297f9146103b6578063313ce567146103ea57806338d52e0f14610410578063402d267d1461042457806341976e091461044357806341b6ccdc146104625780634cdad506146104815780634f1ef286146104a057806352d1902d146104b35780635551396a146104c7578063572ffa0c146104e657806362e48a3e146105055780636e553f651461051957806370a08231146105385780637377ecc414610557578063748747e6146105765780637784c68514610595578063874402bf146105c157806392c18454146105e057806394bf804d1461051957806395d89b41146105ff578063a9059cbb14610613578063ad3cb1cc14610632578063b3d7f6b914610662578063b460af9414610681578063b61ab0e61461069b578063ba08765214610681578063c3c854b6146106ba578063c60244ad146106d9578063c63d75b614610424578063c688d9a5146106f8578063c6e6f59214610717578063ce96cb7714610736578063d905777e14610755578063dd62ed3e14610774578063df88933c14610793578063e2ede6e7146107b2578063ef8b30f7146107d1578063fff8d04e146107f0575b5f80fd5b348015610252575f80fd5b5061025b610804565b6040519081526020015b60405180910390f35b348015610279575f80fd5b50610282610813565b60405161026591906148f6565b34801561029a575f80fd5b5061025b6102a9366004614908565b6108b1565b3480156102b9575f80fd5b506102c26108c2565b005b3480156102cf575f80fd5b506102e36102de366004614943565b61093a565b6040519015158152602001610265565b3480156102fe575f80fd5b5061025b61030d366004614908565b610951565b34801561031d575f80fd5b506102c261032c36600461497e565b61095d565b34801561033c575f80fd5b5061025b61096e565b348015610350575f80fd5b5061025b610982565b348015610364575f80fd5b506102c261037336600461497e565b6109c8565b348015610383575f80fd5b506102e3610392366004614997565b6109d9565b3480156103a2575f80fd5b5061025b6103b1366004614a19565b6109fe565b3480156103c1575f80fd5b506103dd73ac4c6e212a361c968f1725b4d055b47e63f80b7581565b6040516102659190614a8e565b3480156103f5575f80fd5b506103fe610a83565b60405160ff9091168152602001610265565b34801561041b575f80fd5b506103dd610aa6565b34801561042f575f80fd5b5061025b61043e366004614aa2565b610ac0565b34801561044e575f80fd5b5061025b61045d366004614aa2565b610ac6565b34801561046d575f80fd5b506102c261047c366004614aa2565b610b42565b34801561048c575f80fd5b5061025b61049b366004614908565b610bd5565b6102c26104ae366004614be8565b610be8565b3480156104be575f80fd5b5061025b610c07565b3480156104d2575f80fd5b506102c26104e1366004614c34565b610c22565b3480156104f1575f80fd5b506102c2610500366004614c72565b610d3a565b348015610510575f80fd5b5061025b610e50565b348015610524575f80fd5b5061025b610533366004614ccc565b610e6f565b348015610543575f80fd5b5061025b610552366004614aa2565b610e89565b348015610562575f80fd5b506102c2610571366004614c34565b610eb2565b348015610581575f80fd5b506102c2610590366004614aa2565b610f38565b3480156105a0575f80fd5b506105b46105af366004614cfa565b610f49565b6040516102659190614d69565b3480156105cc575f80fd5b506102c26105db366004614aa2565b610fd8565b3480156105eb575f80fd5b506102c26105fa366004614aa2565b610fe9565b34801561060a575f80fd5b50610282610ffa565b34801561061e575f80fd5b506102e361062d366004614943565b611016565b34801561063d575f80fd5b50610282604051806040016040528060058152602001640352e302e360dc1b81525081565b34801561066d575f80fd5b5061025b61067c366004614908565b611023565b34801561068c575f80fd5b5061025b610533366004614dab565b3480156106a6575f80fd5b506102c26106b5366004614aa2565b61102f565b3480156106c5575f80fd5b506102c26106d4366004614df7565b6110b6565b3480156106e4575f80fd5b506102c26106f336600461497e565b6110c8565b348015610703575f80fd5b506102c2610712366004614aa2565b6110d9565b348015610722575f80fd5b5061025b610731366004614908565b6110ea565b348015610741575f80fd5b5061025b610750366004614aa2565b6110f5565b348015610760575f80fd5b5061025b61076f366004614aa2565b611108565b34801561077f575f80fd5b5061025b61078e366004614e23565b611112565b34801561079e575f80fd5b5061025b6107ad366004614e4f565b61114c565b3480156107bd575f80fd5b506102c26107cc366004614ead565b611194565b3480156107dc575f80fd5b5061025b6107eb366004614908565b6111d3565b3480156107fb575f80fd5b5061025b6111f6565b5f61080e5f611335565b905090565b60605f61081e6115ab565b905080600301805461082f90614f56565b80601f016020809104026020016040519081016040528092919081815260200182805461085b90614f56565b80156108a65780601f1061087d576101008083540402835291602001916108a6565b820191905f5260205f20905b81548152906001019060200180831161088957829003601f168201915b505050505091505090565b5f6108bc825f6115cf565b92915050565b6108ca61160c565b73eea27de7b45d1c7c98e89ac248f7a9b894faba846108e76116d5565b60080180546001600160a01b0319166001600160a01b039290921691909117905560408051602081019091525f8152730fa53f1b5f1b9552ed6b6d10c89cd9ec7b7e34a190610937908290610be8565b50565b5f336109478185856116f9565b5060019392505050565b5f6108bc82600161170b565b61096561173f565b610937816117e4565b5f806109786115ab565b6002015492915050565b5f8061098c6116d5565b60028101549091506109c2906109aa906001600160a01b0316610ac6565b670de0b6b3a76400006109bb610e50565b9190611864565b91505090565b6109d061173f565b6109378161190d565b5f336109e685828561198f565b6109f18585856119df565b60019150505b9392505050565b5f610a07611a3c565b610a0f611a5a565b5f610a1a8887611ac0565b90505f610a28828787611be6565b9050610a6d88888b84888b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611eb592505050565b92505050610a79611f6c565b9695505050505050565b5f80610a8d611f71565b90505f81546109c29190600160a01b900460ff16614fa2565b5f80610ab0611f71565b546001600160a01b031692915050565b505f1990565b5f80610ad06116d5565b60068101546040516341976e0960e01b81529192506001600160a01b0316906341976e0990610b03908690600401614a8e565b602060405180830381865afa158015610b1e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109f79190614fbb565b610b4a61173f565b5f610b536116d5565b90506001600160a01b038216610b7c5760405163d92e233d60e01b815260040160405180910390fd5b6009810180546001600160a01b0319166001600160a01b0384161790556040517fd35955139a5369dcd2c236349c7d831c0740cb113591dc789cabec0824f6104690610bc9908490614a8e565b60405180910390a15050565b5f80610be083611f95565b509392505050565b610bf0611fc6565b610bf98261206a565b610c038282612072565b5050565b5f610c10612125565b505f80516020615eb483398151915290565b610c2a61160c565b610c32611a3c565b610c3a6116d5565b60020154604080516020601f85018190048102820181019092528381526001600160a01b03909216919084908490819084018382808284375f92019190915250610c879250611a5a915050565b5f610c90610804565b9050610c9d5f8686611be6565b50610cb8610ca961216e565b610cb16121f0565b600161224e565b5f610cc384846122c0565b9050610ccd6116d5565b600601546040516321a348a160e01b81526001600160a01b03909116906321a348a190610d0290879085908790600401614fd2565b5f6040518083038186803b158015610d18575f80fd5b505afa158015610d2a573d5f803e3d5ffd5b5050505050505050610c03611f6c565b5f610d43612327565b805490915060ff600160401b82041615906001600160401b03165f81158015610d695750825b90505f826001600160401b03166001148015610d845750303b155b905081158015610d92575080155b15610db05760405163f92ee8a960e01b815260040160405180910390fd5b84546001600160401b03191660011785558315610dd957845460ff60401b1916600160401b1785555b610dea610de588614ff3565b61234b565b610e01610dfc36889003880188615125565b61244c565b8315610e4757845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b5f80610e5a612540565b509050610e656111f6565b6109c2908261518c565b5f604051631a8d61e960e11b815260040160405180910390fd5b5f80610e936115ab565b6001600160a01b039093165f9081526020939093525050604090205490565b610eba61160c565b610ec2611a3c565b610eca6116d5565b60010154604080516020601f85018190048102820181019092528381526001600160a01b03909216919084908490819084018382808284375f92019190915250610f179250611a5a915050565b5f610f20610804565b9050610f2d5f86866125c6565b610cb8610ca961216e565b610f4061173f565b6109378161287c565b606081806001600160401b03811115610f6457610f64614abd565b604051908082528060200260200182016040528015610f8d578160200160208202803683370190505b5091505f5b81811015610fd0575f858583610fa78161519f565b9450818110610fb857610fb86151b7565b90506020020135905080546020830285015250610f92565b505092915050565b610fe061173f565b610937816128fb565b610ff161173f565b6109378161297a565b60605f6110056115ab565b905080600401805461082f90614f56565b5f336109478185856119df565b5f6108bc8260016115cf565b61103761173f565b5f6110406116d5565b90506001600160a01b0382166110695760405163d92e233d60e01b815260040160405180910390fd5b600a810180546001600160a01b0319166001600160a01b0384161790556040517f6cd650a77ac6e3f55319493f7e38de4061af1323f9b3b50270823848681124de90610bc9908490614a8e565b6110be61173f565b610c0382826129f9565b6110d061173f565b61093781612aa2565b6110e161173f565b61093781612b24565b5f6108bc825f61170b565b5f6108bc61110283610e89565b5f6115cf565b5f6108bc82610e89565b5f8061111c6115ab565b6001600160a01b039485165f90815260019190910160209081526040808320959096168252939093525050205490565b5f611155611a3c565b61115d611a5a565b5f6111688787612c21565b90506111758786866125c6565b611180818488612ca0565b91505061118b611f6c565b95945050505050565b61119c61160c565b6111a68686612db7565b6111b284848484612e21565b6111cb6111bd61216e565b6111c56121f0565b5f61224e565b505050505050565b5f805f6111df84613059565b90925090506111ee818361518c565b949350505050565b5f806112006116d5565b90505f816006015f9054906101000a90046001600160a01b03166001600160a01b0316634ad45c846040518163ffffffff1660e01b8152600401602060405180830381865afa158015611255573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112799190614fbb565b60028301549091505f906112aa90611299906001600160a01b0316610ac6565b6112a1613080565b8491905f6130ec565b905080836006015f9054906101000a90046001600160a01b03166001600160a01b0316631529a6396040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112ff573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113239190614fbb565b61132d919061518c565b935050505090565b5f8061133f6116d5565b60088101549091506001600160a01b03165f8061135a612540565b60405163ec38a05d60e01b815291935091506001600160a01b0384169063ec38a05d9061138b903090600401614a8e565b602060405180830381865afa1580156113a6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113ca9190614fbb565b6113d490836151cb565b60068501546040516382fee08f60e01b8152600481018390529193505f916001600160a01b03909116906382fee08f90602401602060405180830381865afa158015611422573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114469190614fbb565b600686015460405163c0177bd560e01b8152600481018590529192505f916001600160a01b039091169063c0177bd590602401602060405180830381865afa158015611494573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b89190614fbb565b9050818111156114f1576114cc828261518c565b604051631309868760e11b81526004016114e891815260200190565b60405180910390fd5b5f6114fc828461518c565b90505f611507610aa6565b90505f61151382610ac6565b90505f826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611552573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061157691906151de565b90505f61159a61158783600a6152e1565b848f88613117909392919063ffffffff16565b9d9c50505050505050505050505050565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0090565b5f6109f76115db610804565b6115e69060016151cb565b6115f15f600a6152e1565b6115f961096e565b61160391906151cb565b85919085613117565b6116146116d5565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa15801561165a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061167e91906152ef565b6001600160a01b0316336001600160a01b0316141580156116b357506116a26116d5565b600301546001600160a01b03163314155b156116d3573360405163245aecd360e01b81526004016114e89190614a8e565b565b7f12ca37b393c412d053690654fb6d504d2a16c55c2bd10941af581f2221d9c10090565b6117068383836001613166565b505050565b5f6109f761171a82600a6152e1565b61172261096e565b61172c91906151cb565b611734610804565b6116039060016151cb565b6117476116d5565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa15801561178d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117b191906152ef565b6001600160a01b0316336001600160a01b0316146116d3573360405163245aecd360e01b81526004016114e89190614a8e565b5f6117ed6116d5565b905060fa61ffff831611156118185760fa604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60b01b1916600160b01b61ffff8516021790556040517fad9f7bb2fb869a89410ed22cba28ce6ddb3d518ddb06ec79d90eef53e43d099a90610bc990849061530a565b5f80805f19858709858702925082811083820303915050805f0361189b5783828161189157611891615319565b04925050506109f7565b8084116118a6575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b5f6119166116d5565b90506101f461ffff83161115611943576101f4604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60a01b1916600160a01b61ffff8516021790556040517fd76d222a1569878be0d02545c0819a8399c91999f0d8565d9d1dbfa1c2524df290610bc990849061530a565b5f61199a8484611112565b90505f1981146119d957818110156119cb57828183604051637dc7a0d960e11b81526004016114e893929190614fd2565b6119d984848484035f613166565b50505050565b6001600160a01b038316611a08575f604051634b637e8f60e11b81526004016114e89190614a8e565b6001600160a01b038216611a31575f60405163ec442f0560e01b81526004016114e89190614a8e565b611706838383613247565b63769dd35360e11b5f5c15611a5357805f5260045ffd5b60015f5d50565b611a6261336a565b604051635fc6e58d60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd91635fc6e58d91611a989190600401615378565b5f6040518083038186803b158015611aae575f80fd5b505af41580156119d9573d5f803e3d5ffd5b5f80611aca6116d5565b90505f611ad684611108565b905080851115611aff57838582604051632e52afbb60e21b81526004016114e893929190614fd2565b845f03611b1f57604051631f2a200560e01b815260040160405180910390fd5b5f80611b2a87611f95565b91509150805f14611ba757835460408051632cfc019d60e21b81529051611ba7926001600160a01b03169163b3f006749160048083019260209291908290030181865afa158015611b7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba191906152ef565b82613409565b611bb1868861343d565b611bba82613471565b9450845f03611bdc57604051631f2a200560e01b815260040160405180910390fd5b5050505092915050565b5f80611bf06116d5565b9050611bfa61487f565b60088201546001600160a01b03165f611c15868801886153f2565b9050611c1f612540565b60208501528352611c2e613635565b60a085015260808401526060810151602001515f03611c6057604051631f2a200560e01b815260040160405180910390fd5b606081015160200151611c7390896151cb565b6040820151525f60208201819052888103611c8e575f611c98565b611c986001611335565b600a860154604051632a055ea360e01b81529192506001600160a01b031690632a055ea390611ccd9086908690600401615584565b5f604051808303815f87803b158015611ce4575f80fd5b505af1158015611cf6573d5f803e3d5ffd5b50505050611d02613635565b60e086015260c0850181905260808501515f91611d1f919061518c565b90508915611d3557611d32818b8461372b565b96505b611d8f836040015160200151846040015160400151604051602001611d5b92919061565b565b604051602081830303815290604052888760a001518860e00151611d7f9190615675565b611d899190615675565b83613808565b611d97612540565b606087015260408601528915611e47575f611e378660400151875f0151611dbe919061518c565b87606001518860200151611dd2919061518c565b876001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e0e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e329190614fbb565b613874565b9050611e4581610cb16121f0565b505b8451604086015110611e7357604080860151865191516232a45960e71b81526114e89290600401615694565b846020015185606001511115611ea85784606001518560200151604051633fb9035760e11b81526004016114e8929190615694565b5050505050509392505050565b5f611ebe6138a2565b336001600160a01b03871614611ed957611ed986338761198f565b611ee48488846138e0565b905082811015611f0b5782816040516327014c6d60e11b81526004016114e8929190615694565b856001600160a01b0316876001600160a01b0316336001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8489604051611f5a929190615694565b60405180910390a49695505050505050565b5f805d565b7f0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e0090565b5f805f611fab611fa485613a80565b8590613abf565b90505f611fbb6102a9838761518c565b959194509092505050565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148061204c57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166120405f80516020615eb4833981519152546001600160a01b031690565b6001600160a01b031614155b156116d35760405163703e46dd60e11b815260040160405180910390fd5b61093761173f565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156120cc575060408051601f3d908101601f191682019092526120c991810190614fbb565b60015b6120eb5781604051634c9c8ce360e01b81526004016114e89190614a8e565b5f80516020615eb4833981519152811461211b57604051632a87526960e21b8152600481018290526024016114e8565b6117068383613acf565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146116d35760405163703e46dd60e11b815260040160405180910390fd5b5f806121786116d5565b9050806006015f9054906101000a90046001600160a01b03166001600160a01b03166391b58ae86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109c29190614fbb565b5f806121fa6116d5565b9050806006015f9054906101000a90046001600160a01b03166001600160a01b031663ec9d25526040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cc573d5f803e3d5ffd5b5f6122576116d5565b600681015460405163479fd6fb60e11b81529192506001600160a01b031690638f3fadf69061228e908790879087906004016156b6565b5f6040518083038186803b1580156122a4575f80fd5b505afa1580156122b6573d5f803e3d5ffd5b5050505050505050565b5f806122ca6116d5565b60028101549091506001600160a01b039081169085160361230857828060200190518101906122f991906158ba565b60600151602001519150612320565b8280602001905181019061231c91906158eb565b5191505b5092915050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0090565b5f6123546116d5565b60608301519091506001600160a01b03166123825760405163d92e233d60e01b815260040160405180910390fd5b815161238d90613b24565b61239f82602001518360400151613b35565b606082015181546001600160a01b039182166001600160a01b0319918216178355608084015160018401805491841691831691909117905560a08401516002840180549190931691161790556101408201516123fa906128fb565b6124078260c0015161190d565b6124148260e001516117e4565b612422826101000151612aa2565b61243082610120015161287c565b61243e82610160015161297a565b610c03826101800151612b24565b5f6124556116d5565b82519091506001600160a01b0316158061247a575060208201516001600160a01b0316155b80612490575060408201516001600160a01b0316155b806124a6575060608201516001600160a01b0316155b156124c45760405163d92e233d60e01b815260040160405180910390fd5b81516007820180546001600160a01b03199081166001600160a01b039384161790915560208401516008840180548316918416919091179055604084015160098401805483168285161790556060850151600a8501805490931693169290921790556125319060016129f9565b610c03826060015160016129f9565b5f8061254a61336a565b604051633820305360e21b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163e080c14c916125809190600401615378565b6040805180830381865af415801561259a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125be91906159d2565b915091509091565b5f6125cf6116d5565b90506125d961487f565b60088201546001600160a01b03165f6125f4858701876159f4565b9050865f0361266d5761260561336a565b60408083015151905163ecc134c760e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9263ecc134c79261264092600401615ac4565b5f6040518083038186803b158015612656575f80fd5b505af4158015612668573d5f803e3d5ffd5b505050505b6020810187905261267c612540565b6020808601919091529084526009850154908201516126b7916001600160a01b0316906126a7610aa6565b6001600160a01b03169190613b47565b600984015460405163f6038b6760e01b81526001600160a01b039091169063f6038b67906126eb9085908590600401615adf565b5f604051808303815f87803b158015612702575f80fd5b505af1158015612714573d5f803e3d5ffd5b50505050612720612540565b60608501526040840152602081015161273890613471565b835161274491906151cb565b83604001511161276f576040808401518451915163ee5410af60e01b81526114e89290600401615694565b82602001518360600151116127a357826060015183602001516040516311b7c95d60e11b81526004016114e8929190615694565b602081015115610e4757825160408401515f916127bf9161518c565b90505f846020015185606001516127d6919061518c565b90505f6127e16121f0565b90505f856001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612820573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128449190614fbb565b905061284e61096e565b1561286f575f61285f858584613874565b905061286d8184600161224e565b505b5050505050505050505050565b5f6128856116d5565b90506001600160a01b0382166128ae5760405163d92e233d60e01b815260040160405180910390fd5b6003810180546001600160a01b0319166001600160a01b0384161790556040517f8b67cf08b3b4a582cdf414f29895fde3e3f03a3bf26373a22a8b9bd89e75748890610bc9908490614a8e565b5f6129046116d5565b90506001600160a01b03821661292d5760405163d92e233d60e01b815260040160405180910390fd5b6004810180546001600160a01b0319166001600160a01b0384161790556040517f42bbfb4743223617630fbe3734cfffc55d280da085acdb2426e843716cd5552290610bc9908490614a8e565b5f6129836116d5565b90506001600160a01b0382166129ac5760405163d92e233d60e01b815260040160405180910390fd5b6005810180546001600160a01b0319166001600160a01b0384161790556040517fcba8f51815ef6b4d9d58f668351b97323a16a5ce5c9186a17d27fa45c3e8e42690610bc9908490614a8e565b5f612a026116d5565b60078101546040516361e42a5b60e11b81529192506001600160a01b03169063c3c854b690612a379086908690600401615b66565b5f604051808303815f87803b158015612a4e575f80fd5b505af1158015612a60573d5f803e3d5ffd5b505050507fe25ae1b1d4513ae709d95de0ee5a28a9ecd6f408fcc7652183e73fe1ec46c7b88383604051612a95929190615b66565b60405180910390a1505050565b5f612aab6116d5565b905061012c61ffff83161115612ad85761012c604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60c01b1916600160c01b61ffff8516021790556040517f78d7b33b806f8dd6d1be0926097e8fd70795eef7a373ab8bdbc1f49e9b24347f90610bc990849061530a565b5f612b2d6116d5565b90506001600160a01b0382161580612bb65750306001600160a01b0316826001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b86573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612baa91906152ef565b6001600160a01b031614155b15612bd45760405163d92e233d60e01b815260040160405180910390fd5b6006810180546001600160a01b0319166001600160a01b0384161790556040517ffdf2c3daba11b29cf3b43a19b2f0d11e4755d15d15436ee5a82635ef0ca00a9b90610bc9908490614a8e565b5f80612c2c83610ac0565b905080841115612c5557828482604051633c8097d960e11b81526004016114e893929190614fd2565b835f03612c7557604051631f2a200560e01b815260040160405180910390fd5b612c7f6001611335565b9150612320333086612c8f610aa6565b6001600160a01b0316929190613c09565b5f80612caa6116d5565b90505f612cb5610804565b90505f612cc2878361518c565b90505f80612cd0838a613c42565b9092509050612cdf818361518c565b955087861015612d065787866040516327014c6d60e11b81526004016114e8929190615694565b8015612d5457845460408051632cfc019d60e21b81529051612d54926001600160a01b03169163b3f006749160048083019260209291908290030181865afa158015611b7d573d5f803e3d5ffd5b612d5e8787613409565b866001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d78589604051612da3929190615694565b60405180910390a350505050509392505050565b612dbf61336a565b6040516359492bb160e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd916359492bb191612df9919086908690600401615b81565b5f6040518083038186803b158015612e0f575f80fd5b505af41580156111cb573d5f803e3d5ffd5b5f612e2a6116d5565b60018101546040516370a0823160e01b81529192505f916001600160a01b03909116906370a0823190612e61903090600401614a8e565b602060405180830381865afa158015612e7c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ea09190614fbb565b6001830154909150612ebc906001600160a01b03168783613b47565b5f80876001600160a01b031687604051612ed69190615bbf565b5f604051808303815f865af19150503d805f8114612f0f576040519150601f19603f3d011682016040523d82523d5f602084013e612f14565b606091505b509150915081612f2757612f2781613c8f565b5f612f30610aa6565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612f5b9190614a8e565b602060405180830381865afa158015612f76573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f9a9190614fbb565b9050805f03612fbc57604051631f2a200560e01b815260040160405180910390fd5b612fc78188886125c6565b612fcf61096e565b5f0361304e57845460408051638da5cb5b60e01b8152905161304e926001600160a01b031691638da5cb5b9160048083019260209291908290030181865afa15801561301d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061304191906152ef565b613049610804565b613409565b505050505050505050565b5f80613064836110ea565b915061307961307284613c97565b8390613abf565b9050915091565b5f735a91f87c9e72240bc1b780be0557a61164fd9ffd6320daa1e06040518163ffffffff1660e01b8152600401602060405180830381865af41580156130c8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061080e91906151de565b5f8315806130f8575084155b1561310457505f6111ee565b61118b61311284600a6152e1565b869086855b5f80613124868686611864565b9050600183600281111561313a5761313a6156a2565b14801561315657505f848061315157613151615319565b868809115b1561118b57610a796001826151cb565b5f61316f6115ab565b90506001600160a01b03851661319a575f60405163e602df0560e01b81526004016114e89190614a8e565b6001600160a01b0384166131c3575f604051634a1406b160e11b81526004016114e89190614a8e565b6001600160a01b038086165f9081526001830160209081526040808320938816835292905220839055811561324057836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161323791815260200190565b60405180910390a35b5050505050565b5f6132506115ab565b90506001600160a01b03841661327e5781816002015f82825461327391906151cb565b909155506132db9050565b6001600160a01b0384165f90815260208290526040902054828110156132bd5784818460405163391434e360e21b81526004016114e893929190614fd2565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b0383166132f9576002810180548390039055613317565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161335c91815260200190565b60405180910390a350505050565b6040805160c0810182525f80825260208201819052918101829052606081018290526080810182905260a08101829052906133a36116d5565b90506040518060c001604052806133b8610aa6565b6001600160a01b03908116825260088401548116602083015260078401548116604083015260028401548116606083015283548116608083015260069093015490921660a090920191909152919050565b6001600160a01b038216613432575f60405163ec442f0560e01b81526004016114e89190614a8e565b610c035f8383613247565b6001600160a01b038216613466575f604051634b637e8f60e11b81526004016114e89190614a8e565b610c03825f83613247565b5f8061347b6116d5565b6002810154604080516338d52e0f60e01b815290519293505f926001600160a01b03909216916338d52e0f916004808201926020929091908290030181865afa1580156134ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ee91906152ef565b90505f6134fa82610ac6565b90505f61350861045d610aa6565b90505f836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613547573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061356b91906151de565b6135799060ff16600a615bd5565b90505f613584610aa6565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156135bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135e391906151de565b6135f19060ff16600a615bd5565b90505f6135fe8286615be0565b83613609868c615be0565b6136139190615be0565b61361d9190615bf7565b905061362881613cd6565b9998505050505050505050565b5f805f6136406116d5565b60018101546040516370a0823160e01b81529192506001600160a01b0316906370a0823190613673903090600401614a8e565b602060405180830381865afa15801561368e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136b29190614fbb565b60028201546040516370a0823160e01b81529194506001600160a01b0316906370a08231906136e5903090600401614a8e565b602060405180830381865afa158015613700573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137249190614fbb565b9150509091565b5f806137356116d5565b60018101549091505f9061376590613755906001600160a01b0316610ac6565b8790670de0b6b3a7640000611864565b90505f6137f0613773610aa6565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137d291906151de565b6137dd90600a6152e1565b6137e861045d610aa6565b849190611864565b90506137fd818787613d56565b979650505050505050565b61381061336a565b60405163eca6c04f60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163eca6c04f9161384c9190879087908790600401615c16565b5f6040518083038186803b158015613862575f80fd5b505af4158015610e47573d5f803e3d5ffd5b5f821561389a575f836138878487615be0565b6138919190615bf7565b91506109f79050565b505f196109f7565b6138aa61336a565b60405163175be66160e31b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163badf330891611a989190600401615378565b5f806138ea6116d5565b90506139356040518060e001604052805f81526020015f81526020015f81526020015f8152602001606081526020015f6001600160a01b031681526020015f63ffffffff1681525090565b838060200190518101906139499190615c4b565b6001600160a01b031660a08701526080860152606085015260208401528252505f613972610aa6565b6001840154835160208501519293506001600160a01b03909116915f91829161399f9186918d9190613dd9565b90925090506139cc6001600160a01b03841673ac4c6e212a361c968f1725b4d055b47e63f80b75846140db565b606085015160a08601516080870151604051630be77a3960e31b8152849373ac4c6e212a361c968f1725b4d055b47e63f80b7593635f3bd1c893613a1a938a938a9330938e93600401615cdf565b6020604051808303815f875af1158015613a36573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a5a9190614fbb565b613a6491906151cb565b96508615611ea857611ea86001600160a01b0385168a896141ac565b5f80613a8a6116d5565b60068101546040516307e04ac760e11b81529192506001600160a01b031690630fc0958e90610b039086903390600401615d28565b5f6109f783836127106001613117565b613ad8826141cb565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115613b1c576117068282614225565b610c0361424a565b613b2c614269565b6109378161428e565b613b3d614269565b610c0382826142fb565b5f836001600160a01b031663095ea7b38484604051602401613b6a929190615d3f565b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050509050613ba3848261432b565b6119d957613bff84856001600160a01b031663095ea7b3865f604051602401613bcd929190615d3f565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614370565b6119d98482614370565b6040516001600160a01b0384811660248301528381166044830152606482018390526119d99186918216906323b872dd90608401613bcd565b5f80613c78613c5282600a6152e1565b613c5a61096e565b613c6491906151cb565b613c6f8560016151cb565b8691905f613117565b9150613c8661307285613c97565b90509250929050565b805160208201fd5b5f80613ca16116d5565b600681015460405163ebe6e53d60e01b81529192506001600160a01b03169063ebe6e53d90610b039086903390600401615d28565b5f613cdf61336a565b6040516307d2584160e41b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd91637d25841091613d1791908690600401615ac4565b602060405180830381865af4158015613d32573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108bc9190614fbb565b5f613d5f6116d5565b6006015460405163293772e560e01b81526004810186905260248101859052604481018490526001600160a01b039091169063293772e590606401602060405180830381865afa158015613db5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111ee9190614fbb565b5f805f613de46116d5565b60018101546002820154604080516338d52e0f60e01b815290519394506001600160a01b039283169391909216915f9183916338d52e0f9160048083019260209291908290030181865afa158015613e3e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e6291906152ef565b90505f836001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401613e919190614a8e565b602060405180830381865afa158015613eac573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ed09190614fbb565b90505f8b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401613eff9190614a8e565b602060405180830381865afa158015613f1a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f3e9190614fbb565b90505f613f5a8c3060405180602001604052805f8152506143d3565b60405163d331bef760e01b815260048101829052602481018d9052604481018c90523060648201529091506001600160a01b0385169063d331bef79060840160408051808303815f875af1158015613fb4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613fd891906159d2565b50506040516370a0823160e01b815283906001600160a01b038816906370a0823190614008903090600401614a8e565b602060405180830381865afa158015614023573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140479190614fbb565b614051919061518c565b9850818d6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016140809190614a8e565b602060405180830381865afa15801561409b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140bf9190614fbb565b6140c9919061518c565b97505050505050505094509492505050565b5f81846001600160a01b031663dd62ed3e30866040518363ffffffff1660e01b815260040161410b92919061565b565b602060405180830381865afa158015614126573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061414a9190614fbb565b61415491906151cb565b90506119d98463095ea7b360e01b8584604051602401614175929190615d3f565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526144d9565b6117068363a9059cbb60e01b8484604051602401614175929190615d3f565b806001600160a01b03163b5f036141f75780604051634c9c8ce360e01b81526004016114e89190614a8e565b5f80516020615eb483398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b60606109f78383604051806060016040528060278152602001615ed4602791396145aa565b34156116d35760405163b398979f60e01b815260040160405180910390fd5b614271614614565b6116d357604051631afcd79f60e31b815260040160405180910390fd5b614296614269565b5f61429f611f71565b90505f806142ac8461462d565b91509150816142bc5760126142be565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b614303614269565b5f61430c6115ab565b90506003810161431c8482615d9c565b50600481016119d98382615d9c565b5f805f8060205f8651602088015f8a5af192503d91505f519050828015610a795750811561435c5780600114610a79565b50505050506001600160a01b03163b151590565b5f8060205f8451602086015f885af18061438f576040513d5f823e3d81fd5b50505f513d915081156143a65780600114156143b3565b6001600160a01b0384163b155b156119d95783604051635274afe760e01b81526004016114e89190614a8e565b5f806143dd6116d5565b6002015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561442e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061445291906152ef565b905061445c61336a565b6040516385e9726d60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd916385e9726d9161449a919085908a908a908a90600401615e56565b602060405180830381865af41580156144b5573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118b9190614fbb565b5f61452d826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166147039092919063ffffffff16565b805190915015611706578080602001905181019061454b9190615e98565b6117065760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016114e8565b60605f80856001600160a01b0316856040516145c69190615bbf565b5f60405180830381855af49150503d805f81146145fe576040519150601f19603f3d011682016040523d82523d5f602084013e614603565b606091505b5091509150610a7986838387614711565b5f61461d612327565b54600160401b900460ff16919050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b0387169161467391615bbf565b5f60405180830381855afa9150503d805f81146146ab576040519150601f19603f3d011682016040523d82523d5f602084013e6146b0565b606091505b50915091508180156146c457506020815110155b156146f7575f818060200190518101906146de9190614fbb565b905060ff81116146f5576001969095509350505050565b505b505f9485945092505050565b60606111ee84845f85614789565b6060831561477f5782515f03614778576001600160a01b0385163b6147785760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016114e8565b50816111ee565b6111ee8383614855565b6060824710156147ea5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016114e8565b5f80866001600160a01b031685876040516148059190615bbf565b5f6040518083038185875af1925050503d805f811461483f576040519150601f19603f3d011682016040523d82523d5f602084013e614844565b606091505b50915091506137fd87838387614711565b8151156148655781518083602001fd5b8060405162461bcd60e51b81526004016114e891906148f6565b6040518061014001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6109f760208301846148c8565b5f60208284031215614918575f80fd5b5035919050565b6001600160a01b0381168114610937575f80fd5b803561493e8161491f565b919050565b5f8060408385031215614954575f80fd5b823561495f8161491f565b946020939093013593505050565b803561ffff8116811461493e575f80fd5b5f6020828403121561498e575f80fd5b6109f78261496d565b5f805f606084860312156149a9575f80fd5b83356149b48161491f565b925060208401356149c48161491f565b929592945050506040919091013590565b5f8083601f8401126149e5575f80fd5b5081356001600160401b038111156149fb575f80fd5b602083019150836020828501011115614a12575f80fd5b9250929050565b5f805f805f8060a08789031215614a2e575f80fd5b863595506020870135614a408161491f565b94506040870135614a508161491f565b935060608701356001600160401b03811115614a6a575f80fd5b614a7689828a016149d5565b979a9699509497949695608090950135949350505050565b6001600160a01b0391909116815260200190565b5f60208284031215614ab2575f80fd5b81356109f78161491f565b634e487b7160e01b5f52604160045260245ffd5b6040516101a081016001600160401b0381118282101715614af457614af4614abd565b60405290565b604051608081016001600160401b0381118282101715614af457614af4614abd565b604051606081016001600160401b0381118282101715614af457614af4614abd565b604051601f8201601f191681016001600160401b0381118282101715614b6657614b66614abd565b604052919050565b5f6001600160401b03821115614b8657614b86614abd565b50601f01601f191660200190565b5f82601f830112614ba3575f80fd5b8135602083015f614bbb614bb684614b6e565b614b3e565b9050828152858383011115614bce575f80fd5b828260208301375f92810160200192909252509392505050565b5f8060408385031215614bf9575f80fd5b8235614c048161491f565b915060208301356001600160401b03811115614c1e575f80fd5b614c2a85828601614b94565b9150509250929050565b5f8060208385031215614c45575f80fd5b82356001600160401b03811115614c5a575f80fd5b614c66858286016149d5565b90969095509350505050565b5f8082840360a0811215614c84575f80fd5b83356001600160401b03811115614c99575f80fd5b84016101a08187031215614cab575f80fd5b92506080601f1982011215614cbe575f80fd5b506020830190509250929050565b5f8060408385031215614cdd575f80fd5b823591506020830135614cef8161491f565b809150509250929050565b5f8060208385031215614d0b575f80fd5b82356001600160401b03811115614d20575f80fd5b8301601f81018513614d30575f80fd5b80356001600160401b03811115614d45575f80fd5b8560208260051b8401011115614d59575f80fd5b6020919091019590945092505050565b602080825282518282018190525f918401906040840190835b81811015614da0578351835260209384019390920191600101614d82565b509095945050505050565b5f805f60608486031215614dbd575f80fd5b833592506020840135614dcf8161491f565b91506040840135614ddf8161491f565b809150509250925092565b8015158114610937575f80fd5b5f8060408385031215614e08575f80fd5b8235614e138161491f565b91506020830135614cef81614dea565b5f8060408385031215614e34575f80fd5b8235614e3f8161491f565b91506020830135614cef8161491f565b5f805f805f60808688031215614e63575f80fd5b853594506020860135614e758161491f565b935060408601356001600160401b03811115614e8f575f80fd5b614e9b888289016149d5565b96999598509660600135949350505050565b5f805f805f8060808789031215614ec2575f80fd5b86356001600160401b03811115614ed7575f80fd5b614ee389828a016149d5565b9097509550506020870135614ef78161491f565b935060408701356001600160401b03811115614f11575f80fd5b614f1d89828a01614b94565b93505060608701356001600160401b03811115614f38575f80fd5b614f4489828a016149d5565b979a9699509497509295939492505050565b600181811c90821680614f6a57607f821691505b602082108103614f8857634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b60ff81811683821601908111156108bc576108bc614f8e565b5f60208284031215614fcb575f80fd5b5051919050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f6101a08236031215615004575f80fd5b61500c614ad1565b61501583614933565b815260208301356001600160401b0381111561502f575f80fd5b61503b36828601614b94565b60208301525060408301356001600160401b03811115615059575f80fd5b61506536828601614b94565b60408301525061507760608401614933565b606082015261508860808401614933565b608082015261509960a08401614933565b60a08201526150aa60c0840161496d565b60c08201526150bb60e0840161496d565b60e08201526150cd610100840161496d565b6101008201526150e06101208401614933565b6101208201526150f36101408401614933565b6101408201526151066101608401614933565b6101608201526151196101808401614933565b61018082015292915050565b5f6080828403128015615136575f80fd5b5061513f614afa565b823561514a8161491f565b8152602083013561515a8161491f565b6020820152604083013561516d8161491f565b604082015260608301356151808161491f565b60608201529392505050565b818103818111156108bc576108bc614f8e565b5f600182016151b0576151b0614f8e565b5060010190565b634e487b7160e01b5f52603260045260245ffd5b808201808211156108bc576108bc614f8e565b5f602082840312156151ee575f80fd5b815160ff811681146109f7575f80fd5b6001815b60018411156152395780850481111561521d5761521d614f8e565b600184161561522b57908102905b60019390931c928002615202565b935093915050565b5f8261524f575060016108bc565b8161525b57505f6108bc565b8160018114615271576002811461527b57615297565b60019150506108bc565b60ff84111561528c5761528c614f8e565b50506001821b6108bc565b5060208310610133831016604e8410600b84101617156152ba575081810a6108bc565b6152c65f1984846151fe565b805f19048211156152d9576152d9614f8e565b029392505050565b5f6109f760ff841683615241565b5f602082840312156152ff575f80fd5b81516109f78161491f565b61ffff91909116815260200190565b634e487b7160e01b5f52601260045260245ffd5b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015182169084015260808083015182169084015260a09182015116910152565b60c081016108bc828461532d565b5f60608284031215615396575f80fd5b61539e614b1c565b82358152905060208201356153b28161491f565b602082015260408201356153c58161491f565b604082015292915050565b5f6001600160401b038211156153e8576153e8614abd565b5060051b60200190565b5f60208284031215615402575f80fd5b81356001600160401b03811115615417575f80fd5b820160c08185031215615428575f80fd5b615430614afa565b813581526020808301359082015261544b8560408401615386565b604082015260a08201356001600160401b03811115615468575f80fd5b91909101906080828603121561547c575f80fd5b615484614afa565b823581526020808401359082015260408301356154a08161491f565b604082015260608301356001600160401b038111156154bd575f80fd5b80840193505085601f8401126154d1575f80fd5b82356154df614bb6826153d0565b8082825260208201915060208360051b870101925088831115615500575f80fd5b602086015b838110156155405780356001600160401b03811115615522575f80fd5b6155318b6020838b0101614b94565b84525060209283019201615505565b5080606085015250505080606083015250809250505092915050565b805182526020808201516001600160a01b039081169184019190915260409182015116910152565b6001600160a01b03831681526040602080830182905283518284015283015160608301528201515f906155ba608084018261555c565b5060608381015160c060e0850152805161010085015260208082015161012086015260408201516001600160a01b03166101408601529101516080610160850152805161018085018190529101906101a0600582901b8501810191908501905f5b8181101561564e5761019f198785030183526156388486516148c8565b602095860195909450929092019160010161561b565b5091979650505050505050565b6001600160a01b0392831681529116602082015260400190565b8181035f83128015838313168383128216171561232057612320614f8e565b918252602082015260400190565b634e487b7160e01b5f52602160045260245ffd5b8381526020810183905260608101600283106156e057634e487b7160e01b5f52602160045260245ffd5b826040830152949350505050565b5f606082840312156156fe575f80fd5b615706614b1c565b82518152602083015190915061571b8161491f565b602082015260408201516153c58161491f565b5f82601f83011261573d575f80fd5b815161574b614bb682614b6e565b81815284602083860101111561575f575f80fd5b8160208501602083015e5f918101602001919091529392505050565b5f60c0828403121561578b575f80fd5b615793614afa565b825181526020808401519082015290506157b083604084016156ee565b604082015260a08201516001600160401b038111156157cd575f80fd5b8201608081850312156157de575f80fd5b6157e6614afa565b815181526020808301519082015260408201516158028161491f565b604082015260608201516001600160401b0381111561581f575f80fd5b80830192505084601f830112615833575f80fd5b8151615841614bb6826153d0565b8082825260208201915060208360051b860101925087831115615862575f80fd5b602085015b838110156158a25780516001600160401b03811115615884575f80fd5b6158938a6020838a010161572e565b84525060209283019201615867565b50806060850152505050806060840152505092915050565b5f602082840312156158ca575f80fd5b81516001600160401b038111156158df575f80fd5b6111ee8482850161577b565b5f602082840312156158fb575f80fd5b81516001600160401b03811115615910575f80fd5b820160c08185031215615921575f80fd5b615929614afa565b815181526020808301519082015261594485604084016156ee565b604082015260a08201516001600160401b03811115615961575f80fd5b919091019060608286031215615975575f80fd5b61597d614b1c565b82516001600160401b03811115615992575f80fd5b61599e8782860161572e565b82525060208381015190820152604090920151916159bb8361491f565b604081019290925260608101919091529392505050565b5f80604083850312156159e3575f80fd5b505080516020909101519092909150565b5f60208284031215615a04575f80fd5b81356001600160401b03811115615a19575f80fd5b820160c08185031215615a2a575f80fd5b615a32614afa565b8135815260208083013590820152615a4d8560408401615386565b604082015260a08201356001600160401b03811115615a6a575f80fd5b919091019060608286031215615a7e575f80fd5b615a86614b1c565b82356001600160401b03811115615a9b575f80fd5b615aa787828601614b94565b82525060208381013590820152604090920135916159bb8361491f565b60e08101615ad2828561532d565b8260c08301529392505050565b6001600160a01b03831681526040602080830182905283518284015283015160608301528201515f90615b15608084018261555c565b50606083015160c060e084015280516060610100850152615b3a6101608501826148c8565b60208301516101208601526040909201516001600160a01b031661014090940193909352949350505050565b6001600160a01b039290921682521515602082015260400190565b615b8b818561532d565b60e060c08201528160e082015281836101008301375f81830161010090810191909152601f909201601f1916010192915050565b5f82518060208501845e5f920191825250919050565b5f6109f78383615241565b80820281158282048414176108bc576108bc614f8e565b5f82615c1157634e487b7160e01b5f52601260045260245ffd5b500490565b615c20818661532d565b61012060c08201525f615c376101208301866148c8565b60e083019490945250610100015292915050565b5f805f805f8060c08789031215615c60575f80fd5b86516001600160401b03811115615c75575f80fd5b615c8189828a0161577b565b602089015160408a015160608b015160808c0151939a509198509650945090506001600160401b03811115615cb4575f80fd5b615cc089828a0161572e565b92505060a0870151615cd18161491f565b809150509295509295509295565b6001600160a01b038881168252602082018890528681166040830152858116606083015260808201859052831660a082015260e060c082018190525f90613628908301846148c8565b9182526001600160a01b0316602082015260400190565b6001600160a01b03929092168252602082015260400190565b601f82111561170657805f5260205f20601f840160051c81016020851015615d7d5750805b601f840160051c820191505b81811015613240575f8155600101615d89565b81516001600160401b03811115615db557615db5614abd565b615dc981615dc38454614f56565b84615d58565b6020601f821160018114615dfb575f8315615de45750848201515b5f19600385901b1c1916600184901b178455613240565b5f84815260208120601f198516915b82811015615e2a5787850151825560209485019460019092019101615e0a565b5084821015615e4757868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b615e60818761532d565b6001600160a01b0385811660c083015260e08201859052831661010082015261014061012082018190525f906137fd908301846148c8565b5f60208284031215615ea8575f80fd5b81516109f781614dea56fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220a9af32d33343ced0571272fb4c29de1a1c00946f9c5c00af67f85f2456cc94a064736f6c634300081a0033

Deployed Bytecode

0x608060405260043610610243575f3560e01c806301e1d1141461024757806306fdde031461026e57806307a2d13a1461028f57806308476e6e146102ae578063095ea7b3146102c45780630a28a477146102f3578063161a141c1461031257806318160ddd146103315780631e47b7d21461034557806323ab46941461035957806323b872dd146103785780632ab09d5a146103975780632b3297f9146103b6578063313ce567146103ea57806338d52e0f14610410578063402d267d1461042457806341976e091461044357806341b6ccdc146104625780634cdad506146104815780634f1ef286146104a057806352d1902d146104b35780635551396a146104c7578063572ffa0c146104e657806362e48a3e146105055780636e553f651461051957806370a08231146105385780637377ecc414610557578063748747e6146105765780637784c68514610595578063874402bf146105c157806392c18454146105e057806394bf804d1461051957806395d89b41146105ff578063a9059cbb14610613578063ad3cb1cc14610632578063b3d7f6b914610662578063b460af9414610681578063b61ab0e61461069b578063ba08765214610681578063c3c854b6146106ba578063c60244ad146106d9578063c63d75b614610424578063c688d9a5146106f8578063c6e6f59214610717578063ce96cb7714610736578063d905777e14610755578063dd62ed3e14610774578063df88933c14610793578063e2ede6e7146107b2578063ef8b30f7146107d1578063fff8d04e146107f0575b5f80fd5b348015610252575f80fd5b5061025b610804565b6040519081526020015b60405180910390f35b348015610279575f80fd5b50610282610813565b60405161026591906148f6565b34801561029a575f80fd5b5061025b6102a9366004614908565b6108b1565b3480156102b9575f80fd5b506102c26108c2565b005b3480156102cf575f80fd5b506102e36102de366004614943565b61093a565b6040519015158152602001610265565b3480156102fe575f80fd5b5061025b61030d366004614908565b610951565b34801561031d575f80fd5b506102c261032c36600461497e565b61095d565b34801561033c575f80fd5b5061025b61096e565b348015610350575f80fd5b5061025b610982565b348015610364575f80fd5b506102c261037336600461497e565b6109c8565b348015610383575f80fd5b506102e3610392366004614997565b6109d9565b3480156103a2575f80fd5b5061025b6103b1366004614a19565b6109fe565b3480156103c1575f80fd5b506103dd73ac4c6e212a361c968f1725b4d055b47e63f80b7581565b6040516102659190614a8e565b3480156103f5575f80fd5b506103fe610a83565b60405160ff9091168152602001610265565b34801561041b575f80fd5b506103dd610aa6565b34801561042f575f80fd5b5061025b61043e366004614aa2565b610ac0565b34801561044e575f80fd5b5061025b61045d366004614aa2565b610ac6565b34801561046d575f80fd5b506102c261047c366004614aa2565b610b42565b34801561048c575f80fd5b5061025b61049b366004614908565b610bd5565b6102c26104ae366004614be8565b610be8565b3480156104be575f80fd5b5061025b610c07565b3480156104d2575f80fd5b506102c26104e1366004614c34565b610c22565b3480156104f1575f80fd5b506102c2610500366004614c72565b610d3a565b348015610510575f80fd5b5061025b610e50565b348015610524575f80fd5b5061025b610533366004614ccc565b610e6f565b348015610543575f80fd5b5061025b610552366004614aa2565b610e89565b348015610562575f80fd5b506102c2610571366004614c34565b610eb2565b348015610581575f80fd5b506102c2610590366004614aa2565b610f38565b3480156105a0575f80fd5b506105b46105af366004614cfa565b610f49565b6040516102659190614d69565b3480156105cc575f80fd5b506102c26105db366004614aa2565b610fd8565b3480156105eb575f80fd5b506102c26105fa366004614aa2565b610fe9565b34801561060a575f80fd5b50610282610ffa565b34801561061e575f80fd5b506102e361062d366004614943565b611016565b34801561063d575f80fd5b50610282604051806040016040528060058152602001640352e302e360dc1b81525081565b34801561066d575f80fd5b5061025b61067c366004614908565b611023565b34801561068c575f80fd5b5061025b610533366004614dab565b3480156106a6575f80fd5b506102c26106b5366004614aa2565b61102f565b3480156106c5575f80fd5b506102c26106d4366004614df7565b6110b6565b3480156106e4575f80fd5b506102c26106f336600461497e565b6110c8565b348015610703575f80fd5b506102c2610712366004614aa2565b6110d9565b348015610722575f80fd5b5061025b610731366004614908565b6110ea565b348015610741575f80fd5b5061025b610750366004614aa2565b6110f5565b348015610760575f80fd5b5061025b61076f366004614aa2565b611108565b34801561077f575f80fd5b5061025b61078e366004614e23565b611112565b34801561079e575f80fd5b5061025b6107ad366004614e4f565b61114c565b3480156107bd575f80fd5b506102c26107cc366004614ead565b611194565b3480156107dc575f80fd5b5061025b6107eb366004614908565b6111d3565b3480156107fb575f80fd5b5061025b6111f6565b5f61080e5f611335565b905090565b60605f61081e6115ab565b905080600301805461082f90614f56565b80601f016020809104026020016040519081016040528092919081815260200182805461085b90614f56565b80156108a65780601f1061087d576101008083540402835291602001916108a6565b820191905f5260205f20905b81548152906001019060200180831161088957829003601f168201915b505050505091505090565b5f6108bc825f6115cf565b92915050565b6108ca61160c565b73eea27de7b45d1c7c98e89ac248f7a9b894faba846108e76116d5565b60080180546001600160a01b0319166001600160a01b039290921691909117905560408051602081019091525f8152730fa53f1b5f1b9552ed6b6d10c89cd9ec7b7e34a190610937908290610be8565b50565b5f336109478185856116f9565b5060019392505050565b5f6108bc82600161170b565b61096561173f565b610937816117e4565b5f806109786115ab565b6002015492915050565b5f8061098c6116d5565b60028101549091506109c2906109aa906001600160a01b0316610ac6565b670de0b6b3a76400006109bb610e50565b9190611864565b91505090565b6109d061173f565b6109378161190d565b5f336109e685828561198f565b6109f18585856119df565b60019150505b9392505050565b5f610a07611a3c565b610a0f611a5a565b5f610a1a8887611ac0565b90505f610a28828787611be6565b9050610a6d88888b84888b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611eb592505050565b92505050610a79611f6c565b9695505050505050565b5f80610a8d611f71565b90505f81546109c29190600160a01b900460ff16614fa2565b5f80610ab0611f71565b546001600160a01b031692915050565b505f1990565b5f80610ad06116d5565b60068101546040516341976e0960e01b81529192506001600160a01b0316906341976e0990610b03908690600401614a8e565b602060405180830381865afa158015610b1e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109f79190614fbb565b610b4a61173f565b5f610b536116d5565b90506001600160a01b038216610b7c5760405163d92e233d60e01b815260040160405180910390fd5b6009810180546001600160a01b0319166001600160a01b0384161790556040517fd35955139a5369dcd2c236349c7d831c0740cb113591dc789cabec0824f6104690610bc9908490614a8e565b60405180910390a15050565b5f80610be083611f95565b509392505050565b610bf0611fc6565b610bf98261206a565b610c038282612072565b5050565b5f610c10612125565b505f80516020615eb483398151915290565b610c2a61160c565b610c32611a3c565b610c3a6116d5565b60020154604080516020601f85018190048102820181019092528381526001600160a01b03909216919084908490819084018382808284375f92019190915250610c879250611a5a915050565b5f610c90610804565b9050610c9d5f8686611be6565b50610cb8610ca961216e565b610cb16121f0565b600161224e565b5f610cc384846122c0565b9050610ccd6116d5565b600601546040516321a348a160e01b81526001600160a01b03909116906321a348a190610d0290879085908790600401614fd2565b5f6040518083038186803b158015610d18575f80fd5b505afa158015610d2a573d5f803e3d5ffd5b5050505050505050610c03611f6c565b5f610d43612327565b805490915060ff600160401b82041615906001600160401b03165f81158015610d695750825b90505f826001600160401b03166001148015610d845750303b155b905081158015610d92575080155b15610db05760405163f92ee8a960e01b815260040160405180910390fd5b84546001600160401b03191660011785558315610dd957845460ff60401b1916600160401b1785555b610dea610de588614ff3565b61234b565b610e01610dfc36889003880188615125565b61244c565b8315610e4757845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b5f80610e5a612540565b509050610e656111f6565b6109c2908261518c565b5f604051631a8d61e960e11b815260040160405180910390fd5b5f80610e936115ab565b6001600160a01b039093165f9081526020939093525050604090205490565b610eba61160c565b610ec2611a3c565b610eca6116d5565b60010154604080516020601f85018190048102820181019092528381526001600160a01b03909216919084908490819084018382808284375f92019190915250610f179250611a5a915050565b5f610f20610804565b9050610f2d5f86866125c6565b610cb8610ca961216e565b610f4061173f565b6109378161287c565b606081806001600160401b03811115610f6457610f64614abd565b604051908082528060200260200182016040528015610f8d578160200160208202803683370190505b5091505f5b81811015610fd0575f858583610fa78161519f565b9450818110610fb857610fb86151b7565b90506020020135905080546020830285015250610f92565b505092915050565b610fe061173f565b610937816128fb565b610ff161173f565b6109378161297a565b60605f6110056115ab565b905080600401805461082f90614f56565b5f336109478185856119df565b5f6108bc8260016115cf565b61103761173f565b5f6110406116d5565b90506001600160a01b0382166110695760405163d92e233d60e01b815260040160405180910390fd5b600a810180546001600160a01b0319166001600160a01b0384161790556040517f6cd650a77ac6e3f55319493f7e38de4061af1323f9b3b50270823848681124de90610bc9908490614a8e565b6110be61173f565b610c0382826129f9565b6110d061173f565b61093781612aa2565b6110e161173f565b61093781612b24565b5f6108bc825f61170b565b5f6108bc61110283610e89565b5f6115cf565b5f6108bc82610e89565b5f8061111c6115ab565b6001600160a01b039485165f90815260019190910160209081526040808320959096168252939093525050205490565b5f611155611a3c565b61115d611a5a565b5f6111688787612c21565b90506111758786866125c6565b611180818488612ca0565b91505061118b611f6c565b95945050505050565b61119c61160c565b6111a68686612db7565b6111b284848484612e21565b6111cb6111bd61216e565b6111c56121f0565b5f61224e565b505050505050565b5f805f6111df84613059565b90925090506111ee818361518c565b949350505050565b5f806112006116d5565b90505f816006015f9054906101000a90046001600160a01b03166001600160a01b0316634ad45c846040518163ffffffff1660e01b8152600401602060405180830381865afa158015611255573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112799190614fbb565b60028301549091505f906112aa90611299906001600160a01b0316610ac6565b6112a1613080565b8491905f6130ec565b905080836006015f9054906101000a90046001600160a01b03166001600160a01b0316631529a6396040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112ff573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113239190614fbb565b61132d919061518c565b935050505090565b5f8061133f6116d5565b60088101549091506001600160a01b03165f8061135a612540565b60405163ec38a05d60e01b815291935091506001600160a01b0384169063ec38a05d9061138b903090600401614a8e565b602060405180830381865afa1580156113a6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113ca9190614fbb565b6113d490836151cb565b60068501546040516382fee08f60e01b8152600481018390529193505f916001600160a01b03909116906382fee08f90602401602060405180830381865afa158015611422573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114469190614fbb565b600686015460405163c0177bd560e01b8152600481018590529192505f916001600160a01b039091169063c0177bd590602401602060405180830381865afa158015611494573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b89190614fbb565b9050818111156114f1576114cc828261518c565b604051631309868760e11b81526004016114e891815260200190565b60405180910390fd5b5f6114fc828461518c565b90505f611507610aa6565b90505f61151382610ac6565b90505f826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611552573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061157691906151de565b90505f61159a61158783600a6152e1565b848f88613117909392919063ffffffff16565b9d9c50505050505050505050505050565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0090565b5f6109f76115db610804565b6115e69060016151cb565b6115f15f600a6152e1565b6115f961096e565b61160391906151cb565b85919085613117565b6116146116d5565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa15801561165a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061167e91906152ef565b6001600160a01b0316336001600160a01b0316141580156116b357506116a26116d5565b600301546001600160a01b03163314155b156116d3573360405163245aecd360e01b81526004016114e89190614a8e565b565b7f12ca37b393c412d053690654fb6d504d2a16c55c2bd10941af581f2221d9c10090565b6117068383836001613166565b505050565b5f6109f761171a82600a6152e1565b61172261096e565b61172c91906151cb565b611734610804565b6116039060016151cb565b6117476116d5565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa15801561178d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117b191906152ef565b6001600160a01b0316336001600160a01b0316146116d3573360405163245aecd360e01b81526004016114e89190614a8e565b5f6117ed6116d5565b905060fa61ffff831611156118185760fa604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60b01b1916600160b01b61ffff8516021790556040517fad9f7bb2fb869a89410ed22cba28ce6ddb3d518ddb06ec79d90eef53e43d099a90610bc990849061530a565b5f80805f19858709858702925082811083820303915050805f0361189b5783828161189157611891615319565b04925050506109f7565b8084116118a6575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b5f6119166116d5565b90506101f461ffff83161115611943576101f4604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60a01b1916600160a01b61ffff8516021790556040517fd76d222a1569878be0d02545c0819a8399c91999f0d8565d9d1dbfa1c2524df290610bc990849061530a565b5f61199a8484611112565b90505f1981146119d957818110156119cb57828183604051637dc7a0d960e11b81526004016114e893929190614fd2565b6119d984848484035f613166565b50505050565b6001600160a01b038316611a08575f604051634b637e8f60e11b81526004016114e89190614a8e565b6001600160a01b038216611a31575f60405163ec442f0560e01b81526004016114e89190614a8e565b611706838383613247565b63769dd35360e11b5f5c15611a5357805f5260045ffd5b60015f5d50565b611a6261336a565b604051635fc6e58d60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd91635fc6e58d91611a989190600401615378565b5f6040518083038186803b158015611aae575f80fd5b505af41580156119d9573d5f803e3d5ffd5b5f80611aca6116d5565b90505f611ad684611108565b905080851115611aff57838582604051632e52afbb60e21b81526004016114e893929190614fd2565b845f03611b1f57604051631f2a200560e01b815260040160405180910390fd5b5f80611b2a87611f95565b91509150805f14611ba757835460408051632cfc019d60e21b81529051611ba7926001600160a01b03169163b3f006749160048083019260209291908290030181865afa158015611b7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba191906152ef565b82613409565b611bb1868861343d565b611bba82613471565b9450845f03611bdc57604051631f2a200560e01b815260040160405180910390fd5b5050505092915050565b5f80611bf06116d5565b9050611bfa61487f565b60088201546001600160a01b03165f611c15868801886153f2565b9050611c1f612540565b60208501528352611c2e613635565b60a085015260808401526060810151602001515f03611c6057604051631f2a200560e01b815260040160405180910390fd5b606081015160200151611c7390896151cb565b6040820151525f60208201819052888103611c8e575f611c98565b611c986001611335565b600a860154604051632a055ea360e01b81529192506001600160a01b031690632a055ea390611ccd9086908690600401615584565b5f604051808303815f87803b158015611ce4575f80fd5b505af1158015611cf6573d5f803e3d5ffd5b50505050611d02613635565b60e086015260c0850181905260808501515f91611d1f919061518c565b90508915611d3557611d32818b8461372b565b96505b611d8f836040015160200151846040015160400151604051602001611d5b92919061565b565b604051602081830303815290604052888760a001518860e00151611d7f9190615675565b611d899190615675565b83613808565b611d97612540565b606087015260408601528915611e47575f611e378660400151875f0151611dbe919061518c565b87606001518860200151611dd2919061518c565b876001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e0e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e329190614fbb565b613874565b9050611e4581610cb16121f0565b505b8451604086015110611e7357604080860151865191516232a45960e71b81526114e89290600401615694565b846020015185606001511115611ea85784606001518560200151604051633fb9035760e11b81526004016114e8929190615694565b5050505050509392505050565b5f611ebe6138a2565b336001600160a01b03871614611ed957611ed986338761198f565b611ee48488846138e0565b905082811015611f0b5782816040516327014c6d60e11b81526004016114e8929190615694565b856001600160a01b0316876001600160a01b0316336001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8489604051611f5a929190615694565b60405180910390a49695505050505050565b5f805d565b7f0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e0090565b5f805f611fab611fa485613a80565b8590613abf565b90505f611fbb6102a9838761518c565b959194509092505050565b306001600160a01b037f000000000000000000000000a9855658ec2e5766a9f73e056a0bf55af7135fe016148061204c57507f000000000000000000000000a9855658ec2e5766a9f73e056a0bf55af7135fe06001600160a01b03166120405f80516020615eb4833981519152546001600160a01b031690565b6001600160a01b031614155b156116d35760405163703e46dd60e11b815260040160405180910390fd5b61093761173f565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156120cc575060408051601f3d908101601f191682019092526120c991810190614fbb565b60015b6120eb5781604051634c9c8ce360e01b81526004016114e89190614a8e565b5f80516020615eb4833981519152811461211b57604051632a87526960e21b8152600481018290526024016114e8565b6117068383613acf565b306001600160a01b037f000000000000000000000000a9855658ec2e5766a9f73e056a0bf55af7135fe016146116d35760405163703e46dd60e11b815260040160405180910390fd5b5f806121786116d5565b9050806006015f9054906101000a90046001600160a01b03166001600160a01b03166391b58ae86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109c29190614fbb565b5f806121fa6116d5565b9050806006015f9054906101000a90046001600160a01b03166001600160a01b031663ec9d25526040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cc573d5f803e3d5ffd5b5f6122576116d5565b600681015460405163479fd6fb60e11b81529192506001600160a01b031690638f3fadf69061228e908790879087906004016156b6565b5f6040518083038186803b1580156122a4575f80fd5b505afa1580156122b6573d5f803e3d5ffd5b5050505050505050565b5f806122ca6116d5565b60028101549091506001600160a01b039081169085160361230857828060200190518101906122f991906158ba565b60600151602001519150612320565b8280602001905181019061231c91906158eb565b5191505b5092915050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0090565b5f6123546116d5565b60608301519091506001600160a01b03166123825760405163d92e233d60e01b815260040160405180910390fd5b815161238d90613b24565b61239f82602001518360400151613b35565b606082015181546001600160a01b039182166001600160a01b0319918216178355608084015160018401805491841691831691909117905560a08401516002840180549190931691161790556101408201516123fa906128fb565b6124078260c0015161190d565b6124148260e001516117e4565b612422826101000151612aa2565b61243082610120015161287c565b61243e82610160015161297a565b610c03826101800151612b24565b5f6124556116d5565b82519091506001600160a01b0316158061247a575060208201516001600160a01b0316155b80612490575060408201516001600160a01b0316155b806124a6575060608201516001600160a01b0316155b156124c45760405163d92e233d60e01b815260040160405180910390fd5b81516007820180546001600160a01b03199081166001600160a01b039384161790915560208401516008840180548316918416919091179055604084015160098401805483168285161790556060850151600a8501805490931693169290921790556125319060016129f9565b610c03826060015160016129f9565b5f8061254a61336a565b604051633820305360e21b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163e080c14c916125809190600401615378565b6040805180830381865af415801561259a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125be91906159d2565b915091509091565b5f6125cf6116d5565b90506125d961487f565b60088201546001600160a01b03165f6125f4858701876159f4565b9050865f0361266d5761260561336a565b60408083015151905163ecc134c760e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9263ecc134c79261264092600401615ac4565b5f6040518083038186803b158015612656575f80fd5b505af4158015612668573d5f803e3d5ffd5b505050505b6020810187905261267c612540565b6020808601919091529084526009850154908201516126b7916001600160a01b0316906126a7610aa6565b6001600160a01b03169190613b47565b600984015460405163f6038b6760e01b81526001600160a01b039091169063f6038b67906126eb9085908590600401615adf565b5f604051808303815f87803b158015612702575f80fd5b505af1158015612714573d5f803e3d5ffd5b50505050612720612540565b60608501526040840152602081015161273890613471565b835161274491906151cb565b83604001511161276f576040808401518451915163ee5410af60e01b81526114e89290600401615694565b82602001518360600151116127a357826060015183602001516040516311b7c95d60e11b81526004016114e8929190615694565b602081015115610e4757825160408401515f916127bf9161518c565b90505f846020015185606001516127d6919061518c565b90505f6127e16121f0565b90505f856001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612820573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128449190614fbb565b905061284e61096e565b1561286f575f61285f858584613874565b905061286d8184600161224e565b505b5050505050505050505050565b5f6128856116d5565b90506001600160a01b0382166128ae5760405163d92e233d60e01b815260040160405180910390fd5b6003810180546001600160a01b0319166001600160a01b0384161790556040517f8b67cf08b3b4a582cdf414f29895fde3e3f03a3bf26373a22a8b9bd89e75748890610bc9908490614a8e565b5f6129046116d5565b90506001600160a01b03821661292d5760405163d92e233d60e01b815260040160405180910390fd5b6004810180546001600160a01b0319166001600160a01b0384161790556040517f42bbfb4743223617630fbe3734cfffc55d280da085acdb2426e843716cd5552290610bc9908490614a8e565b5f6129836116d5565b90506001600160a01b0382166129ac5760405163d92e233d60e01b815260040160405180910390fd5b6005810180546001600160a01b0319166001600160a01b0384161790556040517fcba8f51815ef6b4d9d58f668351b97323a16a5ce5c9186a17d27fa45c3e8e42690610bc9908490614a8e565b5f612a026116d5565b60078101546040516361e42a5b60e11b81529192506001600160a01b03169063c3c854b690612a379086908690600401615b66565b5f604051808303815f87803b158015612a4e575f80fd5b505af1158015612a60573d5f803e3d5ffd5b505050507fe25ae1b1d4513ae709d95de0ee5a28a9ecd6f408fcc7652183e73fe1ec46c7b88383604051612a95929190615b66565b60405180910390a1505050565b5f612aab6116d5565b905061012c61ffff83161115612ad85761012c604051638abdc12960e01b81526004016114e8919061530a565b60028101805461ffff60c01b1916600160c01b61ffff8516021790556040517f78d7b33b806f8dd6d1be0926097e8fd70795eef7a373ab8bdbc1f49e9b24347f90610bc990849061530a565b5f612b2d6116d5565b90506001600160a01b0382161580612bb65750306001600160a01b0316826001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b86573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612baa91906152ef565b6001600160a01b031614155b15612bd45760405163d92e233d60e01b815260040160405180910390fd5b6006810180546001600160a01b0319166001600160a01b0384161790556040517ffdf2c3daba11b29cf3b43a19b2f0d11e4755d15d15436ee5a82635ef0ca00a9b90610bc9908490614a8e565b5f80612c2c83610ac0565b905080841115612c5557828482604051633c8097d960e11b81526004016114e893929190614fd2565b835f03612c7557604051631f2a200560e01b815260040160405180910390fd5b612c7f6001611335565b9150612320333086612c8f610aa6565b6001600160a01b0316929190613c09565b5f80612caa6116d5565b90505f612cb5610804565b90505f612cc2878361518c565b90505f80612cd0838a613c42565b9092509050612cdf818361518c565b955087861015612d065787866040516327014c6d60e11b81526004016114e8929190615694565b8015612d5457845460408051632cfc019d60e21b81529051612d54926001600160a01b03169163b3f006749160048083019260209291908290030181865afa158015611b7d573d5f803e3d5ffd5b612d5e8787613409565b866001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d78589604051612da3929190615694565b60405180910390a350505050509392505050565b612dbf61336a565b6040516359492bb160e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd916359492bb191612df9919086908690600401615b81565b5f6040518083038186803b158015612e0f575f80fd5b505af41580156111cb573d5f803e3d5ffd5b5f612e2a6116d5565b60018101546040516370a0823160e01b81529192505f916001600160a01b03909116906370a0823190612e61903090600401614a8e565b602060405180830381865afa158015612e7c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ea09190614fbb565b6001830154909150612ebc906001600160a01b03168783613b47565b5f80876001600160a01b031687604051612ed69190615bbf565b5f604051808303815f865af19150503d805f8114612f0f576040519150601f19603f3d011682016040523d82523d5f602084013e612f14565b606091505b509150915081612f2757612f2781613c8f565b5f612f30610aa6565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612f5b9190614a8e565b602060405180830381865afa158015612f76573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f9a9190614fbb565b9050805f03612fbc57604051631f2a200560e01b815260040160405180910390fd5b612fc78188886125c6565b612fcf61096e565b5f0361304e57845460408051638da5cb5b60e01b8152905161304e926001600160a01b031691638da5cb5b9160048083019260209291908290030181865afa15801561301d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061304191906152ef565b613049610804565b613409565b505050505050505050565b5f80613064836110ea565b915061307961307284613c97565b8390613abf565b9050915091565b5f735a91f87c9e72240bc1b780be0557a61164fd9ffd6320daa1e06040518163ffffffff1660e01b8152600401602060405180830381865af41580156130c8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061080e91906151de565b5f8315806130f8575084155b1561310457505f6111ee565b61118b61311284600a6152e1565b869086855b5f80613124868686611864565b9050600183600281111561313a5761313a6156a2565b14801561315657505f848061315157613151615319565b868809115b1561118b57610a796001826151cb565b5f61316f6115ab565b90506001600160a01b03851661319a575f60405163e602df0560e01b81526004016114e89190614a8e565b6001600160a01b0384166131c3575f604051634a1406b160e11b81526004016114e89190614a8e565b6001600160a01b038086165f9081526001830160209081526040808320938816835292905220839055811561324057836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161323791815260200190565b60405180910390a35b5050505050565b5f6132506115ab565b90506001600160a01b03841661327e5781816002015f82825461327391906151cb565b909155506132db9050565b6001600160a01b0384165f90815260208290526040902054828110156132bd5784818460405163391434e360e21b81526004016114e893929190614fd2565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b0383166132f9576002810180548390039055613317565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161335c91815260200190565b60405180910390a350505050565b6040805160c0810182525f80825260208201819052918101829052606081018290526080810182905260a08101829052906133a36116d5565b90506040518060c001604052806133b8610aa6565b6001600160a01b03908116825260088401548116602083015260078401548116604083015260028401548116606083015283548116608083015260069093015490921660a090920191909152919050565b6001600160a01b038216613432575f60405163ec442f0560e01b81526004016114e89190614a8e565b610c035f8383613247565b6001600160a01b038216613466575f604051634b637e8f60e11b81526004016114e89190614a8e565b610c03825f83613247565b5f8061347b6116d5565b6002810154604080516338d52e0f60e01b815290519293505f926001600160a01b03909216916338d52e0f916004808201926020929091908290030181865afa1580156134ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ee91906152ef565b90505f6134fa82610ac6565b90505f61350861045d610aa6565b90505f836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613547573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061356b91906151de565b6135799060ff16600a615bd5565b90505f613584610aa6565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156135bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135e391906151de565b6135f19060ff16600a615bd5565b90505f6135fe8286615be0565b83613609868c615be0565b6136139190615be0565b61361d9190615bf7565b905061362881613cd6565b9998505050505050505050565b5f805f6136406116d5565b60018101546040516370a0823160e01b81529192506001600160a01b0316906370a0823190613673903090600401614a8e565b602060405180830381865afa15801561368e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136b29190614fbb565b60028201546040516370a0823160e01b81529194506001600160a01b0316906370a08231906136e5903090600401614a8e565b602060405180830381865afa158015613700573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137249190614fbb565b9150509091565b5f806137356116d5565b60018101549091505f9061376590613755906001600160a01b0316610ac6565b8790670de0b6b3a7640000611864565b90505f6137f0613773610aa6565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137d291906151de565b6137dd90600a6152e1565b6137e861045d610aa6565b849190611864565b90506137fd818787613d56565b979650505050505050565b61381061336a565b60405163eca6c04f60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163eca6c04f9161384c9190879087908790600401615c16565b5f6040518083038186803b158015613862575f80fd5b505af4158015610e47573d5f803e3d5ffd5b5f821561389a575f836138878487615be0565b6138919190615bf7565b91506109f79050565b505f196109f7565b6138aa61336a565b60405163175be66160e31b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd9163badf330891611a989190600401615378565b5f806138ea6116d5565b90506139356040518060e001604052805f81526020015f81526020015f81526020015f8152602001606081526020015f6001600160a01b031681526020015f63ffffffff1681525090565b838060200190518101906139499190615c4b565b6001600160a01b031660a08701526080860152606085015260208401528252505f613972610aa6565b6001840154835160208501519293506001600160a01b03909116915f91829161399f9186918d9190613dd9565b90925090506139cc6001600160a01b03841673ac4c6e212a361c968f1725b4d055b47e63f80b75846140db565b606085015160a08601516080870151604051630be77a3960e31b8152849373ac4c6e212a361c968f1725b4d055b47e63f80b7593635f3bd1c893613a1a938a938a9330938e93600401615cdf565b6020604051808303815f875af1158015613a36573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a5a9190614fbb565b613a6491906151cb565b96508615611ea857611ea86001600160a01b0385168a896141ac565b5f80613a8a6116d5565b60068101546040516307e04ac760e11b81529192506001600160a01b031690630fc0958e90610b039086903390600401615d28565b5f6109f783836127106001613117565b613ad8826141cb565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115613b1c576117068282614225565b610c0361424a565b613b2c614269565b6109378161428e565b613b3d614269565b610c0382826142fb565b5f836001600160a01b031663095ea7b38484604051602401613b6a929190615d3f565b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050509050613ba3848261432b565b6119d957613bff84856001600160a01b031663095ea7b3865f604051602401613bcd929190615d3f565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614370565b6119d98482614370565b6040516001600160a01b0384811660248301528381166044830152606482018390526119d99186918216906323b872dd90608401613bcd565b5f80613c78613c5282600a6152e1565b613c5a61096e565b613c6491906151cb565b613c6f8560016151cb565b8691905f613117565b9150613c8661307285613c97565b90509250929050565b805160208201fd5b5f80613ca16116d5565b600681015460405163ebe6e53d60e01b81529192506001600160a01b03169063ebe6e53d90610b039086903390600401615d28565b5f613cdf61336a565b6040516307d2584160e41b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd91637d25841091613d1791908690600401615ac4565b602060405180830381865af4158015613d32573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108bc9190614fbb565b5f613d5f6116d5565b6006015460405163293772e560e01b81526004810186905260248101859052604481018490526001600160a01b039091169063293772e590606401602060405180830381865afa158015613db5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111ee9190614fbb565b5f805f613de46116d5565b60018101546002820154604080516338d52e0f60e01b815290519394506001600160a01b039283169391909216915f9183916338d52e0f9160048083019260209291908290030181865afa158015613e3e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e6291906152ef565b90505f836001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401613e919190614a8e565b602060405180830381865afa158015613eac573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ed09190614fbb565b90505f8b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401613eff9190614a8e565b602060405180830381865afa158015613f1a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f3e9190614fbb565b90505f613f5a8c3060405180602001604052805f8152506143d3565b60405163d331bef760e01b815260048101829052602481018d9052604481018c90523060648201529091506001600160a01b0385169063d331bef79060840160408051808303815f875af1158015613fb4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613fd891906159d2565b50506040516370a0823160e01b815283906001600160a01b038816906370a0823190614008903090600401614a8e565b602060405180830381865afa158015614023573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140479190614fbb565b614051919061518c565b9850818d6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016140809190614a8e565b602060405180830381865afa15801561409b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140bf9190614fbb565b6140c9919061518c565b97505050505050505094509492505050565b5f81846001600160a01b031663dd62ed3e30866040518363ffffffff1660e01b815260040161410b92919061565b565b602060405180830381865afa158015614126573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061414a9190614fbb565b61415491906151cb565b90506119d98463095ea7b360e01b8584604051602401614175929190615d3f565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526144d9565b6117068363a9059cbb60e01b8484604051602401614175929190615d3f565b806001600160a01b03163b5f036141f75780604051634c9c8ce360e01b81526004016114e89190614a8e565b5f80516020615eb483398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b60606109f78383604051806060016040528060278152602001615ed4602791396145aa565b34156116d35760405163b398979f60e01b815260040160405180910390fd5b614271614614565b6116d357604051631afcd79f60e31b815260040160405180910390fd5b614296614269565b5f61429f611f71565b90505f806142ac8461462d565b91509150816142bc5760126142be565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b614303614269565b5f61430c6115ab565b90506003810161431c8482615d9c565b50600481016119d98382615d9c565b5f805f8060205f8651602088015f8a5af192503d91505f519050828015610a795750811561435c5780600114610a79565b50505050506001600160a01b03163b151590565b5f8060205f8451602086015f885af18061438f576040513d5f823e3d81fd5b50505f513d915081156143a65780600114156143b3565b6001600160a01b0384163b155b156119d95783604051635274afe760e01b81526004016114e89190614a8e565b5f806143dd6116d5565b6002015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561442e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061445291906152ef565b905061445c61336a565b6040516385e9726d60e01b8152735a91f87c9e72240bc1b780be0557a61164fd9ffd916385e9726d9161449a919085908a908a908a90600401615e56565b602060405180830381865af41580156144b5573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118b9190614fbb565b5f61452d826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166147039092919063ffffffff16565b805190915015611706578080602001905181019061454b9190615e98565b6117065760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016114e8565b60605f80856001600160a01b0316856040516145c69190615bbf565b5f60405180830381855af49150503d805f81146145fe576040519150601f19603f3d011682016040523d82523d5f602084013e614603565b606091505b5091509150610a7986838387614711565b5f61461d612327565b54600160401b900460ff16919050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b0387169161467391615bbf565b5f60405180830381855afa9150503d805f81146146ab576040519150601f19603f3d011682016040523d82523d5f602084013e6146b0565b606091505b50915091508180156146c457506020815110155b156146f7575f818060200190518101906146de9190614fbb565b905060ff81116146f5576001969095509350505050565b505b505f9485945092505050565b60606111ee84845f85614789565b6060831561477f5782515f03614778576001600160a01b0385163b6147785760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016114e8565b50816111ee565b6111ee8383614855565b6060824710156147ea5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016114e8565b5f80866001600160a01b031685876040516148059190615bbf565b5f6040518083038185875af1925050503d805f811461483f576040519150601f19603f3d011682016040523d82523d5f602084013e614844565b606091505b50915091506137fd87838387614711565b8151156148655781518083602001fd5b8060405162461bcd60e51b81526004016114e891906148f6565b6040518061014001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6109f760208301846148c8565b5f60208284031215614918575f80fd5b5035919050565b6001600160a01b0381168114610937575f80fd5b803561493e8161491f565b919050565b5f8060408385031215614954575f80fd5b823561495f8161491f565b946020939093013593505050565b803561ffff8116811461493e575f80fd5b5f6020828403121561498e575f80fd5b6109f78261496d565b5f805f606084860312156149a9575f80fd5b83356149b48161491f565b925060208401356149c48161491f565b929592945050506040919091013590565b5f8083601f8401126149e5575f80fd5b5081356001600160401b038111156149fb575f80fd5b602083019150836020828501011115614a12575f80fd5b9250929050565b5f805f805f8060a08789031215614a2e575f80fd5b863595506020870135614a408161491f565b94506040870135614a508161491f565b935060608701356001600160401b03811115614a6a575f80fd5b614a7689828a016149d5565b979a9699509497949695608090950135949350505050565b6001600160a01b0391909116815260200190565b5f60208284031215614ab2575f80fd5b81356109f78161491f565b634e487b7160e01b5f52604160045260245ffd5b6040516101a081016001600160401b0381118282101715614af457614af4614abd565b60405290565b604051608081016001600160401b0381118282101715614af457614af4614abd565b604051606081016001600160401b0381118282101715614af457614af4614abd565b604051601f8201601f191681016001600160401b0381118282101715614b6657614b66614abd565b604052919050565b5f6001600160401b03821115614b8657614b86614abd565b50601f01601f191660200190565b5f82601f830112614ba3575f80fd5b8135602083015f614bbb614bb684614b6e565b614b3e565b9050828152858383011115614bce575f80fd5b828260208301375f92810160200192909252509392505050565b5f8060408385031215614bf9575f80fd5b8235614c048161491f565b915060208301356001600160401b03811115614c1e575f80fd5b614c2a85828601614b94565b9150509250929050565b5f8060208385031215614c45575f80fd5b82356001600160401b03811115614c5a575f80fd5b614c66858286016149d5565b90969095509350505050565b5f8082840360a0811215614c84575f80fd5b83356001600160401b03811115614c99575f80fd5b84016101a08187031215614cab575f80fd5b92506080601f1982011215614cbe575f80fd5b506020830190509250929050565b5f8060408385031215614cdd575f80fd5b823591506020830135614cef8161491f565b809150509250929050565b5f8060208385031215614d0b575f80fd5b82356001600160401b03811115614d20575f80fd5b8301601f81018513614d30575f80fd5b80356001600160401b03811115614d45575f80fd5b8560208260051b8401011115614d59575f80fd5b6020919091019590945092505050565b602080825282518282018190525f918401906040840190835b81811015614da0578351835260209384019390920191600101614d82565b509095945050505050565b5f805f60608486031215614dbd575f80fd5b833592506020840135614dcf8161491f565b91506040840135614ddf8161491f565b809150509250925092565b8015158114610937575f80fd5b5f8060408385031215614e08575f80fd5b8235614e138161491f565b91506020830135614cef81614dea565b5f8060408385031215614e34575f80fd5b8235614e3f8161491f565b91506020830135614cef8161491f565b5f805f805f60808688031215614e63575f80fd5b853594506020860135614e758161491f565b935060408601356001600160401b03811115614e8f575f80fd5b614e9b888289016149d5565b96999598509660600135949350505050565b5f805f805f8060808789031215614ec2575f80fd5b86356001600160401b03811115614ed7575f80fd5b614ee389828a016149d5565b9097509550506020870135614ef78161491f565b935060408701356001600160401b03811115614f11575f80fd5b614f1d89828a01614b94565b93505060608701356001600160401b03811115614f38575f80fd5b614f4489828a016149d5565b979a9699509497509295939492505050565b600181811c90821680614f6a57607f821691505b602082108103614f8857634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b60ff81811683821601908111156108bc576108bc614f8e565b5f60208284031215614fcb575f80fd5b5051919050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f6101a08236031215615004575f80fd5b61500c614ad1565b61501583614933565b815260208301356001600160401b0381111561502f575f80fd5b61503b36828601614b94565b60208301525060408301356001600160401b03811115615059575f80fd5b61506536828601614b94565b60408301525061507760608401614933565b606082015261508860808401614933565b608082015261509960a08401614933565b60a08201526150aa60c0840161496d565b60c08201526150bb60e0840161496d565b60e08201526150cd610100840161496d565b6101008201526150e06101208401614933565b6101208201526150f36101408401614933565b6101408201526151066101608401614933565b6101608201526151196101808401614933565b61018082015292915050565b5f6080828403128015615136575f80fd5b5061513f614afa565b823561514a8161491f565b8152602083013561515a8161491f565b6020820152604083013561516d8161491f565b604082015260608301356151808161491f565b60608201529392505050565b818103818111156108bc576108bc614f8e565b5f600182016151b0576151b0614f8e565b5060010190565b634e487b7160e01b5f52603260045260245ffd5b808201808211156108bc576108bc614f8e565b5f602082840312156151ee575f80fd5b815160ff811681146109f7575f80fd5b6001815b60018411156152395780850481111561521d5761521d614f8e565b600184161561522b57908102905b60019390931c928002615202565b935093915050565b5f8261524f575060016108bc565b8161525b57505f6108bc565b8160018114615271576002811461527b57615297565b60019150506108bc565b60ff84111561528c5761528c614f8e565b50506001821b6108bc565b5060208310610133831016604e8410600b84101617156152ba575081810a6108bc565b6152c65f1984846151fe565b805f19048211156152d9576152d9614f8e565b029392505050565b5f6109f760ff841683615241565b5f602082840312156152ff575f80fd5b81516109f78161491f565b61ffff91909116815260200190565b634e487b7160e01b5f52601260045260245ffd5b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015182169084015260808083015182169084015260a09182015116910152565b60c081016108bc828461532d565b5f60608284031215615396575f80fd5b61539e614b1c565b82358152905060208201356153b28161491f565b602082015260408201356153c58161491f565b604082015292915050565b5f6001600160401b038211156153e8576153e8614abd565b5060051b60200190565b5f60208284031215615402575f80fd5b81356001600160401b03811115615417575f80fd5b820160c08185031215615428575f80fd5b615430614afa565b813581526020808301359082015261544b8560408401615386565b604082015260a08201356001600160401b03811115615468575f80fd5b91909101906080828603121561547c575f80fd5b615484614afa565b823581526020808401359082015260408301356154a08161491f565b604082015260608301356001600160401b038111156154bd575f80fd5b80840193505085601f8401126154d1575f80fd5b82356154df614bb6826153d0565b8082825260208201915060208360051b870101925088831115615500575f80fd5b602086015b838110156155405780356001600160401b03811115615522575f80fd5b6155318b6020838b0101614b94565b84525060209283019201615505565b5080606085015250505080606083015250809250505092915050565b805182526020808201516001600160a01b039081169184019190915260409182015116910152565b6001600160a01b03831681526040602080830182905283518284015283015160608301528201515f906155ba608084018261555c565b5060608381015160c060e0850152805161010085015260208082015161012086015260408201516001600160a01b03166101408601529101516080610160850152805161018085018190529101906101a0600582901b8501810191908501905f5b8181101561564e5761019f198785030183526156388486516148c8565b602095860195909450929092019160010161561b565b5091979650505050505050565b6001600160a01b0392831681529116602082015260400190565b8181035f83128015838313168383128216171561232057612320614f8e565b918252602082015260400190565b634e487b7160e01b5f52602160045260245ffd5b8381526020810183905260608101600283106156e057634e487b7160e01b5f52602160045260245ffd5b826040830152949350505050565b5f606082840312156156fe575f80fd5b615706614b1c565b82518152602083015190915061571b8161491f565b602082015260408201516153c58161491f565b5f82601f83011261573d575f80fd5b815161574b614bb682614b6e565b81815284602083860101111561575f575f80fd5b8160208501602083015e5f918101602001919091529392505050565b5f60c0828403121561578b575f80fd5b615793614afa565b825181526020808401519082015290506157b083604084016156ee565b604082015260a08201516001600160401b038111156157cd575f80fd5b8201608081850312156157de575f80fd5b6157e6614afa565b815181526020808301519082015260408201516158028161491f565b604082015260608201516001600160401b0381111561581f575f80fd5b80830192505084601f830112615833575f80fd5b8151615841614bb6826153d0565b8082825260208201915060208360051b860101925087831115615862575f80fd5b602085015b838110156158a25780516001600160401b03811115615884575f80fd5b6158938a6020838a010161572e565b84525060209283019201615867565b50806060850152505050806060840152505092915050565b5f602082840312156158ca575f80fd5b81516001600160401b038111156158df575f80fd5b6111ee8482850161577b565b5f602082840312156158fb575f80fd5b81516001600160401b03811115615910575f80fd5b820160c08185031215615921575f80fd5b615929614afa565b815181526020808301519082015261594485604084016156ee565b604082015260a08201516001600160401b03811115615961575f80fd5b919091019060608286031215615975575f80fd5b61597d614b1c565b82516001600160401b03811115615992575f80fd5b61599e8782860161572e565b82525060208381015190820152604090920151916159bb8361491f565b604081019290925260608101919091529392505050565b5f80604083850312156159e3575f80fd5b505080516020909101519092909150565b5f60208284031215615a04575f80fd5b81356001600160401b03811115615a19575f80fd5b820160c08185031215615a2a575f80fd5b615a32614afa565b8135815260208083013590820152615a4d8560408401615386565b604082015260a08201356001600160401b03811115615a6a575f80fd5b919091019060608286031215615a7e575f80fd5b615a86614b1c565b82356001600160401b03811115615a9b575f80fd5b615aa787828601614b94565b82525060208381013590820152604090920135916159bb8361491f565b60e08101615ad2828561532d565b8260c08301529392505050565b6001600160a01b03831681526040602080830182905283518284015283015160608301528201515f90615b15608084018261555c565b50606083015160c060e084015280516060610100850152615b3a6101608501826148c8565b60208301516101208601526040909201516001600160a01b031661014090940193909352949350505050565b6001600160a01b039290921682521515602082015260400190565b615b8b818561532d565b60e060c08201528160e082015281836101008301375f81830161010090810191909152601f909201601f1916010192915050565b5f82518060208501845e5f920191825250919050565b5f6109f78383615241565b80820281158282048414176108bc576108bc614f8e565b5f82615c1157634e487b7160e01b5f52601260045260245ffd5b500490565b615c20818661532d565b61012060c08201525f615c376101208301866148c8565b60e083019490945250610100015292915050565b5f805f805f8060c08789031215615c60575f80fd5b86516001600160401b03811115615c75575f80fd5b615c8189828a0161577b565b602089015160408a015160608b015160808c0151939a509198509650945090506001600160401b03811115615cb4575f80fd5b615cc089828a0161572e565b92505060a0870151615cd18161491f565b809150509295509295509295565b6001600160a01b038881168252602082018890528681166040830152858116606083015260808201859052831660a082015260e060c082018190525f90613628908301846148c8565b9182526001600160a01b0316602082015260400190565b6001600160a01b03929092168252602082015260400190565b601f82111561170657805f5260205f20601f840160051c81016020851015615d7d5750805b601f840160051c820191505b81811015613240575f8155600101615d89565b81516001600160401b03811115615db557615db5614abd565b615dc981615dc38454614f56565b84615d58565b6020601f821160018114615dfb575f8315615de45750848201515b5f19600385901b1c1916600184901b178455613240565b5f84815260208120601f198516915b82811015615e2a5787850151825560209485019460019092019101615e0a565b5084821015615e4757868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b615e60818761532d565b6001600160a01b0385811660c083015260e08201859052831661010082015261014061012082018190525f906137fd908301846148c8565b5f60208284031215615ea8575f80fd5b81516109f781614dea56fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220a9af32d33343ced0571272fb4c29de1a1c00946f9c5c00af67f85f2456cc94a064736f6c634300081a0033

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.