creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/modules/adaptors/Staking/LidoStakingAdaptor.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { ERC20, SafeTransferLib, Cellar, PriceRouter, Registry, Math } from \"src/modules/adaptors/BaseAdaptor.sol\";\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { StakingAdaptor, IWETH9 } from \"./StakingAdaptor.sol\";\nimport { IUNSTETH, IWSTETH, ISTETH } from \"src/interfaces/external/IStaking.sol\";\n\n/**\n * @title Lido Staking Adaptor\n * @notice Allows Cellars to stake with Lido.\n * @dev Lido supports minting, burning, and wrapping.\n * @author crispymangoes\n */\ncontract LidoStakingAdaptor is StakingAdaptor {\n    using SafeTransferLib for ERC20;\n    using Math for uint256;\n    using Address for address;\n\n    /**\n     * @notice stETH contract deposits are made to.\n     */\n    ISTETH public immutable stETH;\n\n    /**\n     * @notice Wrapper contract for stETH.\n     */\n    IWSTETH public immutable wstETH;\n\n    /**\n     * @notice Contract to handle stETH withdraws.\n     */\n    IUNSTETH public immutable unstETH;\n\n    /**\n     * @notice On deployment, save the `getLastCheckpointIndex` so it can be used\n     *         as the starting index when calling `findCheckPointHints`\n     */\n    uint256 public immutable startingCheckPointIndex;\n\n    constructor(\n        address _wrappedNative,\n        uint8 _maxRequests,\n        address _stETH,\n        address _wstETH,\n        address _unstETH\n    ) StakingAdaptor(_wrappedNative, _maxRequests) {\n        stETH = ISTETH(_stETH);\n        wstETH = IWSTETH(_wstETH);\n        unstETH = IUNSTETH(_unstETH);\n        startingCheckPointIndex = unstETH.getLastCheckpointIndex();\n    }\n\n    //============================================ Global Functions ===========================================\n    /**\n     * @dev Identifier unique to this adaptor for a shared registry.\n     * Normally the identifier would just be the address of this contract, but this\n     * Identifier is needed during Cellar Delegate Call Operations, so getting the address\n     * of the adaptor is more difficult.\n     */\n    function identifier() public pure virtual override returns (bytes32) {\n        return keccak256(abi.encode(\"Lido Staking Adaptor V 0.0\"));\n    }\n\n    //============================================ Override Functions ===========================================\n\n    /**\n     * @notice Stakes into Lido using native asset.\n     */\n    function _mint(uint256 amount, bytes calldata) internal override returns (uint256 amountOut) {\n        ERC20 derivative = ERC20(address(stETH));\n        amountOut = derivative.balanceOf(address(this));\n        stETH.submit{ value: amount }(address(0));\n        amountOut = derivative.balanceOf(address(this)) - amountOut;\n    }\n\n    /**\n     * @notice Wrap stETH.\n     */\n    function _wrap(uint256 amount, bytes calldata) internal override returns (uint256 amountOut) {\n        ERC20 derivative = ERC20(address(stETH));\n        amount = _maxAvailable(derivative, amount);\n        derivative.safeApprove(address(wstETH), amount);\n        amountOut = wstETH.wrap(amount);\n        _revokeExternalApproval(derivative, address(wstETH));\n    }\n\n    /**\n     * @notice Unwrap wstETH.\n     */\n    function _unwrap(uint256 amount, bytes calldata) internal override returns (uint256 amountOut) {\n        amount = _maxAvailable(ERC20(address(wstETH)), amount);\n        amountOut = wstETH.unwrap(amount);\n    }\n\n    /**\n     * @notice Returns balance in pending and finalized withdraw requests.\n     * @dev This function assumes that the primitive and derivative asset are 1:1.\n     */\n    function _balanceOf(address account) internal view override returns (uint256 amount) {\n        uint256[] memory requests = StakingAdaptor(adaptorAddress).getRequestIds(account);\n        IUNSTETH.WithdrawalRequestStatus[] memory statuses = unstETH.getWithdrawalStatus(requests);\n        uint256 lastCheckpointIndex = type(uint256).max;\n        for (uint256 i; i < statuses.length; ++i) {\n            uint256 requestId = requests[i];\n            // If request was already claimed continue.\n            if (statuses[i].isClaimed) continue;\n            if (statuses[i].isFinalized) {\n                // Request has been finalized, and we need to call `getClaimableEther` to determine\n                // the amount of ETH request is worth.\n                // Save last checkpoint index if it has not been set.\n                if (lastCheckpointIndex == type(uint256).max) lastCheckpointIndex = unstETH.getLastCheckpointIndex();\n                // Start by determining what hint to use.\n                uint256[] memory rIds = new uint256[](1);\n                rIds[0] = requestId;\n                uint256[] memory hints = unstETH.findCheckpointHints(\n                    rIds,\n                    startingCheckPointIndex,\n                    lastCheckpointIndex\n                );\n                // Now call getClaimableEther to determine requests value.\n                uint256[] memory finalizedAmounts = unstETH.getClaimableEther(rIds, hints);\n                amount += finalizedAmounts[0];\n            } else {\n                // Request has not been finalized, so report amount as `amountOfStETH`.\n                amount += statuses[i].amountOfStETH;\n            }\n        }\n    }\n\n    /**\n     * @notice Request to withdraw.\n     */\n    function _requestBurn(uint256 amount, bytes calldata) internal override returns (uint256 id) {\n        uint256[] memory amounts = new uint256[](1);\n        amounts[0] = amount;\n        ERC20 derivative = ERC20(address(stETH));\n        amount = _maxAvailable(derivative, amount);\n        derivative.safeApprove(address(unstETH), amount);\n        uint256[] memory ids = unstETH.requestWithdrawals(amounts, address(this));\n        _revokeExternalApproval(derivative, address(unstETH));\n        id = ids[0];\n    }\n\n    /**\n     * @notice Complete a withdraw.\n     * @param wildcard the uint256 hint for the given id\n     *        Optionally leave this blank if not known, but call is more gas intensive.\n     */\n    function _completeBurn(uint256 id, bytes calldata wildcard) internal override {\n        uint256 hint;\n        if (wildcard.length > 0) hint = abi.decode(wildcard, (uint256));\n\n        if (hint == 0) unstETH.claimWithdrawal(id);\n        else {\n            uint256[] memory ids = new uint256[](1);\n            ids[0] = id;\n            uint256[] memory hints = new uint256[](1);\n            hints[0] = hint;\n            unstETH.claimWithdrawals(ids, hints);\n        }\n    }\n\n    /**\n     * @notice Remove a request from requestIds if it is already claimed.\n     */\n    function removeClaimedRequest(uint256 id, bytes calldata) external override {\n        uint256[] memory requests = new uint256[](1);\n        requests[0] = id;\n        IUNSTETH.WithdrawalRequestStatus[] memory statuses = unstETH.getWithdrawalStatus(requests);\n        if (statuses[0].isClaimed) StakingAdaptor(adaptorAddress).removeRequestId(id);\n        else revert StakingAdaptor__RequestNotClaimed(id);\n    }\n}\n"
      },
      "src/modules/adaptors/BaseAdaptor.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { Math } from \"src/utils/Math.sol\";\nimport { SafeTransferLib } from \"@solmate/utils/SafeTransferLib.sol\";\nimport { ERC20 } from \"@solmate/tokens/ERC20.sol\";\nimport { Registry } from \"src/Registry.sol\";\nimport { Cellar } from \"src/base/Cellar.sol\";\nimport { PriceRouter } from \"src/modules/price-router/PriceRouter.sol\";\n\n/**\n * @title Base Adaptor\n * @notice Base contract all adaptors must inherit from.\n * @dev Allows Cellars to interact with arbritrary DeFi assets and protocols.\n * @author crispymangoes\n */\nabstract contract BaseAdaptor {\n    using SafeTransferLib for ERC20;\n    using Math for uint256;\n\n    /**\n     * @notice Attempted to specify an external receiver during a Cellar `callOnAdaptor` call.\n     */\n    error BaseAdaptor__ExternalReceiverBlocked();\n\n    /**\n     * @notice Attempted to deposit to a position where user deposits were not allowed.\n     */\n    error BaseAdaptor__UserDepositsNotAllowed();\n\n    /**\n     * @notice Attempted to withdraw from a position where user withdraws were not allowed.\n     */\n    error BaseAdaptor__UserWithdrawsNotAllowed();\n\n    /**\n     * @notice Attempted swap has bad slippage.\n     */\n    error BaseAdaptor__Slippage();\n\n    /**\n     * @notice Attempted swap used unsupported output asset.\n     */\n    error BaseAdaptor__PricingNotSupported(address asset);\n\n    /**\n     * @notice Attempted to set a constructor minimum health factor to a value\n     *         below `MINIMUM_CONSTRUCTOR_HEALTH_FACTOR()`.\n     */\n    error BaseAdaptor__ConstructorHealthFactorTooLow();\n\n    //============================================ Global Functions ===========================================\n    /**\n     * @dev Identifier unique to this adaptor for a shared registry.\n     * Normally the identifier would just be the address of this contract, but this\n     * Identifier is needed during Cellar Delegate Call Operations, so getting the address\n     * of the adaptor is more difficult.\n     */\n    function identifier() public pure virtual returns (bytes32) {\n        return keccak256(abi.encode(\"Base Adaptor V 0.0\"));\n    }\n\n    function SWAP_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {\n        return 1;\n    }\n\n    function PRICE_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {\n        return 2;\n    }\n\n    /**\n     * @notice Max possible slippage when making a swap router swap.\n     */\n    function slippage() public pure returns (uint32) {\n        return 0.9e4;\n    }\n\n    /**\n     * @notice The default minimum constructor health factor.\n     * @dev Adaptors can choose to override this if they need a different value.\n     */\n    function MINIMUM_CONSTRUCTOR_HEALTH_FACTOR() internal pure virtual returns (uint256) {\n        return 1.01e18;\n    }\n\n    //============================================ Implement Base Functions ===========================================\n    //==================== Base Function Specification ====================\n    // Base functions are functions designed to help the Cellar interact with\n    // an adaptor position, strategists are not intended to use these functions.\n    // Base functions MUST be implemented in adaptor contracts, even if that is just\n    // adding a revert statement to make them uncallable by normal user operations.\n    //\n    // All view Base functions will be called used normal staticcall.\n    // All mutative Base functions will be called using delegatecall.\n    //=====================================================================\n    /**\n     * @notice Function Cellars call to deposit users funds into holding position.\n     * @param assets the amount of assets to deposit\n     * @param adaptorData data needed to deposit into a position\n     * @param configurationData data settable when strategists add positions to their Cellar\n     *                          Allows strategist to control how the adaptor interacts with the position\n     */\n    function deposit(uint256 assets, bytes memory adaptorData, bytes memory configurationData) public virtual;\n\n    /**\n     * @notice Function Cellars call to withdraw funds from positions to send to users.\n     * @param receiver the address that should receive withdrawn funds\n     * @param adaptorData data needed to withdraw from a position\n     * @param configurationData data settable when strategists add positions to their Cellar\n     *                          Allows strategist to control how the adaptor interacts with the position\n     */\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        bytes memory adaptorData,\n        bytes memory configurationData\n    ) public virtual;\n\n    /**\n     * @notice Function Cellars use to determine `assetOf` balance of an adaptor position.\n     * @param adaptorData data needed to interact with the position\n     * @return balance of the position in terms of `assetOf`\n     */\n    function balanceOf(bytes memory adaptorData) public view virtual returns (uint256);\n\n    /**\n     * @notice Functions Cellars use to determine the withdrawable balance from an adaptor position.\n     * @dev Debt positions MUST return 0 for their `withdrawableFrom`\n     * @notice accepts adaptorData and configurationData\n     * @return withdrawable balance of the position in terms of `assetOf`\n     */\n    function withdrawableFrom(bytes memory, bytes memory) public view virtual returns (uint256);\n\n    /**\n     * @notice Function Cellars use to determine the underlying ERC20 asset of a position.\n     * @param adaptorData data needed to withdraw from a position\n     * @return the underlying ERC20 asset of a position\n     */\n    function assetOf(bytes memory adaptorData) public view virtual returns (ERC20);\n\n    /**\n     * @notice When positions are added to the Registry, this function can be used in order to figure out\n     *         what assets this adaptor needs to price, and confirm pricing is properly setup.\n     */\n    function assetsUsed(bytes memory adaptorData) public view virtual returns (ERC20[] memory assets) {\n        assets = new ERC20[](1);\n        assets[0] = assetOf(adaptorData);\n    }\n\n    /**\n     * @notice Functions Registry/Cellars use to determine if this adaptor reports debt values.\n     * @dev returns true if this adaptor reports debt values.\n     */\n    function isDebt() public view virtual returns (bool);\n\n    //============================================ Strategist Functions ===========================================\n    //==================== Strategist Function Specification ====================\n    // Strategist functions are only callable by strategists through the Cellars\n    // `callOnAdaptor` function. A cellar will never call any of these functions,\n    // when a normal user interacts with a cellar(depositing/withdrawing)\n    //\n    // All strategist functions will be called using delegatecall.\n    // Strategist functions are intentionally \"blind\" to what positions the cellar\n    // is currently holding. This allows strategists to enter temporary positions\n    // while rebalancing.\n    // To mitigate strategist from abusing this and moving funds in untracked\n    // positions, the cellar will enforce a Total Value Locked check that\n    // insures TVL has not deviated too much from `callOnAdaptor`.\n    //===========================================================================\n\n    //============================================ Helper Functions ===========================================\n    /**\n     * @notice Helper function that allows adaptor calls to use the max available of an ERC20 asset\n     * by passing in type(uint256).max\n     * @param token the ERC20 asset to work with\n     * @param amount when `type(uint256).max` is used, this function returns `token`s `balanceOf`\n     * otherwise this function returns amount.\n     */\n    function _maxAvailable(ERC20 token, uint256 amount) internal view virtual returns (uint256) {\n        if (amount == type(uint256).max) return token.balanceOf(address(this));\n        else return amount;\n    }\n\n    /**\n     * @notice Helper function that checks if `spender` has any more approval for `asset`, and if so revokes it.\n     */\n    function _revokeExternalApproval(ERC20 asset, address spender) internal {\n        if (asset.allowance(address(this), spender) > 0) asset.safeApprove(spender, 0);\n    }\n\n    /**\n     * @notice Helper function that validates external receivers are allowed.\n     */\n    function _externalReceiverCheck(address receiver) internal view {\n        if (receiver != address(this) && Cellar(address(this)).blockExternalReceiver())\n            revert BaseAdaptor__ExternalReceiverBlocked();\n    }\n\n    /**\n     * @notice Helper function that validates external receivers are allowed.\n     */\n    function _verifyConstructorMinimumHealthFactor(uint256 minimumHealthFactor) internal pure {\n        if (minimumHealthFactor < MINIMUM_CONSTRUCTOR_HEALTH_FACTOR())\n            revert BaseAdaptor__ConstructorHealthFactorTooLow();\n    }\n\n    /**\n     * @notice Allows strategists to zero out an approval for a given `asset`.\n     * @param asset the ERC20 asset to revoke `spender`s approval for\n     * @param spender the address to revoke approval for\n     */\n    function revokeApproval(ERC20 asset, address spender) public {\n        asset.safeApprove(spender, 0);\n    }\n\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "src/modules/adaptors/Staking/StakingAdaptor.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { ERC20, SafeTransferLib, Cellar, PriceRouter, Registry, Math } from \"src/modules/adaptors/BaseAdaptor.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\nimport { IWETH9 } from \"src/interfaces/external/IWETH9.sol\";\nimport { BaseAdaptor, ERC20, SafeTransferLib } from \"src/modules/adaptors/BaseAdaptor.sol\";\n\n/**\n * @title Staking Adaptor\n * @notice Serves as a universal template for a variety of staking adaptors.\n * @notice A staking adaptor position will only check for value that is locked in unstaking\n *         requests, other value must be accounted for using other adaptors.\n * @dev Allows inheriting adaptors to implement staking, unstaking, wrapping, unwrapping.\n * @author crispymangoes\n */\ncontract StakingAdaptor is BaseAdaptor {\n    using SafeTransferLib for ERC20;\n    using Math for uint256;\n\n    //==================== Adaptor Data Specification ====================\n    // adaptorData = abi.encode(ERC20 primitive)\n    // Where:\n    // primitive is the primitive asset that is returned from unstaking/burning a derivative.\n    //================= Configuration Data Specification =================\n    // NOT USED\n    //====================================================================\n\n    // ========================================= GLOBAL STATE =========================================\n\n    /**\n     * @notice Stores burn/withdraw request ids for callers.\n     */\n    mapping(address => uint256[]) public requestIds;\n\n    //========================================= ERRORS =========================================\n\n    error StakingAdaptor__RequestNotFound(uint256 id);\n    error StakingAdaptor__DuplicateRequest(uint256 id);\n    error StakingAdaptor__MaximumRequestsExceeded();\n    error StakingAdaptor__NotSupported();\n    error StakingAdaptor__ZeroAmount();\n    error StakingAdaptor__MinimumAmountNotMet(uint256 actual, uint256 minimum);\n    error StakingAdaptor__RequestNotClaimed(uint256 id);\n\n    /**\n     * @notice Attempted to read `locked` from unstructured storage, but found uninitialized value.\n     * @dev Most likely an external contract made a delegate call to this contract.\n     */\n    error StakingAdaptor___StorageSlotNotInitialized();\n\n    /**\n     * @notice Attempted to reenter into this contract.\n     */\n    error StakingAdaptor___Reentrancy();\n\n    //========================================= IMMUTABLES ==========================================\n\n    /**\n     * @notice The wrapper contract for the primitive/native asset.\n     */\n    IWETH9 public immutable wrappedPrimitive;\n\n    /**\n     * @notice The address of this adaptor.\n     */\n    address internal immutable adaptorAddress;\n\n    /**\n     * @notice The maximum requests a caller can store in `requestIds`.\n     * @dev This cap is here because `requestIds` must be iterated through in `_balanceOf`\n     *      and it is unsafe to have an unbounded for loop.\n     */\n    uint8 internal immutable maximumRequests;\n\n    /**\n     * @notice The slot to store value needed to check for re-entrancy.\n     */\n    bytes32 public immutable lockedStoragePosition;\n\n    constructor(address _wrappedPrimitive, uint8 _maximumRequests) {\n        wrappedPrimitive = IWETH9(_wrappedPrimitive);\n        maximumRequests = _maximumRequests;\n        adaptorAddress = address(this);\n\n        lockedStoragePosition =\n            keccak256(abi.encode(uint256(keccak256(\"staking.adaptor.storage\")) - 1)) &\n            ~bytes32(uint256(0xff));\n\n        // Initialize locked storage to 1;\n        setLockedStorage(1);\n    }\n\n    //========================================= Unstructured Reentrancy =========================================\n\n    /**\n     * @notice Helper function to read `locked` from unstructured storage.\n     */\n    function readLockedStorage() internal view returns (uint256 locked) {\n        bytes32 position = lockedStoragePosition;\n        assembly {\n            locked := sload(position)\n        }\n    }\n\n    /**\n     * @notice Helper function to set `locked` to unstructured storage.\n     */\n    function setLockedStorage(uint256 state) internal {\n        bytes32 position = lockedStoragePosition;\n        assembly {\n            sstore(position, state)\n        }\n    }\n\n    /**\n     * @notice nonReentrant modifier that uses unstructured storage.\n     */\n    modifier nonReentrant() virtual {\n        uint256 locked = readLockedStorage();\n        if (locked == 0) revert StakingAdaptor___StorageSlotNotInitialized();\n        if (locked != 1) revert StakingAdaptor___Reentrancy();\n\n        setLockedStorage(2);\n\n        _;\n\n        setLockedStorage(1);\n    }\n\n    //========================================= Request Id Storage =========================================\n\n    /**\n     * @notice Add a request id to callers `requestIds` array.\n     * @dev Reverts if maximum requests are stored, or if request id is duplicated.\n     */\n    function addRequestId(uint256 id) external nonReentrant {\n        uint256[] storage ids = requestIds[msg.sender];\n        uint256 idsLength = ids.length;\n        if (idsLength >= maximumRequests) revert StakingAdaptor__MaximumRequestsExceeded();\n        for (uint256 i = 0; i < idsLength; ++i) {\n            if (ids[i] == id) revert StakingAdaptor__DuplicateRequest(id);\n        }\n        ids.push(id);\n    }\n\n    /**\n     * @notice Remove a request id from callers `requestIds` array.\n     * @dev Reverts if request id is not found.\n     */\n    function removeRequestId(uint256 id) external nonReentrant {\n        uint256[] storage ids = requestIds[msg.sender];\n        uint256 idsLength = ids.length;\n        for (uint256 i = 0; i < idsLength; ++i) {\n            if (ids[i] == id) {\n                // Copy last element to current position.\n                ids[i] = ids[idsLength - 1];\n                ids.pop();\n                return;\n            }\n        }\n        revert StakingAdaptor__RequestNotFound(id);\n    }\n\n    /**\n     * @notice Get a callers `requestIds` array.\n     */\n    function getRequestIds(address user) external view returns (uint256[] memory) {\n        return requestIds[user];\n    }\n\n    //============================================ Implement Base Functions ===========================================\n\n    /**\n     * @notice This adaptor does not support user deposits.\n     */\n    function deposit(uint256, bytes memory, bytes memory) public pure override {\n        revert BaseAdaptor__UserDepositsNotAllowed();\n    }\n\n    /**\n     * @notice This adaptor does not support user withdraws.\n     */\n    function withdraw(uint256, address, bytes memory, bytes memory) public pure override {\n        revert BaseAdaptor__UserWithdrawsNotAllowed();\n    }\n\n    /**\n     * @notice This adaptor is not user withdrawable.\n     */\n    function withdrawableFrom(bytes memory, bytes memory) public pure override returns (uint256) {\n        return 0;\n    }\n\n    /**\n     * @notice Returns the balance of `primitive` that is unstaking.\n     */\n    function balanceOf(bytes memory) public view override returns (uint256) {\n        return _balanceOf(msg.sender);\n    }\n\n    /**\n     * @notice Returns `primitive`\n     */\n    function assetOf(bytes memory adaptorData) public pure override returns (ERC20) {\n        ERC20 primitive = abi.decode(adaptorData, (ERC20));\n        return primitive;\n    }\n\n    /**\n     * @notice This adaptor returns collateral, and not debt.\n     */\n    function isDebt() public pure override returns (bool) {\n        return false;\n    }\n\n    //============================================ Strategist Functions ===========================================\n\n    /**\n     * @notice Allows a strategist to `mint` a derivative asset using the chains native asset.\n     * @dev Will automatically unwrap the native asset.\n     * @param amount the amount of native asset to use for minting\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function mint(uint256 amount, uint256 minAmountOut, bytes calldata wildcard) external virtual {\n        if (amount == 0) revert StakingAdaptor__ZeroAmount();\n\n        amount = _maxAvailable(ERC20(address(wrappedPrimitive)), amount);\n        wrappedPrimitive.withdraw(amount);\n\n        uint256 amountMinted = _mint(amount, wildcard);\n        if (amountMinted < minAmountOut) revert StakingAdaptor__MinimumAmountNotMet(amountMinted, minAmountOut);\n    }\n\n    /**\n     * @notice Allows a strategist to request to burn/withdraw a derivative for a chains native asset.\n     * @param amount the amount of derivative to burn/withdraw\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function requestBurn(uint256 amount, bytes calldata wildcard) external virtual {\n        if (amount == 0) revert StakingAdaptor__ZeroAmount();\n\n        uint256 id = _requestBurn(amount, wildcard);\n\n        // Add request id to staking adaptor.\n        StakingAdaptor(adaptorAddress).addRequestId(id);\n    }\n\n    /**\n     * @notice Allows a strategist to complete a burn/withdraw of a derivative asset for a native asset.\n     * @dev Will automatically wrap the native asset received from burn/withdraw.\n     * @param id the request id\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function completeBurn(uint256 id, uint256 minAmountOut, bytes calldata wildcard) external virtual {\n        uint256 primitiveDelta = address(this).balance;\n        _completeBurn(id, wildcard);\n        primitiveDelta = address(this).balance - primitiveDelta;\n        if (primitiveDelta < minAmountOut) revert StakingAdaptor__MinimumAmountNotMet(primitiveDelta, minAmountOut);\n        wrappedPrimitive.deposit{ value: primitiveDelta }();\n        StakingAdaptor(adaptorAddress).removeRequestId(id);\n    }\n\n    /**\n     * @notice Allows a strategist to cancel an active burn/withdraw request.\n     * @param id the request id\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function cancelBurn(uint256 id, bytes calldata wildcard) external virtual {\n        _cancelBurn(id, wildcard);\n        StakingAdaptor(adaptorAddress).removeRequestId(id);\n    }\n\n    /**\n     * @notice Allows a strategist to wrap a derivative asset.\n     * @param amount the amount of derivative to wrap\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function wrap(uint256 amount, uint256 minAmountOut, bytes calldata wildcard) external virtual {\n        if (amount == 0) revert StakingAdaptor__ZeroAmount();\n\n        uint256 amountOut = _wrap(amount, wildcard);\n        if (amountOut < minAmountOut) revert StakingAdaptor__MinimumAmountNotMet(amountOut, minAmountOut);\n    }\n\n    /**\n     * @notice Allows a strategist to unwrap a wrapped derivative asset.\n     * @param amount the amount of wrapped derivative to unwrap\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function unwrap(uint256 amount, uint256 minAmountOut, bytes calldata wildcard) external virtual {\n        if (amount == 0) revert StakingAdaptor__ZeroAmount();\n\n        uint256 amountOut = _unwrap(amount, wildcard);\n        if (amountOut < minAmountOut) revert StakingAdaptor__MinimumAmountNotMet(amountOut, minAmountOut);\n    }\n\n    /**\n     * @notice Allows a strategist to mint a derivative asset using an ERC20.\n     * @param depositAsset the ERC20 asset to mint with\n     * @param amount the amount of `depositAsset` to mint with\n     * @param minAmountOut the minimum amount of derivative out\n     * @param wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function mintERC20(\n        ERC20 depositAsset,\n        uint256 amount,\n        uint256 minAmountOut,\n        bytes calldata wildcard\n    ) external virtual {\n        if (amount == 0) revert StakingAdaptor__ZeroAmount();\n\n        uint256 amountOut = _mintERC20(depositAsset, amount, minAmountOut, wildcard);\n        if (amountOut < minAmountOut) revert StakingAdaptor__MinimumAmountNotMet(amountOut, minAmountOut);\n    }\n\n    /**\n     * @notice Allows strategist to remove a request from `requestIds` if it has already been claimed.\n     * @dev id the request id to remove\n     * @dev wildcard arbitrary abi encoded data that can be used by inheriting adaptors\n     */\n    function removeClaimedRequest(uint256, bytes calldata) external virtual {\n        if (true) revert StakingAdaptor__NotSupported();\n    }\n\n    //============================================ Interface Helper Functions ===========================================\n    //============================== Interface Details =========================================\n    // Staking protocols have very similar patterns when staking/unstaking, and wrapping/unwrapping.\n    // This pattern has been generalized to the below interface helper functions.\n    // Note inheriting adaptors do NOT need to implement all helper functions, rather they\n    // should only implement the functions that they actually logically support.\n    // ie A lot of protocols do not support unstaking, so the burn related functions should not be\n    // implemented. Some protocols do not have a wrapped asset, so the wrapping functions\n    // should not be implemented.\n\n    // Note the below base implementations use this weird `if (true) revert` pattern so that\n    // if a helper interface is not implemented, calls to the associated strategist function will\n    // revert.\n    // Also this was the only way I could get it so that the compiler would not complain about\n    // unreachable code :)\n    //==========================================================================================\n\n    /**\n     * @notice An inheriting adaptor should implement `_balanceOf` if they support unstaking.\n     * @dev Should report both balances in both pending and finalized unstaking requests.\n     * @dev Address input is the address to get balances for.\n     */\n    function _balanceOf(address) internal view virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_mint` if they support staking with native.\n     * @dev Uint256 is the amount of native to mint with.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _mint(uint256, bytes calldata) internal virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_wrap` if they support wrapping a derivative.\n     * @dev Uint256 is the amount of derivative to wrap.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _wrap(uint256, bytes calldata) internal virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_unwrap` if they support unwrapping a derivative.\n     * @dev Uint256 is the amount of wrapped derivative to unwrap.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _unwrap(uint256, bytes calldata) internal virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_requestBurn` if they support unstaking.\n     * @dev Uint256 is the amount of derivative to unstake.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     * @dev Returns the request id.\n     */\n    function _requestBurn(uint256, bytes calldata) internal virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_completeBurn` if they support unstaking.\n     * @dev Uint256 is the request id.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _completeBurn(uint256, bytes calldata) internal virtual {\n        if (true) revert StakingAdaptor__NotSupported();\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_cancelBurn` if they support canceling unstaking.\n     * @dev Uint256 is the request id.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _cancelBurn(uint256, bytes calldata) internal virtual {\n        if (true) revert StakingAdaptor__NotSupported();\n    }\n\n    /**\n     * @notice An inheriting adaptor should implement `_mintERC20` if they support minting using ERC20 assets.\n     * @dev It is a good idea for inheriting adaptors to implement a value in vs value out check.\n     * @dev First arg is the ERC20 to mint with.\n     * @dev Second arg is the amount of ERC20.\n     * @dev Third arg is the minimum amount of derivative out from mint.\n     * @dev bytes arbitrary abi encoded data that can be used by inheriting adaptors.\n     */\n    function _mintERC20(ERC20, uint256, uint256, bytes calldata) internal virtual returns (uint256) {\n        if (true) revert StakingAdaptor__NotSupported();\n        return 0;\n    }\n}\n"
      },
      "src/interfaces/external/IStaking.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\n// Swell\ninterface ISWETH {\n    function deposit() external payable;\n}\n\n// EtherFi\ninterface ILiquidityPool {\n    function deposit() external payable returns (uint256);\n\n    function requestWithdraw(address recipient, uint256 amount) external returns (uint256);\n\n    function amountForShare(uint256 shares) external view returns (uint256);\n\n    function etherFiAdminContract() external view returns (address);\n\n    function addEthAmountLockedForWithdrawal(uint128 _amount) external;\n}\n\ninterface IWithdrawRequestNft {\n    struct WithdrawRequest {\n        uint96 amountOfEEth;\n        uint96 shareOfEEth;\n        bool isValid;\n        uint32 feeGwei;\n    }\n\n    function claimWithdraw(uint256 tokenId) external;\n\n    function getRequest(uint256 requestId) external view returns (WithdrawRequest memory);\n\n    function finalizeRequests(uint256 requestId) external;\n\n    function owner() external view returns (address);\n\n    function updateAdmin(address admin, bool isAdmin) external;\n}\n\ninterface IWEETH {\n    function wrap(uint256 amount) external returns (uint256);\n\n    function unwrap(uint256 amount) external returns (uint256);\n}\n\n// Kelp DAO\ninterface ILRTDepositPool {\n    function depositAsset(\n        address asset,\n        uint256 depositAmount,\n        uint256 minRSETHAmountToReceive,\n        string calldata referralId\n    ) external;\n}\n\n// Lido\ninterface ISTETH {\n    function submit(address referral) external payable returns (uint256);\n}\n\ninterface IWSTETH {\n    function wrap(uint256 amount) external returns (uint256);\n\n    function unwrap(uint256 amount) external returns (uint256);\n}\n\ninterface IUNSTETH {\n    struct WithdrawalRequestStatus {\n        /// @notice stETH token amount that was locked on withdrawal queue for this request\n        uint256 amountOfStETH;\n        /// @notice amount of stETH shares locked on withdrawal queue for this request\n        uint256 amountOfShares;\n        /// @notice address that can claim or transfer this request\n        address owner;\n        /// @notice timestamp of when the request was created, in seconds\n        uint256 timestamp;\n        /// @notice true, if request is finalized\n        bool isFinalized;\n        /// @notice true, if request is claimed. Request is claimable if (isFinalized && !isClaimed)\n        bool isClaimed;\n    }\n\n    function getWithdrawalStatus(\n        uint256[] calldata _requestIds\n    ) external view returns (WithdrawalRequestStatus[] memory statuses);\n\n    function requestWithdrawals(\n        uint256[] calldata _amounts,\n        address _owner\n    ) external returns (uint256[] memory requestIds);\n\n    function claimWithdrawal(uint256 _requestId) external;\n\n    function claimWithdrawals(uint256[] calldata _requestIds, uint256[] calldata _hints) external;\n\n    function finalize(uint256 _lastRequestIdToBeFinalized, uint256 _maxShareRate) external payable;\n\n    function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n    function FINALIZE_ROLE() external view returns (bytes32);\n\n    function getLastFinalizedRequestId() external view returns (uint256);\n\n    function getLastCheckpointIndex() external view returns (uint256);\n\n    function findCheckpointHints(\n        uint256[] memory requestIds,\n        uint256 firstIndex,\n        uint256 lastIndex\n    ) external view returns (uint256[] memory);\n\n    function getClaimableEther(\n        uint256[] memory requestIds,\n        uint256[] memory hints\n    ) external view returns (uint256[] memory);\n}\n\n// Renzo\ninterface IRestakeManager {\n    function depositETH() external payable;\n}\n\n// Stader\ninterface IStakePoolManager {\n    function deposit(address _receiver) external payable returns (uint256);\n\n    function getExchangeRate() external view returns (uint256);\n}\n\ninterface IStaderConfig {\n    function getDecimals() external view returns (uint256);\n}\n\ninterface IUserWithdrawManager {\n    struct WithdrawRequest {\n        address owner;\n        uint256 ethXAmount;\n        uint256 ethExpected;\n        uint256 ethFinalized;\n        uint256 requestTime;\n    }\n\n    function requestWithdraw(uint256 _ethXAmount, address _owner) external returns (uint256);\n\n    function claim(uint256 _requestId) external;\n\n    function userWithdrawRequests(uint256) external view returns (WithdrawRequest memory);\n\n    function finalizeUserWithdrawalRequest() external;\n}\n"
      },
      "src/utils/Math.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nlibrary Math {\n    /**\n     * @notice Substract with a floor of 0 for the result.\n     */\n    function subMinZero(uint256 x, uint256 y) internal pure returns (uint256) {\n        return x > y ? x - y : 0;\n    }\n\n    /**\n     * @notice Used to change the decimals of precision used for an amount.\n     */\n    function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {\n        if (fromDecimals == toDecimals) {\n            return amount;\n        } else if (fromDecimals < toDecimals) {\n            return amount * 10 ** (toDecimals - fromDecimals);\n        } else {\n            return amount / 10 ** (fromDecimals - toDecimals);\n        }\n    }\n\n    // ===================================== OPENZEPPELIN'S MATH =====================================\n\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    // ================================= SOLMATE's FIXEDPOINTMATHLIB =================================\n\n    uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {\n        assembly {\n            // Store x * y in z for now.\n            z := mul(x, y)\n\n            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n                revert(0, 0)\n            }\n\n            // Divide z by the denominator.\n            z := div(z, denominator)\n        }\n    }\n\n    function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {\n        assembly {\n            // Store x * y in z for now.\n            z := mul(x, y)\n\n            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n                revert(0, 0)\n            }\n\n            // First, divide z - 1 by the denominator and add 1.\n            // We allow z - 1 to underflow if z is 0, because we multiply the\n            // end result by 0 if z is zero, ensuring we return 0 if z is zero.\n            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\n        }\n    }\n}\n"
      },
      "lib/solmate/src/utils/SafeTransferLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n    /*//////////////////////////////////////////////////////////////\n                             ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            success := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"
      },
      "lib/solmate/src/tokens/ERC20.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                            METADATA STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    string public name;\n\n    string public symbol;\n\n    uint8 public immutable decimals;\n\n    /*//////////////////////////////////////////////////////////////\n                              ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 public totalSupply;\n\n    mapping(address => uint256) public balanceOf;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*//////////////////////////////////////////////////////////////\n                            EIP-2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal immutable INITIAL_CHAIN_ID;\n\n    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n    mapping(address => uint256) public nonces;\n\n    /*//////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    ) {\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n\n        INITIAL_CHAIN_ID = block.chainid;\n        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        allowance[msg.sender][spender] = amount;\n\n        emit Approval(msg.sender, spender, amount);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        balanceOf[msg.sender] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(msg.sender, to, amount);\n\n        return true;\n    }\n\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n        balanceOf[from] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        return true;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             EIP-2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            address recoveredAddress = ecrecover(\n                keccak256(\n                    abi.encodePacked(\n                        \"\\x19\\x01\",\n                        DOMAIN_SEPARATOR(),\n                        keccak256(\n                            abi.encode(\n                                keccak256(\n                                    \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n                                ),\n                                owner,\n                                spender,\n                                value,\n                                nonces[owner]++,\n                                deadline\n                            )\n                        )\n                    )\n                ),\n                v,\n                r,\n                s\n            );\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n    }\n\n    function computeDomainSeparator() internal view virtual returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(bytes(name)),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function _mint(address to, uint256 amount) internal virtual {\n        totalSupply += amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(address(0), to, amount);\n    }\n\n    function _burn(address from, uint256 amount) internal virtual {\n        balanceOf[from] -= amount;\n\n        // Cannot underflow because a user's balance\n        // will never be larger than the total supply.\n        unchecked {\n            totalSupply -= amount;\n        }\n\n        emit Transfer(from, address(0), amount);\n    }\n}\n"
      },
      "src/Registry.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { Cellar } from \"src/base/Cellar.sol\";\nimport { ERC20 } from \"@solmate/tokens/ERC20.sol\";\nimport { BaseAdaptor } from \"src/modules/adaptors/BaseAdaptor.sol\";\nimport { PriceRouter } from \"src/modules/price-router/PriceRouter.sol\";\n\ncontract Registry is Ownable {\n    // ============================================= ADDRESS CONFIG =============================================\n\n    /**\n     * @notice Emitted when the address of a contract is changed.\n     * @param id value representing the unique ID tied to the changed contract\n     * @param oldAddress address of the contract before the change\n     * @param newAddress address of the contract after the contract\n     */\n    event AddressChanged(uint256 indexed id, address oldAddress, address newAddress);\n\n    /**\n     * @notice Attempted to set the address of a contract that is not registered.\n     * @param id id of the contract that is not registered\n     */\n    error Registry__ContractNotRegistered(uint256 id);\n\n    /**\n     * @notice Emitted when depositor privilege changes.\n     * @param depositor depositor address\n     * @param state the new state of the depositor privilege\n     */\n    event DepositorOnBehalfChanged(address depositor, bool state);\n\n    /**\n     * @notice The unique ID that the next registered contract will have.\n     */\n    uint256 public nextId;\n\n    /**\n     * @notice Get the address associated with an id.\n     */\n    mapping(uint256 => address) public getAddress;\n\n    /**\n     * @notice In order for an address to make deposits on behalf of users they must be approved.\n     */\n    mapping(address => bool) public approvedForDepositOnBehalf;\n\n    /**\n     * @notice toggles a depositors  ability to deposit into cellars on behalf of users.\n     */\n    function setApprovedForDepositOnBehalf(address depositor, bool state) external onlyOwner {\n        approvedForDepositOnBehalf[depositor] = state;\n        emit DepositorOnBehalfChanged(depositor, state);\n    }\n\n    /**\n     * @notice Set the address of the contract at a given id.\n     */\n    function setAddress(uint256 id, address newAddress) external {\n        if (id > 0) {\n            _checkOwner();\n            if (id >= nextId) revert Registry__ContractNotRegistered(id);\n        } else {\n            if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();\n        }\n\n        emit AddressChanged(id, getAddress[id], newAddress);\n\n        getAddress[id] = newAddress;\n    }\n\n    // ============================================= INITIALIZATION =============================================\n\n    /**\n     * @param gravityBridge address of GravityBridge contract\n     * @param swapRouter address of SwapRouter contract\n     * @param priceRouter address of PriceRouter contract\n     */\n    constructor(address newOwner, address gravityBridge, address swapRouter, address priceRouter) Ownable() {\n        _register(gravityBridge);\n        _register(swapRouter);\n        _register(priceRouter);\n        transferOwnership(newOwner);\n    }\n\n    // ============================================ REGISTER CONFIG ============================================\n\n    /**\n     * @notice Emitted when a new contract is registered.\n     * @param id value representing the unique ID tied to the new contract\n     * @param newContract address of the new contract\n     */\n    event Registered(uint256 indexed id, address indexed newContract);\n\n    /**\n     * @notice Register the address of a new contract.\n     * @param newContract address of the new contract to register\n     */\n    function register(address newContract) external onlyOwner {\n        _register(newContract);\n    }\n\n    function _register(address newContract) internal {\n        getAddress[nextId] = newContract;\n\n        emit Registered(nextId, newContract);\n\n        nextId++;\n    }\n\n    // ============================================= ADDRESS 0 LOGIC =============================================\n    /**\n     * Address 0 is the address of the gravity bridge, and special abilities that the owner does not have.\n     * - It can change what address is stored at address 0.\n     * - It can change the owner of this contract.\n     */\n\n    /**\n     * @notice Emitted when an ownership transition is started.\n     */\n    event OwnerTransitionStarted(address newOwner, uint256 startTime);\n\n    /**\n     * @notice Emitted when an ownership transition is cancelled.\n     */\n    event OwnerTransitionCancelled();\n\n    /**\n     * @notice Emitted when an ownership transition is completed.\n     */\n    event OwnerTransitionComplete(address newOwner);\n\n    /**\n     * @notice Attempted to call a function intended for Zero Id address.\n     */\n    error Registry__OnlyCallableByZeroId();\n\n    /**\n     * @notice Attempted to transition owner to the zero address.\n     */\n    error Registry__NewOwnerCanNotBeZero();\n\n    /**\n     * @notice Attempted to perform a restricted action while ownership transition is pending.\n     */\n    error Registry__TransitionPending();\n\n    /**\n     * @notice Attempted to cancel or complete a transition when one is not active.\n     */\n    error Registry__TransitionNotPending();\n\n    /**\n     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.\n     */\n    error Registry__OnlyCallableByPendingOwner();\n\n    /**\n     * @notice The amount of time it takes for an ownership transition to work.\n     */\n    uint256 public constant TRANSITION_PERIOD = 7 days;\n\n    /**\n     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.\n     */\n    address public pendingOwner;\n\n    /**\n     * @notice The starting time stamp of the transition.\n     */\n    uint256 public transitionStart;\n\n    /**\n     * @notice Allows Zero Id address to set a new owner, after the transition period is up.\n     */\n    function transitionOwner(address newOwner) external {\n        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();\n        if (pendingOwner != address(0)) revert Registry__TransitionPending();\n        if (newOwner == address(0)) revert Registry__NewOwnerCanNotBeZero();\n\n        pendingOwner = newOwner;\n        transitionStart = block.timestamp;\n    }\n\n    /**\n     * @notice Allows Zero Id address to cancel an ongoing owner transition.\n     */\n    function cancelTransition() external {\n        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();\n        if (pendingOwner == address(0)) revert Registry__TransitionNotPending();\n\n        pendingOwner = address(0);\n        transitionStart = 0;\n    }\n\n    /**\n     * @notice Allows pending owner to complete the ownership transition.\n     */\n    function completeTransition() external {\n        if (pendingOwner == address(0)) revert Registry__TransitionNotPending();\n        if (msg.sender != pendingOwner) revert Registry__OnlyCallableByPendingOwner();\n        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert Registry__TransitionPending();\n\n        _transferOwnership(pendingOwner);\n\n        pendingOwner = address(0);\n        transitionStart = 0;\n    }\n\n    /**\n     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.\n     */\n    function _checkOwner() internal view override {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        if (transitionStart != 0) revert Registry__TransitionPending();\n    }\n\n    // ============================================ PAUSE LOGIC ============================================\n\n    /**\n     * @notice Emitted when a target is paused.\n     */\n    event TargetPaused(address target);\n\n    /**\n     * @notice Emitted when a target is unpaused.\n     */\n    event TargetUnpaused(address target);\n\n    /**\n     * @notice Attempted to unpause a target that was not paused.\n     */\n    error Registry__TargetNotPaused(address target);\n\n    /**\n     * @notice Attempted to pause a target that was already paused.\n     */\n    error Registry__TargetAlreadyPaused(address target);\n\n    /**\n     * @notice Mapping stores whether or not a cellar is paused.\n     */\n    mapping(address => bool) public isCallerPaused;\n\n    /**\n     * @notice Allows multisig to pause multiple cellars in a single call.\n     */\n    function batchPause(address[] calldata targets) external onlyOwner {\n        for (uint256 i; i < targets.length; ++i) _pauseTarget(targets[i]);\n    }\n\n    /**\n     * @notice Allows multisig to unpause multiple cellars in a single call.\n     */\n    function batchUnpause(address[] calldata targets) external onlyOwner {\n        for (uint256 i; i < targets.length; ++i) _unpauseTarget(targets[i]);\n    }\n\n    /**\n     * @notice Helper function to pause some target.\n     */\n    function _pauseTarget(address target) internal {\n        if (isCallerPaused[target]) revert Registry__TargetAlreadyPaused(target);\n        isCallerPaused[target] = true;\n        emit TargetPaused(target);\n    }\n\n    /**\n     * @notice Helper function to unpause some target.\n     */\n    function _unpauseTarget(address target) internal {\n        if (!isCallerPaused[target]) revert Registry__TargetNotPaused(target);\n        isCallerPaused[target] = false;\n        emit TargetUnpaused(target);\n    }\n\n    // ============================================ ADAPTOR LOGIC ============================================\n\n    /**\n     * @notice Attempted to trust an adaptor with non unique identifier.\n     */\n    error Registry__IdentifierNotUnique();\n\n    /**\n     * @notice Attempted to use an untrusted adaptor.\n     */\n    error Registry__AdaptorNotTrusted(address adaptor);\n\n    /**\n     * @notice Attempted to trust an already trusted adaptor.\n     */\n    error Registry__AdaptorAlreadyTrusted(address adaptor);\n\n    /**\n     * @notice Maps an adaptor address to bool indicating whether it has been set up in the registry.\n     */\n    mapping(address => bool) public isAdaptorTrusted;\n\n    /**\n     * @notice Maps an adaptors identfier to bool, to track if the identifier is unique wrt the registry.\n     */\n    mapping(bytes32 => bool) public isIdentifierUsed;\n\n    /**\n     * @notice Trust an adaptor to be used by cellars\n     * @param adaptor address of the adaptor to trust\n     */\n    function trustAdaptor(address adaptor) external onlyOwner {\n        if (isAdaptorTrusted[adaptor]) revert Registry__AdaptorAlreadyTrusted(adaptor);\n        bytes32 identifier = BaseAdaptor(adaptor).identifier();\n        if (isIdentifierUsed[identifier]) revert Registry__IdentifierNotUnique();\n        isAdaptorTrusted[adaptor] = true;\n        isIdentifierUsed[identifier] = true;\n    }\n\n    /**\n     * @notice Allows registry to distrust adaptors.\n     * @dev Doing so prevents Cellars from adding this adaptor to their catalogue.\n     */\n    function distrustAdaptor(address adaptor) external onlyOwner {\n        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);\n        // Set trust to false.\n        isAdaptorTrusted[adaptor] = false;\n\n        // We are NOT resetting `isIdentifierUsed` because if this adaptor is distrusted, then something needs\n        // to change about the new one being re-trusted.\n    }\n\n    /**\n     * @notice Reverts if `adaptor` is not trusted by the registry.\n     */\n    function revertIfAdaptorIsNotTrusted(address adaptor) external view {\n        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);\n    }\n\n    // ============================================ POSITION LOGIC ============================================\n    /**\n     * @notice stores data related to Cellar positions.\n     * @param adaptors address of the adaptor to use for this position\n     * @param isDebt bool indicating whether this position takes on debt or not\n     * @param adaptorData arbitrary data needed to correclty set up a position\n     * @param configurationData arbitrary data settable by strategist to change cellar <-> adaptor interaction\n     */\n    struct PositionData {\n        address adaptor;\n        bool isDebt;\n        bytes adaptorData;\n        bytes configurationData;\n    }\n\n    /**\n     * @notice Emitted when a new position is added to the registry.\n     * @param id the positions id\n     * @param adaptor address of the adaptor this position uses\n     * @param isDebt bool indicating whether this position takes on debt or not\n     * @param adaptorData arbitrary bytes used to configure this position\n     */\n    event Registry__PositionTrusted(uint32 id, address adaptor, bool isDebt, bytes adaptorData);\n\n    /**\n     * @notice Emitted when a position is distrusted.\n     * @param id the positions id\n     */\n    event Registry__PositionDistrusted(uint32 id);\n\n    /**\n     * @notice Attempted to trust a position not being used.\n     * @param position address of the invalid position\n     */\n    error Registry__PositionPricingNotSetUp(address position);\n\n    /**\n     * @notice Attempted to add a position with bad input values.\n     */\n    error Registry__InvalidPositionInput();\n\n    /**\n     * @notice Attempted to add a position that does not exist.\n     */\n    error Registry__PositionDoesNotExist();\n\n    /**\n     * @notice Attempted to add a position that is not trusted.\n     */\n    error Registry__PositionIsNotTrusted(uint32 position);\n\n    /**\n     * @notice Addresses of the positions currently used by the cellar.\n     */\n    uint256 public constant PRICE_ROUTER_REGISTRY_SLOT = 2;\n\n    /**\n     * @notice Maps a position hash to a position Id.\n     * @dev can be used by adaptors to verify that a certain position is open during Cellar `callOnAdaptor` calls.\n     */\n    mapping(bytes32 => uint32) public getPositionHashToPositionId;\n\n    /**\n     * @notice Maps a position id to its position data.\n     * @dev used by Cellars when adding new positions.\n     */\n    mapping(uint32 => PositionData) public getPositionIdToPositionData;\n\n    /**\n     * @notice Maps a position to a bool indicating whether or not it is trusted.\n     */\n    mapping(uint32 => bool) public isPositionTrusted;\n\n    /**\n     * @notice Trust a position to be used by the cellar.\n     * @param positionId the position id of the newly added position\n     * @param adaptor the adaptor address this position uses\n     * @param adaptorData arbitrary bytes used to configure this position\n     */\n    function trustPosition(uint32 positionId, address adaptor, bytes memory adaptorData) external onlyOwner {\n        bytes32 identifier = BaseAdaptor(adaptor).identifier();\n        bool isDebt = BaseAdaptor(adaptor).isDebt();\n        bytes32 positionHash = keccak256(abi.encode(identifier, isDebt, adaptorData));\n\n        if (positionId == 0) revert Registry__InvalidPositionInput();\n        // Make sure positionId is not already in use.\n        PositionData storage pData = getPositionIdToPositionData[positionId];\n        if (pData.adaptor != address(0)) revert Registry__InvalidPositionInput();\n\n        // Check that...\n        // `adaptor` is a non zero address\n        // position has not been already set up\n        if (adaptor == address(0) || getPositionHashToPositionId[positionHash] != 0)\n            revert Registry__InvalidPositionInput();\n\n        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);\n\n        // Set position data.\n        pData.adaptor = adaptor;\n        pData.isDebt = isDebt;\n        pData.adaptorData = adaptorData;\n        pData.configurationData = abi.encode(0);\n\n        // Globally trust the position.\n        isPositionTrusted[positionId] = true;\n\n        getPositionHashToPositionId[positionHash] = positionId;\n\n        // Check that assets position uses are supported for pricing operations.\n        ERC20[] memory assets = BaseAdaptor(adaptor).assetsUsed(adaptorData);\n        PriceRouter priceRouter = PriceRouter(getAddress[PRICE_ROUTER_REGISTRY_SLOT]);\n        for (uint256 i; i < assets.length; i++) {\n            if (!priceRouter.isSupported(assets[i])) revert Registry__PositionPricingNotSetUp(address(assets[i]));\n        }\n\n        emit Registry__PositionTrusted(positionId, adaptor, isDebt, adaptorData);\n    }\n\n    /**\n     * @notice Allows registry to distrust positions.\n     * @dev Doing so prevents Cellars from adding this position to their catalogue,\n     *      and adding the position to their tracked arrays.\n     */\n    function distrustPosition(uint32 positionId) external onlyOwner {\n        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);\n        isPositionTrusted[positionId] = false;\n        emit Registry__PositionDistrusted(positionId);\n    }\n\n    /**\n     * @notice Called by Cellars to add a new position to themselves.\n     * @param positionId the id of the position the cellar wants to add\n     * @return adaptor the address of the adaptor, isDebt bool indicating whether position is\n     *         debt or not, and adaptorData needed to interact with position\n     */\n    function addPositionToCellar(\n        uint32 positionId\n    ) external view returns (address adaptor, bool isDebt, bytes memory adaptorData) {\n        if (positionId == 0) revert Registry__PositionDoesNotExist();\n        PositionData memory positionData = getPositionIdToPositionData[positionId];\n        if (positionData.adaptor == address(0)) revert Registry__PositionDoesNotExist();\n\n        revertIfPositionIsNotTrusted(positionId);\n\n        return (positionData.adaptor, positionData.isDebt, positionData.adaptorData);\n    }\n\n    /**\n     * @notice Reverts if `positionId` is not trusted by the registry.\n     */\n    function revertIfPositionIsNotTrusted(uint32 positionId) public view {\n        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);\n    }\n}\n"
      },
      "src/base/Cellar.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport {Math} from \"src/utils/Math.sol\";\nimport {ERC4626} from \"@solmate/mixins/ERC4626.sol\";\nimport {SafeTransferLib} from \"@solmate/utils/SafeTransferLib.sol\";\nimport {ERC20} from \"@solmate/tokens/ERC20.sol\";\n// import { ERC4626, SafeTransferLib, Math, ERC20 } from \"src/base/ERC4626.sol\";\nimport {Registry} from \"src/Registry.sol\";\nimport {PriceRouter} from \"src/modules/price-router/PriceRouter.sol\";\nimport {Uint32Array} from \"src/utils/Uint32Array.sol\";\nimport {BaseAdaptor} from \"src/modules/adaptors/BaseAdaptor.sol\";\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {ERC721Holder} from \"@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol\";\nimport {Auth, Authority} from \"@solmate/auth/Auth.sol\";\n\n/**\n * @title Sommelier Cellar\n * @notice A composable ERC4626 that can use arbitrary DeFi assets/positions using adaptors.\n * @author crispymangoes\n */\ncontract Cellar is ERC4626, Auth, ERC721Holder {\n    using Uint32Array for uint32[];\n    using SafeTransferLib for ERC20;\n    using Math for uint256;\n    using Address for address;\n\n    // ========================================= One Slot Values =========================================\n    // Below values are frequently accessed in the same TXs. By moving them to the top\n    // they will be stored in the same slot, reducing cold access reads.\n\n    /**\n     * @notice The maximum amount of shares that can be in circulation.\n     * @dev Can be decreased by the strategist.\n     * @dev Can be increased by Sommelier Governance.\n     */\n    uint192 public shareSupplyCap;\n\n    /**\n     * @notice `locked` is public, so that the state can be checked even during view function calls.\n     */\n    bool public locked;\n\n    /**\n     * @notice Whether or not the contract is shutdown in case of an emergency.\n     */\n    bool public isShutdown;\n\n    /**\n     * @notice Pauses all user entry/exits, and strategist rebalances.\n     */\n    bool public ignorePause;\n\n    /**\n     * @notice This bool is used to stop strategists from abusing Base Adaptor functions(deposit/withdraw).\n     */\n    bool public blockExternalReceiver;\n\n    /**\n     * @notice Stores the position id of the holding position in the creditPositions array.\n     */\n    uint32 public holdingPosition;\n\n    // ========================================= MULTICALL =========================================\n\n    /**\n     * @notice Allows caller to call multiple functions in a single TX.\n     * @dev Does NOT return the function return values.\n     */\n    function multicall(bytes[] calldata data) external {\n        for (uint256 i = 0; i < data.length; i++) {\n            address(this).functionDelegateCall(data[i]);\n        }\n    }\n\n    // ========================================= REENTRANCY GUARD =========================================\n\n    modifier nonReentrant() {\n        require(!locked, \"REENTRANCY\");\n\n        locked = true;\n\n        _;\n\n        locked = false;\n    }\n\n    // ========================================= _isAuthorized ========================================\n\n    function _isAuthorized() internal requiresAuth {}\n\n    // ========================================= PRICE ROUTER CACHE =========================================\n\n    /**\n     * @notice Cached price router contract.\n     * @dev This way cellar has to \"opt in\" to price router changes.\n     */\n    PriceRouter public priceRouter;\n\n    /**\n     * @notice Updates the cellar to use the lastest price router in the registry.\n     * @param checkTotalAssets If true totalAssets is checked before and after updating the price router,\n     *        and is verified to be withing a +- 5% envelope.\n     *        If false totalAssets is only called after updating the price router.]\n     * @param allowableRange The +- range the total assets may deviate between the old and new price router.\n     *                       - 1_000 == 10%\n     *                       - 500 == 5%\n     * @param expectedPriceRouter The registry price router differed from the expected price router.\n     * @dev `allowableRange` reverts from arithmetic underflow if it is greater than 10_000, this is\n     *      desired behavior.\n     * @dev Callable by Sommelier Governance.\n     */\n    function cachePriceRouter(bool checkTotalAssets, uint16 allowableRange, address expectedPriceRouter) external {\n        _isAuthorized();\n        uint256 minAssets;\n        uint256 maxAssets;\n\n        if (checkTotalAssets) {\n            uint256 assetsBefore = totalAssets();\n            minAssets = assetsBefore.mulDivDown(1e4 - allowableRange, 1e4);\n            maxAssets = assetsBefore.mulDivDown(1e4 + allowableRange, 1e4);\n        }\n\n        // Make sure expected price router is equal to price router grabbed from registry.\n        _checkRegistryAddressAgainstExpected(PRICE_ROUTER_REGISTRY_SLOT, expectedPriceRouter);\n\n        priceRouter = PriceRouter(expectedPriceRouter);\n        uint256 assetsAfter = totalAssets();\n\n        if (checkTotalAssets) {\n            if (assetsAfter < minAssets || assetsAfter > maxAssets) {\n                revert Cellar__TotalAssetDeviatedOutsideRange(assetsAfter, minAssets, maxAssets);\n            }\n        }\n    }\n\n    // ========================================= POSITIONS CONFIG =========================================\n\n    /**\n     * @notice Emitted when a position is added.\n     * @param position id of position that was added\n     * @param index index that position was added at\n     */\n    event PositionAdded(uint32 position, uint256 index);\n\n    /**\n     * @notice Emitted when a position is removed.\n     * @param position id of position that was removed\n     * @param index index that position was removed from\n     */\n    event PositionRemoved(uint32 position, uint256 index);\n\n    /**\n     * @notice Emitted when the positions at two indexes are swapped.\n     * @param newPosition1 id of position (previously at index2) that replaced index1.\n     * @param newPosition2 id of position (previously at index1) that replaced index2.\n     * @param index1 index of first position involved in the swap\n     * @param index2 index of second position involved in the swap.\n     */\n    event PositionSwapped(uint32 newPosition1, uint32 newPosition2, uint256 index1, uint256 index2);\n\n    /**\n     * @notice Emitted when Governance adds/removes a position to/from the cellars catalogue.\n     */\n    event PositionCatalogueAltered(uint32 positionId, bool inCatalogue);\n\n    /**\n     * @notice Emitted when Governance adds/removes an adaptor to/from the cellars catalogue.\n     */\n    event AdaptorCatalogueAltered(address adaptor, bool inCatalogue);\n\n    /**\n     * @notice Attempted to add a position that is already being used.\n     * @param position id of the position\n     */\n    error Cellar__PositionAlreadyUsed(uint32 position);\n\n    /**\n     * @notice Attempted to make an unused position the holding position.\n     * @param position id of the position\n     */\n    error Cellar__PositionNotUsed(uint32 position);\n\n    /**\n     * @notice Attempted to add a position that is not in the catalogue.\n     * @param position id of the position\n     */\n    error Cellar__PositionNotInCatalogue(uint32 position);\n\n    /**\n     * @notice Attempted an action on a position that is required to be empty before the action can be performed.\n     * @param position address of the non-empty position\n     * @param sharesRemaining amount of shares remaining in the position\n     */\n    error Cellar__PositionNotEmpty(uint32 position, uint256 sharesRemaining);\n\n    /**\n     * @notice Attempted an operation with an asset that was different then the one expected.\n     * @param asset address of the asset\n     * @param expectedAsset address of the expected asset\n     */\n    error Cellar__AssetMismatch(address asset, address expectedAsset);\n\n    /**\n     * @notice Attempted to add a position when the position array is full.\n     * @param maxPositions maximum number of positions that can be used\n     */\n    error Cellar__PositionArrayFull(uint256 maxPositions);\n\n    /**\n     * @notice Attempted to add a position, with mismatched debt.\n     * @param position the posiiton id that was mismatched\n     */\n    error Cellar__DebtMismatch(uint32 position);\n\n    /**\n     * @notice Attempted to remove the Cellars holding position.\n     */\n    error Cellar__RemovingHoldingPosition();\n\n    /**\n     * @notice Attempted to add an invalid holding position.\n     * @param positionId the id of the invalid position.\n     */\n    error Cellar__InvalidHoldingPosition(uint32 positionId);\n\n    /**\n     * @notice Attempted to force out the wrong position.\n     */\n    error Cellar__FailedToForceOutPosition();\n\n    /**\n     * @notice Array of uint32s made up of cellars credit positions Ids.\n     */\n    uint32[] internal creditPositions;\n\n    /**\n     * @notice Array of uint32s made up of cellars debt positions Ids.\n     */\n    uint32[] internal debtPositions;\n\n    /**\n     * @notice Tell whether a position is currently used.\n     */\n    mapping(uint256 => bool) public isPositionUsed;\n\n    /**\n     * @notice Get position data given position id.\n     */\n    mapping(uint32 => Registry.PositionData) internal getPositionData;\n\n    /**\n     * @notice Get the ids of the credit positions currently used by the cellar.\n     */\n    function getCreditPositions() external view returns (uint32[] memory) {\n        return creditPositions;\n    }\n\n    /**\n     * @notice Get the ids of the debt positions currently used by the cellar.\n     */\n    function getDebtPositions() external view returns (uint32[] memory) {\n        return debtPositions;\n    }\n\n    /**\n     * @notice Maximum amount of positions a cellar can have in it's credit/debt arrays.\n     */\n    uint256 internal constant MAX_POSITIONS = 32;\n\n    /**\n     * @notice Allows owner to change the holding position.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function setHoldingPosition(uint32 positionId) public {\n        _isAuthorized();\n        if (!isPositionUsed[positionId]) revert Cellar__PositionNotUsed(positionId);\n        if (_assetOf(positionId) != asset) revert Cellar__AssetMismatch(address(asset), address(_assetOf(positionId)));\n        if (getPositionData[positionId].isDebt) revert Cellar__InvalidHoldingPosition(positionId);\n        holdingPosition = positionId;\n    }\n\n    /**\n     * @notice Positions the strategist is approved to use without any governance intervention.\n     */\n    mapping(uint32 => bool) internal positionCatalogue;\n\n    /**\n     * @notice Adaptors the strategist is approved to use without any governance intervention.\n     */\n    mapping(address => bool) internal adaptorCatalogue;\n\n    /**\n     * @notice Allows Governance to add positions to this cellar's catalogue.\n     * @dev Callable by Sommelier Governance.\n     */\n    function addPositionToCatalogue(uint32 positionId) public {\n        _isAuthorized();\n        // Make sure position is not paused and is trusted.\n        registry.revertIfPositionIsNotTrusted(positionId);\n        positionCatalogue[positionId] = true;\n        emit PositionCatalogueAltered(positionId, true);\n    }\n\n    /**\n     * @notice Allows Governance to remove positions from this cellar's catalogue.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function removePositionFromCatalogue(uint32 positionId) external {\n        _isAuthorized();\n        positionCatalogue[positionId] = false;\n        emit PositionCatalogueAltered(positionId, false);\n    }\n\n    /**\n     * @notice Allows Governance to add adaptors to this cellar's catalogue.\n     * @dev Callable by Sommelier Governance.\n     */\n    function addAdaptorToCatalogue(address adaptor) external {\n        _isAuthorized();\n        // Make sure adaptor is trusted.\n        registry.revertIfAdaptorIsNotTrusted(adaptor);\n        adaptorCatalogue[adaptor] = true;\n        emit AdaptorCatalogueAltered(adaptor, true);\n    }\n\n    /**\n     * @notice Allows Governance to remove adaptors from this cellar's catalogue.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function removeAdaptorFromCatalogue(address adaptor) external {\n        _isAuthorized();\n        adaptorCatalogue[adaptor] = false;\n        emit AdaptorCatalogueAltered(adaptor, false);\n    }\n\n    /**\n     * @notice Insert a trusted position to the list of positions used by the cellar at a given index.\n     * @param index index at which to insert the position\n     * @param positionId id of position to add\n     * @param configurationData data used to configure how the position behaves\n     * @dev Callable by Sommelier Strategist.\n     */\n    function addPosition(uint32 index, uint32 positionId, bytes memory configurationData, bool inDebtArray) public {\n        _isAuthorized();\n        _whenNotShutdown();\n\n        // Check if position is already being used.\n        if (isPositionUsed[positionId]) revert Cellar__PositionAlreadyUsed(positionId);\n\n        // Check if position is in the position catalogue.\n        if (!positionCatalogue[positionId]) revert Cellar__PositionNotInCatalogue(positionId);\n\n        // Grab position data from registry.\n        // Also checks if position is not trusted and reverts if so.\n        (address adaptor, bool isDebt, bytes memory adaptorData) = registry.addPositionToCellar(positionId);\n\n        if (isDebt != inDebtArray) revert Cellar__DebtMismatch(positionId);\n\n        // Copy position data from registry to here.\n        getPositionData[positionId] = Registry.PositionData({\n            adaptor: adaptor,\n            isDebt: isDebt,\n            adaptorData: adaptorData,\n            configurationData: configurationData\n        });\n\n        if (isDebt) {\n            if (debtPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS);\n            // Add new position at a specified index.\n            debtPositions.add(index, positionId);\n        } else {\n            if (creditPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS);\n            // Add new position at a specified index.\n            creditPositions.add(index, positionId);\n        }\n\n        isPositionUsed[positionId] = true;\n\n        emit PositionAdded(positionId, index);\n    }\n\n    /**\n     * @notice Remove the position at a given index from the list of positions used by the cellar.\n     * @dev Called by strategist.\n     * @param index index at which to remove the position\n     * @dev Callable by Sommelier Strategist.\n     */\n    function removePosition(uint32 index, bool inDebtArray) external {\n        _isAuthorized();\n        // Get position being removed.\n        uint32 positionId = inDebtArray ? debtPositions[index] : creditPositions[index];\n\n        // Only remove position if it is empty, and if it is not the holding position.\n        uint256 positionBalance = _balanceOf(positionId);\n        if (positionBalance > 0) revert Cellar__PositionNotEmpty(positionId, positionBalance);\n\n        _removePosition(index, positionId, inDebtArray);\n    }\n\n    /**\n     * @notice Allows Sommelier Governance to forceably remove a position from the Cellar without checking its balance is zero.\n     * @dev Callable by Sommelier Governance.\n     */\n    function forcePositionOut(uint32 index, uint32 positionId, bool inDebtArray) external {\n        _isAuthorized();\n        // Get position being removed.\n        uint32 _positionId = inDebtArray ? debtPositions[index] : creditPositions[index];\n        // Make sure position id right, and is distrusted.\n        if (positionId != _positionId || registry.isPositionTrusted(positionId)) {\n            revert Cellar__FailedToForceOutPosition();\n        }\n\n        _removePosition(index, positionId, inDebtArray);\n    }\n\n    /**\n     * @notice Internal helper function to remove positions from cellars tracked arrays.\n     */\n    function _removePosition(uint32 index, uint32 positionId, bool inDebtArray) internal {\n        if (positionId == holdingPosition) revert Cellar__RemovingHoldingPosition();\n\n        if (inDebtArray) {\n            // Remove position at the given index.\n            debtPositions.remove(index);\n        } else {\n            creditPositions.remove(index);\n        }\n\n        isPositionUsed[positionId] = false;\n        delete getPositionData[positionId];\n\n        emit PositionRemoved(positionId, index);\n    }\n\n    /**\n     * @notice Swap the positions at two given indexes.\n     * @param index1 index of first position to swap\n     * @param index2 index of second position to swap\n     * @param inDebtArray bool indicating to switch positions in the debt array, or the credit array.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function swapPositions(uint32 index1, uint32 index2, bool inDebtArray) external {\n        _isAuthorized();\n        // Get the new positions that will be at each index.\n        uint32 newPosition1;\n        uint32 newPosition2;\n\n        if (inDebtArray) {\n            newPosition1 = debtPositions[index2];\n            newPosition2 = debtPositions[index1];\n            // Swap positions.\n            (debtPositions[index1], debtPositions[index2]) = (newPosition1, newPosition2);\n        } else {\n            newPosition1 = creditPositions[index2];\n            newPosition2 = creditPositions[index1];\n            // Swap positions.\n            (creditPositions[index1], creditPositions[index2]) = (newPosition1, newPosition2);\n        }\n\n        emit PositionSwapped(newPosition1, newPosition2, index1, index2);\n    }\n\n    // =============================================== FEES CONFIG ===============================================\n\n    /**\n     * @notice Emitted when strategist platform fee cut is changed.\n     * @param oldPlatformCut value strategist platform fee cut was changed from\n     * @param newPlatformCut value strategist platform fee cut was changed to\n     */\n    event StrategistPlatformCutChanged(uint64 oldPlatformCut, uint64 newPlatformCut);\n\n    /**\n     * @notice Emitted when strategists payout address is changed.\n     * @param oldPayoutAddress value strategists payout address was changed from\n     * @param newPayoutAddress value strategists payout address was changed to\n     */\n    event StrategistPayoutAddressChanged(address oldPayoutAddress, address newPayoutAddress);\n\n    /**\n     * @notice Attempted to change strategist fee cut with invalid value.\n     */\n    error Cellar__InvalidFeeCut();\n\n    /**\n     * @notice Attempted to change platform fee with invalid value.\n     */\n    error Cellar__InvalidFee();\n\n    /**\n     * @notice Data related to fees.\n     * @param strategistPlatformCut Determines how much platform fees go to strategist.\n     *                              This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%).\n     * @param platformFee The percentage of total assets accrued as platform fees over a year.\n     *                       This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%).\n     * @param strategistPayoutAddress Address to send the strategists fee shares.\n     */\n    struct FeeData {\n        uint64 strategistPlatformCut;\n        uint64 platformFee;\n        uint64 lastAccrual;\n        address strategistPayoutAddress;\n    }\n\n    /**\n     * @notice Stores all fee data for cellar.\n     */\n    FeeData public feeData = FeeData({\n        strategistPlatformCut: 0.75e18,\n        platformFee: 0.01e18,\n        lastAccrual: 0,\n        strategistPayoutAddress: address(0)\n    });\n\n    /**\n     * @notice Sets the max possible performance fee for this cellar.\n     */\n    uint64 internal constant MAX_PLATFORM_FEE = 0.2e18;\n\n    /**\n     * @notice Sets the max possible fee cut for this cellar.\n     */\n    uint64 internal constant MAX_FEE_CUT = 1e18;\n\n    /**\n     * @notice Sets the Strategists cut of platform fees\n     * @param cut the platform cut for the strategist\n     * @dev Callable by Sommelier Governance.\n     */\n    function setStrategistPlatformCut(uint64 cut) external {\n        _isAuthorized();\n        if (cut > MAX_FEE_CUT) revert Cellar__InvalidFeeCut();\n        emit StrategistPlatformCutChanged(feeData.strategistPlatformCut, cut);\n\n        feeData.strategistPlatformCut = cut;\n    }\n\n    /**\n     * @notice Sets the Strategists payout address\n     * @param payout the new strategist payout address\n     * @dev Callable by Sommelier Strategist.\n     */\n    function setStrategistPayoutAddress(address payout) external {\n        _isAuthorized();\n        emit StrategistPayoutAddressChanged(feeData.strategistPayoutAddress, payout);\n\n        feeData.strategistPayoutAddress = payout;\n    }\n\n    // =========================================== EMERGENCY LOGIC ===========================================\n\n    /**\n     * @notice Emitted when cellar emergency state is changed.\n     * @param isShutdown whether the cellar is shutdown\n     */\n    event ShutdownChanged(bool isShutdown);\n\n    /**\n     * @notice Attempted action was prevented due to contract being shutdown.\n     */\n    error Cellar__ContractShutdown();\n\n    /**\n     * @notice Attempted action was prevented due to contract not being shutdown.\n     */\n    error Cellar__ContractNotShutdown();\n\n    /**\n     * @notice Attempted to interact with the cellar when it is paused.\n     */\n    error Cellar__Paused();\n\n    /**\n     * @notice View function external contracts can use to see if the cellar is paused.\n     */\n    function isPaused() external view returns (bool) {\n        if (!ignorePause) {\n            return registry.isCallerPaused(address(this));\n        }\n        return false;\n    }\n\n    /**\n     * @notice Pauses all user entry/exits, and strategist rebalances.\n     */\n    function _checkIfPaused() internal view {\n        if (!ignorePause) {\n            if (registry.isCallerPaused(address(this))) revert Cellar__Paused();\n        }\n    }\n\n    /**\n     * @notice Allows governance to choose whether or not to respect a pause.\n     * @dev Callable by Sommelier Governance.\n     */\n    function toggleIgnorePause() external {\n        _isAuthorized();\n        ignorePause = ignorePause ? false : true;\n    }\n\n    /**\n     * @notice Prevent a function from being called during a shutdown.\n     */\n    function _whenNotShutdown() internal view {\n        if (isShutdown) revert Cellar__ContractShutdown();\n    }\n\n    /**\n     * @notice Shutdown the cellar. Used in an emergency or if the cellar has been deprecated.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function initiateShutdown() external {\n        _isAuthorized();\n        _whenNotShutdown();\n        isShutdown = true;\n\n        emit ShutdownChanged(true);\n    }\n\n    /**\n     * @notice Restart the cellar.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function liftShutdown() external {\n        _isAuthorized();\n        if (!isShutdown) revert Cellar__ContractNotShutdown();\n        isShutdown = false;\n\n        emit ShutdownChanged(false);\n    }\n\n    // =========================================== CONSTRUCTOR ===========================================\n\n    /**\n     * @notice Id to get the gravity bridge from the registry.\n     */\n    uint256 internal constant GRAVITY_BRIDGE_REGISTRY_SLOT = 0;\n\n    /**\n     * @notice Id to get the price router from the registry.\n     */\n    uint256 internal constant PRICE_ROUTER_REGISTRY_SLOT = 2;\n\n    /**\n     * @notice The minimum amount of shares to be minted in the contructor.\n     */\n    uint256 internal constant MINIMUM_CONSTRUCTOR_MINT = 1e4;\n\n    /**\n     * @notice Attempted to deploy contract without minting enough shares.\n     */\n    error Cellar__MinimumConstructorMintNotMet();\n\n    /**\n     * @notice Address of the platform's registry contract. Used to get the latest address of modules.\n     */\n    Registry public immutable registry;\n\n    /**\n     * @dev Owner should be set to the Gravity Bridge, which relays instructions from the Steward\n     *      module to the cellars.\n     *      https://github.com/PeggyJV/steward\n     *      https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol\n     * @param _registry address of the platform's registry contract\n     * @param _asset address of underlying token used for the for accounting, depositing, and withdrawing\n     * @param _name name of this cellar's share token\n     * @param _symbol symbol of this cellar's share token\n     * @param _holdingPosition the holding position of the Cellar\n     *        must use a position that does NOT call back to cellar on use(Like ERC20 positions).\n     * @param _holdingPositionConfig configuration data for holding position\n     * @param _initialDeposit initial amount of assets to deposit into the Cellar\n     * @param _strategistPlatformCut platform cut to use\n     * @param _shareSupplyCap starting share supply cap\n     */\n    constructor(\n        address _owner,\n        Registry _registry,\n        ERC20 _asset,\n        string memory _name,\n        string memory _symbol,\n        uint32 _holdingPosition,\n        bytes memory _holdingPositionConfig,\n        uint256 _initialDeposit,\n        uint64 _strategistPlatformCut,\n        uint192 _shareSupplyCap\n    ) ERC4626(_asset, _name, _symbol) Auth(msg.sender, Authority(address(0))) {\n        registry = _registry;\n        priceRouter = PriceRouter(_registry.getAddress(PRICE_ROUTER_REGISTRY_SLOT));\n\n        // Initialize holding position.\n        addPositionToCatalogue(_holdingPosition);\n        addPosition(0, _holdingPosition, _holdingPositionConfig, false);\n        setHoldingPosition(_holdingPosition);\n\n        // Update Share Supply Cap.\n        shareSupplyCap = _shareSupplyCap;\n\n        if (_initialDeposit < MINIMUM_CONSTRUCTOR_MINT) revert Cellar__MinimumConstructorMintNotMet();\n\n        // Deposit into Cellar, and mint shares to Deployer address.\n        _asset.safeTransferFrom(_owner, address(this), _initialDeposit);\n        // Set the share price as 1:1 with underlying asset.\n        _mint(msg.sender, _initialDeposit);\n        // Deposit _initialDeposit into holding position.\n        _depositTo(_holdingPosition, _initialDeposit);\n\n        feeData.strategistPlatformCut = _strategistPlatformCut;\n        transferOwnership(_owner);\n    }\n\n    // =========================================== CORE LOGIC ===========================================\n\n    /**\n     * @notice Attempted an action with zero shares.\n     */\n    error Cellar__ZeroShares();\n\n    /**\n     * @notice Attempted an action with zero assets.\n     */\n    error Cellar__ZeroAssets();\n\n    /**\n     * @notice Withdraw did not withdraw all assets.\n     * @param assetsOwed the remaining assets owed that were not withdrawn.\n     */\n    error Cellar__IncompleteWithdraw(uint256 assetsOwed);\n\n    /**\n     * @notice Attempted to withdraw an illiquid position.\n     * @param illiquidPosition the illiquid position.\n     */\n    error Cellar__IlliquidWithdraw(address illiquidPosition);\n\n    /**\n     * @notice called at the beginning of deposit.\n     */\n    function beforeDeposit(ERC20, uint256, uint256, address) internal view virtual {\n        _whenNotShutdown();\n        _checkIfPaused();\n    }\n\n    /**\n     * @notice called at the end of deposit.\n     * @param position the position to deposit to.\n     * @param assets amount of assets deposited by user.\n     */\n    function afterDeposit(uint32 position, uint256 assets, uint256, address) internal virtual {\n        _depositTo(position, assets);\n    }\n\n    /**\n     * @notice called at the beginning of withdraw.\n     */\n    function beforeWithdraw(uint256, uint256, address, address) internal view virtual {\n        _checkIfPaused();\n    }\n\n    /**\n     * @notice Called when users enter the cellar via deposit or mint.\n     */\n    function _enter(ERC20 depositAsset, uint32 position, uint256 assets, uint256 shares, address receiver)\n        internal\n        virtual\n    {\n        beforeDeposit(asset, assets, shares, receiver);\n\n        // Need to transfer before minting or ERC777s could reenter.\n        depositAsset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n\n        afterDeposit(position, assets, shares, receiver);\n    }\n\n    /**\n     * @notice Deposits assets into the cellar, and returns shares to receiver.\n     * @param assets amount of assets deposited by user.\n     * @param receiver address to receive the shares.\n     * @return shares amount of shares given for deposit.\n     */\n    function deposit(uint256 assets, address receiver) public virtual override nonReentrant returns (uint256 shares) {\n        // Use `_calculateTotalAssetsOrTotalAssetsWithdrawable` instead of totalAssets bc re-entrancy is already checked in this function.\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n\n        // Check for rounding error since we round down in previewDeposit.\n        if ((shares = _convertToShares(assets, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroShares();\n\n        if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded();\n\n        _enter(asset, holdingPosition, assets, shares, receiver);\n    }\n\n    /**\n     * @notice Mints shares from the cellar, and returns shares to receiver.\n     * @param shares amount of shares requested by user.\n     * @param receiver address to receive the shares.\n     * @return assets amount of assets deposited into the cellar.\n     */\n    function mint(uint256 shares, address receiver) public override nonReentrant returns (uint256 assets) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n\n        // previewMint rounds up, but initial mint could return zero assets, so check for rounding error.\n        if ((assets = _previewMint(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets();\n\n        if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded();\n\n        _enter(asset, holdingPosition, assets, shares, receiver);\n    }\n\n    /**\n     * @notice Called when users exit the cellar via withdraw or redeem.\n     */\n    function _exit(uint256 assets, uint256 shares, address receiver, address owner) internal {\n        beforeWithdraw(assets, shares, receiver, owner);\n\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        _burn(owner, shares);\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n        _withdrawInOrder(assets, receiver);\n\n        /// @notice `afterWithdraw` is currently not used.\n        // afterWithdraw(assets, shares, receiver, owner);\n    }\n\n    /**\n     * @notice Withdraw assets from the cellar by redeeming shares.\n     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.\n     *      Since there are no swaps involved in this function, the receiver may receive multiple\n     *      assets. The value of all the assets returned will be equal to the amount defined by\n     *      `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets`\n     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many\n     *      tokens).\n     * @param assets equivalent value of the assets withdrawn, denominated in the cellar's asset\n     * @param receiver address that will receive withdrawn assets\n     * @param owner address that owns the shares being redeemed\n     * @return shares amount of shares redeemed\n     */\n    function withdraw(uint256 assets, address receiver, address owner)\n        public\n        override\n        nonReentrant\n        returns (uint256 shares)\n    {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n\n        // No need to check for rounding error, `previewWithdraw` rounds up.\n        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);\n\n        _exit(assets, shares, receiver, owner);\n    }\n\n    /**\n     * @notice Redeem shares to withdraw assets from the cellar.\n     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.\n     *      Since there are no swaps involved in this function, the receiver may receive multiple\n     *      assets. The value of all the assets returned will be equal to the amount defined by\n     *      `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets`\n     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many\n     *      tokens).\n     * @param shares amount of shares to redeem\n     * @param receiver address that will receive withdrawn assets\n     * @param owner address that owns the shares being redeemed\n     * @return assets equivalent value of the assets withdrawn, denominated in the cellar's asset\n     */\n    function redeem(uint256 shares, address receiver, address owner)\n        public\n        override\n        nonReentrant\n        returns (uint256 assets)\n    {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n\n        // Check for rounding error since we round down in previewRedeem.\n        if ((assets = _convertToAssets(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets();\n\n        _exit(assets, shares, receiver, owner);\n    }\n\n    /**\n     * @notice Struct used in `_withdrawInOrder` in order to hold multiple pricing values in a single variable.\n     * @dev Prevents stack too deep errors.\n     */\n    struct WithdrawPricing {\n        uint256 priceBaseUSD;\n        uint256 oneBase;\n        uint256 priceQuoteUSD;\n        uint256 oneQuote;\n    }\n\n    /**\n     * @notice Multipler used to insure calculations use very high precision.\n     */\n    uint256 private constant PRECISION_MULTIPLIER = 1e18;\n\n    /**\n     * @dev Withdraw from positions in the order defined by `positions`.\n     * @param assets the amount of assets to withdraw from cellar\n     * @param receiver the address to sent withdrawn assets to\n     * @dev Only loop through credit array because debt can not be withdraw by users.\n     */\n    function _withdrawInOrder(uint256 assets, address receiver) internal {\n        // Save asset price in USD, and decimals to reduce external calls.\n        WithdrawPricing memory pricingInfo;\n        pricingInfo.priceQuoteUSD = priceRouter.getPriceInUSD(asset);\n        pricingInfo.oneQuote = 10 ** decimals;\n        uint256 creditLength = creditPositions.length;\n        for (uint256 i; i < creditLength; ++i) {\n            uint32 position = creditPositions[i];\n            uint256 withdrawableBalance = _withdrawableFrom(position);\n            // Move on to next position if this one is empty.\n            if (withdrawableBalance == 0) continue;\n            ERC20 positionAsset = _assetOf(position);\n\n            pricingInfo.priceBaseUSD = priceRouter.getPriceInUSD(positionAsset);\n            pricingInfo.oneBase = 10 ** positionAsset.decimals();\n            uint256 totalWithdrawableBalanceInAssets;\n            {\n                uint256 withdrawableBalanceInUSD = (PRECISION_MULTIPLIER * withdrawableBalance).mulDivDown(\n                    pricingInfo.priceBaseUSD, pricingInfo.oneBase\n                );\n                totalWithdrawableBalanceInAssets =\n                    withdrawableBalanceInUSD.mulDivDown(pricingInfo.oneQuote, pricingInfo.priceQuoteUSD);\n                totalWithdrawableBalanceInAssets = totalWithdrawableBalanceInAssets / PRECISION_MULTIPLIER;\n            }\n\n            // We want to pull as much as we can from this position, but no more than needed.\n            uint256 amount;\n\n            if (totalWithdrawableBalanceInAssets > assets) {\n                // Convert assets into position asset.\n                uint256 assetsInUSD =\n                    (PRECISION_MULTIPLIER * assets).mulDivDown(pricingInfo.priceQuoteUSD, pricingInfo.oneQuote);\n                amount = assetsInUSD.mulDivDown(pricingInfo.oneBase, pricingInfo.priceBaseUSD);\n                amount = amount / PRECISION_MULTIPLIER;\n                assets = 0;\n            } else {\n                amount = withdrawableBalance;\n                assets = assets - totalWithdrawableBalanceInAssets;\n            }\n\n            // Withdraw from position.\n            _withdrawFrom(position, amount, receiver);\n\n            // Stop if no more assets to withdraw.\n            if (assets == 0) break;\n        }\n        // If withdraw did not remove all assets owed, revert.\n        if (assets > 0) revert Cellar__IncompleteWithdraw(assets);\n    }\n\n    // ========================================= ACCOUNTING LOGIC =========================================\n\n    /**\n     * @notice Get the Cellars Total Assets, and Total Supply.\n     * @dev bool input is not used, but if it were used the following is true.\n     *      true: return the largest possible total assets\n     *      false: return the smallest possible total assets\n     */\n    function _getTotalAssetsAndTotalSupply(bool)\n        internal\n        view\n        virtual\n        returns (uint256 _totalAssets, uint256 _totalSupply)\n    {\n        _totalAssets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);\n        _totalSupply = totalSupply;\n    }\n\n    /**\n     * @notice Internal accounting function that can report total assets, or total assets withdrawable.\n     * @param reportWithdrawable if true, then the withdrawable total assets is reported,\n     *                           if false, then the total assets is reported\n     */\n    function _calculateTotalAssetsOrTotalAssetsWithdrawable(bool reportWithdrawable)\n        internal\n        view\n        returns (uint256 assets)\n    {\n        uint256 numOfCreditPositions = creditPositions.length;\n        ERC20[] memory creditAssets = new ERC20[](numOfCreditPositions);\n        uint256[] memory creditBalances = new uint256[](numOfCreditPositions);\n        // If we just need the withdrawable, then query credit array value.\n        if (reportWithdrawable) {\n            for (uint256 i; i < numOfCreditPositions; ++i) {\n                uint32 position = creditPositions[i];\n                // If the withdrawable balance is zero there is no point to query the asset since a zero balance has zero value.\n                if ((creditBalances[i] = _withdrawableFrom(position)) == 0) continue;\n                creditAssets[i] = _assetOf(position);\n            }\n            assets = priceRouter.getValues(creditAssets, creditBalances, asset);\n        } else {\n            uint256 numOfDebtPositions = debtPositions.length;\n            ERC20[] memory debtAssets = new ERC20[](numOfDebtPositions);\n            uint256[] memory debtBalances = new uint256[](numOfDebtPositions);\n            for (uint256 i; i < numOfCreditPositions; ++i) {\n                uint32 position = creditPositions[i];\n                // If the balance is zero there is no point to query the asset since a zero balance has zero value.\n                if ((creditBalances[i] = _balanceOf(position)) == 0) continue;\n                creditAssets[i] = _assetOf(position);\n            }\n            for (uint256 i; i < numOfDebtPositions; ++i) {\n                uint32 position = debtPositions[i];\n                // If the balance is zero there is no point to query the asset since a zero balance has zero value.\n                if ((debtBalances[i] = _balanceOf(position)) == 0) continue;\n                debtAssets[i] = _assetOf(position);\n            }\n            assets = priceRouter.getValuesDelta(creditAssets, creditBalances, debtAssets, debtBalances, asset);\n        }\n    }\n\n    /**\n     * @notice The total amount of assets in the cellar.\n     * @dev EIP4626 states totalAssets needs to be inclusive of fees.\n     * Since performance fees mint shares, total assets remains unchanged,\n     * so this implementation is inclusive of fees even though it does not explicitly show it.\n     * @dev EIP4626 states totalAssets must not revert, but it is possible for `totalAssets` to revert\n     * so it does NOT conform to ERC4626 standards.\n     * @dev Run a re-entrancy check because totalAssets can be wrong if re-entering from deposit/withdraws.\n     */\n    function totalAssets() public view override returns (uint256 assets) {\n        _checkIfPaused();\n        require(!locked, \"REENTRANCY\");\n        assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);\n    }\n\n    /**\n     * @notice The total amount of withdrawable assets in the cellar.\n     * @dev Run a re-entrancy check because totalAssetsWithdrawable can be wrong if re-entering from deposit/withdraws.\n     */\n    function totalAssetsWithdrawable() public view returns (uint256 assets) {\n        _checkIfPaused();\n        require(!locked, \"REENTRANCY\");\n        assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(true);\n    }\n\n    /**\n     * @notice The amount of assets that the cellar would exchange for the amount of shares provided.\n     * @dev Use preview functions to get accurate assets.\n     * @dev Under estimates assets.\n     * @param shares amount of shares to convert\n     * @return assets the shares can be exchanged for\n     */\n    function convertToAssets(uint256 shares) public view override returns (uint256 assets) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n        assets = _convertToAssets(shares, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice The amount of shares that the cellar would exchange for the amount of assets provided.\n     * @dev Use preview functions to get accurate shares.\n     * @dev Under estimates shares.\n     * @param assets amount of assets to convert\n     * @return shares the assets can be exchanged for\n     */\n    function convertToShares(uint256 assets) public view override returns (uint256 shares) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n        shares = _convertToShares(assets, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice Simulate the effects of minting shares at the current block, given current on-chain conditions.\n     * @param shares amount of shares to mint\n     * @return assets that will be deposited\n     */\n    function previewMint(uint256 shares) public view override returns (uint256 assets) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n        assets = _previewMint(shares, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice Simulate the effects of withdrawing assets at the current block, given current on-chain conditions.\n     * @param assets amount of assets to withdraw\n     * @return shares that will be redeemed\n     */\n    function previewWithdraw(uint256 assets) public view override returns (uint256 shares) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice Simulate the effects of depositing assets at the current block, given current on-chain conditions.\n     * @param assets amount of assets to deposit\n     * @return shares that will be minted\n     */\n    function previewDeposit(uint256 assets) public view override returns (uint256 shares) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n        shares = _convertToShares(assets, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice Simulate the effects of redeeming shares at the current block, given current on-chain conditions.\n     * @param shares amount of shares to redeem\n     * @return assets that will be returned\n     */\n    function previewRedeem(uint256 shares) public view override returns (uint256 assets) {\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n        assets = _convertToAssets(shares, _totalAssets, _totalSupply);\n    }\n\n    /**\n     * @notice Finds the max amount of value an `owner` can remove from the cellar.\n     * @param owner address of the user to find max value.\n     * @param inShares if false, then returns value in terms of assets\n     *                 if true then returns value in terms of shares\n     */\n    function _findMax(address owner, bool inShares) internal view virtual returns (uint256 maxOut) {\n        _checkIfPaused();\n        // Get amount of assets to withdraw.\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);\n        uint256 assets = _convertToAssets(balanceOf[owner], _totalAssets, _totalSupply);\n\n        uint256 withdrawable = _calculateTotalAssetsOrTotalAssetsWithdrawable(true);\n        maxOut = assets <= withdrawable ? assets : withdrawable;\n\n        if (inShares) maxOut = _convertToShares(maxOut, _totalAssets, _totalSupply);\n        // else leave maxOut in terms of assets.\n    }\n\n    /**\n     * @notice Returns the max amount withdrawable by a user inclusive of performance fees\n     * @dev EIP4626 states maxWithdraw must not revert, but it is possible for `totalAssets` to revert\n     * so it does NOT conform to ERC4626 standards.\n     * @param owner address to check maxWithdraw of.\n     * @return the max amount of assets withdrawable by `owner`.\n     */\n    function maxWithdraw(address owner) public view override returns (uint256) {\n        require(!locked, \"REENTRANCY\");\n        return _findMax(owner, false);\n    }\n\n    /**\n     * @notice Returns the max amount shares redeemable by a user\n     * @dev EIP4626 states maxRedeem must not revert, but it is possible for `totalAssets` to revert\n     * so it does NOT conform to ERC4626 standards.\n     * @param owner address to check maxRedeem of.\n     * @return the max amount of shares redeemable by `owner`.\n     */\n    function maxRedeem(address owner) public view override returns (uint256) {\n        require(!locked, \"REENTRANCY\");\n        return _findMax(owner, true);\n    }\n\n    /**\n     * @dev Used to more efficiently convert amount of shares to assets using a stored `totalAssets` value.\n     */\n    function _convertToAssets(uint256 shares, uint256 _totalAssets, uint256 _totalSupply)\n        internal\n        pure\n        returns (uint256 assets)\n    {\n        assets = shares.mulDivDown(_totalAssets, _totalSupply);\n    }\n\n    /**\n     * @dev Used to more efficiently convert amount of assets to shares using a stored `totalAssets` value.\n     */\n    function _convertToShares(uint256 assets, uint256 _totalAssets, uint256 _totalSupply)\n        internal\n        pure\n        returns (uint256 shares)\n    {\n        shares = assets.mulDivDown(_totalSupply, _totalAssets);\n    }\n\n    /**\n     * @dev Used to more efficiently simulate minting shares using a stored `totalAssets` value.\n     */\n    function _previewMint(uint256 shares, uint256 _totalAssets, uint256 _totalSupply)\n        internal\n        pure\n        returns (uint256 assets)\n    {\n        assets = shares.mulDivUp(_totalAssets, _totalSupply);\n    }\n\n    /**\n     * @dev Used to more efficiently simulate withdrawing assets using a stored `totalAssets` value.\n     */\n    function _previewWithdraw(uint256 assets, uint256 _totalAssets, uint256 _totalSupply)\n        internal\n        pure\n        returns (uint256 shares)\n    {\n        shares = assets.mulDivUp(_totalSupply, _totalAssets);\n    }\n\n    // =========================================== ADAPTOR LOGIC ===========================================\n\n    /**\n     * @notice Emitted on when the rebalance deviation is changed.\n     * @param oldDeviation the old rebalance deviation\n     * @param newDeviation the new rebalance deviation\n     */\n    event RebalanceDeviationChanged(uint256 oldDeviation, uint256 newDeviation);\n\n    /**\n     * @notice totalAssets deviated outside the range set by `allowedRebalanceDeviation`.\n     * @param assets the total assets in the cellar\n     * @param min the minimum allowed assets\n     * @param max the maximum allowed assets\n     */\n    error Cellar__TotalAssetDeviatedOutsideRange(uint256 assets, uint256 min, uint256 max);\n\n    /**\n     * @notice Total shares in a cellar changed when they should stay constant.\n     * @param current the current amount of total shares\n     * @param expected the expected amount of total shares\n     */\n    error Cellar__TotalSharesMustRemainConstant(uint256 current, uint256 expected);\n\n    /**\n     * @notice Total shares in a cellar changed when they should stay constant.\n     * @param requested the requested rebalance  deviation\n     * @param max the max rebalance deviation.\n     */\n    error Cellar__InvalidRebalanceDeviation(uint256 requested, uint256 max);\n\n    /**\n     * @notice Strategist attempted to use an adaptor that is either paused or is not trusted by governance.\n     * @param adaptor the adaptor address that is paused or not trusted.\n     */\n    error Cellar__CallToAdaptorNotAllowed(address adaptor);\n\n    /**\n     * @notice Stores the max possible rebalance deviation for this cellar.\n     */\n    uint64 internal constant MAX_REBALANCE_DEVIATION = 0.1e18;\n\n    /**\n     * @notice The percent the total assets of a cellar may deviate during a `callOnAdaptor`(rebalance) call.\n     */\n    uint256 internal allowedRebalanceDeviation = 0.0003e18;\n\n    /**\n     * @notice Allows governance to change this cellars rebalance deviation.\n     * @param newDeviation the new rebalance deviation value.\n     * @dev Callable by Sommelier Governance.\n     */\n    function setRebalanceDeviation(uint256 newDeviation) external {\n        _isAuthorized();\n        if (newDeviation > MAX_REBALANCE_DEVIATION) {\n            revert Cellar__InvalidRebalanceDeviation(newDeviation, MAX_REBALANCE_DEVIATION);\n        }\n\n        uint256 oldDeviation = allowedRebalanceDeviation;\n        allowedRebalanceDeviation = newDeviation;\n\n        emit RebalanceDeviationChanged(oldDeviation, newDeviation);\n    }\n\n    /**\n     * @notice Struct used to make calls to adaptors.\n     * @param adaptor the address of the adaptor to make calls to\n     * @param the abi encoded function calls to make to the `adaptor`\n     */\n    struct AdaptorCall {\n        address adaptor;\n        bytes[] callData;\n    }\n\n    /**\n     * @notice Emitted when adaptor calls are made.\n     */\n    event AdaptorCalled(address adaptor, bytes data);\n\n    /**\n     * @notice Internal helper function that accepts an Adaptor Call array, and makes calls to each adaptor.\n     */\n    function _makeAdaptorCalls(AdaptorCall[] memory data) internal {\n        for (uint256 i = 0; i < data.length; ++i) {\n            address adaptor = data[i].adaptor;\n            // Revert if adaptor not in catalogue, or adaptor is paused.\n            if (!adaptorCatalogue[adaptor]) revert Cellar__CallToAdaptorNotAllowed(adaptor);\n            for (uint256 j = 0; j < data[i].callData.length; j++) {\n                adaptor.functionDelegateCall(data[i].callData[j]);\n                emit AdaptorCalled(adaptor, data[i].callData[j]);\n            }\n        }\n    }\n\n    /**\n     * @notice Allows strategists to manage their Cellar using arbitrary logic calls to adaptors.\n     * @dev There are several safety checks in this function to prevent strategists from abusing it.\n     *      - `blockExternalReceiver`\n     *      - `totalAssets` must not change by much\n     *      - `totalShares` must remain constant\n     *      - adaptors must be set up to be used with this cellar\n     * @dev Since `totalAssets` is allowed to deviate slightly, strategists could abuse this by sending\n     *      multiple `callOnAdaptor` calls rapidly, to gradually change the share price.\n     *      To mitigate this, rate limiting will be put in place on the Sommelier side.\n     * @dev Callable by Sommelier Strategist, and Automation Actions contract.\n     */\n    function callOnAdaptor(AdaptorCall[] calldata data) external virtual nonReentrant {\n        _isAuthorized();\n        _whenNotShutdown();\n        _checkIfPaused();\n        blockExternalReceiver = true;\n\n        // Record `totalAssets` and `totalShares` before making any external calls.\n        uint256 minimumAllowedAssets;\n        uint256 maximumAllowedAssets;\n        uint256 totalShares;\n        {\n            uint256 assetsBeforeAdaptorCall = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);\n            minimumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 - allowedRebalanceDeviation), 1e18);\n            maximumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 + allowedRebalanceDeviation), 1e18);\n            totalShares = totalSupply;\n        }\n\n        // Run all adaptor calls.\n        _makeAdaptorCalls(data);\n\n        // After making every external call, check that the totalAssets has not deviated significantly, and that totalShares is the same.\n        uint256 assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);\n        if (assets < minimumAllowedAssets || assets > maximumAllowedAssets) {\n            revert Cellar__TotalAssetDeviatedOutsideRange(assets, minimumAllowedAssets, maximumAllowedAssets);\n        }\n        if (totalShares != totalSupply) revert Cellar__TotalSharesMustRemainConstant(totalSupply, totalShares);\n\n        blockExternalReceiver = false;\n    }\n\n    // ============================================ LIMITS LOGIC ============================================\n\n    /**\n     * @notice Attempted entry would raise totalSupply above Share Supply Cap.\n     */\n    error Cellar__ShareSupplyCapExceeded();\n\n    /**\n     * @notice Proposed share supply cap is not logical.\n     */\n    error Cellar__InvalidShareSupplyCap();\n\n    /**\n     * @notice Increases the share supply cap.\n     * @dev Callable by Sommelier Governance.\n     */\n    function increaseShareSupplyCap(uint192 _newShareSupplyCap) public {\n        _isAuthorized();\n        if (_newShareSupplyCap < shareSupplyCap) revert Cellar__InvalidShareSupplyCap();\n\n        shareSupplyCap = _newShareSupplyCap;\n    }\n\n    /**\n     * @notice Decreases the share supply cap.\n     * @dev Callable by Sommelier Strategist.\n     */\n    function decreaseShareSupplyCap(uint192 _newShareSupplyCap) public {\n        _isAuthorized();\n        if (_newShareSupplyCap > shareSupplyCap) revert Cellar__InvalidShareSupplyCap();\n\n        shareSupplyCap = _newShareSupplyCap;\n    }\n\n    /**\n     * @notice Total amount of assets that can be deposited for a user.\n     * @return assets maximum amount of assets that can be deposited\n     */\n    function maxDeposit(address) public view override returns (uint256) {\n        if (isShutdown) return 0;\n\n        uint192 _cap = shareSupplyCap;\n        if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max;\n\n        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);\n        if (_totalSupply >= _cap) {\n            return 0;\n        } else {\n            uint256 shareDelta = _cap - _totalSupply;\n            return _convertToAssets(shareDelta, _totalAssets, _totalSupply);\n        }\n    }\n\n    /**\n     * @notice Total amount of shares that can be minted for a user.\n     * @return shares maximum amount of shares that can be minted\n     */\n    function maxMint(address) public view override returns (uint256) {\n        if (isShutdown) return 0;\n\n        uint192 _cap;\n        if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max;\n\n        uint256 _totalSupply = totalSupply;\n\n        return _totalSupply >= _cap ? 0 : _cap - _totalSupply;\n    }\n\n    // ========================================== HELPER FUNCTIONS ==========================================\n\n    /**\n     * @dev Deposit into a position according to its position type and update related state.\n     * @param position address to deposit funds into\n     * @param assets the amount of assets to deposit into the position\n     */\n    function _depositTo(uint32 position, uint256 assets) internal {\n        address adaptor = getPositionData[position].adaptor;\n        adaptor.functionDelegateCall(\n            abi.encodeWithSelector(\n                BaseAdaptor.deposit.selector,\n                assets,\n                getPositionData[position].adaptorData,\n                getPositionData[position].configurationData\n            )\n        );\n    }\n\n    /**\n     * @dev Withdraw from a position according to its position type and update related state.\n     * @param position address to withdraw funds from\n     * @param assets the amount of assets to withdraw from the position\n     * @param receiver the address to sent withdrawn assets to\n     */\n    function _withdrawFrom(uint32 position, uint256 assets, address receiver) internal {\n        address adaptor = getPositionData[position].adaptor;\n        adaptor.functionDelegateCall(\n            abi.encodeWithSelector(\n                BaseAdaptor.withdraw.selector,\n                assets,\n                receiver,\n                getPositionData[position].adaptorData,\n                getPositionData[position].configurationData\n            )\n        );\n    }\n\n    /**\n     * @dev Get the withdrawable balance of a position according to its position type.\n     * @param position position to get the withdrawable balance of\n     */\n    function _withdrawableFrom(uint32 position) internal view returns (uint256) {\n        // Debt positions always return 0 for their withdrawable.\n        if (getPositionData[position].isDebt) return 0;\n        return BaseAdaptor(getPositionData[position].adaptor).withdrawableFrom(\n            getPositionData[position].adaptorData, getPositionData[position].configurationData\n        );\n    }\n\n    /**\n     * @dev Get the balance of a position according to its position type.\n     * @dev For ERC4626 position balances, this uses `previewRedeem` as opposed\n     *      to `convertToAssets` so that balanceOf ERC4626 positions includes fees taken on withdraw.\n     * @param position position to get the balance of\n     */\n    function _balanceOf(uint32 position) internal view returns (uint256) {\n        address adaptor = getPositionData[position].adaptor;\n        return BaseAdaptor(adaptor).balanceOf(getPositionData[position].adaptorData);\n    }\n\n    /**\n     * @dev Get the asset of a position according to its position type.\n     * @param position to get the asset of\n     */\n    function _assetOf(uint32 position) internal view returns (ERC20) {\n        address adaptor = getPositionData[position].adaptor;\n        return BaseAdaptor(adaptor).assetOf(getPositionData[position].adaptorData);\n    }\n\n    /**\n     * @notice Attempted to use an address from the registry, but address was not expected.\n     */\n    error Cellar__ExpectedAddressDoesNotMatchActual();\n\n    /**\n     * @notice Attempted to set an address to registry Id 0.\n     */\n    error Cellar__SettingValueToRegistryIdZeroIsProhibited();\n\n    /**\n     * @notice Verify that `_registryId` in registry corresponds to expected address.\n     */\n    function _checkRegistryAddressAgainstExpected(uint256 _registryId, address _expected) internal view {\n        if (_registryId == 0) revert Cellar__SettingValueToRegistryIdZeroIsProhibited();\n        if (registry.getAddress(_registryId) != _expected) revert Cellar__ExpectedAddressDoesNotMatchActual();\n    }\n}\n"
      },
      "src/modules/price-router/PriceRouter.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { SafeTransferLib } from \"@solmate/utils/SafeTransferLib.sol\";\nimport { ERC20 } from \"@solmate/tokens/ERC20.sol\";\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IChainlinkAggregator } from \"src/interfaces/external/IChainlinkAggregator.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport { Math } from \"src/utils/Math.sol\";\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { Extension } from \"src/modules/price-router/Extensions/Extension.sol\";\nimport { Registry } from \"src/Registry.sol\";\n\nimport { UniswapV3Pool } from \"src/interfaces/external/UniswapV3Pool.sol\";\nimport { OracleLibrary } from \"@uniswapV3P/libraries/OracleLibrary.sol\";\n\n/**\n * @title Sommelier Price Router\n * @notice Provides a universal interface allowing Sommelier contracts to retrieve secure pricing\n *         data from Chainlink.\n * @author crispymangoes\n */\ncontract PriceRouter is Ownable {\n    using SafeTransferLib for ERC20;\n    using SafeCast for int256;\n    using Math for uint256;\n    using Address for address;\n\n    event AddAsset(address indexed asset);\n\n    event IntentToEditAsset(\n        address asset,\n        AssetSettings _settings,\n        bytes _storage,\n        bytes32 editHash,\n        uint256 assetEditableAt\n    );\n\n    event EditAssetCancelled(address asset, bytes32 editHash);\n\n    event EditAssetComplete(address asset, bytes32 editHash);\n\n    Registry public immutable registry;\n    ERC20 public immutable WETH;\n\n    constructor(address newOwner, Registry _registry, ERC20 _weth) {\n        registry = _registry;\n        WETH = _weth;\n        transferOwnership(newOwner);\n    }\n\n    // =========================================== ASSETS CONFIG ===========================================\n    /**\n     * @notice Bare minimum settings all derivatives support.\n     * @param derivative the derivative used to price the asset\n     * @param source the address used to price the asset\n     */\n    struct AssetSettings {\n        uint8 derivative;\n        address source;\n    }\n\n    /**\n     * @notice Mapping between an asset to price and its `AssetSettings`.\n     */\n    mapping(ERC20 => AssetSettings) public getAssetSettings;\n\n    // ======================================= OWNERSHIP TRANSISITION =======================================\n\n    /**\n     * @notice Emitted when an ownership transition is started.\n     */\n    event OwnerTransitionStarted(address newOwner, uint256 startTime);\n\n    /**\n     * @notice Emitted when an ownership transition is cancelled.\n     */\n    event OwnerTransitionCancelled();\n\n    /**\n     * @notice Emitted when an ownership transition is completed.\n     */\n    event OwnerTransitionComplete(address newOwner);\n\n    /**\n     * @notice Attempted to call a function intended for Zero Id address.\n     */\n    error PriceRouter__OnlyCallableByZeroId();\n\n    /**\n     * @notice Attempted to transition owner to the zero address.\n     */\n    error PriceRouter__NewOwnerCanNotBeZero();\n\n    /**\n     * @notice Attempted to perform a restricted action while ownership transition is pending.\n     */\n    error PriceRouter__TransitionPending();\n\n    /**\n     * @notice Attempted to cancel or complete a transition when one is not active.\n     */\n    error PriceRouter__TransitionNotPending();\n\n    /**\n     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.\n     */\n    error PriceRouter__OnlyCallableByPendingOwner();\n\n    /**\n     * @notice The amount of time it takes for an ownership transition to work.\n     */\n    uint256 public constant TRANSITION_PERIOD = 7 days;\n\n    /**\n     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.\n     */\n    address public pendingOwner;\n\n    /**\n     * @notice The starting time stamp of the transition.\n     */\n    uint256 public transitionStart;\n\n    /**\n     * @notice Allows Zero Id address to set a new owner, after the transition period is up.\n     */\n    function transitionOwner(address newOwner) external {\n        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();\n        if (pendingOwner != address(0)) revert PriceRouter__TransitionPending();\n        if (newOwner == address(0)) revert PriceRouter__NewOwnerCanNotBeZero();\n\n        pendingOwner = newOwner;\n        transitionStart = block.timestamp;\n    }\n\n    /**\n     * @notice Allows Zero Id address to cancel an ongoing owner transition.\n     */\n    function cancelTransition() external {\n        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();\n        if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending();\n\n        pendingOwner = address(0);\n        transitionStart = 0;\n    }\n\n    /**\n     * @notice Allows pending owner to complete the ownership transition.\n     */\n    function completeTransition() external {\n        if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending();\n        if (msg.sender != pendingOwner) revert PriceRouter__OnlyCallableByPendingOwner();\n        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert PriceRouter__TransitionPending();\n\n        _transferOwnership(pendingOwner);\n\n        pendingOwner = address(0);\n        transitionStart = 0;\n    }\n\n    /**\n     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.\n     */\n    function _checkOwner() internal view override {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        if (transitionStart != 0) revert PriceRouter__TransitionPending();\n    }\n\n    // ======================================= ASSET OPERATIONS =======================================\n\n    /**\n     * @notice Attempted to set a minimum price below the Chainlink minimum price (with buffer).\n     * @param minPrice minimum price attempted to set\n     * @param bufferedMinPrice minimum price that can be set including buffer\n     */\n    error PriceRouter__InvalidMinPrice(uint256 minPrice, uint256 bufferedMinPrice);\n\n    /**\n     * @notice Attempted to set a maximum price above the Chainlink maximum price (with buffer).\n     * @param maxPrice maximum price attempted to set\n     * @param bufferedMaxPrice maximum price that can be set including buffer\n     */\n    error PriceRouter__InvalidMaxPrice(uint256 maxPrice, uint256 bufferedMaxPrice);\n\n    /**\n     * @notice Attempted to add an invalid asset.\n     * @param asset address of the invalid asset\n     */\n    error PriceRouter__InvalidAsset(address asset);\n\n    /**\n     * @notice Attempted to add an asset that is already supported.\n     */\n    error PriceRouter__AssetAlreadyAdded(address asset);\n\n    /**\n     * @notice Attempted to edit an asset that is not supported.\n     */\n    error PriceRouter__AssetNotAdded(address asset);\n\n    /**\n     * @notice Attempted to edit an asset that is not editable.\n     */\n    error PriceRouter__AssetNotEditable(address asset);\n\n    /**\n     * @notice Attempted to cancel the editing of an asset that is not pending edit.\n     */\n    error PriceRouter__AssetNotPendingEdit(address asset);\n\n    /**\n     * @notice Attempted to add an asset, but actual answer was outside range of expectedAnswer.\n     */\n    error PriceRouter__BadAnswer(uint256 answer, uint256 expectedAnswer);\n\n    /**\n     * @notice Attempted to perform an operation using an unknown derivative.\n     */\n    error PriceRouter__UnknownDerivative(uint8 unknownDerivative);\n\n    /**\n     * @notice Attempted to add an asset with invalid min/max prices.\n     * @param min price\n     * @param max price\n     */\n    error PriceRouter__MinPriceGreaterThanMaxPrice(uint256 min, uint256 max);\n\n    /**\n     * @notice The allowed deviation between the expected answer vs the actual answer.\n     */\n    uint256 public constant EXPECTED_ANSWER_DEVIATION = 0.02e18;\n\n    /**\n     * @notice The amount of time that must pass between owner calling `startEditAsset`, and `completeEditAsset`.\n     */\n    uint64 public constant EDIT_ASSET_DELAY = 7 days;\n\n    /**\n     * @notice Stores the timestamp when an asset can be editted.\n     */\n    mapping(bytes32 => uint256) public assetEditableTimestamp;\n\n    /**\n     * @notice Allows owner to add assets to the price router.\n     * @dev Performs a sanity check by comparing the price router computed price to\n     * a user input `_expectedAnswer`.\n     * @param _asset the asset to add to the pricing router\n     * @param _settings the settings for `_asset`\n     *        @dev The `derivative` value in settings MUST be non zero.\n     * @param _storage arbitrary bytes data used to configure `_asset` pricing\n     * @param _expectedAnswer the expected answer for the asset from  `_getPriceInUSD`\n     */\n    function addAsset(\n        ERC20 _asset,\n        AssetSettings memory _settings,\n        bytes memory _storage,\n        uint256 _expectedAnswer\n    ) external onlyOwner {\n        // Check that asset is not already added.\n        if (getAssetSettings[_asset].derivative > 0) revert PriceRouter__AssetAlreadyAdded(address(_asset));\n\n        _updateAsset(_asset, _settings, _storage, _expectedAnswer);\n\n        emit AddAsset(address(_asset));\n    }\n\n    /**\n     * @notice Allows owner to start the edit asset process.\n     * @dev Saves a hash of the inputs, and maps it to the timestamp when `_asset` is editable.\n     * @param _asset the asset to edit in the pricing router\n     * @param _settings the settings for `_asset`\n     *        @dev The `derivative` value in settings MUST be non zero.\n     * @param _storage arbitrary bytes data used to configure `_asset` pricing\n     */\n    function startEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner {\n        // Make sure the asset has been added.\n        if (getAssetSettings[_asset].derivative == 0) revert PriceRouter__AssetNotAdded(address(_asset));\n        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));\n\n        uint256 assetEditableAt = block.timestamp + EDIT_ASSET_DELAY;\n        assetEditableTimestamp[editHash] = assetEditableAt;\n\n        emit IntentToEditAsset(address(_asset), _settings, _storage, editHash, assetEditableAt);\n    }\n\n    /**\n     * @notice Once `EDIT_ASSET_DELAY` has passed, `_asset` is now editable using the\n     *         same inputs given to `startEditAsset`.\n     * @param _asset the asset to finish editing in the pricing router\n     * @param _settings the settings for `_asset`\n     *        @dev The `derivative` value in settings MUST be non zero.\n     * @param _storage arbitrary bytes data used to configure `_asset` pricing\n     */\n    function completeEditAsset(\n        ERC20 _asset,\n        AssetSettings memory _settings,\n        bytes memory _storage,\n        uint256 _expectedAnswer\n    ) external onlyOwner {\n        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));\n\n        // Make sure asset can be edited.\n        uint256 assetEditableAt = assetEditableTimestamp[editHash];\n        if (assetEditableAt == 0 || block.timestamp < assetEditableAt)\n            revert PriceRouter__AssetNotEditable(address(_asset));\n\n        // Reset edit timestamp.\n        assetEditableTimestamp[editHash] = 0;\n\n        // Edit the asset.\n        _updateAsset(_asset, _settings, _storage, _expectedAnswer);\n\n        emit EditAssetComplete(address(_asset), editHash);\n    }\n\n    /**\n     * @notice Cancel a pending edit for `_asset`.\n     * @param _asset the asset to cancel editing of in the pricing router\n     * @param _settings the settings for `_asset`\n     *        @dev The `derivative` value in settings MUST be non zero.\n     * @param _storage arbitrary bytes data used to configure `_asset` pricing\n     */\n    function cancelEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner {\n        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));\n\n        // Make sure asset is pending edit.\n        uint256 assetEditableAt = assetEditableTimestamp[editHash];\n        if (assetEditableAt == 0) revert PriceRouter__AssetNotPendingEdit(address(_asset));\n\n        assetEditableTimestamp[editHash] = 0;\n\n        emit EditAssetCancelled(address(_asset), editHash);\n    }\n\n    /**\n     * @notice Helper function to update an `_asset`s configuration.\n     * @param _asset the asset to update in the pricing router\n     * @param _settings the settings for `_asset`\n     *        @dev The `derivative` value in settings MUST be non zero.\n     * @param _storage arbitrary bytes data used to configure `_asset` pricing\n     */\n    function _updateAsset(\n        ERC20 _asset,\n        AssetSettings memory _settings,\n        bytes memory _storage,\n        uint256 _expectedAnswer\n    ) internal {\n        if (address(_asset) == address(0)) revert PriceRouter__InvalidAsset(address(_asset));\n\n        // Zero is an invalid derivative.\n        if (_settings.derivative == 0) revert PriceRouter__UnknownDerivative(_settings.derivative);\n\n        // Call setup function for appropriate derivative.\n        if (_settings.derivative == 1) {\n            _setupPriceForChainlinkDerivative(_asset, _settings.source, _storage);\n        } else if (_settings.derivative == 2) {\n            _setupPriceForTwapDerivative(_asset, _settings.source, _storage);\n        } else if (_settings.derivative == 3) {\n            Extension(_settings.source).setupSource(_asset, _storage);\n        } else revert PriceRouter__UnknownDerivative(_settings.derivative);\n\n        // Check `_getPriceInUSD` against `_expectedAnswer`.\n        uint256 minAnswer = _expectedAnswer.mulWadDown((1e18 - EXPECTED_ANSWER_DEVIATION));\n        uint256 maxAnswer = _expectedAnswer.mulWadDown((1e18 + EXPECTED_ANSWER_DEVIATION));\n\n        getAssetSettings[_asset] = _settings;\n        uint256 answer = _getPriceInUSD(_asset, _settings);\n        if (answer < minAnswer || answer > maxAnswer) revert PriceRouter__BadAnswer(answer, _expectedAnswer);\n    }\n\n    /**\n     * @notice return bool indicating whether or not an asset has been set up.\n     * @dev Since `addAsset` enforces the derivative is non zero, checking if the stored setting\n     *      is nonzero is sufficient to see if the asset is set up.\n     */\n    function isSupported(ERC20 asset) external view returns (bool) {\n        return getAssetSettings[asset].derivative > 0;\n    }\n\n    // ======================================= PRICING OPERATIONS =======================================\n\n    /**\n     * @notice Get `asset` price in USD.\n     * @dev Returns price in USD with 8 decimals.\n     */\n    function getPriceInUSD(ERC20 asset) external view returns (uint256) {\n        AssetSettings memory assetSettings = getAssetSettings[asset];\n        return _getPriceInUSD(asset, assetSettings);\n    }\n\n    /**\n     * @notice Get multiple `asset` prices in USD.\n     * @dev Returns array of prices in USD with 8 decimals.\n     */\n    function getPricesInUSD(ERC20[] calldata assets) external view returns (uint256[] memory prices) {\n        prices = new uint256[](assets.length);\n        for (uint256 i; i < assets.length; ++i) {\n            AssetSettings memory assetSettings = getAssetSettings[assets[i]];\n            prices[i] = _getPriceInUSD(assets[i], assetSettings);\n        }\n    }\n\n    /**\n     * @notice Get the value of an asset in terms of another asset.\n     * @param baseAsset address of the asset to get the price of in terms of the quote asset\n     * @param amount amount of the base asset to price\n     * @param quoteAsset address of the asset that the base asset is priced in terms of\n     * @return value value of the amount of base assets specified in terms of the quote asset\n     */\n    function getValue(ERC20 baseAsset, uint256 amount, ERC20 quoteAsset) external view returns (uint256 value) {\n        AssetSettings memory baseSettings = getAssetSettings[baseAsset];\n        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];\n        if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));\n        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));\n        uint256 priceBaseUSD = _getPriceInUSD(baseAsset, baseSettings);\n        uint256 priceQuoteUSD = _getPriceInUSD(quoteAsset, quoteSettings);\n        value = _getValueInQuote(priceBaseUSD, priceQuoteUSD, baseAsset.decimals(), quoteAsset.decimals(), amount);\n    }\n\n    /**\n     * @notice Helper function that compares `_getValues` between input 0 and input 1.\n     */\n    function getValuesDelta(\n        ERC20[] calldata baseAssets0,\n        uint256[] calldata amounts0,\n        ERC20[] calldata baseAssets1,\n        uint256[] calldata amounts1,\n        ERC20 quoteAsset\n    ) external view returns (uint256) {\n        uint256 value0 = _getValues(baseAssets0, amounts0, quoteAsset);\n        uint256 value1 = _getValues(baseAssets1, amounts1, quoteAsset);\n        return value0 - value1;\n    }\n\n    /**\n     * @notice Helper function that determines the value of assets using `_getValues`.\n     */\n    function getValues(\n        ERC20[] calldata baseAssets,\n        uint256[] calldata amounts,\n        ERC20 quoteAsset\n    ) external view returns (uint256) {\n        return _getValues(baseAssets, amounts, quoteAsset);\n    }\n\n    /**\n     * @notice Get the exchange rate between two assets.\n     * @param baseAsset address of the asset to get the exchange rate of in terms of the quote asset\n     * @param quoteAsset address of the asset that the base asset is exchanged for\n     * @return exchangeRate rate of exchange between the base asset and the quote asset\n     */\n    function getExchangeRate(ERC20 baseAsset, ERC20 quoteAsset) public view returns (uint256 exchangeRate) {\n        AssetSettings memory baseSettings = getAssetSettings[baseAsset];\n        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];\n        if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));\n        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));\n\n        exchangeRate = _getExchangeRate(baseAsset, baseSettings, quoteAsset, quoteSettings, quoteAsset.decimals());\n    }\n\n    /**\n     * @notice Get the exchange rates between multiple assets and another asset.\n     * @param baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset\n     * @param quoteAsset address of the asset that the base assets are exchanged for\n     * @return exchangeRates rate of exchange between the base assets and the quote asset\n     */\n    function getExchangeRates(\n        ERC20[] memory baseAssets,\n        ERC20 quoteAsset\n    ) external view returns (uint256[] memory exchangeRates) {\n        uint8 quoteAssetDecimals = quoteAsset.decimals();\n        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];\n        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));\n\n        uint256 numOfAssets = baseAssets.length;\n        exchangeRates = new uint256[](numOfAssets);\n        for (uint256 i; i < numOfAssets; ++i) {\n            AssetSettings memory baseSettings = getAssetSettings[baseAssets[i]];\n            if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAssets[i]));\n            exchangeRates[i] = _getExchangeRate(\n                baseAssets[i],\n                baseSettings,\n                quoteAsset,\n                quoteSettings,\n                quoteAssetDecimals\n            );\n        }\n    }\n\n    // =========================================== HELPER FUNCTIONS ===========================================\n\n    /**\n     * @notice Attempted to update the asset to one that is not supported by the platform.\n     * @param asset address of the unsupported asset\n     */\n    error PriceRouter__UnsupportedAsset(address asset);\n\n    /**\n     * @notice Gets the exchange rate between a base and a quote asset\n     * @param baseAsset the asset to convert into quoteAsset\n     * @param quoteAsset the asset base asset is converted into\n     * @return exchangeRate value of base asset in terms of quote asset\n     */\n    function _getExchangeRate(\n        ERC20 baseAsset,\n        AssetSettings memory baseSettings,\n        ERC20 quoteAsset,\n        AssetSettings memory quoteSettings,\n        uint8 quoteAssetDecimals\n    ) internal view returns (uint256) {\n        uint256 basePrice = _getPriceInUSD(baseAsset, baseSettings);\n        uint256 quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);\n        uint256 exchangeRate = basePrice.mulDivDown(10 ** quoteAssetDecimals, quotePrice);\n        return exchangeRate;\n    }\n\n    /**\n     * @notice Helper function to get an assets price in USD.\n     * @dev Returns price in USD with 8 decimals.\n     */\n    function _getPriceInUSD(ERC20 asset, AssetSettings memory settings) internal view returns (uint256) {\n        _runPreFlightCheck();\n        // Call get price function using appropriate derivative.\n        uint256 price;\n        if (settings.derivative == 1) {\n            price = _getPriceForChainlinkDerivative(asset, settings.source);\n        } else if (settings.derivative == 2) {\n            price = _getPriceForTwapDerivative(asset, settings.source);\n        } else if (settings.derivative == 3) {\n            price = Extension(settings.source).getPriceInUSD(asset);\n        } else revert PriceRouter__UnknownDerivative(settings.derivative);\n\n        return price;\n    }\n\n    /**\n     * @notice If any safety checks needs to be run before pricing operations, they should be added here.\n     */\n    function _runPreFlightCheck() internal view virtual {}\n\n    /**\n     * @notice math function that preserves precision by multiplying the amountBase before dividing.\n     * @param priceBaseUSD the base asset price in USD\n     * @param priceQuoteUSD the quote asset price in USD\n     * @param baseDecimals the base asset decimals\n     * @param quoteDecimals the quote asset decimals\n     * @param amountBase the amount of base asset\n     */\n    function _getValueInQuote(\n        uint256 priceBaseUSD,\n        uint256 priceQuoteUSD,\n        uint8 baseDecimals,\n        uint8 quoteDecimals,\n        uint256 amountBase\n    ) internal pure returns (uint256 valueInQuote) {\n        // Get value in quote asset, but maintain as much precision as possible.\n        // Cleaner equations below.\n        // baseToUSD = amountBase * priceBaseUSD / 10**baseDecimals.\n        // valueInQuote = baseToUSD * 10**quoteDecimals / priceQuoteUSD\n        valueInQuote = amountBase.mulDivDown(\n            (priceBaseUSD * 10 ** quoteDecimals),\n            (10 ** baseDecimals * priceQuoteUSD)\n        );\n    }\n\n    /**\n     * @notice Attempted an operation with arrays of unequal lengths that were expected to be equal length.\n     */\n    error PriceRouter__LengthMismatch();\n\n    /**\n     * @notice Get the total value of multiple assets in terms of another asset.\n     * @param baseAssets addresses of the assets to get the price of in terms of the quote asset\n     * @param amounts amounts of each base asset to price\n     * @param quoteAsset address of the assets that the base asset is priced in terms of\n     * @return value total value of the amounts of each base assets specified in terms of the quote asset\n     */\n    function _getValues(\n        ERC20[] calldata baseAssets,\n        uint256[] calldata amounts,\n        ERC20 quoteAsset\n    ) internal view returns (uint256) {\n        if (baseAssets.length != amounts.length) revert PriceRouter__LengthMismatch();\n        uint256 quotePrice;\n        {\n            AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];\n            if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));\n            quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);\n        }\n        uint256 valueInQuote;\n        uint8 quoteDecimals = quoteAsset.decimals();\n\n        for (uint256 i = 0; i < baseAssets.length; ++i) {\n            // Skip zero amount values.\n            if (amounts[i] == 0) continue;\n            ERC20 baseAsset = baseAssets[i];\n            if (baseAsset == quoteAsset) valueInQuote += amounts[i];\n            else {\n                uint256 basePrice;\n                {\n                    AssetSettings memory baseSettings = getAssetSettings[baseAsset];\n                    if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));\n                    basePrice = _getPriceInUSD(baseAsset, baseSettings);\n                }\n                valueInQuote += _getValueInQuote(\n                    basePrice,\n                    quotePrice,\n                    baseAsset.decimals(),\n                    quoteDecimals,\n                    amounts[i]\n                );\n            }\n        }\n        return valueInQuote;\n    }\n\n    // =========================================== CHAINLINK PRICE DERIVATIVE ===========================================\\\n    /**\n     * @notice Stores data for Chainlink derivative assets.\n     * @param max the max valid price of the asset\n     * @param min the min valid price of the asset\n     * @param heartbeat the max amount of time between price updates\n     * @param inETH bool indicating whether the price feed is\n     *        denominated in ETH(true) or USD(false)\n     */\n    struct ChainlinkDerivativeStorage {\n        uint144 max;\n        uint80 min;\n        uint24 heartbeat;\n        bool inETH;\n    }\n\n    /**\n     * @notice Buffered min price exceedes 80 bits of data.\n     */\n    error PriceRouter__BufferedMinOverflow();\n\n    /**\n     * @notice Returns Chainlink Derivative Storage\n     */\n    mapping(ERC20 => ChainlinkDerivativeStorage) public getChainlinkDerivativeStorage;\n\n    /**\n     * @notice If zero is specified for a Chainlink asset heartbeat, this value is used instead.\n     */\n    uint24 public constant DEFAULT_HEART_BEAT = 1 days;\n\n    /**\n     * @notice Setup function for pricing Chainlink derivative assets.\n     * @dev _source The address of the Chainlink Data feed.\n     * @dev _storage A ChainlinkDerivativeStorage value defining valid prices.\n     */\n    function _setupPriceForChainlinkDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {\n        ChainlinkDerivativeStorage memory parameters = abi.decode(_storage, (ChainlinkDerivativeStorage));\n\n        // Use Chainlink to get the min and max of the asset.\n        IChainlinkAggregator aggregator = IChainlinkAggregator(IChainlinkAggregator(_source).aggregator());\n        uint256 minFromChainklink = uint256(uint192(aggregator.minAnswer()));\n        uint256 maxFromChainlink = uint256(uint192(aggregator.maxAnswer()));\n\n        // Add a ~10% buffer to minimum and maximum price from Chainlink because Chainlink can stop updating\n        // its price before/above the min/max price.\n        uint256 bufferedMinPrice = (minFromChainklink * 1.1e18) / 1e18;\n        uint256 bufferedMaxPrice = (maxFromChainlink * 0.9e18) / 1e18;\n\n        if (parameters.min == 0) {\n            // Revert if bufferedMinPrice overflows because uint80 is too small to hold the minimum price,\n            // and lowering it to uint80 is not safe because the price feed can stop being updated before\n            // it actually gets to that lower price.\n            if (bufferedMinPrice > type(uint80).max) revert PriceRouter__BufferedMinOverflow();\n            parameters.min = uint80(bufferedMinPrice);\n        } else {\n            if (parameters.min < bufferedMinPrice)\n                revert PriceRouter__InvalidMinPrice(parameters.min, bufferedMinPrice);\n        }\n\n        if (parameters.max == 0) {\n            //Do not revert even if bufferedMaxPrice is greater than uint144, because lowering it to uint144 max is more conservative.\n            parameters.max = bufferedMaxPrice > type(uint144).max ? type(uint144).max : uint144(bufferedMaxPrice);\n        } else {\n            if (parameters.max > bufferedMaxPrice)\n                revert PriceRouter__InvalidMaxPrice(parameters.max, bufferedMaxPrice);\n        }\n\n        if (parameters.min >= parameters.max)\n            revert PriceRouter__MinPriceGreaterThanMaxPrice(parameters.min, parameters.max);\n\n        parameters.heartbeat = parameters.heartbeat != 0 ? parameters.heartbeat : DEFAULT_HEART_BEAT;\n\n        getChainlinkDerivativeStorage[_asset] = parameters;\n    }\n\n    /**\n     * @notice Get the price of a Chainlink derivative in terms of USD.\n     */\n    function _getPriceForChainlinkDerivative(ERC20 _asset, address _source) internal view returns (uint256) {\n        ChainlinkDerivativeStorage memory parameters = getChainlinkDerivativeStorage[_asset];\n        IChainlinkAggregator aggregator = IChainlinkAggregator(_source);\n        (, int256 _price, , uint256 _timestamp, ) = aggregator.latestRoundData();\n        uint256 price = _price.toUint256();\n        _checkPriceFeed(address(_asset), price, _timestamp, parameters.max, parameters.min, parameters.heartbeat);\n        // If price is in ETH, then convert price into USD.\n        if (parameters.inETH) {\n            uint256 _ethToUsd = _getPriceInUSD(WETH, getAssetSettings[WETH]);\n            price = price.mulWadDown(_ethToUsd);\n        }\n        return price;\n    }\n\n    /**\n     * @notice Attempted an operation to price an asset that under its minimum valid price.\n     * @param asset address of the asset that is under its minimum valid price\n     * @param price price of the asset\n     * @param minPrice minimum valid price of the asset\n     */\n    error PriceRouter__AssetBelowMinPrice(address asset, uint256 price, uint256 minPrice);\n\n    /**\n     * @notice Attempted an operation to price an asset that under its maximum valid price.\n     * @param asset address of the asset that is under its maximum valid price\n     * @param price price of the asset\n     * @param maxPrice maximum valid price of the asset\n     */\n    error PriceRouter__AssetAboveMaxPrice(address asset, uint256 price, uint256 maxPrice);\n\n    /**\n     * @notice Attempted to fetch a price for an asset that has not been updated in too long.\n     * @param asset address of the asset thats price is stale\n     * @param timeSinceLastUpdate seconds since the last price update\n     * @param heartbeat maximum allowed time between price updates\n     */\n    error PriceRouter__StalePrice(address asset, uint256 timeSinceLastUpdate, uint256 heartbeat);\n\n    /**\n     * @notice helper function to validate a price feed is safe to use.\n     * @param asset ERC20 asset price feed data is for.\n     * @param value the price value the price feed gave.\n     * @param timestamp the last timestamp the price feed was updated.\n     * @param max the upper price bound\n     * @param min the lower price bound\n     * @param heartbeat the max amount of time between price updates\n     */\n    function _checkPriceFeed(\n        address asset,\n        uint256 value,\n        uint256 timestamp,\n        uint144 max,\n        uint88 min,\n        uint24 heartbeat\n    ) internal view {\n        if (value < min) revert PriceRouter__AssetBelowMinPrice(address(asset), value, min);\n\n        if (value > max) revert PriceRouter__AssetAboveMaxPrice(address(asset), value, max);\n\n        uint256 timeSinceLastUpdate = block.timestamp - timestamp;\n        if (timeSinceLastUpdate > heartbeat)\n            revert PriceRouter__StalePrice(address(asset), timeSinceLastUpdate, heartbeat);\n    }\n\n    // =========================================== TWAP PRICE DERIVATIVE ===========================================\n\n    /**\n     * @notice Stores data for Twap derivative assets.\n     * @param secondsAgo the twap duration\n     * @param baseDecimals the base assets decimals\n     * @param quoteDecimals the quote assets decimals\n     * @param quoteToken the asset the twap quotes in\n     */\n    struct TwapDerivativeStorage {\n        uint32 secondsAgo;\n        uint8 baseDecimals;\n        uint8 quoteDecimals;\n        ERC20 quoteToken;\n    }\n\n    /**\n     * @notice Tried setting up a Twap for an asset where the underlying pools does not use the asset.\n     */\n    error PriceRouter__TwapAssetNotInPool();\n\n    /**\n     * @notice Provided secondsAgo does not meet minimum,\n     */\n    error PriceRouter__SecondsAgoDoesNotMeetMinimum();\n\n    /**\n     * @notice Returns Twap Derivative Storage\n     */\n    mapping(ERC20 => TwapDerivativeStorage) public getTwapDerivativeStorage;\n\n    /**\n     * @notice The smallest possible TWAP that can be used.\n     */\n    uint32 public constant MINIMUM_SECONDS_AGO = 900;\n\n    /**\n     * @notice Setup function for pricing Twap derivative assets.\n     * @dev Make sure that TWAP assets have sufficient observations, and increase them if not before adding.\n     * @dev _source The address of the Uniswap V3 pool.\n     * @dev _storage A TwapDerivativeStorage value defining valid prices.\n     */\n    function _setupPriceForTwapDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {\n        TwapDerivativeStorage memory parameters = abi.decode(_storage, (TwapDerivativeStorage));\n\n        // Verify seconds ago is reasonable.\n        if (parameters.secondsAgo < MINIMUM_SECONDS_AGO) revert PriceRouter__SecondsAgoDoesNotMeetMinimum();\n\n        UniswapV3Pool pool = UniswapV3Pool(_source);\n\n        ERC20 token0 = ERC20(pool.token0());\n        ERC20 token1 = ERC20(pool.token1());\n        if (token0 == _asset) {\n            parameters.baseDecimals = _asset.decimals();\n            parameters.quoteDecimals = token1.decimals();\n            parameters.quoteToken = token1;\n        } else if (token1 == _asset) {\n            parameters.baseDecimals = _asset.decimals();\n            parameters.quoteDecimals = token0.decimals();\n            parameters.quoteToken = token0;\n        } else revert PriceRouter__TwapAssetNotInPool();\n\n        getTwapDerivativeStorage[_asset] = parameters;\n    }\n\n    /**\n     * @notice Get the price of a Twap derivative in terms of USD.\n     */\n    function _getPriceForTwapDerivative(ERC20 asset, address _source) internal view returns (uint256) {\n        TwapDerivativeStorage memory parameters = getTwapDerivativeStorage[asset];\n        (int24 arithmeticMeanTick, ) = OracleLibrary.consult(_source, parameters.secondsAgo);\n        // Get the amount of quote token each base token is worth.\n        uint256 quoteAmount = OracleLibrary.getQuoteAtTick(\n            arithmeticMeanTick,\n            uint128(10 ** parameters.baseDecimals),\n            address(asset),\n            address(parameters.quoteToken)\n        );\n        uint256 quotePrice = _getPriceInUSD(parameters.quoteToken, getAssetSettings[parameters.quoteToken]);\n        return quoteAmount.mulDivDown(quotePrice, 10 ** parameters.quoteDecimals);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n"
      },
      "src/interfaces/external/IWETH9.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\ninterface IWETH9 {\n    function deposit() external payable;\n\n    function withdraw(uint256 wad) external;\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "lib/solmate/src/mixins/ERC4626.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\nimport {SafeTransferLib} from \"../utils/SafeTransferLib.sol\";\nimport {FixedPointMathLib} from \"../utils/FixedPointMathLib.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n    using SafeTransferLib for ERC20;\n    using FixedPointMathLib for uint256;\n\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed caller,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /*//////////////////////////////////////////////////////////////\n                               IMMUTABLES\n    //////////////////////////////////////////////////////////////*/\n\n    ERC20 public immutable asset;\n\n    constructor(\n        ERC20 _asset,\n        string memory _name,\n        string memory _symbol\n    ) ERC20(_name, _symbol, _asset.decimals()) {\n        asset = _asset;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        DEPOSIT/WITHDRAWAL LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n        // Check for rounding error since we round down in previewDeposit.\n        require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n\n        afterDeposit(assets, shares);\n    }\n\n    function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n        assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n\n        afterDeposit(assets, shares);\n    }\n\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner\n    ) public virtual returns (uint256 shares) {\n        shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        beforeWithdraw(assets, shares);\n\n        _burn(owner, shares);\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n        asset.safeTransfer(receiver, assets);\n    }\n\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner\n    ) public virtual returns (uint256 assets) {\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        // Check for rounding error since we round down in previewRedeem.\n        require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n        beforeWithdraw(assets, shares);\n\n        _burn(owner, shares);\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n        asset.safeTransfer(receiver, assets);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ACCOUNTING LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function totalAssets() public view virtual returns (uint256);\n\n    function convertToShares(uint256 assets) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n    }\n\n    function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n    }\n\n    function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n        return convertToShares(assets);\n    }\n\n    function previewMint(uint256 shares) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n    }\n\n    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n    }\n\n    function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n        return convertToAssets(shares);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                     DEPOSIT/WITHDRAWAL LIMIT LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function maxDeposit(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    function maxMint(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    function maxWithdraw(address owner) public view virtual returns (uint256) {\n        return convertToAssets(balanceOf[owner]);\n    }\n\n    function maxRedeem(address owner) public view virtual returns (uint256) {\n        return balanceOf[owner];\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                          INTERNAL HOOKS LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n    function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n"
      },
      "src/utils/Uint32Array.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\n/**\n * @notice A library to extend the uint32 array data type.\n */\nlibrary Uint32Array {\n    // =========================================== ADDRESS STORAGE ===========================================\n\n    /**\n     * @notice Add an uint32 to the array at a given index.\n     * @param array uint32 array to add the uint32 to\n     * @param index index to add the uint32 at\n     * @param value uint32 to add to the array\n     */\n    function add(uint32[] storage array, uint32 index, uint32 value) internal {\n        uint256 len = array.length;\n\n        if (len > 0) {\n            array.push(array[len - 1]);\n\n            for (uint256 i = len - 1; i > index; i--) array[i] = array[i - 1];\n\n            array[index] = value;\n        } else {\n            array.push(value);\n        }\n    }\n\n    /**\n     * @notice Remove a uint32 from the array at a given index.\n     * @param array uint32 array to remove the uint32 from\n     * @param index index to remove the uint32 at\n     */\n    function remove(uint32[] storage array, uint32 index) internal {\n        uint256 len = array.length;\n\n        require(index < len, \"Index out of bounds\");\n\n        for (uint256 i = index; i < len - 1; i++) array[i] = array[i + 1];\n\n        array.pop();\n    }\n\n    /**\n     * @notice Check whether an array contains an uint32.\n     * @param array uint32 array to check\n     * @param value uint32 to check for\n     */\n    function contains(uint32[] storage array, uint32 value) internal view returns (bool) {\n        for (uint256 i; i < array.length; i++) if (value == array[i]) return true;\n\n        return false;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Receiver.sol\";\n\n/**\n * @dev Implementation of the {IERC721Receiver} interface.\n *\n * Accepts all token transfers.\n * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.\n */\ncontract ERC721Holder is IERC721Receiver {\n    /**\n     * @dev See {IERC721Receiver-onERC721Received}.\n     *\n     * Always returns `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address,\n        address,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC721Received.selector;\n    }\n}\n"
      },
      "lib/solmate/src/auth/Auth.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\nabstract contract Auth {\n    event OwnershipTransferred(address indexed user, address indexed newOwner);\n\n    event AuthorityUpdated(address indexed user, Authority indexed newAuthority);\n\n    address public owner;\n\n    Authority public authority;\n\n    constructor(address _owner, Authority _authority) {\n        owner = _owner;\n        authority = _authority;\n\n        emit OwnershipTransferred(msg.sender, _owner);\n        emit AuthorityUpdated(msg.sender, _authority);\n    }\n\n    modifier requiresAuth() virtual {\n        require(isAuthorized(msg.sender, msg.sig), \"UNAUTHORIZED\");\n\n        _;\n    }\n\n    function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {\n        Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\n\n        // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be\n        // aware that this makes protected functions uncallable even to the owner if the authority is out of order.\n        return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;\n    }\n\n    function setAuthority(Authority newAuthority) public virtual {\n        // We check if the caller is the owner first because we want to ensure they can\n        // always swap out the authority even if it's reverting or using up a lot of gas.\n        require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));\n\n        authority = newAuthority;\n\n        emit AuthorityUpdated(msg.sender, newAuthority);\n    }\n\n    function transferOwnership(address newOwner) public virtual requiresAuth {\n        owner = newOwner;\n\n        emit OwnershipTransferred(msg.sender, newOwner);\n    }\n}\n\n/// @notice A generic interface for a contract which provides authorization data to an Auth instance.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\ninterface Authority {\n    function canCall(\n        address user,\n        address target,\n        bytes4 functionSig\n    ) external view returns (bool);\n}\n"
      },
      "src/interfaces/external/IChainlinkAggregator.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol\";\n\ninterface IChainlinkAggregator is AggregatorV2V3Interface {\n    function maxAnswer() external view returns (int192);\n\n    function minAnswer() external view returns (int192);\n\n    function aggregator() external view returns (address);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "src/modules/price-router/Extensions/Extension.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.21;\n\nimport { ERC20 } from \"@solmate/tokens/ERC20.sol\";\nimport { PriceRouter } from \"src/modules/price-router/PriceRouter.sol\";\nimport { Math } from \"src/utils/Math.sol\";\n\n/**\n * @title Sommelier Price Router Extension abstract contract.\n * @notice Provides shared logic between Extensions.\n * @author crispymangoes\n */\nabstract contract Extension {\n    /**\n     * @notice Attempted to call a function only callable by the price router.\n     */\n    error Extension__OnlyPriceRouter();\n\n    /**\n     * @notice Prevents non price router contracts from calling a function.\n     */\n    modifier onlyPriceRouter() {\n        if (msg.sender != address(priceRouter)) revert Extension__OnlyPriceRouter();\n        _;\n    }\n\n    /**\n     * @notice The Sommelier PriceRouter contract.\n     */\n    PriceRouter public immutable priceRouter;\n\n    constructor(PriceRouter _priceRouter) {\n        priceRouter = _priceRouter;\n    }\n\n    /**\n     * @notice Setup function is called when an asset is added/edited.\n     */\n    function setupSource(ERC20 asset, bytes memory sourceData) external virtual;\n\n    /**\n     * @notice Returns the price of an asset in USD.\n     */\n    function getPriceInUSD(ERC20 asset) external view virtual returns (uint256);\n}\n"
      },
      "src/interfaces/external/UniswapV3Pool.sol": {
        "content": "pragma solidity ^0.8.10;\n\ninterface UniswapV3Pool {\n    event Burn(\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n    event Collect(\n        address indexed owner,\n        address recipient,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount0,\n        uint128 amount1\n    );\n    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n    event Flash(\n        address indexed sender,\n        address indexed recipient,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 paid0,\n        uint256 paid1\n    );\n    event IncreaseObservationCardinalityNext(\n        uint16 observationCardinalityNextOld,\n        uint16 observationCardinalityNextNew\n    );\n    event Initialize(uint160 sqrtPriceX96, int24 tick);\n    event Mint(\n        address sender,\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n    event Swap(\n        address indexed sender,\n        address indexed recipient,\n        int256 amount0,\n        int256 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick\n    );\n\n    function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);\n\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    function factory() external view returns (address);\n\n    function fee() external view returns (uint24);\n\n    function feeGrowthGlobal0X128() external view returns (uint256);\n\n    function feeGrowthGlobal1X128() external view returns (uint256);\n\n    function flash(address recipient, uint256 amount0, uint256 amount1, bytes memory data) external;\n\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n\n    function initialize(uint160 sqrtPriceX96) external;\n\n    function liquidity() external view returns (uint128);\n\n    function maxLiquidityPerTick() external view returns (uint128);\n\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes memory data\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    function observations(\n        uint256\n    )\n        external\n        view\n        returns (\n            uint32 blockTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n            bool initialized\n        );\n\n    function observe(\n        uint32[] memory secondsAgos\n    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n    function positions(\n        bytes32\n    )\n        external\n        view\n        returns (\n            uint128 liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        );\n\n    function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n    function slot0()\n        external\n        view\n        returns (\n            uint160 sqrtPriceX96,\n            int24 tick,\n            uint16 observationIndex,\n            uint16 observationCardinality,\n            uint16 observationCardinalityNext,\n            uint8 feeProtocol,\n            bool unlocked\n        );\n\n    function snapshotCumulativesInside(\n        int24 tickLower,\n        int24 tickUpper\n    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);\n\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes memory data\n    ) external returns (int256 amount0, int256 amount1);\n\n    function tickBitmap(int16) external view returns (uint256);\n\n    function tickSpacing() external view returns (int24);\n\n    function ticks(\n        int24\n    )\n        external\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128,\n            int56 tickCumulativeOutside,\n            uint160 secondsPerLiquidityOutsideX128,\n            uint32 secondsOutside,\n            bool initialized\n        );\n\n    function token0() external view returns (address);\n\n    function token1() external view returns (address);\n}\n"
      },
      "lib/v3-periphery/contracts/libraries/OracleLibrary.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0 <0.9.0;\n\nimport '@uniswap/v3-core/contracts/libraries/FullMath.sol';\nimport '@uniswap/v3-core/contracts/libraries/TickMath.sol';\nimport '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n    /// @param pool Address of the pool that we want to observe\n    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n    function consult(address pool, uint32 secondsAgo)\n        internal\n        view\n        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n    {\n        require(secondsAgo != 0, 'BP');\n\n        uint32[] memory secondsAgos = new uint32[](2);\n        secondsAgos[0] = secondsAgo;\n        secondsAgos[1] = 0;\n\n        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool)\n            .observe(secondsAgos);\n\n        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n        uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -\n            secondsPerLiquidityCumulativeX128s[0];\n\n        arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n        // Always round to negative infinity\n        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n    }\n\n    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n    /// @param tick Tick value used to calculate the quote\n    /// @param baseAmount Amount of token to be converted\n    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n    function getQuoteAtTick(\n        int24 tick,\n        uint128 baseAmount,\n        address baseToken,\n        address quoteToken\n    ) internal pure returns (uint256 quoteAmount) {\n        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\n        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself\n        if (sqrtRatioX96 <= type(uint128).max) {\n            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;\n            quoteAmount = baseToken < quoteToken\n                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n        } else {\n            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n            quoteAmount = baseToken < quoteToken\n                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n        }\n    }\n\n    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n    /// @param pool Address of Uniswap V3 pool that we want to observe\n    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n        require(observationCardinality > 0, 'NI');\n\n        (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations(\n            (observationIndex + 1) % observationCardinality\n        );\n\n        // The next index might not be initialized if the cardinality is in the process of increasing\n        // In this case the oldest observation is always in index 0\n        if (!initialized) {\n            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n        }\n\n        unchecked {\n            secondsAgo = uint32(block.timestamp) - observationTimestamp;\n        }\n    }\n\n    /// @notice Given a pool, it returns the tick value as of the start of the current block\n    /// @param pool Address of Uniswap V3 pool\n    /// @return The tick that the pool was in at the start of the current block\n    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n        // 2 observations are needed to reliably calculate the block starting tick\n        require(observationCardinality > 1, 'NEO');\n\n        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n        // therefore the tick in `slot0` is the same as at the beginning of the current block.\n        // We don't need to check if this observation is initialized - it is guaranteed to be.\n        (\n            uint32 observationTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n\n        ) = IUniswapV3Pool(pool).observations(observationIndex);\n        if (observationTimestamp != uint32(block.timestamp)) {\n            return (tick, IUniswapV3Pool(pool).liquidity());\n        }\n\n        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n        (\n            uint32 prevObservationTimestamp,\n            int56 prevTickCumulative,\n            uint160 prevSecondsPerLiquidityCumulativeX128,\n            bool prevInitialized\n        ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n        require(prevInitialized, 'ONI');\n\n        uint32 delta = observationTimestamp - prevObservationTimestamp;\n        tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta)));\n        uint128 liquidity = uint128(\n            (uint192(delta) * type(uint160).max) /\n                (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n        );\n        return (tick, liquidity);\n    }\n\n    /// @notice Information for calculating a weighted arithmetic mean tick\n    struct WeightedTickData {\n        int24 tick;\n        uint128 weight;\n    }\n\n    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n    /// @param weightedTickData An array of ticks and weights\n    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n        internal\n        pure\n        returns (int24 weightedArithmeticMeanTick)\n    {\n        // Accumulates the sum of products between each tick and its weight\n        int256 numerator;\n\n        // Accumulates the sum of the weights\n        uint256 denominator;\n\n        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n        for (uint256 i; i < weightedTickData.length; i++) {\n            numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n            denominator += weightedTickData[i].weight;\n        }\n\n        weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n        // Always round to negative infinity\n        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n    }\n\n    /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n    /// @dev Useful for calculating relative prices along routes.\n    /// @dev There must be one tick for each pairwise set of tokens.\n    /// @param tokens The token contract addresses\n    /// @param ticks The ticks, representing the price of each token pair in `tokens`\n    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n    function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n        internal\n        pure\n        returns (int256 syntheticTick)\n    {\n        require(tokens.length - 1 == ticks.length, 'DL');\n        for (uint256 i = 1; i <= ticks.length; i++) {\n            // check the tokens for address sort order, then accumulate the\n            // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "lib/solmate/src/utils/FixedPointMathLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n    /*//////////////////////////////////////////////////////////////\n                    SIMPLIFIED FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n    }\n\n    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n    }\n\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    LOW LEVEL FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function mulDivDown(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // Divide x * y by the denominator.\n            z := div(mul(x, y), denominator)\n        }\n    }\n\n    function mulDivUp(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // If x * y modulo the denominator is strictly greater than 0,\n            // 1 is added to round up the division of x * y by the denominator.\n            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n        }\n    }\n\n    function rpow(\n        uint256 x,\n        uint256 n,\n        uint256 scalar\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            switch x\n            case 0 {\n                switch n\n                case 0 {\n                    // 0 ** 0 = 1\n                    z := scalar\n                }\n                default {\n                    // 0 ** n = 0\n                    z := 0\n                }\n            }\n            default {\n                switch mod(n, 2)\n                case 0 {\n                    // If n is even, store scalar in z for now.\n                    z := scalar\n                }\n                default {\n                    // If n is odd, store x in z for now.\n                    z := x\n                }\n\n                // Shifting right by 1 is like dividing by 2.\n                let half := shr(1, scalar)\n\n                for {\n                    // Shift n right by 1 before looping to halve it.\n                    n := shr(1, n)\n                } n {\n                    // Shift n right by 1 each iteration to halve it.\n                    n := shr(1, n)\n                } {\n                    // Revert immediately if x ** 2 would overflow.\n                    // Equivalent to iszero(eq(div(xx, x), x)) here.\n                    if shr(128, x) {\n                        revert(0, 0)\n                    }\n\n                    // Store x squared.\n                    let xx := mul(x, x)\n\n                    // Round to the nearest number.\n                    let xxRound := add(xx, half)\n\n                    // Revert if xx + half overflowed.\n                    if lt(xxRound, xx) {\n                        revert(0, 0)\n                    }\n\n                    // Set x to scaled xxRound.\n                    x := div(xxRound, scalar)\n\n                    // If n is even:\n                    if mod(n, 2) {\n                        // Compute z * x.\n                        let zx := mul(z, x)\n\n                        // If z * x overflowed:\n                        if iszero(eq(div(zx, x), z)) {\n                            // Revert if x is non-zero.\n                            if iszero(iszero(x)) {\n                                revert(0, 0)\n                            }\n                        }\n\n                        // Round to the nearest number.\n                        let zxRound := add(zx, half)\n\n                        // Revert if zx + half overflowed.\n                        if lt(zxRound, zx) {\n                            revert(0, 0)\n                        }\n\n                        // Return properly scaled zxRound.\n                        z := div(zxRound, scalar)\n                    }\n                }\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        GENERAL NUMBER UTILITIES\n    //////////////////////////////////////////////////////////////*/\n\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Mod x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            z := mod(x, y)\n        }\n    }\n\n    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Divide x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            r := div(x, y)\n        }\n    }\n\n    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Add 1 to x * y if x % y > 0. Note this will\n            // return 0 instead of reverting if y is zero.\n            z := add(gt(mod(x, y), 0), div(x, y))\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "lib/chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./AggregatorInterface.sol\";\nimport \"./AggregatorV3Interface.sol\";\n\ninterface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}\n"
      },
      "lib/v3-core/contracts/libraries/FullMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = a * b\n            // Compute the product mod 2**256 and mod 2**256 - 1\n            // then use the Chinese Remainder Theorem to reconstruct\n            // the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2**256 + prod0\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(a, b, not(0))\n                prod0 := mul(a, b)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division\n            if (prod1 == 0) {\n                require(denominator > 0);\n                assembly {\n                    result := div(prod0, denominator)\n                }\n                return result;\n            }\n\n            // Make sure the result is less than 2**256.\n            // Also prevents denominator == 0\n            require(denominator > prod1);\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0]\n            // Compute remainder using mulmod\n            uint256 remainder;\n            assembly {\n                remainder := mulmod(a, b, denominator)\n            }\n            // Subtract 256 bit number from 512 bit number\n            assembly {\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator\n            // Compute largest power of two divisor of denominator.\n            // Always >= 1.\n            uint256 twos = (0 - denominator) & denominator;\n            // Divide denominator by power of two\n            assembly {\n                denominator := div(denominator, twos)\n            }\n\n            // Divide [prod1 prod0] by the factors of two\n            assembly {\n                prod0 := div(prod0, twos)\n            }\n            // Shift in bits from prod1 into prod0. For this we need\n            // to flip `twos` such that it is 2**256 / twos.\n            // If twos is zero, then it becomes one\n            assembly {\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2**256\n            // Now that denominator is an odd number, it has an inverse\n            // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n            // Compute the inverse by starting with a seed that is correct\n            // correct for four bits. That is, denominator * inv = 1 mod 2**4\n            uint256 inv = (3 * denominator) ^ 2;\n            // Now use Newton-Raphson iteration to improve the precision.\n            // Thanks to Hensel's lifting lemma, this also works in modular\n            // arithmetic, doubling the correct bits in each step.\n            inv *= 2 - denominator * inv; // inverse mod 2**8\n            inv *= 2 - denominator * inv; // inverse mod 2**16\n            inv *= 2 - denominator * inv; // inverse mod 2**32\n            inv *= 2 - denominator * inv; // inverse mod 2**64\n            inv *= 2 - denominator * inv; // inverse mod 2**128\n            inv *= 2 - denominator * inv; // inverse mod 2**256\n\n            // Because the division is now exact we can divide by multiplying\n            // with the modular inverse of denominator. This will give us the\n            // correct result modulo 2**256. Since the precoditions guarantee\n            // that the outcome is less than 2**256, this is the final result.\n            // We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inv;\n            return result;\n        }\n    }\n\n    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            result = mulDiv(a, b, denominator);\n            if (mulmod(a, b, denominator) > 0) {\n                require(result < type(uint256).max);\n                result++;\n            }\n        }\n    }\n}\n"
      },
      "lib/v3-core/contracts/libraries/TickMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n    error T();\n    error R();\n\n    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n    int24 internal constant MAX_TICK = -MIN_TICK;\n\n    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n    uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n    /// @notice Calculates sqrt(1.0001^tick) * 2^96\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n    /// at the given tick\n    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        unchecked {\n            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n            if (absTick > uint256(int256(MAX_TICK))) revert T();\n\n            uint256 ratio = absTick & 0x1 != 0\n                ? 0xfffcb933bd6fad37aa2d162d1a594001\n                : 0x100000000000000000000000000000000;\n            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n            if (tick > 0) ratio = type(uint256).max / ratio;\n\n            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n        }\n    }\n\n    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        unchecked {\n            // second inequality must be < because the price can never reach the price at the max tick\n            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();\n            uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n            uint256 r = ratio;\n            uint256 msb = 0;\n\n            assembly {\n                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(5, gt(r, 0xFFFFFFFF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(4, gt(r, 0xFFFF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(3, gt(r, 0xFF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(2, gt(r, 0xF))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := shl(1, gt(r, 0x3))\n                msb := or(msb, f)\n                r := shr(f, r)\n            }\n            assembly {\n                let f := gt(r, 0x1)\n                msb := or(msb, f)\n            }\n\n            if (msb >= 128) r = ratio >> (msb - 127);\n            else r = ratio << (127 - msb);\n\n            int256 log_2 = (int256(msb) - 128) << 64;\n\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(63, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(62, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(61, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(60, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(59, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(58, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(57, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(56, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(55, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(54, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(53, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(52, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(51, f))\n                r := shr(f, r)\n            }\n            assembly {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(50, f))\n            }\n\n            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n        }\n    }\n}\n"
      },
      "lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';\nimport {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';\nimport {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';\nimport {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';\nimport {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';\nimport {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';\nimport {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n    IUniswapV3PoolImmutables,\n    IUniswapV3PoolState,\n    IUniswapV3PoolDerivedState,\n    IUniswapV3PoolActions,\n    IUniswapV3PoolOwnerActions,\n    IUniswapV3PoolErrors,\n    IUniswapV3PoolEvents\n{\n\n}\n"
      },
      "lib/chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorInterface {\n  function latestAnswer() external view returns (int256);\n\n  function latestTimestamp() external view returns (uint256);\n\n  function latestRound() external view returns (uint256);\n\n  function getAnswer(uint256 roundId) external view returns (int256);\n\n  function getTimestamp(uint256 roundId) external view returns (uint256);\n\n  event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);\n\n  event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n}\n"
      },
      "lib/chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n  function decimals() external view returns (uint8);\n\n  function description() external view returns (string memory);\n\n  function version() external view returns (uint256);\n\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n    /// @return The contract address\n    function factory() external view returns (address);\n\n    /// @notice The first of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token0() external view returns (address);\n\n    /// @notice The second of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token1() external view returns (address);\n\n    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n    /// @return The fee\n    function fee() external view returns (uint24);\n\n    /// @notice The pool tick spacing\n    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n    /// This value is an int24 to avoid casting even though it is always positive.\n    /// @return The tick spacing\n    function tickSpacing() external view returns (int24);\n\n    /// @notice The maximum amount of position liquidity that can use any tick in the range\n    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n    /// @return The max amount of liquidity per tick\n    function maxLiquidityPerTick() external view returns (uint128);\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n    /// when accessed externally.\n    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.\n    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n    /// boundary.\n    /// @return observationIndex The index of the last oracle observation that was written,\n    /// @return observationCardinality The current maximum number of observations stored in the pool,\n    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n    /// @return feeProtocol The protocol fee for both tokens of the pool.\n    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n    /// 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.\n    /// unlocked Whether the pool is currently locked to reentrancy\n    function slot0()\n        external\n        view\n        returns (\n            uint160 sqrtPriceX96,\n            int24 tick,\n            uint16 observationIndex,\n            uint16 observationCardinality,\n            uint16 observationCardinalityNext,\n            uint8 feeProtocol,\n            bool unlocked\n        );\n\n    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal0X128() external view returns (uint256);\n\n    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal1X128() external view returns (uint256);\n\n    /// @notice The amounts of token0 and token1 that are owed to the protocol\n    /// @dev Protocol fees will never exceed uint128 max in either token\n    function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n    /// @notice The currently in range liquidity available to the pool\n    /// @dev This value has no relationship to the total liquidity across all ticks\n    /// @return The liquidity at the current price of the pool\n    function liquidity() external view returns (uint128);\n\n    /// @notice Look up information about a specific tick in the pool\n    /// @param tick The tick to look up\n    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n    /// tick upper\n    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,\n    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,\n    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n    /// a specific position.\n    function ticks(int24 tick)\n        external\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128,\n            int56 tickCumulativeOutside,\n            uint160 secondsPerLiquidityOutsideX128,\n            uint32 secondsOutside,\n            bool initialized\n        );\n\n    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n    function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n    /// @notice Returns the information about a position by the position's key\n    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n    /// @return liquidity The amount of liquidity in the position,\n    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n    function positions(bytes32 key)\n        external\n        view\n        returns (\n            uint128 liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        );\n\n    /// @notice Returns data about a specific observation index\n    /// @param index The element of the observations array to fetch\n    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n    /// ago, rather than at a specific index in the array.\n    /// @return blockTimestamp The timestamp of the observation,\n    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n    /// @return initialized whether the observation has been initialized and the values are safe to use\n    function observations(uint256 index)\n        external\n        view\n        returns (\n            uint32 blockTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n            bool initialized\n        );\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n    /// you must call it with secondsAgos = [3600, 0].\n    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n    /// timestamp\n    function observe(uint32[] calldata secondsAgos)\n        external\n        view\n        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n    /// snapshot is taken and the second snapshot is taken.\n    /// @param tickLower The lower tick of the range\n    /// @param tickUpper The upper tick of the range\n    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n    /// @return secondsInside The snapshot of seconds per liquidity for the range\n    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n        external\n        view\n        returns (\n            int56 tickCumulativeInside,\n            uint160 secondsPerLiquidityInsideX128,\n            uint32 secondsInside\n        );\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n    /// @notice Sets the initial price for the pool\n    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n    function initialize(uint160 sqrtPriceX96) external;\n\n    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n    /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n    /// @param recipient The address for which the liquidity will be created\n    /// @param tickLower The lower tick of the position in which to add liquidity\n    /// @param tickUpper The upper tick of the position in which to add liquidity\n    /// @param amount The amount of liquidity to mint\n    /// @param data Any data that should be passed through to the callback\n    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes calldata data\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Collects tokens owed to a position\n    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n    /// @param recipient The address which should receive the fees collected\n    /// @param tickLower The lower tick of the position for which to collect fees\n    /// @param tickUpper The upper tick of the position for which to collect fees\n    /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n    /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n    /// @return amount0 The amount of fees collected in token0\n    /// @return amount1 The amount of fees collected in token1\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n    /// @dev Fees must be collected separately via a call to #collect\n    /// @param tickLower The lower tick of the position for which to burn liquidity\n    /// @param tickUpper The upper tick of the position for which to burn liquidity\n    /// @param amount How much liquidity to burn\n    /// @return amount0 The amount of token0 sent to the recipient\n    /// @return amount1 The amount of token1 sent to the recipient\n    function burn(\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Swap token0 for token1, or token1 for token0\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n    /// @param recipient The address to receive the output of the swap\n    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n    /// @param data Any data to be passed through to the callback\n    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes calldata data\n    ) external returns (int256 amount0, int256 amount1);\n\n    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n    /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n    /// @param recipient The address which will receive the token0 and token1 amounts\n    /// @param amount0 The amount of token0 to send\n    /// @param amount1 The amount of token1 to send\n    /// @param data Any data to be passed through to the callback\n    function flash(\n        address recipient,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata data\n    ) external;\n\n    /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n    /// the input observationCardinalityNext.\n    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n    /// @notice Set the denominator of the protocol's % share of the fees\n    /// @param feeProtocol0 new protocol fee for token0 of the pool\n    /// @param feeProtocol1 new protocol fee for token1 of the pool\n    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n    /// @notice Collect the protocol fee accrued to the pool\n    /// @param recipient The address to which collected protocol fees should be sent\n    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n    /// @return amount0 The protocol fee collected in token0\n    /// @return amount1 The protocol fee collected in token1\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolErrors.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Errors emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolErrors {\n    error LOK();\n    error TLU();\n    error TLM();\n    error TUM();\n    error AI();\n    error M0();\n    error M1();\n    error AS();\n    error IIA();\n    error L();\n    error F0();\n    error F1();\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n    event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n    /// @notice Emitted when liquidity is minted for a given position\n    /// @param sender The address that minted the liquidity\n    /// @param owner The owner of the position and recipient of any minted liquidity\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity minted to the position range\n    /// @param amount0 How much token0 was required for the minted liquidity\n    /// @param amount1 How much token1 was required for the minted liquidity\n    event Mint(\n        address sender,\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted when fees are collected by the owner of a position\n    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n    /// @param owner The owner of the position for which fees are collected\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount0 The amount of token0 fees collected\n    /// @param amount1 The amount of token1 fees collected\n    event Collect(\n        address indexed owner,\n        address recipient,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount0,\n        uint128 amount1\n    );\n\n    /// @notice Emitted when a position's liquidity is removed\n    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n    /// @param owner The owner of the position for which liquidity is removed\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity to remove\n    /// @param amount0 The amount of token0 withdrawn\n    /// @param amount1 The amount of token1 withdrawn\n    event Burn(\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted by the pool for any swaps between token0 and token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the output of the swap\n    /// @param amount0 The delta of the token0 balance of the pool\n    /// @param amount1 The delta of the token1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of price of the pool after the swap\n    event Swap(\n        address indexed sender,\n        address indexed recipient,\n        int256 amount0,\n        int256 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick\n    );\n\n    /// @notice Emitted by the pool for any flashes of token0/token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the tokens from flash\n    /// @param amount0 The amount of token0 that was flashed\n    /// @param amount1 The amount of token1 that was flashed\n    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n    event Flash(\n        address indexed sender,\n        address indexed recipient,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 paid0,\n        uint256 paid1\n    );\n\n    /// @notice Emitted by the pool for increases to the number of observations that can be stored\n    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n    /// just before a mint/swap/burn.\n    /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n    /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n    event IncreaseObservationCardinalityNext(\n        uint16 observationCardinalityNextOld,\n        uint16 observationCardinalityNextNew\n    );\n\n    /// @notice Emitted when the protocol fee is changed by the pool\n    /// @param feeProtocol0Old The previous value of the token0 protocol fee\n    /// @param feeProtocol1Old The previous value of the token1 protocol fee\n    /// @param feeProtocol0New The updated value of the token0 protocol fee\n    /// @param feeProtocol1New The updated value of the token1 protocol fee\n    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n    /// @param sender The address that collects the protocol fees\n    /// @param recipient The address that receives the collected protocol fees\n    /// @param amount0 The amount of token0 protocol fees that is withdrawn\n    /// @param amount0 The amount of token1 protocol fees that is withdrawn\n    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@solmate/=lib/solmate/src/",
        "@forge-std/=lib/forge-std/src/",
        "@ds-test/=lib/forge-std/lib/ds-test/src/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "@openzeppelin/=lib/openzeppelin-contracts/",
        "@uniswap/v3-periphery/=lib/v3-periphery/",
        "@uniswap/v3-core/=lib/v3-core/",
        "@chainlink/=lib/chainlink/",
        "@uniswapV3P/=lib/v3-periphery/contracts/",
        "@uniswapV3C/=lib/v3-core/contracts/",
        "@balancer/=lib/balancer-v2-monorepo/pkg/",
        "@ccip/=lib/ccip/",
        "@pendle/=lib/pendle-core-v2-public/",
        "@balancer-labs/=lib/balancer-v2-monorepo/../../node_modules/@balancer-labs/",
        "axelar-gmp-sdk-solidity/=lib/axelar-gmp-sdk-solidity/contracts/",
        "balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
        "ccip/=lib/ccip/contracts/",
        "chainlink/=lib/chainlink/integration-tests/contracts/ethereum/src/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
        "solmate/=lib/solmate/src/",
        "v3-core/=lib/v3-core/contracts/",
        "v3-periphery/=lib/v3-periphery/contracts/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "abi"
          ]
        }
      },
      "evmVersion": "shanghai",
      "libraries": {}
    }
  }}