ETH Price: $3,875.18 (-1.32%)

Token

ERC-20: Turbo EETH (TurboEETH)
 

Overview

Max Total Supply

47.704250237186518072 TurboEETH

Holders

127

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 18 Decimals)

Balance
0.000000073363923359 TurboEETH

Value
$0.00
0x5d0a0352dff6b7d10d0814f85597a0c8b5c361c6
Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
CellarWithOracleWithBalancerFlashLoansWithMultiAssetDepositWithNativeSupport

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion
File 1 of 44 : CellarWithOracleWithBalancerFlashLoansWithMultiAssetDepositWithNativeSupport.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Registry, ERC20, Math, SafeTransferLib, Address } from "src/base/Cellar.sol";
import { CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit } from "src/base/permutations/advanced/CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit.sol";

contract CellarWithOracleWithBalancerFlashLoansWithMultiAssetDepositWithNativeSupport is
    CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit
{
    //============================== IMMUTABLES ===============================

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint64 _strategistPlatformCut,
        uint192 _shareSupplyCap,
        address _balancerVault
    )
        CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _strategistPlatformCut,
            _shareSupplyCap,
            _balancerVault
        )
    {}

    /**
     * @notice Implement receive so Cellar can accept native transfers.
     */
    receive() external payable {}
}

File 2 of 44 : Cellar.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Math } from "src/utils/Math.sol";
import { ERC4626 } from "@solmate/mixins/ERC4626.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
// import { ERC4626, SafeTransferLib, Math, ERC20 } from "src/base/ERC4626.sol";
import { Registry } from "src/Registry.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { Uint32Array } from "src/utils/Uint32Array.sol";
import { BaseAdaptor } from "src/modules/adaptors/BaseAdaptor.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import { Owned } from "@solmate/auth/Owned.sol";

/**
 * @title Sommelier Cellar
 * @notice A composable ERC4626 that can use arbitrary DeFi assets/positions using adaptors.
 * @author crispymangoes
 */
contract Cellar is ERC4626, Owned, ERC721Holder {
    using Uint32Array for uint32[];
    using SafeTransferLib for ERC20;
    using Math for uint256;
    using Address for address;

    // ========================================= One Slot Values =========================================
    // Below values are frequently accessed in the same TXs. By moving them to the top
    // they will be stored in the same slot, reducing cold access reads.

    /**
     * @notice The maximum amount of shares that can be in circulation.
     * @dev Can be decreased by the strategist.
     * @dev Can be increased by Sommelier Governance.
     */
    uint192 public shareSupplyCap;

    /**
     * @notice `locked` is public, so that the state can be checked even during view function calls.
     */
    bool public locked;

    /**
     * @notice Whether or not the contract is shutdown in case of an emergency.
     */
    bool public isShutdown;

    /**
     * @notice Pauses all user entry/exits, and strategist rebalances.
     */
    bool public ignorePause;

    /**
     * @notice This bool is used to stop strategists from abusing Base Adaptor functions(deposit/withdraw).
     */
    bool public blockExternalReceiver;

    /**
     * @notice Stores the position id of the holding position in the creditPositions array.
     */
    uint32 public holdingPosition;

    // ========================================= MULTICALL =========================================

    /**
     * @notice Allows caller to call multiple functions in a single TX.
     * @dev Does NOT return the function return values.
     */
    function multicall(bytes[] calldata data) external {
        for (uint256 i = 0; i < data.length; i++) address(this).functionDelegateCall(data[i]);
    }

    // ========================================= REENTRANCY GUARD =========================================

    modifier nonReentrant() {
        require(!locked, "REENTRANCY");

        locked = true;

        _;

        locked = false;
    }

    // ========================================= _onlyOwner ========================================

    function _onlyOwner() internal onlyOwner {}

    // ========================================= PRICE ROUTER CACHE =========================================

    /**
     * @notice Cached price router contract.
     * @dev This way cellar has to "opt in" to price router changes.
     */
    PriceRouter public priceRouter;

    /**
     * @notice Updates the cellar to use the lastest price router in the registry.
     * @param checkTotalAssets If true totalAssets is checked before and after updating the price router,
     *        and is verified to be withing a +- 5% envelope.
     *        If false totalAssets is only called after updating the price router.]
     * @param allowableRange The +- range the total assets may deviate between the old and new price router.
     *                       - 1_000 == 10%
     *                       - 500 == 5%
     * @param expectedPriceRouter The registry price router differed from the expected price router.
     * @dev `allowableRange` reverts from arithmetic underflow if it is greater than 10_000, this is
     *      desired behavior.
     * @dev Callable by Sommelier Governance.
     */
    function cachePriceRouter(bool checkTotalAssets, uint16 allowableRange, address expectedPriceRouter) external {
        _onlyOwner();
        uint256 minAssets;
        uint256 maxAssets;

        if (checkTotalAssets) {
            uint256 assetsBefore = totalAssets();
            minAssets = assetsBefore.mulDivDown(1e4 - allowableRange, 1e4);
            maxAssets = assetsBefore.mulDivDown(1e4 + allowableRange, 1e4);
        }

        // Make sure expected price router is equal to price router grabbed from registry.
        _checkRegistryAddressAgainstExpected(PRICE_ROUTER_REGISTRY_SLOT, expectedPriceRouter);

        priceRouter = PriceRouter(expectedPriceRouter);
        uint256 assetsAfter = totalAssets();

        if (checkTotalAssets) {
            if (assetsAfter < minAssets || assetsAfter > maxAssets)
                revert Cellar__TotalAssetDeviatedOutsideRange(assetsAfter, minAssets, maxAssets);
        }
    }

    // ========================================= POSITIONS CONFIG =========================================

    /**
     * @notice Emitted when a position is added.
     * @param position id of position that was added
     * @param index index that position was added at
     */
    event PositionAdded(uint32 position, uint256 index);

    /**
     * @notice Emitted when a position is removed.
     * @param position id of position that was removed
     * @param index index that position was removed from
     */
    event PositionRemoved(uint32 position, uint256 index);

    /**
     * @notice Emitted when the positions at two indexes are swapped.
     * @param newPosition1 id of position (previously at index2) that replaced index1.
     * @param newPosition2 id of position (previously at index1) that replaced index2.
     * @param index1 index of first position involved in the swap
     * @param index2 index of second position involved in the swap.
     */
    event PositionSwapped(uint32 newPosition1, uint32 newPosition2, uint256 index1, uint256 index2);

    /**
     * @notice Emitted when Governance adds/removes a position to/from the cellars catalogue.
     */
    event PositionCatalogueAltered(uint32 positionId, bool inCatalogue);

    /**
     * @notice Emitted when Governance adds/removes an adaptor to/from the cellars catalogue.
     */
    event AdaptorCatalogueAltered(address adaptor, bool inCatalogue);

    /**
     * @notice Attempted to add a position that is already being used.
     * @param position id of the position
     */
    error Cellar__PositionAlreadyUsed(uint32 position);

    /**
     * @notice Attempted to make an unused position the holding position.
     * @param position id of the position
     */
    error Cellar__PositionNotUsed(uint32 position);

    /**
     * @notice Attempted to add a position that is not in the catalogue.
     * @param position id of the position
     */
    error Cellar__PositionNotInCatalogue(uint32 position);

    /**
     * @notice Attempted an action on a position that is required to be empty before the action can be performed.
     * @param position address of the non-empty position
     * @param sharesRemaining amount of shares remaining in the position
     */
    error Cellar__PositionNotEmpty(uint32 position, uint256 sharesRemaining);

    /**
     * @notice Attempted an operation with an asset that was different then the one expected.
     * @param asset address of the asset
     * @param expectedAsset address of the expected asset
     */
    error Cellar__AssetMismatch(address asset, address expectedAsset);

    /**
     * @notice Attempted to add a position when the position array is full.
     * @param maxPositions maximum number of positions that can be used
     */
    error Cellar__PositionArrayFull(uint256 maxPositions);

    /**
     * @notice Attempted to add a position, with mismatched debt.
     * @param position the posiiton id that was mismatched
     */
    error Cellar__DebtMismatch(uint32 position);

    /**
     * @notice Attempted to remove the Cellars holding position.
     */
    error Cellar__RemovingHoldingPosition();

    /**
     * @notice Attempted to add an invalid holding position.
     * @param positionId the id of the invalid position.
     */
    error Cellar__InvalidHoldingPosition(uint32 positionId);

    /**
     * @notice Attempted to force out the wrong position.
     */
    error Cellar__FailedToForceOutPosition();

    /**
     * @notice Array of uint32s made up of cellars credit positions Ids.
     */
    uint32[] internal creditPositions;

    /**
     * @notice Array of uint32s made up of cellars debt positions Ids.
     */
    uint32[] internal debtPositions;

    /**
     * @notice Tell whether a position is currently used.
     */
    mapping(uint256 => bool) public isPositionUsed;

    /**
     * @notice Get position data given position id.
     */
    mapping(uint32 => Registry.PositionData) internal getPositionData;

    /**
     * @notice Get the ids of the credit positions currently used by the cellar.
     */
    function getCreditPositions() external view returns (uint32[] memory) {
        return creditPositions;
    }

    /**
     * @notice Get the ids of the debt positions currently used by the cellar.
     */
    function getDebtPositions() external view returns (uint32[] memory) {
        return debtPositions;
    }

    /**
     * @notice Maximum amount of positions a cellar can have in it's credit/debt arrays.
     */
    uint256 internal constant MAX_POSITIONS = 32;

    /**
     * @notice Allows owner to change the holding position.
     * @dev Callable by Sommelier Strategist.
     */
    function setHoldingPosition(uint32 positionId) public {
        _onlyOwner();
        if (!isPositionUsed[positionId]) revert Cellar__PositionNotUsed(positionId);
        if (_assetOf(positionId) != asset) revert Cellar__AssetMismatch(address(asset), address(_assetOf(positionId)));
        if (getPositionData[positionId].isDebt) revert Cellar__InvalidHoldingPosition(positionId);
        holdingPosition = positionId;
    }

    /**
     * @notice Positions the strategist is approved to use without any governance intervention.
     */
    mapping(uint32 => bool) internal positionCatalogue;

    /**
     * @notice Adaptors the strategist is approved to use without any governance intervention.
     */
    mapping(address => bool) internal adaptorCatalogue;

    /**
     * @notice Allows Governance to add positions to this cellar's catalogue.
     * @dev Callable by Sommelier Governance.
     */
    function addPositionToCatalogue(uint32 positionId) public {
        _onlyOwner();
        // Make sure position is not paused and is trusted.
        registry.revertIfPositionIsNotTrusted(positionId);
        positionCatalogue[positionId] = true;
        emit PositionCatalogueAltered(positionId, true);
    }

    /**
     * @notice Allows Governance to remove positions from this cellar's catalogue.
     * @dev Callable by Sommelier Strategist.
     */
    function removePositionFromCatalogue(uint32 positionId) external {
        _onlyOwner();
        positionCatalogue[positionId] = false;
        emit PositionCatalogueAltered(positionId, false);
    }

    /**
     * @notice Allows Governance to add adaptors to this cellar's catalogue.
     * @dev Callable by Sommelier Governance.
     */
    function addAdaptorToCatalogue(address adaptor) external {
        _onlyOwner();
        // Make sure adaptor is not paused and is trusted.
        registry.revertIfAdaptorIsNotTrusted(adaptor);
        adaptorCatalogue[adaptor] = true;
        emit AdaptorCatalogueAltered(adaptor, true);
    }

    /**
     * @notice Allows Governance to remove adaptors from this cellar's catalogue.
     * @dev Callable by Sommelier Strategist.
     */
    function removeAdaptorFromCatalogue(address adaptor) external {
        _onlyOwner();
        adaptorCatalogue[adaptor] = false;
        emit AdaptorCatalogueAltered(adaptor, false);
    }

    /**
     * @notice Insert a trusted position to the list of positions used by the cellar at a given index.
     * @param index index at which to insert the position
     * @param positionId id of position to add
     * @param configurationData data used to configure how the position behaves
     * @dev Callable by Sommelier Strategist.
     */
    function addPosition(uint32 index, uint32 positionId, bytes memory configurationData, bool inDebtArray) public {
        _onlyOwner();
        _whenNotShutdown();

        // Check if position is already being used.
        if (isPositionUsed[positionId]) revert Cellar__PositionAlreadyUsed(positionId);

        // Check if position is in the position catalogue.
        if (!positionCatalogue[positionId]) revert Cellar__PositionNotInCatalogue(positionId);

        // Grab position data from registry.
        // Also checks if position is not trusted and reverts if so.
        (address adaptor, bool isDebt, bytes memory adaptorData) = registry.addPositionToCellar(positionId);

        if (isDebt != inDebtArray) revert Cellar__DebtMismatch(positionId);

        // Copy position data from registry to here.
        getPositionData[positionId] = Registry.PositionData({
            adaptor: adaptor,
            isDebt: isDebt,
            adaptorData: adaptorData,
            configurationData: configurationData
        });

        if (isDebt) {
            if (debtPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS);
            // Add new position at a specified index.
            debtPositions.add(index, positionId);
        } else {
            if (creditPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS);
            // Add new position at a specified index.
            creditPositions.add(index, positionId);
        }

        isPositionUsed[positionId] = true;

        emit PositionAdded(positionId, index);
    }

    /**
     * @notice Remove the position at a given index from the list of positions used by the cellar.
     * @dev Called by strategist.
     * @param index index at which to remove the position
     * @dev Callable by Sommelier Strategist.
     */
    function removePosition(uint32 index, bool inDebtArray) external {
        _onlyOwner();
        // Get position being removed.
        uint32 positionId = inDebtArray ? debtPositions[index] : creditPositions[index];

        // Only remove position if it is empty, and if it is not the holding position.
        uint256 positionBalance = _balanceOf(positionId);
        if (positionBalance > 0) revert Cellar__PositionNotEmpty(positionId, positionBalance);

        _removePosition(index, positionId, inDebtArray);
    }

    /**
     * @notice Allows Sommelier Governance to forceably remove a position from the Cellar without checking its balance is zero.
     * @dev Callable by Sommelier Governance.
     */
    function forcePositionOut(uint32 index, uint32 positionId, bool inDebtArray) external {
        _onlyOwner();
        // Get position being removed.
        uint32 _positionId = inDebtArray ? debtPositions[index] : creditPositions[index];
        // Make sure position id right, and is distrusted.
        if (positionId != _positionId || registry.isPositionTrusted(positionId))
            revert Cellar__FailedToForceOutPosition();

        _removePosition(index, positionId, inDebtArray);
    }

    /**
     * @notice Internal helper function to remove positions from cellars tracked arrays.
     */
    function _removePosition(uint32 index, uint32 positionId, bool inDebtArray) internal {
        if (positionId == holdingPosition) revert Cellar__RemovingHoldingPosition();

        if (inDebtArray) {
            // Remove position at the given index.
            debtPositions.remove(index);
        } else {
            creditPositions.remove(index);
        }

        isPositionUsed[positionId] = false;
        delete getPositionData[positionId];

        emit PositionRemoved(positionId, index);
    }

    /**
     * @notice Swap the positions at two given indexes.
     * @param index1 index of first position to swap
     * @param index2 index of second position to swap
     * @param inDebtArray bool indicating to switch positions in the debt array, or the credit array.
     * @dev Callable by Sommelier Strategist.
     */
    function swapPositions(uint32 index1, uint32 index2, bool inDebtArray) external {
        _onlyOwner();
        // Get the new positions that will be at each index.
        uint32 newPosition1;
        uint32 newPosition2;

        if (inDebtArray) {
            newPosition1 = debtPositions[index2];
            newPosition2 = debtPositions[index1];
            // Swap positions.
            (debtPositions[index1], debtPositions[index2]) = (newPosition1, newPosition2);
        } else {
            newPosition1 = creditPositions[index2];
            newPosition2 = creditPositions[index1];
            // Swap positions.
            (creditPositions[index1], creditPositions[index2]) = (newPosition1, newPosition2);
        }

        emit PositionSwapped(newPosition1, newPosition2, index1, index2);
    }

    // =============================================== FEES CONFIG ===============================================

    /**
     * @notice Emitted when strategist platform fee cut is changed.
     * @param oldPlatformCut value strategist platform fee cut was changed from
     * @param newPlatformCut value strategist platform fee cut was changed to
     */
    event StrategistPlatformCutChanged(uint64 oldPlatformCut, uint64 newPlatformCut);

    /**
     * @notice Emitted when strategists payout address is changed.
     * @param oldPayoutAddress value strategists payout address was changed from
     * @param newPayoutAddress value strategists payout address was changed to
     */
    event StrategistPayoutAddressChanged(address oldPayoutAddress, address newPayoutAddress);

    /**
     * @notice Attempted to change strategist fee cut with invalid value.
     */
    error Cellar__InvalidFeeCut();

    /**
     * @notice Attempted to change platform fee with invalid value.
     */
    error Cellar__InvalidFee();

    /**
     * @notice Data related to fees.
     * @param strategistPlatformCut Determines how much platform fees go to strategist.
     *                              This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%).
     * @param platformFee The percentage of total assets accrued as platform fees over a year.
                          This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%).
     * @param strategistPayoutAddress Address to send the strategists fee shares.
     */
    struct FeeData {
        uint64 strategistPlatformCut;
        uint64 platformFee;
        uint64 lastAccrual;
        address strategistPayoutAddress;
    }

    /**
     * @notice Stores all fee data for cellar.
     */
    FeeData public feeData =
        FeeData({
            strategistPlatformCut: 0.75e18,
            platformFee: 0.01e18,
            lastAccrual: 0,
            strategistPayoutAddress: address(0)
        });

    /**
     * @notice Sets the max possible performance fee for this cellar.
     */
    uint64 internal constant MAX_PLATFORM_FEE = 0.2e18;

    /**
     * @notice Sets the max possible fee cut for this cellar.
     */
    uint64 internal constant MAX_FEE_CUT = 1e18;

    /**
     * @notice Sets the Strategists cut of platform fees
     * @param cut the platform cut for the strategist
     * @dev Callable by Sommelier Governance.
     */
    function setStrategistPlatformCut(uint64 cut) external {
        _onlyOwner();
        if (cut > MAX_FEE_CUT) revert Cellar__InvalidFeeCut();
        emit StrategistPlatformCutChanged(feeData.strategistPlatformCut, cut);

        feeData.strategistPlatformCut = cut;
    }

    /**
     * @notice Sets the Strategists payout address
     * @param payout the new strategist payout address
     * @dev Callable by Sommelier Strategist.
     */
    function setStrategistPayoutAddress(address payout) external {
        _onlyOwner();
        emit StrategistPayoutAddressChanged(feeData.strategistPayoutAddress, payout);

        feeData.strategistPayoutAddress = payout;
    }

    // =========================================== EMERGENCY LOGIC ===========================================

    /**
     * @notice Emitted when cellar emergency state is changed.
     * @param isShutdown whether the cellar is shutdown
     */
    event ShutdownChanged(bool isShutdown);

    /**
     * @notice Attempted action was prevented due to contract being shutdown.
     */
    error Cellar__ContractShutdown();

    /**
     * @notice Attempted action was prevented due to contract not being shutdown.
     */
    error Cellar__ContractNotShutdown();

    /**
     * @notice Attempted to interact with the cellar when it is paused.
     */
    error Cellar__Paused();

    /**
     * @notice View function external contracts can use to see if the cellar is paused.
     */
    function isPaused() external view returns (bool) {
        if (!ignorePause) {
            return registry.isCallerPaused(address(this));
        }
        return false;
    }

    /**
     * @notice Pauses all user entry/exits, and strategist rebalances.
     */
    function _checkIfPaused() internal view {
        if (!ignorePause) {
            if (registry.isCallerPaused(address(this))) revert Cellar__Paused();
        }
    }

    /**
     * @notice Allows governance to choose whether or not to respect a pause.
     * @dev Callable by Sommelier Governance.
     */
    function toggleIgnorePause() external {
        _onlyOwner();
        ignorePause = ignorePause ? false : true;
    }

    /**
     * @notice Prevent a function from being called during a shutdown.
     */
    function _whenNotShutdown() internal view {
        if (isShutdown) revert Cellar__ContractShutdown();
    }

    /**
     * @notice Shutdown the cellar. Used in an emergency or if the cellar has been deprecated.
     * @dev Callable by Sommelier Strategist.
     */
    function initiateShutdown() external {
        _onlyOwner();
        _whenNotShutdown();
        isShutdown = true;

        emit ShutdownChanged(true);
    }

    /**
     * @notice Restart the cellar.
     * @dev Callable by Sommelier Strategist.
     */
    function liftShutdown() external {
        _onlyOwner();
        if (!isShutdown) revert Cellar__ContractNotShutdown();
        isShutdown = false;

        emit ShutdownChanged(false);
    }

    // =========================================== CONSTRUCTOR ===========================================

    /**
     * @notice Id to get the gravity bridge from the registry.
     */
    uint256 internal constant GRAVITY_BRIDGE_REGISTRY_SLOT = 0;

    /**
     * @notice Id to get the price router from the registry.
     */
    uint256 internal constant PRICE_ROUTER_REGISTRY_SLOT = 2;

    /**
     * @notice The minimum amount of shares to be minted in the contructor.
     */
    uint256 internal constant MINIMUM_CONSTRUCTOR_MINT = 1e4;

    /**
     * @notice Attempted to deploy contract without minting enough shares.
     */
    error Cellar__MinimumConstructorMintNotMet();

    /**
     * @notice Address of the platform's registry contract. Used to get the latest address of modules.
     */
    Registry public immutable registry;

    /**
     * @dev Owner should be set to the Gravity Bridge, which relays instructions from the Steward
     *      module to the cellars.
     *      https://github.com/PeggyJV/steward
     *      https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol
     * @param _registry address of the platform's registry contract
     * @param _asset address of underlying token used for the for accounting, depositing, and withdrawing
     * @param _name name of this cellar's share token
     * @param _symbol symbol of this cellar's share token
     * @param _holdingPosition the holding position of the Cellar
     *        must use a position that does NOT call back to cellar on use(Like ERC20 positions).
     * @param _holdingPositionConfig configuration data for holding position
     * @param _initialDeposit initial amount of assets to deposit into the Cellar
     * @param _strategistPlatformCut platform cut to use
     * @param _shareSupplyCap starting share supply cap
     */
    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint64 _strategistPlatformCut,
        uint192 _shareSupplyCap
    ) ERC4626(_asset, _name, _symbol) Owned(msg.sender) {
        registry = _registry;
        priceRouter = PriceRouter(_registry.getAddress(PRICE_ROUTER_REGISTRY_SLOT));

        // Initialize holding position.
        addPositionToCatalogue(_holdingPosition);
        addPosition(0, _holdingPosition, _holdingPositionConfig, false);
        setHoldingPosition(_holdingPosition);

        // Update Share Supply Cap.
        shareSupplyCap = _shareSupplyCap;

        if (_initialDeposit < MINIMUM_CONSTRUCTOR_MINT) revert Cellar__MinimumConstructorMintNotMet();

        // Deposit into Cellar, and mint shares to Deployer address.
        _asset.safeTransferFrom(_owner, address(this), _initialDeposit);
        // Set the share price as 1:1 with underlying asset.
        _mint(msg.sender, _initialDeposit);
        // Deposit _initialDeposit into holding position.
        _depositTo(_holdingPosition, _initialDeposit);

        feeData.strategistPlatformCut = _strategistPlatformCut;
        transferOwnership(_owner);
    }

    // =========================================== CORE LOGIC ===========================================

    /**
     * @notice Attempted an action with zero shares.
     */
    error Cellar__ZeroShares();

    /**
     * @notice Attempted an action with zero assets.
     */
    error Cellar__ZeroAssets();

    /**
     * @notice Withdraw did not withdraw all assets.
     * @param assetsOwed the remaining assets owed that were not withdrawn.
     */
    error Cellar__IncompleteWithdraw(uint256 assetsOwed);

    /**
     * @notice Attempted to withdraw an illiquid position.
     * @param illiquidPosition the illiquid position.
     */
    error Cellar__IlliquidWithdraw(address illiquidPosition);

    /**
     * @notice called at the beginning of deposit.
     */
    function beforeDeposit(ERC20, uint256, uint256, address) internal view virtual {
        _whenNotShutdown();
        _checkIfPaused();
    }

    /**
     * @notice called at the end of deposit.
     * @param position the position to deposit to.
     * @param assets amount of assets deposited by user.
     */
    function afterDeposit(uint32 position, uint256 assets, uint256, address) internal virtual {
        _depositTo(position, assets);
    }

    /**
     * @notice called at the beginning of withdraw.
     */
    function beforeWithdraw(uint256, uint256, address, address) internal view virtual {
        _checkIfPaused();
    }

    /**
     * @notice Called when users enter the cellar via deposit or mint.
     */
    function _enter(
        ERC20 depositAsset,
        uint32 position,
        uint256 assets,
        uint256 shares,
        address receiver
    ) internal virtual {
        beforeDeposit(asset, assets, shares, receiver);

        // Need to transfer before minting or ERC777s could reenter.
        depositAsset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(position, assets, shares, receiver);
    }

    /**
     * @notice Deposits assets into the cellar, and returns shares to receiver.
     * @param assets amount of assets deposited by user.
     * @param receiver address to receive the shares.
     * @return shares amount of shares given for deposit.
     */
    function deposit(uint256 assets, address receiver) public virtual override nonReentrant returns (uint256 shares) {
        // Use `_calculateTotalAssetsOrTotalAssetsWithdrawable` instead of totalAssets bc re-entrancy is already checked in this function.
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);

        // Check for rounding error since we round down in previewDeposit.
        if ((shares = _convertToShares(assets, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroShares();

        if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded();

        _enter(asset, holdingPosition, assets, shares, receiver);
    }

    /**
     * @notice Mints shares from the cellar, and returns shares to receiver.
     * @param shares amount of shares requested by user.
     * @param receiver address to receive the shares.
     * @return assets amount of assets deposited into the cellar.
     */
    function mint(uint256 shares, address receiver) public override nonReentrant returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);

        // previewMint rounds up, but initial mint could return zero assets, so check for rounding error.
        if ((assets = _previewMint(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets();

        if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded();

        _enter(asset, holdingPosition, assets, shares, receiver);
    }

    /**
     * @notice Called when users exit the cellar via withdraw or redeem.
     */
    function _exit(uint256 assets, uint256 shares, address receiver, address owner) internal {
        beforeWithdraw(assets, shares, receiver, owner);

        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        _burn(owner, shares);

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

        /// @notice `afterWithdraw` is currently not used.
        // afterWithdraw(assets, shares, receiver, owner);
    }

    /**
     * @notice Withdraw assets from the cellar by redeeming shares.
     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.
     *      Since there are no swaps involved in this function, the receiver may receive multiple
     *      assets. The value of all the assets returned will be equal to the amount defined by
     *      `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets`
     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many
     *      tokens).
     * @param assets equivalent value of the assets withdrawn, denominated in the cellar's asset
     * @param receiver address that will receive withdrawn assets
     * @param owner address that owns the shares being redeemed
     * @return shares amount of shares redeemed
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public override nonReentrant returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);

        // No need to check for rounding error, `previewWithdraw` rounds up.
        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);

        _exit(assets, shares, receiver, owner);
    }

    /**
     * @notice Redeem shares to withdraw assets from the cellar.
     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.
     *      Since there are no swaps involved in this function, the receiver may receive multiple
     *      assets. The value of all the assets returned will be equal to the amount defined by
     *      `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets`
     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many
     *      tokens).
     * @param shares amount of shares to redeem
     * @param receiver address that will receive withdrawn assets
     * @param owner address that owns the shares being redeemed
     * @return assets equivalent value of the assets withdrawn, denominated in the cellar's asset
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public override nonReentrant returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);

        // Check for rounding error since we round down in previewRedeem.
        if ((assets = _convertToAssets(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets();

        _exit(assets, shares, receiver, owner);
    }

    /**
     * @notice Struct used in `_withdrawInOrder` in order to hold multiple pricing values in a single variable.
     * @dev Prevents stack too deep errors.
     */
    struct WithdrawPricing {
        uint256 priceBaseUSD;
        uint256 oneBase;
        uint256 priceQuoteUSD;
        uint256 oneQuote;
    }

    /**
     * @notice Multipler used to insure calculations use very high precision.
     */
    uint256 private constant PRECISION_MULTIPLIER = 1e18;

    /**
     * @dev Withdraw from positions in the order defined by `positions`.
     * @param assets the amount of assets to withdraw from cellar
     * @param receiver the address to sent withdrawn assets to
     * @dev Only loop through credit array because debt can not be withdraw by users.
     */
    function _withdrawInOrder(uint256 assets, address receiver) internal {
        // Save asset price in USD, and decimals to reduce external calls.
        WithdrawPricing memory pricingInfo;
        pricingInfo.priceQuoteUSD = priceRouter.getPriceInUSD(asset);
        pricingInfo.oneQuote = 10 ** decimals;
        uint256 creditLength = creditPositions.length;
        for (uint256 i; i < creditLength; ++i) {
            uint32 position = creditPositions[i];
            uint256 withdrawableBalance = _withdrawableFrom(position);
            // Move on to next position if this one is empty.
            if (withdrawableBalance == 0) continue;
            ERC20 positionAsset = _assetOf(position);

            pricingInfo.priceBaseUSD = priceRouter.getPriceInUSD(positionAsset);
            pricingInfo.oneBase = 10 ** positionAsset.decimals();
            uint256 totalWithdrawableBalanceInAssets;
            {
                uint256 withdrawableBalanceInUSD = (PRECISION_MULTIPLIER * withdrawableBalance).mulDivDown(
                    pricingInfo.priceBaseUSD,
                    pricingInfo.oneBase
                );
                totalWithdrawableBalanceInAssets = withdrawableBalanceInUSD.mulDivDown(
                    pricingInfo.oneQuote,
                    pricingInfo.priceQuoteUSD
                );
                totalWithdrawableBalanceInAssets = totalWithdrawableBalanceInAssets / PRECISION_MULTIPLIER;
            }

            // We want to pull as much as we can from this position, but no more than needed.
            uint256 amount;

            if (totalWithdrawableBalanceInAssets > assets) {
                // Convert assets into position asset.
                uint256 assetsInUSD = (PRECISION_MULTIPLIER * assets).mulDivDown(
                    pricingInfo.priceQuoteUSD,
                    pricingInfo.oneQuote
                );
                amount = assetsInUSD.mulDivDown(pricingInfo.oneBase, pricingInfo.priceBaseUSD);
                amount = amount / PRECISION_MULTIPLIER;
                assets = 0;
            } else {
                amount = withdrawableBalance;
                assets = assets - totalWithdrawableBalanceInAssets;
            }

            // Withdraw from position.
            _withdrawFrom(position, amount, receiver);

            // Stop if no more assets to withdraw.
            if (assets == 0) break;
        }
        // If withdraw did not remove all assets owed, revert.
        if (assets > 0) revert Cellar__IncompleteWithdraw(assets);
    }

    // ========================================= ACCOUNTING LOGIC =========================================

    /**
     * @notice Get the Cellars Total Assets, and Total Supply.
     * @dev bool input is not used, but if it were used the following is true.
     *      true: return the largest possible total assets
     *      false: return the smallest possible total assets
     */
    function _getTotalAssetsAndTotalSupply(
        bool
    ) internal view virtual returns (uint256 _totalAssets, uint256 _totalSupply) {
        _totalAssets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);
        _totalSupply = totalSupply;
    }

    /**
     * @notice Internal accounting function that can report total assets, or total assets withdrawable.
     * @param reportWithdrawable if true, then the withdrawable total assets is reported,
     *                           if false, then the total assets is reported
     */
    function _calculateTotalAssetsOrTotalAssetsWithdrawable(
        bool reportWithdrawable
    ) internal view returns (uint256 assets) {
        uint256 numOfCreditPositions = creditPositions.length;
        ERC20[] memory creditAssets = new ERC20[](numOfCreditPositions);
        uint256[] memory creditBalances = new uint256[](numOfCreditPositions);
        // If we just need the withdrawable, then query credit array value.
        if (reportWithdrawable) {
            for (uint256 i; i < numOfCreditPositions; ++i) {
                uint32 position = creditPositions[i];
                // If the withdrawable balance is zero there is no point to query the asset since a zero balance has zero value.
                if ((creditBalances[i] = _withdrawableFrom(position)) == 0) continue;
                creditAssets[i] = _assetOf(position);
            }
            assets = priceRouter.getValues(creditAssets, creditBalances, asset);
        } else {
            uint256 numOfDebtPositions = debtPositions.length;
            ERC20[] memory debtAssets = new ERC20[](numOfDebtPositions);
            uint256[] memory debtBalances = new uint256[](numOfDebtPositions);
            for (uint256 i; i < numOfCreditPositions; ++i) {
                uint32 position = creditPositions[i];
                // If the balance is zero there is no point to query the asset since a zero balance has zero value.
                if ((creditBalances[i] = _balanceOf(position)) == 0) continue;
                creditAssets[i] = _assetOf(position);
            }
            for (uint256 i; i < numOfDebtPositions; ++i) {
                uint32 position = debtPositions[i];
                // If the balance is zero there is no point to query the asset since a zero balance has zero value.
                if ((debtBalances[i] = _balanceOf(position)) == 0) continue;
                debtAssets[i] = _assetOf(position);
            }
            assets = priceRouter.getValuesDelta(creditAssets, creditBalances, debtAssets, debtBalances, asset);
        }
    }

    /**
     * @notice The total amount of assets in the cellar.
     * @dev EIP4626 states totalAssets needs to be inclusive of fees.
     * Since performance fees mint shares, total assets remains unchanged,
     * so this implementation is inclusive of fees even though it does not explicitly show it.
     * @dev EIP4626 states totalAssets must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @dev Run a re-entrancy check because totalAssets can be wrong if re-entering from deposit/withdraws.
     */
    function totalAssets() public view override returns (uint256 assets) {
        _checkIfPaused();
        require(!locked, "REENTRANCY");
        assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);
    }

    /**
     * @notice The total amount of withdrawable assets in the cellar.
     * @dev Run a re-entrancy check because totalAssetsWithdrawable can be wrong if re-entering from deposit/withdraws.
     */
    function totalAssetsWithdrawable() public view returns (uint256 assets) {
        _checkIfPaused();
        require(!locked, "REENTRANCY");
        assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(true);
    }

    /**
     * @notice The amount of assets that the cellar would exchange for the amount of shares provided.
     * @dev Use preview functions to get accurate assets.
     * @dev Under estimates assets.
     * @param shares amount of shares to convert
     * @return assets the shares can be exchanged for
     */
    function convertToAssets(uint256 shares) public view override returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);
        assets = _convertToAssets(shares, _totalAssets, _totalSupply);
    }

    /**
     * @notice The amount of shares that the cellar would exchange for the amount of assets provided.
     * @dev Use preview functions to get accurate shares.
     * @dev Under estimates shares.
     * @param assets amount of assets to convert
     * @return shares the assets can be exchanged for
     */
    function convertToShares(uint256 assets) public view override returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
        shares = _convertToShares(assets, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of minting shares at the current block, given current on-chain conditions.
     * @param shares amount of shares to mint
     * @return assets that will be deposited
     */
    function previewMint(uint256 shares) public view override returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
        assets = _previewMint(shares, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of withdrawing assets at the current block, given current on-chain conditions.
     * @param assets amount of assets to withdraw
     * @return shares that will be redeemed
     */
    function previewWithdraw(uint256 assets) public view override returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);
        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of depositing assets at the current block, given current on-chain conditions.
     * @param assets amount of assets to deposit
     * @return shares that will be minted
     */
    function previewDeposit(uint256 assets) public view override returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
        shares = _convertToShares(assets, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of redeeming shares at the current block, given current on-chain conditions.
     * @param shares amount of shares to redeem
     * @return assets that will be returned
     */
    function previewRedeem(uint256 shares) public view override returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);
        assets = _convertToAssets(shares, _totalAssets, _totalSupply);
    }

    /**
     * @notice Finds the max amount of value an `owner` can remove from the cellar.
     * @param owner address of the user to find max value.
     * @param inShares if false, then returns value in terms of assets
     *                 if true then returns value in terms of shares
     */
    function _findMax(address owner, bool inShares) internal view virtual returns (uint256 maxOut) {
        _checkIfPaused();
        // Get amount of assets to withdraw.
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false);
        uint256 assets = _convertToAssets(balanceOf[owner], _totalAssets, _totalSupply);

        uint256 withdrawable = _calculateTotalAssetsOrTotalAssetsWithdrawable(true);
        maxOut = assets <= withdrawable ? assets : withdrawable;

        if (inShares) maxOut = _convertToShares(maxOut, _totalAssets, _totalSupply);
        // else leave maxOut in terms of assets.
    }

    /**
     * @notice Returns the max amount withdrawable by a user inclusive of performance fees
     * @dev EIP4626 states maxWithdraw must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @param owner address to check maxWithdraw of.
     * @return the max amount of assets withdrawable by `owner`.
     */
    function maxWithdraw(address owner) public view override returns (uint256) {
        require(!locked, "REENTRANCY");
        return _findMax(owner, false);
    }

    /**
     * @notice Returns the max amount shares redeemable by a user
     * @dev EIP4626 states maxRedeem must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @param owner address to check maxRedeem of.
     * @return the max amount of shares redeemable by `owner`.
     */
    function maxRedeem(address owner) public view override returns (uint256) {
        require(!locked, "REENTRANCY");
        return _findMax(owner, true);
    }

    /**
     * @dev Used to more efficiently convert amount of shares to assets using a stored `totalAssets` value.
     */
    function _convertToAssets(
        uint256 shares,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 assets) {
        assets = shares.mulDivDown(_totalAssets, _totalSupply);
    }

    /**
     * @dev Used to more efficiently convert amount of assets to shares using a stored `totalAssets` value.
     */
    function _convertToShares(
        uint256 assets,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 shares) {
        shares = assets.mulDivDown(_totalSupply, _totalAssets);
    }

    /**
     * @dev Used to more efficiently simulate minting shares using a stored `totalAssets` value.
     */
    function _previewMint(
        uint256 shares,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 assets) {
        assets = shares.mulDivUp(_totalAssets, _totalSupply);
    }

    /**
     * @dev Used to more efficiently simulate withdrawing assets using a stored `totalAssets` value.
     */
    function _previewWithdraw(
        uint256 assets,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 shares) {
        shares = assets.mulDivUp(_totalSupply, _totalAssets);
    }

    // =========================================== ADAPTOR LOGIC ===========================================

    /**
     * @notice Emitted on when the rebalance deviation is changed.
     * @param oldDeviation the old rebalance deviation
     * @param newDeviation the new rebalance deviation
     */
    event RebalanceDeviationChanged(uint256 oldDeviation, uint256 newDeviation);

    /**
     * @notice totalAssets deviated outside the range set by `allowedRebalanceDeviation`.
     * @param assets the total assets in the cellar
     * @param min the minimum allowed assets
     * @param max the maximum allowed assets
     */
    error Cellar__TotalAssetDeviatedOutsideRange(uint256 assets, uint256 min, uint256 max);

    /**
     * @notice Total shares in a cellar changed when they should stay constant.
     * @param current the current amount of total shares
     * @param expected the expected amount of total shares
     */
    error Cellar__TotalSharesMustRemainConstant(uint256 current, uint256 expected);

    /**
     * @notice Total shares in a cellar changed when they should stay constant.
     * @param requested the requested rebalance  deviation
     * @param max the max rebalance deviation.
     */
    error Cellar__InvalidRebalanceDeviation(uint256 requested, uint256 max);

    /**
     * @notice Strategist attempted to use an adaptor that is either paused or is not trusted by governance.
     * @param adaptor the adaptor address that is paused or not trusted.
     */
    error Cellar__CallToAdaptorNotAllowed(address adaptor);

    /**
     * @notice Stores the max possible rebalance deviation for this cellar.
     */
    uint64 internal constant MAX_REBALANCE_DEVIATION = 0.1e18;

    /**
     * @notice The percent the total assets of a cellar may deviate during a `callOnAdaptor`(rebalance) call.
     */
    uint256 internal allowedRebalanceDeviation = 0.0003e18;

    /**
     * @notice Allows governance to change this cellars rebalance deviation.
     * @param newDeviation the new rebalance deviation value.
     * @dev Callable by Sommelier Governance.
     */
    function setRebalanceDeviation(uint256 newDeviation) external {
        _onlyOwner();
        if (newDeviation > MAX_REBALANCE_DEVIATION)
            revert Cellar__InvalidRebalanceDeviation(newDeviation, MAX_REBALANCE_DEVIATION);

        uint256 oldDeviation = allowedRebalanceDeviation;
        allowedRebalanceDeviation = newDeviation;

        emit RebalanceDeviationChanged(oldDeviation, newDeviation);
    }

    /**
     * @notice Struct used to make calls to adaptors.
     * @param adaptor the address of the adaptor to make calls to
     * @param the abi encoded function calls to make to the `adaptor`
     */
    struct AdaptorCall {
        address adaptor;
        bytes[] callData;
    }

    /**
     * @notice Emitted when adaptor calls are made.
     */
    event AdaptorCalled(address adaptor, bytes data);

    /**
     * @notice Internal helper function that accepts an Adaptor Call array, and makes calls to each adaptor.
     */
    function _makeAdaptorCalls(AdaptorCall[] memory data) internal {
        for (uint256 i = 0; i < data.length; ++i) {
            address adaptor = data[i].adaptor;
            // Revert if adaptor not in catalogue, or adaptor is paused.
            if (!adaptorCatalogue[adaptor]) revert Cellar__CallToAdaptorNotAllowed(adaptor);
            for (uint256 j = 0; j < data[i].callData.length; j++) {
                adaptor.functionDelegateCall(data[i].callData[j]);
                emit AdaptorCalled(adaptor, data[i].callData[j]);
            }
        }
    }

    /**
     * @notice Allows strategists to manage their Cellar using arbitrary logic calls to adaptors.
     * @dev There are several safety checks in this function to prevent strategists from abusing it.
     *      - `blockExternalReceiver`
     *      - `totalAssets` must not change by much
     *      - `totalShares` must remain constant
     *      - adaptors must be set up to be used with this cellar
     * @dev Since `totalAssets` is allowed to deviate slightly, strategists could abuse this by sending
     *      multiple `callOnAdaptor` calls rapidly, to gradually change the share price.
     *      To mitigate this, rate limiting will be put in place on the Sommelier side.
     * @dev Callable by Sommelier Strategist, and Automation Actions contract.
     */
    function callOnAdaptor(AdaptorCall[] calldata data) external virtual nonReentrant {
        _onlyOwner();
        _whenNotShutdown();
        _checkIfPaused();
        blockExternalReceiver = true;

        // Record `totalAssets` and `totalShares` before making any external calls.
        uint256 minimumAllowedAssets;
        uint256 maximumAllowedAssets;
        uint256 totalShares;
        {
            uint256 assetsBeforeAdaptorCall = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);
            minimumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 - allowedRebalanceDeviation), 1e18);
            maximumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 + allowedRebalanceDeviation), 1e18);
            totalShares = totalSupply;
        }

        // Run all adaptor calls.
        _makeAdaptorCalls(data);

        // After making every external call, check that the totalAssets has not deviated significantly, and that totalShares is the same.
        uint256 assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false);
        if (assets < minimumAllowedAssets || assets > maximumAllowedAssets) {
            revert Cellar__TotalAssetDeviatedOutsideRange(assets, minimumAllowedAssets, maximumAllowedAssets);
        }
        if (totalShares != totalSupply) revert Cellar__TotalSharesMustRemainConstant(totalSupply, totalShares);

        blockExternalReceiver = false;
    }

    // ============================================ LIMITS LOGIC ============================================

    /**
     * @notice Attempted entry would raise totalSupply above Share Supply Cap.
     */
    error Cellar__ShareSupplyCapExceeded();

    /**
     * @notice Proposed share supply cap is not logical.
     */
    error Cellar__InvalidShareSupplyCap();

    /**
     * @notice Increases the share supply cap.
     * @dev Callable by Sommelier Governance.
     */
    function increaseShareSupplyCap(uint192 _newShareSupplyCap) public {
        _onlyOwner();
        if (_newShareSupplyCap < shareSupplyCap) revert Cellar__InvalidShareSupplyCap();

        shareSupplyCap = _newShareSupplyCap;
    }

    /**
     * @notice Decreases the share supply cap.
     * @dev Callable by Sommelier Strategist.
     */
    function decreaseShareSupplyCap(uint192 _newShareSupplyCap) public {
        _onlyOwner();
        if (_newShareSupplyCap > shareSupplyCap) revert Cellar__InvalidShareSupplyCap();

        shareSupplyCap = _newShareSupplyCap;
    }

    /**
     * @notice Total amount of assets that can be deposited for a user.
     * @return assets maximum amount of assets that can be deposited
     */
    function maxDeposit(address) public view override returns (uint256) {
        if (isShutdown) return 0;

        uint192 _cap = shareSupplyCap;
        if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max;

        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
        if (_totalSupply >= _cap) return 0;
        else {
            uint256 shareDelta = _cap - _totalSupply;
            return _convertToAssets(shareDelta, _totalAssets, _totalSupply);
        }
    }

    /**
     * @notice Total amount of shares that can be minted for a user.
     * @return shares maximum amount of shares that can be minted
     */
    function maxMint(address) public view override returns (uint256) {
        if (isShutdown) return 0;

        uint192 _cap;
        if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max;

        uint256 _totalSupply = totalSupply;

        return _totalSupply >= _cap ? 0 : _cap - _totalSupply;
    }

    // ========================================== HELPER FUNCTIONS ==========================================

    /**
     * @dev Deposit into a position according to its position type and update related state.
     * @param position address to deposit funds into
     * @param assets the amount of assets to deposit into the position
     */
    function _depositTo(uint32 position, uint256 assets) internal {
        address adaptor = getPositionData[position].adaptor;
        adaptor.functionDelegateCall(
            abi.encodeWithSelector(
                BaseAdaptor.deposit.selector,
                assets,
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            )
        );
    }

    /**
     * @dev Withdraw from a position according to its position type and update related state.
     * @param position address to withdraw funds from
     * @param assets the amount of assets to withdraw from the position
     * @param receiver the address to sent withdrawn assets to
     */
    function _withdrawFrom(uint32 position, uint256 assets, address receiver) internal {
        address adaptor = getPositionData[position].adaptor;
        adaptor.functionDelegateCall(
            abi.encodeWithSelector(
                BaseAdaptor.withdraw.selector,
                assets,
                receiver,
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            )
        );
    }

    /**
     * @dev Get the withdrawable balance of a position according to its position type.
     * @param position position to get the withdrawable balance of
     */
    function _withdrawableFrom(uint32 position) internal view returns (uint256) {
        // Debt positions always return 0 for their withdrawable.
        if (getPositionData[position].isDebt) return 0;
        return
            BaseAdaptor(getPositionData[position].adaptor).withdrawableFrom(
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            );
    }

    /**
     * @dev Get the balance of a position according to its position type.
     * @dev For ERC4626 position balances, this uses `previewRedeem` as opposed
     *      to `convertToAssets` so that balanceOf ERC4626 positions includes fees taken on withdraw.
     * @param position position to get the balance of
     */
    function _balanceOf(uint32 position) internal view returns (uint256) {
        address adaptor = getPositionData[position].adaptor;
        return BaseAdaptor(adaptor).balanceOf(getPositionData[position].adaptorData);
    }

    /**
     * @dev Get the asset of a position according to its position type.
     * @param position to get the asset of
     */
    function _assetOf(uint32 position) internal view returns (ERC20) {
        address adaptor = getPositionData[position].adaptor;
        return BaseAdaptor(adaptor).assetOf(getPositionData[position].adaptorData);
    }

    /**
     * @notice Attempted to use an address from the registry, but address was not expected.
     */
    error Cellar__ExpectedAddressDoesNotMatchActual();

    /**
     * @notice Attempted to set an address to registry Id 0.
     */
    error Cellar__SettingValueToRegistryIdZeroIsProhibited();

    /**
     * @notice Verify that `_registryId` in registry corresponds to expected address.
     */
    function _checkRegistryAddressAgainstExpected(uint256 _registryId, address _expected) internal view {
        if (_registryId == 0) revert Cellar__SettingValueToRegistryIdZeroIsProhibited();
        if (registry.getAddress(_registryId) != _expected) revert Cellar__ExpectedAddressDoesNotMatchActual();
    }
}

File 3 of 44 : CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Registry, ERC20, Math, SafeTransferLib, Address } from "src/base/Cellar.sol";
import { CellarWithOracleWithBalancerFlashLoans } from "src/base/permutations/CellarWithOracleWithBalancerFlashLoans.sol";

contract CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit is CellarWithOracleWithBalancerFlashLoans {
    using Math for uint256;
    using SafeTransferLib for ERC20;
    using Address for address;

    // ========================================= STRUCTS =========================================

    /**
     * @notice Stores data needed for multi-asset deposits into this cellar.
     * @param isSupported bool indicating that mapped asset is supported
     * @param holdingPosition the holding position to deposit alternative assets into
     * @param depositFee fee taken for depositing this alternative asset
     */
    struct AlternativeAssetData {
        bool isSupported;
        uint32 holdingPosition;
        uint32 depositFee;
    }

    // ========================================= CONSTANTS =========================================

    /**
     * @notice The max possible fee that can be charged for an alternative asset deposit.
     */
    uint32 internal constant MAX_ALTERNATIVE_ASSET_FEE = 0.1e8;

    // ========================================= GLOBAL STATE =========================================

    /**
     * @notice Maps alternative assets to alternative asset data.
     */
    mapping(ERC20 => AlternativeAssetData) public alternativeAssetData;

    //============================== ERRORS ===============================

    error CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge();
    error CellarWithMultiAssetDeposit__AlternativeAssetNotSupported();
    error CellarWithMultiAssetDeposit__CallDataLengthNotSupported();

    //============================== EVENTS ===============================

    /**
     * @notice Emitted when an alternative asset is added or updated.
     */
    event AlternativeAssetUpdated(address asset, uint32 holdingPosition, uint32 depositFee);

    /**
     * @notice Emitted when an alternative asser is removed.
     */
    event AlternativeAssetDropped(address asset);

    /**
     * @notice Emitted during multi asset deposits.
     * @dev Multi asset deposits will emit 2 events, the ERC4626 compliant Deposit event
     *      and this event. These events were intentionally separated out so we can
     *      keep the compliant event, but also have an event that emits the depositAsset.
     */
    event MultiAssetDeposit(
        address indexed caller,
        address indexed owner,
        address depositAsset,
        uint256 assets,
        uint256 shares
    );

    //============================== IMMUTABLES ===============================

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint64 _strategistPlatformCut,
        uint192 _shareSupplyCap,
        address _balancerVault
    )
        CellarWithOracleWithBalancerFlashLoans(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _strategistPlatformCut,
            _shareSupplyCap,
            _balancerVault
        )
    {}

    //============================== OWNER FUNCTIONS ===============================

    /**
     * @notice Allows the owner to add, or update an existing alternative asset deposit.
     * @dev Callable by Sommelier Strategists.
     * @param _alternativeAsset the ERC20 alternative asset that can be deposited
     * @param _alternativeHoldingPosition the holding position to direct alternative asset deposits to
     * @param _alternativeAssetFee the fee to charge for depositing this alternative asset
     */
    function setAlternativeAssetData(
        ERC20 _alternativeAsset,
        uint32 _alternativeHoldingPosition,
        uint32 _alternativeAssetFee
    ) external {
        _onlyOwner();
        if (!isPositionUsed[_alternativeHoldingPosition]) revert Cellar__PositionNotUsed(_alternativeHoldingPosition);
        if (_assetOf(_alternativeHoldingPosition) != _alternativeAsset)
            revert Cellar__AssetMismatch(address(_alternativeAsset), address(_assetOf(_alternativeHoldingPosition)));
        if (getPositionData[_alternativeHoldingPosition].isDebt)
            revert Cellar__InvalidHoldingPosition(_alternativeHoldingPosition);
        if (_alternativeAssetFee > MAX_ALTERNATIVE_ASSET_FEE)
            revert CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge();

        alternativeAssetData[_alternativeAsset] = AlternativeAssetData(
            true,
            _alternativeHoldingPosition,
            _alternativeAssetFee
        );

        emit AlternativeAssetUpdated(address(_alternativeAsset), _alternativeHoldingPosition, _alternativeAssetFee);
    }

    /**
     * @notice Allows the owner to stop an alternative asset from being deposited.
     * @dev Callable by Sommelier Strategists.
     * @param _alternativeAsset the asset to not allow for alternative asset deposits anymore
     */
    function dropAlternativeAssetData(ERC20 _alternativeAsset) external {
        _onlyOwner();
        delete alternativeAssetData[_alternativeAsset];

        emit AlternativeAssetDropped(address(_alternativeAsset));
    }

    /**
     * @notice Deposits assets into the cellar, and returns shares to receiver.
     * @param assets amount of assets deposited by user.
     * @param receiver address to receive the shares.
     * @return shares amount of shares given for deposit.
     */
    function deposit(uint256 assets, address receiver) public override nonReentrant returns (uint256 shares) {
        shares = _deposit(asset, assets, assets, assets, holdingPosition, receiver);
    }

    /**
     * @notice Allows users to deposit into cellar using alternative assets.
     * @param depositAsset the asset to deposit
     * @param assets amount of depositAsset to deposit
     * @param receiver address to receive the shares
     */
    function multiAssetDeposit(
        ERC20 depositAsset,
        uint256 assets,
        address receiver
    ) public nonReentrant returns (uint256 shares) {
        // Convert assets from depositAsset to asset.
        (
            uint256 assetsConvertedToAsset,
            uint256 assetsConvertedToAssetWithFeeRemoved,
            uint32 position
        ) = _getMultiAssetDepositData(depositAsset, assets);

        shares = _deposit(
            depositAsset,
            assets,
            assetsConvertedToAsset,
            assetsConvertedToAssetWithFeeRemoved,
            position,
            receiver
        );

        emit MultiAssetDeposit(msg.sender, receiver, address(depositAsset), assets, shares);
    }

    //============================== PREVIEW FUNCTIONS ===============================

    /**
     * @notice Preview function to see how many shares a multi asset deposit will give user.
     */
    function previewMultiAssetDeposit(ERC20 depositAsset, uint256 assets) external view returns (uint256 shares) {
        // Convert assets from depositAsset to asset.
        (uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, ) = _getMultiAssetDepositData(
            depositAsset,
            assets
        );

        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
        shares = _convertToShares(
            assetsConvertedToAssetWithFeeRemoved,
            _totalAssets + (assetsConvertedToAsset - assetsConvertedToAssetWithFeeRemoved),
            _totalSupply
        );
    }

    //============================== HELPER FUNCTIONS ===============================

    /**
     * @notice Helper function to fulfill normal deposits and multi asset deposits.
     */
    function _deposit(
        ERC20 depositAsset,
        uint256 assets,
        uint256 assetsConvertedToAsset,
        uint256 assetsConvertedToAssetWithFeeRemoved,
        uint32 position,
        address receiver
    ) internal returns (uint256 shares) {
        // Use `_calculateTotalAssetsOrTotalAssetsWithdrawable` instead of totalAssets bc re-entrancy is already checked in this function.
        (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);

        // Perform share calculation using assetsConvertedToAssetWithFeeRemoved.
        // Check for rounding error since we round down in previewDeposit.
        // NOTE for totalAssets, we add the delta between assetsConvertedToAsset, and assetsConvertedToAssetWithFeeRemoved, so that the fee the caller pays
        // to join with the alternative asset is factored into share price calculation.
        if (
            (shares = _convertToShares(
                assetsConvertedToAssetWithFeeRemoved,
                _totalAssets + (assetsConvertedToAsset - assetsConvertedToAssetWithFeeRemoved),
                _totalSupply
            )) == 0
        ) revert Cellar__ZeroShares();

        if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded();

        // _enter into holding position but passing in actual assets.
        _enter(depositAsset, position, assets, shares, receiver);
    }

    /**
     * @notice Helper function to verify asset is supported for multi asset deposit,
     *         convert assets from depositAsset to asset, and account for alternative asset fee.
     */
    function _getMultiAssetDepositData(
        ERC20 depositAsset,
        uint256 assets
    )
        internal
        view
        returns (uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, uint32 position)
    {
        AlternativeAssetData memory assetData = alternativeAssetData[depositAsset];
        if (!assetData.isSupported) revert CellarWithMultiAssetDeposit__AlternativeAssetNotSupported();

        // Convert assets from depositAsset to asset.
        assetsConvertedToAsset = priceRouter.getValue(depositAsset, assets, asset);

        // Collect alternative asset fee.
        assetsConvertedToAssetWithFeeRemoved = assetsConvertedToAsset.mulDivDown(1e8 - assetData.depositFee, 1e8);

        position = assetData.holdingPosition;
    }
}

File 4 of 44 : Math.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

library Math {
    /**
     * @notice Substract with a floor of 0 for the result.
     */
    function subMinZero(uint256 x, uint256 y) internal pure returns (uint256) {
        return x > y ? x - y : 0;
    }

    /**
     * @notice Used to change the decimals of precision used for an amount.
     */
    function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * 10 ** (toDecimals - fromDecimals);
        } else {
            return amount / 10 ** (fromDecimals - toDecimals);
        }
    }

    // ===================================== OPENZEPPELIN'S MATH =====================================

    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    // ================================= SOLMATE's FIXEDPOINTMATHLIB =================================

    uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // Divide z by the denominator.
            z := div(z, denominator)
        }
    }

    function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // First, divide z - 1 by the denominator and add 1.
            // We allow z - 1 to underflow if z is 0, because we multiply the
            // end result by 0 if z is zero, ensuring we return 0 if z is zero.
            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
        }
    }
}

File 5 of 44 : ERC4626.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";

/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);

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

    /*//////////////////////////////////////////////////////////////
                               IMMUTABLES
    //////////////////////////////////////////////////////////////*/

    ERC20 public immutable asset;

    constructor(
        ERC20 _asset,
        string memory _name,
        string memory _symbol
    ) ERC20(_name, _symbol, _asset.decimals()) {
        asset = _asset;
    }

    /*//////////////////////////////////////////////////////////////
                        DEPOSIT/WITHDRAWAL LOGIC
    //////////////////////////////////////////////////////////////*/

    function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
        // Check for rounding error since we round down in previewDeposit.
        require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");

        // Need to transfer before minting or ERC777s could reenter.
        asset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(assets, shares);
    }

    function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
        assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.

        // Need to transfer before minting or ERC777s could reenter.
        asset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(assets, shares);
    }

    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public virtual returns (uint256 shares) {
        shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.

        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        beforeWithdraw(assets, shares);

        _burn(owner, shares);

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

        asset.safeTransfer(receiver, assets);
    }

    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public virtual returns (uint256 assets) {
        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        // Check for rounding error since we round down in previewRedeem.
        require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");

        beforeWithdraw(assets, shares);

        _burn(owner, shares);

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

        asset.safeTransfer(receiver, assets);
    }

    /*//////////////////////////////////////////////////////////////
                            ACCOUNTING LOGIC
    //////////////////////////////////////////////////////////////*/

    function totalAssets() public view virtual returns (uint256);

    function convertToShares(uint256 assets) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
    }

    function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
    }

    function previewDeposit(uint256 assets) public view virtual returns (uint256) {
        return convertToShares(assets);
    }

    function previewMint(uint256 shares) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
    }

    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
    }

    function previewRedeem(uint256 shares) public view virtual returns (uint256) {
        return convertToAssets(shares);
    }

    /*//////////////////////////////////////////////////////////////
                     DEPOSIT/WITHDRAWAL LIMIT LOGIC
    //////////////////////////////////////////////////////////////*/

    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return convertToAssets(balanceOf[owner]);
    }

    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf[owner];
    }

    /*//////////////////////////////////////////////////////////////
                          INTERNAL HOOKS LOGIC
    //////////////////////////////////////////////////////////////*/

    function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}

    function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}

File 6 of 44 : SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @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.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

File 7 of 44 : ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

File 8 of 44 : Registry.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Cellar } from "src/base/Cellar.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { BaseAdaptor } from "src/modules/adaptors/BaseAdaptor.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";

contract Registry is Ownable {
    // ============================================= ADDRESS CONFIG =============================================

    /**
     * @notice Emitted when the address of a contract is changed.
     * @param id value representing the unique ID tied to the changed contract
     * @param oldAddress address of the contract before the change
     * @param newAddress address of the contract after the contract
     */
    event AddressChanged(uint256 indexed id, address oldAddress, address newAddress);

    /**
     * @notice Attempted to set the address of a contract that is not registered.
     * @param id id of the contract that is not registered
     */
    error Registry__ContractNotRegistered(uint256 id);

    /**
     * @notice Emitted when depositor privilege changes.
     * @param depositor depositor address
     * @param state the new state of the depositor privilege
     */
    event DepositorOnBehalfChanged(address depositor, bool state);

    /**
     * @notice The unique ID that the next registered contract will have.
     */
    uint256 public nextId;

    /**
     * @notice Get the address associated with an id.
     */
    mapping(uint256 => address) public getAddress;

    /**
     * @notice In order for an address to make deposits on behalf of users they must be approved.
     */
    mapping(address => bool) public approvedForDepositOnBehalf;

    /**
     * @notice toggles a depositors  ability to deposit into cellars on behalf of users.
     */
    function setApprovedForDepositOnBehalf(address depositor, bool state) external onlyOwner {
        approvedForDepositOnBehalf[depositor] = state;
        emit DepositorOnBehalfChanged(depositor, state);
    }

    /**
     * @notice Set the address of the contract at a given id.
     */
    function setAddress(uint256 id, address newAddress) external {
        if (id > 0) {
            _checkOwner();
            if (id >= nextId) revert Registry__ContractNotRegistered(id);
        } else {
            if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        }

        emit AddressChanged(id, getAddress[id], newAddress);

        getAddress[id] = newAddress;
    }

    // ============================================= INITIALIZATION =============================================

    /**
     * @param gravityBridge address of GravityBridge contract
     * @param swapRouter address of SwapRouter contract
     * @param priceRouter address of PriceRouter contract
     */
    constructor(address newOwner, address gravityBridge, address swapRouter, address priceRouter) Ownable() {
        _register(gravityBridge);
        _register(swapRouter);
        _register(priceRouter);
        transferOwnership(newOwner);
    }

    // ============================================ REGISTER CONFIG ============================================

    /**
     * @notice Emitted when a new contract is registered.
     * @param id value representing the unique ID tied to the new contract
     * @param newContract address of the new contract
     */
    event Registered(uint256 indexed id, address indexed newContract);

    /**
     * @notice Register the address of a new contract.
     * @param newContract address of the new contract to register
     */
    function register(address newContract) external onlyOwner {
        _register(newContract);
    }

    function _register(address newContract) internal {
        getAddress[nextId] = newContract;

        emit Registered(nextId, newContract);

        nextId++;
    }

    // ============================================= ADDRESS 0 LOGIC =============================================
    /**
     * Address 0 is the address of the gravity bridge, and special abilities that the owner does not have.
     * - It can change what address is stored at address 0.
     * - It can change the owner of this contract.
     */

    /**
     * @notice Emitted when an ownership transition is started.
     */
    event OwnerTransitionStarted(address newOwner, uint256 startTime);

    /**
     * @notice Emitted when an ownership transition is cancelled.
     */
    event OwnerTransitionCancelled();

    /**
     * @notice Emitted when an ownership transition is completed.
     */
    event OwnerTransitionComplete(address newOwner);

    /**
     * @notice Attempted to call a function intended for Zero Id address.
     */
    error Registry__OnlyCallableByZeroId();

    /**
     * @notice Attempted to transition owner to the zero address.
     */
    error Registry__NewOwnerCanNotBeZero();

    /**
     * @notice Attempted to perform a restricted action while ownership transition is pending.
     */
    error Registry__TransitionPending();

    /**
     * @notice Attempted to cancel or complete a transition when one is not active.
     */
    error Registry__TransitionNotPending();

    /**
     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.
     */
    error Registry__OnlyCallableByPendingOwner();

    /**
     * @notice The amount of time it takes for an ownership transition to work.
     */
    uint256 public constant TRANSITION_PERIOD = 7 days;

    /**
     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.
     */
    address public pendingOwner;

    /**
     * @notice The starting time stamp of the transition.
     */
    uint256 public transitionStart;

    /**
     * @notice Allows Zero Id address to set a new owner, after the transition period is up.
     */
    function transitionOwner(address newOwner) external {
        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        if (pendingOwner != address(0)) revert Registry__TransitionPending();
        if (newOwner == address(0)) revert Registry__NewOwnerCanNotBeZero();

        pendingOwner = newOwner;
        transitionStart = block.timestamp;
    }

    /**
     * @notice Allows Zero Id address to cancel an ongoing owner transition.
     */
    function cancelTransition() external {
        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        if (pendingOwner == address(0)) revert Registry__TransitionNotPending();

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Allows pending owner to complete the ownership transition.
     */
    function completeTransition() external {
        if (pendingOwner == address(0)) revert Registry__TransitionNotPending();
        if (msg.sender != pendingOwner) revert Registry__OnlyCallableByPendingOwner();
        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert Registry__TransitionPending();

        _transferOwnership(pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.
     */
    function _checkOwner() internal view override {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        if (transitionStart != 0) revert Registry__TransitionPending();
    }

    // ============================================ PAUSE LOGIC ============================================

    /**
     * @notice Emitted when a target is paused.
     */
    event TargetPaused(address target);

    /**
     * @notice Emitted when a target is unpaused.
     */
    event TargetUnpaused(address target);

    /**
     * @notice Attempted to unpause a target that was not paused.
     */
    error Registry__TargetNotPaused(address target);

    /**
     * @notice Attempted to pause a target that was already paused.
     */
    error Registry__TargetAlreadyPaused(address target);

    /**
     * @notice Mapping stores whether or not a cellar is paused.
     */
    mapping(address => bool) public isCallerPaused;

    /**
     * @notice Allows multisig to pause multiple cellars in a single call.
     */
    function batchPause(address[] calldata targets) external onlyOwner {
        for (uint256 i; i < targets.length; ++i) _pauseTarget(targets[i]);
    }

    /**
     * @notice Allows multisig to unpause multiple cellars in a single call.
     */
    function batchUnpause(address[] calldata targets) external onlyOwner {
        for (uint256 i; i < targets.length; ++i) _unpauseTarget(targets[i]);
    }

    /**
     * @notice Helper function to pause some target.
     */
    function _pauseTarget(address target) internal {
        if (isCallerPaused[target]) revert Registry__TargetAlreadyPaused(target);
        isCallerPaused[target] = true;
        emit TargetPaused(target);
    }

    /**
     * @notice Helper function to unpause some target.
     */
    function _unpauseTarget(address target) internal {
        if (!isCallerPaused[target]) revert Registry__TargetNotPaused(target);
        isCallerPaused[target] = false;
        emit TargetUnpaused(target);
    }

    // ============================================ ADAPTOR LOGIC ============================================

    /**
     * @notice Attempted to trust an adaptor with non unique identifier.
     */
    error Registry__IdentifierNotUnique();

    /**
     * @notice Attempted to use an untrusted adaptor.
     */
    error Registry__AdaptorNotTrusted(address adaptor);

    /**
     * @notice Attempted to trust an already trusted adaptor.
     */
    error Registry__AdaptorAlreadyTrusted(address adaptor);

    /**
     * @notice Maps an adaptor address to bool indicating whether it has been set up in the registry.
     */
    mapping(address => bool) public isAdaptorTrusted;

    /**
     * @notice Maps an adaptors identfier to bool, to track if the identifier is unique wrt the registry.
     */
    mapping(bytes32 => bool) public isIdentifierUsed;

    /**
     * @notice Trust an adaptor to be used by cellars
     * @param adaptor address of the adaptor to trust
     */
    function trustAdaptor(address adaptor) external onlyOwner {
        if (isAdaptorTrusted[adaptor]) revert Registry__AdaptorAlreadyTrusted(adaptor);
        bytes32 identifier = BaseAdaptor(adaptor).identifier();
        if (isIdentifierUsed[identifier]) revert Registry__IdentifierNotUnique();
        isAdaptorTrusted[adaptor] = true;
        isIdentifierUsed[identifier] = true;
    }

    /**
     * @notice Allows registry to distrust adaptors.
     * @dev Doing so prevents Cellars from adding this adaptor to their catalogue.
     */
    function distrustAdaptor(address adaptor) external onlyOwner {
        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);
        // Set trust to false.
        isAdaptorTrusted[adaptor] = false;

        // We are NOT resetting `isIdentifierUsed` because if this adaptor is distrusted, then something needs
        // to change about the new one being re-trusted.
    }

    /**
     * @notice Reverts if `adaptor` is not trusted by the registry.
     */
    function revertIfAdaptorIsNotTrusted(address adaptor) external view {
        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);
    }

    // ============================================ POSITION LOGIC ============================================
    /**
     * @notice stores data related to Cellar positions.
     * @param adaptors address of the adaptor to use for this position
     * @param isDebt bool indicating whether this position takes on debt or not
     * @param adaptorData arbitrary data needed to correclty set up a position
     * @param configurationData arbitrary data settable by strategist to change cellar <-> adaptor interaction
     */
    struct PositionData {
        address adaptor;
        bool isDebt;
        bytes adaptorData;
        bytes configurationData;
    }

    /**
     * @notice Emitted when a new position is added to the registry.
     * @param id the positions id
     * @param adaptor address of the adaptor this position uses
     * @param isDebt bool indicating whether this position takes on debt or not
     * @param adaptorData arbitrary bytes used to configure this position
     */
    event Registry__PositionTrusted(uint32 id, address adaptor, bool isDebt, bytes adaptorData);

    /**
     * @notice Emitted when a position is distrusted.
     * @param id the positions id
     */
    event Registry__PositionDistrusted(uint32 id);

    /**
     * @notice Attempted to trust a position not being used.
     * @param position address of the invalid position
     */
    error Registry__PositionPricingNotSetUp(address position);

    /**
     * @notice Attempted to add a position with bad input values.
     */
    error Registry__InvalidPositionInput();

    /**
     * @notice Attempted to add a position that does not exist.
     */
    error Registry__PositionDoesNotExist();

    /**
     * @notice Attempted to add a position that is not trusted.
     */
    error Registry__PositionIsNotTrusted(uint32 position);

    /**
     * @notice Addresses of the positions currently used by the cellar.
     */
    uint256 public constant PRICE_ROUTER_REGISTRY_SLOT = 2;

    /**
     * @notice Maps a position hash to a position Id.
     * @dev can be used by adaptors to verify that a certain position is open during Cellar `callOnAdaptor` calls.
     */
    mapping(bytes32 => uint32) public getPositionHashToPositionId;

    /**
     * @notice Maps a position id to its position data.
     * @dev used by Cellars when adding new positions.
     */
    mapping(uint32 => PositionData) public getPositionIdToPositionData;

    /**
     * @notice Maps a position to a bool indicating whether or not it is trusted.
     */
    mapping(uint32 => bool) public isPositionTrusted;

    /**
     * @notice Trust a position to be used by the cellar.
     * @param positionId the position id of the newly added position
     * @param adaptor the adaptor address this position uses
     * @param adaptorData arbitrary bytes used to configure this position
     */
    function trustPosition(uint32 positionId, address adaptor, bytes memory adaptorData) external onlyOwner {
        bytes32 identifier = BaseAdaptor(adaptor).identifier();
        bool isDebt = BaseAdaptor(adaptor).isDebt();
        bytes32 positionHash = keccak256(abi.encode(identifier, isDebt, adaptorData));

        if (positionId == 0) revert Registry__InvalidPositionInput();
        // Make sure positionId is not already in use.
        PositionData storage pData = getPositionIdToPositionData[positionId];
        if (pData.adaptor != address(0)) revert Registry__InvalidPositionInput();

        // Check that...
        // `adaptor` is a non zero address
        // position has not been already set up
        if (adaptor == address(0) || getPositionHashToPositionId[positionHash] != 0)
            revert Registry__InvalidPositionInput();

        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);

        // Set position data.
        pData.adaptor = adaptor;
        pData.isDebt = isDebt;
        pData.adaptorData = adaptorData;
        pData.configurationData = abi.encode(0);

        // Globally trust the position.
        isPositionTrusted[positionId] = true;

        getPositionHashToPositionId[positionHash] = positionId;

        // Check that assets position uses are supported for pricing operations.
        ERC20[] memory assets = BaseAdaptor(adaptor).assetsUsed(adaptorData);
        PriceRouter priceRouter = PriceRouter(getAddress[PRICE_ROUTER_REGISTRY_SLOT]);
        for (uint256 i; i < assets.length; i++) {
            if (!priceRouter.isSupported(assets[i])) revert Registry__PositionPricingNotSetUp(address(assets[i]));
        }

        emit Registry__PositionTrusted(positionId, adaptor, isDebt, adaptorData);
    }

    /**
     * @notice Allows registry to distrust positions.
     * @dev Doing so prevents Cellars from adding this position to their catalogue,
     *      and adding the position to their tracked arrays.
     */
    function distrustPosition(uint32 positionId) external onlyOwner {
        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);
        isPositionTrusted[positionId] = false;
        emit Registry__PositionDistrusted(positionId);
    }

    /**
     * @notice Called by Cellars to add a new position to themselves.
     * @param positionId the id of the position the cellar wants to add
     * @return adaptor the address of the adaptor, isDebt bool indicating whether position is
     *         debt or not, and adaptorData needed to interact with position
     */
    function addPositionToCellar(
        uint32 positionId
    ) external view returns (address adaptor, bool isDebt, bytes memory adaptorData) {
        if (positionId == 0) revert Registry__PositionDoesNotExist();
        PositionData memory positionData = getPositionIdToPositionData[positionId];
        if (positionData.adaptor == address(0)) revert Registry__PositionDoesNotExist();

        revertIfPositionIsNotTrusted(positionId);

        return (positionData.adaptor, positionData.isDebt, positionData.adaptorData);
    }

    /**
     * @notice Reverts if `positionId` is not trusted by the registry.
     */
    function revertIfPositionIsNotTrusted(uint32 positionId) public view {
        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);
    }
}

File 9 of 44 : PriceRouter.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Math } from "src/utils/Math.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Extension } from "src/modules/price-router/Extensions/Extension.sol";
import { Registry } from "src/Registry.sol";

import { UniswapV3Pool } from "src/interfaces/external/UniswapV3Pool.sol";
import { OracleLibrary } from "@uniswapV3P/libraries/OracleLibrary.sol";

/**
 * @title Sommelier Price Router
 * @notice Provides a universal interface allowing Sommelier contracts to retrieve secure pricing
 *         data from Chainlink.
 * @author crispymangoes
 */
contract PriceRouter is Ownable {
    using SafeTransferLib for ERC20;
    using SafeCast for int256;
    using Math for uint256;
    using Address for address;

    event AddAsset(address indexed asset);

    event IntentToEditAsset(
        address asset,
        AssetSettings _settings,
        bytes _storage,
        bytes32 editHash,
        uint256 assetEditableAt
    );

    event EditAssetCancelled(address asset, bytes32 editHash);

    event EditAssetComplete(address asset, bytes32 editHash);

    Registry public immutable registry;
    ERC20 public immutable WETH;

    constructor(address newOwner, Registry _registry, ERC20 _weth) {
        registry = _registry;
        WETH = _weth;
        transferOwnership(newOwner);
    }

    // =========================================== ASSETS CONFIG ===========================================
    /**
     * @notice Bare minimum settings all derivatives support.
     * @param derivative the derivative used to price the asset
     * @param source the address used to price the asset
     */
    struct AssetSettings {
        uint8 derivative;
        address source;
    }

    /**
     * @notice Mapping between an asset to price and its `AssetSettings`.
     */
    mapping(ERC20 => AssetSettings) public getAssetSettings;

    // ======================================= OWNERSHIP TRANSISITION =======================================

    /**
     * @notice Emitted when an ownership transition is started.
     */
    event OwnerTransitionStarted(address newOwner, uint256 startTime);

    /**
     * @notice Emitted when an ownership transition is cancelled.
     */
    event OwnerTransitionCancelled();

    /**
     * @notice Emitted when an ownership transition is completed.
     */
    event OwnerTransitionComplete(address newOwner);

    /**
     * @notice Attempted to call a function intended for Zero Id address.
     */
    error PriceRouter__OnlyCallableByZeroId();

    /**
     * @notice Attempted to transition owner to the zero address.
     */
    error PriceRouter__NewOwnerCanNotBeZero();

    /**
     * @notice Attempted to perform a restricted action while ownership transition is pending.
     */
    error PriceRouter__TransitionPending();

    /**
     * @notice Attempted to cancel or complete a transition when one is not active.
     */
    error PriceRouter__TransitionNotPending();

    /**
     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.
     */
    error PriceRouter__OnlyCallableByPendingOwner();

    /**
     * @notice The amount of time it takes for an ownership transition to work.
     */
    uint256 public constant TRANSITION_PERIOD = 7 days;

    /**
     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.
     */
    address public pendingOwner;

    /**
     * @notice The starting time stamp of the transition.
     */
    uint256 public transitionStart;

    /**
     * @notice Allows Zero Id address to set a new owner, after the transition period is up.
     */
    function transitionOwner(address newOwner) external {
        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();
        if (pendingOwner != address(0)) revert PriceRouter__TransitionPending();
        if (newOwner == address(0)) revert PriceRouter__NewOwnerCanNotBeZero();

        pendingOwner = newOwner;
        transitionStart = block.timestamp;
    }

    /**
     * @notice Allows Zero Id address to cancel an ongoing owner transition.
     */
    function cancelTransition() external {
        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();
        if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending();

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Allows pending owner to complete the ownership transition.
     */
    function completeTransition() external {
        if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending();
        if (msg.sender != pendingOwner) revert PriceRouter__OnlyCallableByPendingOwner();
        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert PriceRouter__TransitionPending();

        _transferOwnership(pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.
     */
    function _checkOwner() internal view override {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        if (transitionStart != 0) revert PriceRouter__TransitionPending();
    }

    // ======================================= ASSET OPERATIONS =======================================

    /**
     * @notice Attempted to set a minimum price below the Chainlink minimum price (with buffer).
     * @param minPrice minimum price attempted to set
     * @param bufferedMinPrice minimum price that can be set including buffer
     */
    error PriceRouter__InvalidMinPrice(uint256 minPrice, uint256 bufferedMinPrice);

    /**
     * @notice Attempted to set a maximum price above the Chainlink maximum price (with buffer).
     * @param maxPrice maximum price attempted to set
     * @param bufferedMaxPrice maximum price that can be set including buffer
     */
    error PriceRouter__InvalidMaxPrice(uint256 maxPrice, uint256 bufferedMaxPrice);

    /**
     * @notice Attempted to add an invalid asset.
     * @param asset address of the invalid asset
     */
    error PriceRouter__InvalidAsset(address asset);

    /**
     * @notice Attempted to add an asset that is already supported.
     */
    error PriceRouter__AssetAlreadyAdded(address asset);

    /**
     * @notice Attempted to edit an asset that is not supported.
     */
    error PriceRouter__AssetNotAdded(address asset);

    /**
     * @notice Attempted to edit an asset that is not editable.
     */
    error PriceRouter__AssetNotEditable(address asset);

    /**
     * @notice Attempted to cancel the editing of an asset that is not pending edit.
     */
    error PriceRouter__AssetNotPendingEdit(address asset);

    /**
     * @notice Attempted to add an asset, but actual answer was outside range of expectedAnswer.
     */
    error PriceRouter__BadAnswer(uint256 answer, uint256 expectedAnswer);

    /**
     * @notice Attempted to perform an operation using an unknown derivative.
     */
    error PriceRouter__UnknownDerivative(uint8 unknownDerivative);

    /**
     * @notice Attempted to add an asset with invalid min/max prices.
     * @param min price
     * @param max price
     */
    error PriceRouter__MinPriceGreaterThanMaxPrice(uint256 min, uint256 max);

    /**
     * @notice The allowed deviation between the expected answer vs the actual answer.
     */
    uint256 public constant EXPECTED_ANSWER_DEVIATION = 0.02e18;

    /**
     * @notice The amount of time that must pass between owner calling `startEditAsset`, and `completeEditAsset`.
     */
    uint64 public constant EDIT_ASSET_DELAY = 7 days;

    /**
     * @notice Stores the timestamp when an asset can be editted.
     */
    mapping(bytes32 => uint256) public assetEditableTimestamp;

    /**
     * @notice Allows owner to add assets to the price router.
     * @dev Performs a sanity check by comparing the price router computed price to
     * a user input `_expectedAnswer`.
     * @param _asset the asset to add to the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     * @param _expectedAnswer the expected answer for the asset from  `_getPriceInUSD`
     */
    function addAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 _expectedAnswer
    ) external onlyOwner {
        // Check that asset is not already added.
        if (getAssetSettings[_asset].derivative > 0) revert PriceRouter__AssetAlreadyAdded(address(_asset));

        _updateAsset(_asset, _settings, _storage, _expectedAnswer);

        emit AddAsset(address(_asset));
    }

    /**
     * @notice Allows owner to start the edit asset process.
     * @dev Saves a hash of the inputs, and maps it to the timestamp when `_asset` is editable.
     * @param _asset the asset to edit in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     */
    function startEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner {
        // Make sure the asset has been added.
        if (getAssetSettings[_asset].derivative == 0) revert PriceRouter__AssetNotAdded(address(_asset));
        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));

        uint256 assetEditableAt = block.timestamp + EDIT_ASSET_DELAY;
        assetEditableTimestamp[editHash] = assetEditableAt;

        emit IntentToEditAsset(address(_asset), _settings, _storage, editHash, assetEditableAt);
    }

    /**
     * @notice Once `EDIT_ASSET_DELAY` has passed, `_asset` is now editable using the
     *         same inputs given to `startEditAsset`.
     * @param _asset the asset to finish editing in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     */
    function completeEditAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 _expectedAnswer
    ) external onlyOwner {
        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));

        // Make sure asset can be edited.
        uint256 assetEditableAt = assetEditableTimestamp[editHash];
        if (assetEditableAt == 0 || block.timestamp < assetEditableAt)
            revert PriceRouter__AssetNotEditable(address(_asset));

        // Reset edit timestamp.
        assetEditableTimestamp[editHash] = 0;

        // Edit the asset.
        _updateAsset(_asset, _settings, _storage, _expectedAnswer);

        emit EditAssetComplete(address(_asset), editHash);
    }

    /**
     * @notice Cancel a pending edit for `_asset`.
     * @param _asset the asset to cancel editing of in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     */
    function cancelEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner {
        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage));

        // Make sure asset is pending edit.
        uint256 assetEditableAt = assetEditableTimestamp[editHash];
        if (assetEditableAt == 0) revert PriceRouter__AssetNotPendingEdit(address(_asset));

        assetEditableTimestamp[editHash] = 0;

        emit EditAssetCancelled(address(_asset), editHash);
    }

    /**
     * @notice Helper function to update an `_asset`s configuration.
     * @param _asset the asset to update in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     */
    function _updateAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 _expectedAnswer
    ) internal {
        if (address(_asset) == address(0)) revert PriceRouter__InvalidAsset(address(_asset));

        // Zero is an invalid derivative.
        if (_settings.derivative == 0) revert PriceRouter__UnknownDerivative(_settings.derivative);

        // Call setup function for appropriate derivative.
        if (_settings.derivative == 1) {
            _setupPriceForChainlinkDerivative(_asset, _settings.source, _storage);
        } else if (_settings.derivative == 2) {
            _setupPriceForTwapDerivative(_asset, _settings.source, _storage);
        } else if (_settings.derivative == 3) {
            Extension(_settings.source).setupSource(_asset, _storage);
        } else revert PriceRouter__UnknownDerivative(_settings.derivative);

        // Check `_getPriceInUSD` against `_expectedAnswer`.
        uint256 minAnswer = _expectedAnswer.mulWadDown((1e18 - EXPECTED_ANSWER_DEVIATION));
        uint256 maxAnswer = _expectedAnswer.mulWadDown((1e18 + EXPECTED_ANSWER_DEVIATION));

        getAssetSettings[_asset] = _settings;
        uint256 answer = _getPriceInUSD(_asset, _settings);
        if (answer < minAnswer || answer > maxAnswer) revert PriceRouter__BadAnswer(answer, _expectedAnswer);
    }

    /**
     * @notice return bool indicating whether or not an asset has been set up.
     * @dev Since `addAsset` enforces the derivative is non zero, checking if the stored setting
     *      is nonzero is sufficient to see if the asset is set up.
     */
    function isSupported(ERC20 asset) external view returns (bool) {
        return getAssetSettings[asset].derivative > 0;
    }

    // ======================================= PRICING OPERATIONS =======================================

    /**
     * @notice Get `asset` price in USD.
     * @dev Returns price in USD with 8 decimals.
     */
    function getPriceInUSD(ERC20 asset) external view returns (uint256) {
        AssetSettings memory assetSettings = getAssetSettings[asset];
        return _getPriceInUSD(asset, assetSettings);
    }

    /**
     * @notice Get multiple `asset` prices in USD.
     * @dev Returns array of prices in USD with 8 decimals.
     */
    function getPricesInUSD(ERC20[] calldata assets) external view returns (uint256[] memory prices) {
        prices = new uint256[](assets.length);
        for (uint256 i; i < assets.length; ++i) {
            AssetSettings memory assetSettings = getAssetSettings[assets[i]];
            prices[i] = _getPriceInUSD(assets[i], assetSettings);
        }
    }

    /**
     * @notice Get the value of an asset in terms of another asset.
     * @param baseAsset address of the asset to get the price of in terms of the quote asset
     * @param amount amount of the base asset to price
     * @param quoteAsset address of the asset that the base asset is priced in terms of
     * @return value value of the amount of base assets specified in terms of the quote asset
     */
    function getValue(ERC20 baseAsset, uint256 amount, ERC20 quoteAsset) external view returns (uint256 value) {
        AssetSettings memory baseSettings = getAssetSettings[baseAsset];
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
        if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));
        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));
        uint256 priceBaseUSD = _getPriceInUSD(baseAsset, baseSettings);
        uint256 priceQuoteUSD = _getPriceInUSD(quoteAsset, quoteSettings);
        value = _getValueInQuote(priceBaseUSD, priceQuoteUSD, baseAsset.decimals(), quoteAsset.decimals(), amount);
    }

    /**
     * @notice Helper function that compares `_getValues` between input 0 and input 1.
     */
    function getValuesDelta(
        ERC20[] calldata baseAssets0,
        uint256[] calldata amounts0,
        ERC20[] calldata baseAssets1,
        uint256[] calldata amounts1,
        ERC20 quoteAsset
    ) external view returns (uint256) {
        uint256 value0 = _getValues(baseAssets0, amounts0, quoteAsset);
        uint256 value1 = _getValues(baseAssets1, amounts1, quoteAsset);
        return value0 - value1;
    }

    /**
     * @notice Helper function that determines the value of assets using `_getValues`.
     */
    function getValues(
        ERC20[] calldata baseAssets,
        uint256[] calldata amounts,
        ERC20 quoteAsset
    ) external view returns (uint256) {
        return _getValues(baseAssets, amounts, quoteAsset);
    }

    /**
     * @notice Get the exchange rate between two assets.
     * @param baseAsset address of the asset to get the exchange rate of in terms of the quote asset
     * @param quoteAsset address of the asset that the base asset is exchanged for
     * @return exchangeRate rate of exchange between the base asset and the quote asset
     */
    function getExchangeRate(ERC20 baseAsset, ERC20 quoteAsset) public view returns (uint256 exchangeRate) {
        AssetSettings memory baseSettings = getAssetSettings[baseAsset];
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
        if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));
        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));

        exchangeRate = _getExchangeRate(baseAsset, baseSettings, quoteAsset, quoteSettings, quoteAsset.decimals());
    }

    /**
     * @notice Get the exchange rates between multiple assets and another asset.
     * @param baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset
     * @param quoteAsset address of the asset that the base assets are exchanged for
     * @return exchangeRates rate of exchange between the base assets and the quote asset
     */
    function getExchangeRates(
        ERC20[] memory baseAssets,
        ERC20 quoteAsset
    ) external view returns (uint256[] memory exchangeRates) {
        uint8 quoteAssetDecimals = quoteAsset.decimals();
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
        if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));

        uint256 numOfAssets = baseAssets.length;
        exchangeRates = new uint256[](numOfAssets);
        for (uint256 i; i < numOfAssets; ++i) {
            AssetSettings memory baseSettings = getAssetSettings[baseAssets[i]];
            if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAssets[i]));
            exchangeRates[i] = _getExchangeRate(
                baseAssets[i],
                baseSettings,
                quoteAsset,
                quoteSettings,
                quoteAssetDecimals
            );
        }
    }

    // =========================================== HELPER FUNCTIONS ===========================================

    /**
     * @notice Attempted to update the asset to one that is not supported by the platform.
     * @param asset address of the unsupported asset
     */
    error PriceRouter__UnsupportedAsset(address asset);

    /**
     * @notice Gets the exchange rate between a base and a quote asset
     * @param baseAsset the asset to convert into quoteAsset
     * @param quoteAsset the asset base asset is converted into
     * @return exchangeRate value of base asset in terms of quote asset
     */
    function _getExchangeRate(
        ERC20 baseAsset,
        AssetSettings memory baseSettings,
        ERC20 quoteAsset,
        AssetSettings memory quoteSettings,
        uint8 quoteAssetDecimals
    ) internal view returns (uint256) {
        uint256 basePrice = _getPriceInUSD(baseAsset, baseSettings);
        uint256 quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);
        uint256 exchangeRate = basePrice.mulDivDown(10 ** quoteAssetDecimals, quotePrice);
        return exchangeRate;
    }

    /**
     * @notice Helper function to get an assets price in USD.
     * @dev Returns price in USD with 8 decimals.
     */
    function _getPriceInUSD(ERC20 asset, AssetSettings memory settings) internal view returns (uint256) {
        _runPreFlightCheck();
        // Call get price function using appropriate derivative.
        uint256 price;
        if (settings.derivative == 1) {
            price = _getPriceForChainlinkDerivative(asset, settings.source);
        } else if (settings.derivative == 2) {
            price = _getPriceForTwapDerivative(asset, settings.source);
        } else if (settings.derivative == 3) {
            price = Extension(settings.source).getPriceInUSD(asset);
        } else revert PriceRouter__UnknownDerivative(settings.derivative);

        return price;
    }

    /**
     * @notice If any safety checks needs to be run before pricing operations, they should be added here.
     */
    function _runPreFlightCheck() internal view virtual {}

    /**
     * @notice math function that preserves precision by multiplying the amountBase before dividing.
     * @param priceBaseUSD the base asset price in USD
     * @param priceQuoteUSD the quote asset price in USD
     * @param baseDecimals the base asset decimals
     * @param quoteDecimals the quote asset decimals
     * @param amountBase the amount of base asset
     */
    function _getValueInQuote(
        uint256 priceBaseUSD,
        uint256 priceQuoteUSD,
        uint8 baseDecimals,
        uint8 quoteDecimals,
        uint256 amountBase
    ) internal pure returns (uint256 valueInQuote) {
        // Get value in quote asset, but maintain as much precision as possible.
        // Cleaner equations below.
        // baseToUSD = amountBase * priceBaseUSD / 10**baseDecimals.
        // valueInQuote = baseToUSD * 10**quoteDecimals / priceQuoteUSD
        valueInQuote = amountBase.mulDivDown(
            (priceBaseUSD * 10 ** quoteDecimals),
            (10 ** baseDecimals * priceQuoteUSD)
        );
    }

    /**
     * @notice Attempted an operation with arrays of unequal lengths that were expected to be equal length.
     */
    error PriceRouter__LengthMismatch();

    /**
     * @notice Get the total value of multiple assets in terms of another asset.
     * @param baseAssets addresses of the assets to get the price of in terms of the quote asset
     * @param amounts amounts of each base asset to price
     * @param quoteAsset address of the assets that the base asset is priced in terms of
     * @return value total value of the amounts of each base assets specified in terms of the quote asset
     */
    function _getValues(
        ERC20[] calldata baseAssets,
        uint256[] calldata amounts,
        ERC20 quoteAsset
    ) internal view returns (uint256) {
        if (baseAssets.length != amounts.length) revert PriceRouter__LengthMismatch();
        uint256 quotePrice;
        {
            AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
            if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset));
            quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);
        }
        uint256 valueInQuote;
        uint8 quoteDecimals = quoteAsset.decimals();

        for (uint256 i = 0; i < baseAssets.length; ++i) {
            // Skip zero amount values.
            if (amounts[i] == 0) continue;
            ERC20 baseAsset = baseAssets[i];
            if (baseAsset == quoteAsset) valueInQuote += amounts[i];
            else {
                uint256 basePrice;
                {
                    AssetSettings memory baseSettings = getAssetSettings[baseAsset];
                    if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset));
                    basePrice = _getPriceInUSD(baseAsset, baseSettings);
                }
                valueInQuote += _getValueInQuote(
                    basePrice,
                    quotePrice,
                    baseAsset.decimals(),
                    quoteDecimals,
                    amounts[i]
                );
            }
        }
        return valueInQuote;
    }

    // =========================================== CHAINLINK PRICE DERIVATIVE ===========================================\
    /**
     * @notice Stores data for Chainlink derivative assets.
     * @param max the max valid price of the asset
     * @param min the min valid price of the asset
     * @param heartbeat the max amount of time between price updates
     * @param inETH bool indicating whether the price feed is
     *        denominated in ETH(true) or USD(false)
     */
    struct ChainlinkDerivativeStorage {
        uint144 max;
        uint80 min;
        uint24 heartbeat;
        bool inETH;
    }

    /**
     * @notice Buffered min price exceedes 80 bits of data.
     */
    error PriceRouter__BufferedMinOverflow();

    /**
     * @notice Returns Chainlink Derivative Storage
     */
    mapping(ERC20 => ChainlinkDerivativeStorage) public getChainlinkDerivativeStorage;

    /**
     * @notice If zero is specified for a Chainlink asset heartbeat, this value is used instead.
     */
    uint24 public constant DEFAULT_HEART_BEAT = 1 days;

    /**
     * @notice Setup function for pricing Chainlink derivative assets.
     * @dev _source The address of the Chainlink Data feed.
     * @dev _storage A ChainlinkDerivativeStorage value defining valid prices.
     */
    function _setupPriceForChainlinkDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {
        ChainlinkDerivativeStorage memory parameters = abi.decode(_storage, (ChainlinkDerivativeStorage));

        // Use Chainlink to get the min and max of the asset.
        IChainlinkAggregator aggregator = IChainlinkAggregator(IChainlinkAggregator(_source).aggregator());
        uint256 minFromChainklink = uint256(uint192(aggregator.minAnswer()));
        uint256 maxFromChainlink = uint256(uint192(aggregator.maxAnswer()));

        // Add a ~10% buffer to minimum and maximum price from Chainlink because Chainlink can stop updating
        // its price before/above the min/max price.
        uint256 bufferedMinPrice = (minFromChainklink * 1.1e18) / 1e18;
        uint256 bufferedMaxPrice = (maxFromChainlink * 0.9e18) / 1e18;

        if (parameters.min == 0) {
            // Revert if bufferedMinPrice overflows because uint80 is too small to hold the minimum price,
            // and lowering it to uint80 is not safe because the price feed can stop being updated before
            // it actually gets to that lower price.
            if (bufferedMinPrice > type(uint80).max) revert PriceRouter__BufferedMinOverflow();
            parameters.min = uint80(bufferedMinPrice);
        } else {
            if (parameters.min < bufferedMinPrice)
                revert PriceRouter__InvalidMinPrice(parameters.min, bufferedMinPrice);
        }

        if (parameters.max == 0) {
            //Do not revert even if bufferedMaxPrice is greater than uint144, because lowering it to uint144 max is more conservative.
            parameters.max = bufferedMaxPrice > type(uint144).max ? type(uint144).max : uint144(bufferedMaxPrice);
        } else {
            if (parameters.max > bufferedMaxPrice)
                revert PriceRouter__InvalidMaxPrice(parameters.max, bufferedMaxPrice);
        }

        if (parameters.min >= parameters.max)
            revert PriceRouter__MinPriceGreaterThanMaxPrice(parameters.min, parameters.max);

        parameters.heartbeat = parameters.heartbeat != 0 ? parameters.heartbeat : DEFAULT_HEART_BEAT;

        getChainlinkDerivativeStorage[_asset] = parameters;
    }

    /**
     * @notice Get the price of a Chainlink derivative in terms of USD.
     */
    function _getPriceForChainlinkDerivative(ERC20 _asset, address _source) internal view returns (uint256) {
        ChainlinkDerivativeStorage memory parameters = getChainlinkDerivativeStorage[_asset];
        IChainlinkAggregator aggregator = IChainlinkAggregator(_source);
        (, int256 _price, , uint256 _timestamp, ) = aggregator.latestRoundData();
        uint256 price = _price.toUint256();
        _checkPriceFeed(address(_asset), price, _timestamp, parameters.max, parameters.min, parameters.heartbeat);
        // If price is in ETH, then convert price into USD.
        if (parameters.inETH) {
            uint256 _ethToUsd = _getPriceInUSD(WETH, getAssetSettings[WETH]);
            price = price.mulWadDown(_ethToUsd);
        }
        return price;
    }

    /**
     * @notice Attempted an operation to price an asset that under its minimum valid price.
     * @param asset address of the asset that is under its minimum valid price
     * @param price price of the asset
     * @param minPrice minimum valid price of the asset
     */
    error PriceRouter__AssetBelowMinPrice(address asset, uint256 price, uint256 minPrice);

    /**
     * @notice Attempted an operation to price an asset that under its maximum valid price.
     * @param asset address of the asset that is under its maximum valid price
     * @param price price of the asset
     * @param maxPrice maximum valid price of the asset
     */
    error PriceRouter__AssetAboveMaxPrice(address asset, uint256 price, uint256 maxPrice);

    /**
     * @notice Attempted to fetch a price for an asset that has not been updated in too long.
     * @param asset address of the asset thats price is stale
     * @param timeSinceLastUpdate seconds since the last price update
     * @param heartbeat maximum allowed time between price updates
     */
    error PriceRouter__StalePrice(address asset, uint256 timeSinceLastUpdate, uint256 heartbeat);

    /**
     * @notice helper function to validate a price feed is safe to use.
     * @param asset ERC20 asset price feed data is for.
     * @param value the price value the price feed gave.
     * @param timestamp the last timestamp the price feed was updated.
     * @param max the upper price bound
     * @param min the lower price bound
     * @param heartbeat the max amount of time between price updates
     */
    function _checkPriceFeed(
        address asset,
        uint256 value,
        uint256 timestamp,
        uint144 max,
        uint88 min,
        uint24 heartbeat
    ) internal view {
        if (value < min) revert PriceRouter__AssetBelowMinPrice(address(asset), value, min);

        if (value > max) revert PriceRouter__AssetAboveMaxPrice(address(asset), value, max);

        uint256 timeSinceLastUpdate = block.timestamp - timestamp;
        if (timeSinceLastUpdate > heartbeat)
            revert PriceRouter__StalePrice(address(asset), timeSinceLastUpdate, heartbeat);
    }

    // =========================================== TWAP PRICE DERIVATIVE ===========================================

    /**
     * @notice Stores data for Twap derivative assets.
     * @param secondsAgo the twap duration
     * @param baseDecimals the base assets decimals
     * @param quoteDecimals the quote assets decimals
     * @param quoteToken the asset the twap quotes in
     */
    struct TwapDerivativeStorage {
        uint32 secondsAgo;
        uint8 baseDecimals;
        uint8 quoteDecimals;
        ERC20 quoteToken;
    }

    /**
     * @notice Tried setting up a Twap for an asset where the underlying pools does not use the asset.
     */
    error PriceRouter__TwapAssetNotInPool();

    /**
     * @notice Provided secondsAgo does not meet minimum,
     */
    error PriceRouter__SecondsAgoDoesNotMeetMinimum();

    /**
     * @notice Returns Twap Derivative Storage
     */
    mapping(ERC20 => TwapDerivativeStorage) public getTwapDerivativeStorage;

    /**
     * @notice The smallest possible TWAP that can be used.
     */
    uint32 public constant MINIMUM_SECONDS_AGO = 900;

    /**
     * @notice Setup function for pricing Twap derivative assets.
     * @dev Make sure that TWAP assets have sufficient observations, and increase them if not before adding.
     * @dev _source The address of the Uniswap V3 pool.
     * @dev _storage A TwapDerivativeStorage value defining valid prices.
     */
    function _setupPriceForTwapDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {
        TwapDerivativeStorage memory parameters = abi.decode(_storage, (TwapDerivativeStorage));

        // Verify seconds ago is reasonable.
        if (parameters.secondsAgo < MINIMUM_SECONDS_AGO) revert PriceRouter__SecondsAgoDoesNotMeetMinimum();

        UniswapV3Pool pool = UniswapV3Pool(_source);

        ERC20 token0 = ERC20(pool.token0());
        ERC20 token1 = ERC20(pool.token1());
        if (token0 == _asset) {
            parameters.baseDecimals = _asset.decimals();
            parameters.quoteDecimals = token1.decimals();
            parameters.quoteToken = token1;
        } else if (token1 == _asset) {
            parameters.baseDecimals = _asset.decimals();
            parameters.quoteDecimals = token0.decimals();
            parameters.quoteToken = token0;
        } else revert PriceRouter__TwapAssetNotInPool();

        getTwapDerivativeStorage[_asset] = parameters;
    }

    /**
     * @notice Get the price of a Twap derivative in terms of USD.
     */
    function _getPriceForTwapDerivative(ERC20 asset, address _source) internal view returns (uint256) {
        TwapDerivativeStorage memory parameters = getTwapDerivativeStorage[asset];
        (int24 arithmeticMeanTick, ) = OracleLibrary.consult(_source, parameters.secondsAgo);
        // Get the amount of quote token each base token is worth.
        uint256 quoteAmount = OracleLibrary.getQuoteAtTick(
            arithmeticMeanTick,
            uint128(10 ** parameters.baseDecimals),
            address(asset),
            address(parameters.quoteToken)
        );
        uint256 quotePrice = _getPriceInUSD(parameters.quoteToken, getAssetSettings[parameters.quoteToken]);
        return quoteAmount.mulDivDown(quotePrice, 10 ** parameters.quoteDecimals);
    }
}

File 10 of 44 : Uint32Array.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

/**
 * @notice A library to extend the uint32 array data type.
 */
library Uint32Array {
    // =========================================== ADDRESS STORAGE ===========================================

    /**
     * @notice Add an uint32 to the array at a given index.
     * @param array uint32 array to add the uint32 to
     * @param index index to add the uint32 at
     * @param value uint32 to add to the array
     */
    function add(uint32[] storage array, uint32 index, uint32 value) internal {
        uint256 len = array.length;

        if (len > 0) {
            array.push(array[len - 1]);

            for (uint256 i = len - 1; i > index; i--) array[i] = array[i - 1];

            array[index] = value;
        } else {
            array.push(value);
        }
    }

    /**
     * @notice Remove a uint32 from the array at a given index.
     * @param array uint32 array to remove the uint32 from
     * @param index index to remove the uint32 at
     */
    function remove(uint32[] storage array, uint32 index) internal {
        uint256 len = array.length;

        require(index < len, "Index out of bounds");

        for (uint256 i = index; i < len - 1; i++) array[i] = array[i + 1];

        array.pop();
    }

    /**
     * @notice Check whether an array contains an uint32.
     * @param array uint32 array to check
     * @param value uint32 to check for
     */
    function contains(uint32[] storage array, uint32 value) internal view returns (bool) {
        for (uint256 i; i < array.length; i++) if (value == array[i]) return true;

        return false;
    }
}

File 11 of 44 : BaseAdaptor.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Math } from "src/utils/Math.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { Registry } from "src/Registry.sol";
import { Cellar } from "src/base/Cellar.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";

/**
 * @title Base Adaptor
 * @notice Base contract all adaptors must inherit from.
 * @dev Allows Cellars to interact with arbritrary DeFi assets and protocols.
 * @author crispymangoes
 */
abstract contract BaseAdaptor {
    using SafeTransferLib for ERC20;
    using Math for uint256;

    /**
     * @notice Attempted to specify an external receiver during a Cellar `callOnAdaptor` call.
     */
    error BaseAdaptor__ExternalReceiverBlocked();

    /**
     * @notice Attempted to deposit to a position where user deposits were not allowed.
     */
    error BaseAdaptor__UserDepositsNotAllowed();

    /**
     * @notice Attempted to withdraw from a position where user withdraws were not allowed.
     */
    error BaseAdaptor__UserWithdrawsNotAllowed();

    /**
     * @notice Attempted swap has bad slippage.
     */
    error BaseAdaptor__Slippage();

    /**
     * @notice Attempted swap used unsupported output asset.
     */
    error BaseAdaptor__PricingNotSupported(address asset);

    /**
     * @notice Attempted to set a constructor minimum health factor to a value
     *         below `MINIMUM_CONSTRUCTOR_HEALTH_FACTOR()`.
     */
    error BaseAdaptor__ConstructorHealthFactorTooLow();

    //============================================ Global Functions ===========================================
    /**
     * @dev Identifier unique to this adaptor for a shared registry.
     * Normally the identifier would just be the address of this contract, but this
     * Identifier is needed during Cellar Delegate Call Operations, so getting the address
     * of the adaptor is more difficult.
     */
    function identifier() public pure virtual returns (bytes32) {
        return keccak256(abi.encode("Base Adaptor V 0.0"));
    }

    function SWAP_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {
        return 1;
    }

    function PRICE_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {
        return 2;
    }

    /**
     * @notice Max possible slippage when making a swap router swap.
     */
    function slippage() public pure returns (uint32) {
        return 0.9e4;
    }

    /**
     * @notice The default minimum constructor health factor.
     * @dev Adaptors can choose to override this if they need a different value.
     */
    function MINIMUM_CONSTRUCTOR_HEALTH_FACTOR() internal pure virtual returns (uint256) {
        return 1.05e18;
    }

    //============================================ Implement Base Functions ===========================================
    //==================== Base Function Specification ====================
    // Base functions are functions designed to help the Cellar interact with
    // an adaptor position, strategists are not intended to use these functions.
    // Base functions MUST be implemented in adaptor contracts, even if that is just
    // adding a revert statement to make them uncallable by normal user operations.
    //
    // All view Base functions will be called used normal staticcall.
    // All mutative Base functions will be called using delegatecall.
    //=====================================================================
    /**
     * @notice Function Cellars call to deposit users funds into holding position.
     * @param assets the amount of assets to deposit
     * @param adaptorData data needed to deposit into a position
     * @param configurationData data settable when strategists add positions to their Cellar
     *                          Allows strategist to control how the adaptor interacts with the position
     */
    function deposit(uint256 assets, bytes memory adaptorData, bytes memory configurationData) public virtual;

    /**
     * @notice Function Cellars call to withdraw funds from positions to send to users.
     * @param receiver the address that should receive withdrawn funds
     * @param adaptorData data needed to withdraw from a position
     * @param configurationData data settable when strategists add positions to their Cellar
     *                          Allows strategist to control how the adaptor interacts with the position
     */
    function withdraw(
        uint256 assets,
        address receiver,
        bytes memory adaptorData,
        bytes memory configurationData
    ) public virtual;

    /**
     * @notice Function Cellars use to determine `assetOf` balance of an adaptor position.
     * @param adaptorData data needed to interact with the position
     * @return balance of the position in terms of `assetOf`
     */
    function balanceOf(bytes memory adaptorData) public view virtual returns (uint256);

    /**
     * @notice Functions Cellars use to determine the withdrawable balance from an adaptor position.
     * @dev Debt positions MUST return 0 for their `withdrawableFrom`
     * @notice accepts adaptorData and configurationData
     * @return withdrawable balance of the position in terms of `assetOf`
     */
    function withdrawableFrom(bytes memory, bytes memory) public view virtual returns (uint256);

    /**
     * @notice Function Cellars use to determine the underlying ERC20 asset of a position.
     * @param adaptorData data needed to withdraw from a position
     * @return the underlying ERC20 asset of a position
     */
    function assetOf(bytes memory adaptorData) public view virtual returns (ERC20);

    /**
     * @notice When positions are added to the Registry, this function can be used in order to figure out
     *         what assets this adaptor needs to price, and confirm pricing is properly setup.
     */
    function assetsUsed(bytes memory adaptorData) public view virtual returns (ERC20[] memory assets) {
        assets = new ERC20[](1);
        assets[0] = assetOf(adaptorData);
    }

    /**
     * @notice Functions Registry/Cellars use to determine if this adaptor reports debt values.
     * @dev returns true if this adaptor reports debt values.
     */
    function isDebt() public view virtual returns (bool);

    //============================================ Strategist Functions ===========================================
    //==================== Strategist Function Specification ====================
    // Strategist functions are only callable by strategists through the Cellars
    // `callOnAdaptor` function. A cellar will never call any of these functions,
    // when a normal user interacts with a cellar(depositing/withdrawing)
    //
    // All strategist functions will be called using delegatecall.
    // Strategist functions are intentionally "blind" to what positions the cellar
    // is currently holding. This allows strategists to enter temporary positions
    // while rebalancing.
    // To mitigate strategist from abusing this and moving funds in untracked
    // positions, the cellar will enforce a Total Value Locked check that
    // insures TVL has not deviated too much from `callOnAdaptor`.
    //===========================================================================

    //============================================ Helper Functions ===========================================
    /**
     * @notice Helper function that allows adaptor calls to use the max available of an ERC20 asset
     * by passing in type(uint256).max
     * @param token the ERC20 asset to work with
     * @param amount when `type(uint256).max` is used, this function returns `token`s `balanceOf`
     * otherwise this function returns amount.
     */
    function _maxAvailable(ERC20 token, uint256 amount) internal view virtual returns (uint256) {
        if (amount == type(uint256).max) return token.balanceOf(address(this));
        else return amount;
    }

    /**
     * @notice Helper function that checks if `spender` has any more approval for `asset`, and if so revokes it.
     */
    function _revokeExternalApproval(ERC20 asset, address spender) internal {
        if (asset.allowance(address(this), spender) > 0) asset.safeApprove(spender, 0);
    }

    /**
     * @notice Helper function that validates external receivers are allowed.
     */
    function _externalReceiverCheck(address receiver) internal view {
        if (receiver != address(this) && Cellar(address(this)).blockExternalReceiver())
            revert BaseAdaptor__ExternalReceiverBlocked();
    }

    /**
     * @notice Helper function that validates external receivers are allowed.
     */
    function _verifyConstructorMinimumHealthFactor(uint256 minimumHealthFactor) internal pure {
        if (minimumHealthFactor < MINIMUM_CONSTRUCTOR_HEALTH_FACTOR())
            revert BaseAdaptor__ConstructorHealthFactorTooLow();
    }

    /**
     * @notice Allows strategists to zero out an approval for a given `asset`.
     * @param asset the ERC20 asset to revoke `spender`s approval for
     * @param spender the address to revoke approval for
     */
    function revokeApproval(ERC20 asset, address spender) public {
        asset.safeApprove(spender, 0);
    }

}

File 12 of 44 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

File 13 of 44 : ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address,
        address,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

File 14 of 44 : Owned.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OwnershipTransferred(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function transferOwnership(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

File 15 of 44 : CellarWithOracleWithBalancerFlashLoans.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Registry, ERC20, Math, SafeTransferLib } from "src/base/Cellar.sol";
import { IFlashLoanRecipient, IERC20 } from "@balancer/interfaces/contracts/vault/IFlashLoanRecipient.sol";
import { CellarWithOracle } from "src/base/permutations/CellarWithOracle.sol";

import { ERC4626SharePriceOracle } from "src/base/ERC4626SharePriceOracle.sol";

contract CellarWithOracleWithBalancerFlashLoans is CellarWithOracle, IFlashLoanRecipient {
    using Math for uint256;
    using SafeTransferLib for ERC20;

    /**
     * @notice The Balancer Vault contract on current network.
     * @dev For mainnet use 0xBA12222222228d8Ba445958a75a0704d566BF2C8.
     */
    address internal immutable balancerVault;

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint64 _strategistPlatformCut,
        uint192 _shareSupplyCap,
        address _balancerVault
    )
        CellarWithOracle(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _strategistPlatformCut,
            _shareSupplyCap
        )
    {
        balancerVault = _balancerVault;
    }

    // ========================================= Balancer Flash Loan Support =========================================
    /**
     * @notice External contract attempted to initiate a flash loan.
     */
    error Cellar__ExternalInitiator();

    /**
     * @notice receiveFlashLoan was not called by Balancer Vault.
     */
    error Cellar__CallerNotBalancerVault();

    /**
     * @notice Allows strategist to utilize balancer flashloans while rebalancing the cellar.
     * @dev Balancer does not provide an initiator, so instead insure we are in the `callOnAdaptor` context
     *      by reverting if `blockExternalReceiver` is false.
     */
    function receiveFlashLoan(
        IERC20[] calldata tokens,
        uint256[] calldata amounts,
        uint256[] calldata feeAmounts,
        bytes calldata userData
    ) external {
        if (msg.sender != balancerVault) revert Cellar__CallerNotBalancerVault();
        if (!blockExternalReceiver) revert Cellar__ExternalInitiator();

        AdaptorCall[] memory data = abi.decode(userData, (AdaptorCall[]));

        // Run all adaptor calls.
        _makeAdaptorCalls(data);

        // Approve pool to repay all debt.
        for (uint256 i = 0; i < amounts.length; ++i) {
            ERC20(address(tokens[i])).safeTransfer(balancerVault, (amounts[i] + feeAmounts[i]));
        }
    }
}

File 16 of 44 : FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, z)
            }

            // Goal was to get z*z*y within a small factor of x. More iterations could
            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
            // We ensured y >= 256 so that the relative difference between y and y+1 is small.
            // That's not possible if x < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.

            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.

            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.

            // There is no overflow risk here since y < 2^136 after the first branch above.
            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If x+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

File 17 of 44 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 18 of 44 : IChainlinkAggregator.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";

interface IChainlinkAggregator is AggregatorV2V3Interface {
    function maxAnswer() external view returns (int192);

    function minAnswer() external view returns (int192);

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 20 of 44 : Extension.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { Math } from "src/utils/Math.sol";

/**
 * @title Sommelier Price Router Extension abstract contract.
 * @notice Provides shared logic between Extensions.
 * @author crispymangoes
 */
abstract contract Extension {
    /**
     * @notice Attempted to call a function only callable by the price router.
     */
    error Extension__OnlyPriceRouter();

    /**
     * @notice Prevents non price router contracts from calling a function.
     */
    modifier onlyPriceRouter() {
        if (msg.sender != address(priceRouter)) revert Extension__OnlyPriceRouter();
        _;
    }

    /**
     * @notice The Sommelier PriceRouter contract.
     */
    PriceRouter public immutable priceRouter;

    constructor(PriceRouter _priceRouter) {
        priceRouter = _priceRouter;
    }

    /**
     * @notice Setup function is called when an asset is added/edited.
     */
    function setupSource(ERC20 asset, bytes memory sourceData) external virtual;

    /**
     * @notice Returns the price of an asset in USD.
     */
    function getPriceInUSD(ERC20 asset) external view virtual returns (uint256);
}

File 21 of 44 : UniswapV3Pool.sol
pragma solidity ^0.8.10;

interface UniswapV3Pool {
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );
    event Initialize(uint160 sqrtPriceX96, int24 tick);
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);

    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    function factory() external view returns (address);

    function fee() external view returns (uint24);

    function feeGrowthGlobal0X128() external view returns (uint256);

    function feeGrowthGlobal1X128() external view returns (uint256);

    function flash(address recipient, uint256 amount0, uint256 amount1, bytes memory data) external;

    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;

    function initialize(uint160 sqrtPriceX96) external;

    function liquidity() external view returns (uint128);

    function maxLiquidityPerTick() external view returns (uint128);

    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes memory data
    ) external returns (uint256 amount0, uint256 amount1);

    function observations(
        uint256
    )
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );

    function observe(
        uint32[] memory secondsAgos
    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    function positions(
        bytes32
    )
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    function protocolFees() external view returns (uint128 token0, uint128 token1);

    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes memory data
    ) external returns (int256 amount0, int256 amount1);

    function tickBitmap(int16) external view returns (uint256);

    function tickSpacing() external view returns (int24);

    function ticks(
        int24
    )
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    function token0() external view returns (address);

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

File 22 of 44 : OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
    /// @param pool Address of the pool that we want to observe
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, 'BP');

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool)
            .observe(secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -
            secondsPerLiquidityCumulativeX128s[0];

        arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;

        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
    /// @param pool Address of Uniswap V3 pool that we want to observe
    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
        require(observationCardinality > 0, 'NI');

        (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations(
            (observationIndex + 1) % observationCardinality
        );

        // The next index might not be initialized if the cardinality is in the process of increasing
        // In this case the oldest observation is always in index 0
        if (!initialized) {
            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
        }

        unchecked {
            secondsAgo = uint32(block.timestamp) - observationTimestamp;
        }
    }

    /// @notice Given a pool, it returns the tick value as of the start of the current block
    /// @param pool Address of Uniswap V3 pool
    /// @return The tick that the pool was in at the start of the current block
    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();

        // 2 observations are needed to reliably calculate the block starting tick
        require(observationCardinality > 1, 'NEO');

        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block
        // therefore the tick in `slot0` is the same as at the beginning of the current block.
        // We don't need to check if this observation is initialized - it is guaranteed to be.
        (
            uint32 observationTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,

        ) = IUniswapV3Pool(pool).observations(observationIndex);
        if (observationTimestamp != uint32(block.timestamp)) {
            return (tick, IUniswapV3Pool(pool).liquidity());
        }

        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
        (
            uint32 prevObservationTimestamp,
            int56 prevTickCumulative,
            uint160 prevSecondsPerLiquidityCumulativeX128,
            bool prevInitialized
        ) = IUniswapV3Pool(pool).observations(prevIndex);

        require(prevInitialized, 'ONI');

        uint32 delta = observationTimestamp - prevObservationTimestamp;
        tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta)));
        uint128 liquidity = uint128(
            (uint192(delta) * type(uint160).max) /
                (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
        );
        return (tick, liquidity);
    }

    /// @notice Information for calculating a weighted arithmetic mean tick
    struct WeightedTickData {
        int24 tick;
        uint128 weight;
    }

    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
    /// @param weightedTickData An array of ticks and weights
    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
        internal
        pure
        returns (int24 weightedArithmeticMeanTick)
    {
        // Accumulates the sum of products between each tick and its weight
        int256 numerator;

        // Accumulates the sum of the weights
        uint256 denominator;

        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
        for (uint256 i; i < weightedTickData.length; i++) {
            numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));
            denominator += weightedTickData[i].weight;
        }

        weightedArithmeticMeanTick = int24(numerator / int256(denominator));
        // Always round to negative infinity
        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
    }

    /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
    /// @dev Useful for calculating relative prices along routes.
    /// @dev There must be one tick for each pairwise set of tokens.
    /// @param tokens The token contract addresses
    /// @param ticks The ticks, representing the price of each token pair in `tokens`
    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
    function getChainedPrice(address[] memory tokens, int24[] memory ticks)
        internal
        pure
        returns (int256 syntheticTick)
    {
        require(tokens.length - 1 == ticks.length, 'DL');
        for (uint256 i = 1; i <= ticks.length; i++) {
            // check the tokens for address sort order, then accumulate the
            // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
        }
    }
}

File 23 of 44 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

File 24 of 44 : IFlashLoanRecipient.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

// Inspired by Aave Protocol's IFlashLoanReceiver.

import "../solidity-utils/openzeppelin/IERC20.sol";

interface IFlashLoanRecipient {
    /**
     * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
     *
     * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
     * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
     * Vault, or else the entire flash loan will revert.
     *
     * `userData` is the same value passed in the `IVault.flashLoan` call.
     */
    function receiveFlashLoan(
        IERC20[] memory tokens,
        uint256[] memory amounts,
        uint256[] memory feeAmounts,
        bytes memory userData
    ) external;
}

File 25 of 44 : CellarWithOracle.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Cellar, Registry, ERC20, Math } from "src/base/Cellar.sol";
import { ERC4626SharePriceOracle } from "src/base/ERC4626SharePriceOracle.sol";

contract CellarWithOracle is Cellar {
    using Math for uint256;

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint64 _strategistPlatformCut,
        uint192 _shareSupplyCap
    )
        Cellar(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _strategistPlatformCut,
            _shareSupplyCap
        )
    {}

    /**
     * @notice The ERC4626 Share Price Oracle this Cellar uses to calculate its totalAssets,
     *         during user entry/exits.
     */
    ERC4626SharePriceOracle public sharePriceOracle;

    /**
     * @notice Emitted when Share Price Oracle is changed.
     */
    event SharePriceOracleUpdated(address newOracle);

    /**
     * @notice The decimals the Cellar is expecting the oracle to have.
     */
    uint8 internal constant ORACLE_DECIMALS = 18;

    /**
     * @notice Some failure occurred while trying to setup/use the oracle.
     */
    error Cellar__OracleFailure();

    /**
     * @notice Change the share price oracle this Cellar uses for share price calculations.
     * @dev Only callable through Sommelier Governance.
     * @dev Trying to set the share price oracle to the zero address will revert here.
     * @dev Callable by Sommelier Governance.
     */
    function setSharePriceOracle(uint256 _registryId, ERC4626SharePriceOracle _sharePriceOracle) external onlyOwner {
        _checkRegistryAddressAgainstExpected(_registryId, address(_sharePriceOracle));
        if (_sharePriceOracle.decimals() != ORACLE_DECIMALS || address(_sharePriceOracle.target()) != address(this))
            revert Cellar__OracleFailure();
        sharePriceOracle = _sharePriceOracle;
        emit SharePriceOracleUpdated(address(_sharePriceOracle));
    }

    /**
     * @notice Estimate totalAssets be querying oracle to get latest answer, and time weighted average answer.
     * @dev If useUpper is true, use larger of the 2 to maximize share price
     *      else use smaller of the 2 to minimize share price
     * @dev _totalAssets calculation is dependent on the Cellar having the same amount of decimals as the underlying asset.
     */
    function _getTotalAssetsAndTotalSupply(
        bool useUpper
    ) internal view override returns (uint256 _totalAssets, uint256 _totalSupply) {
        ERC4626SharePriceOracle _sharePriceOracle = sharePriceOracle;

        // Check if sharePriceOracle is set.
        if (address(_sharePriceOracle) != address(0)) {
            // Consult the oracle.
            (uint256 latestAnswer, uint256 timeWeightedAverageAnswer, bool isNotSafeToUse) = _sharePriceOracle
                .getLatest();
            if (isNotSafeToUse) revert Cellar__OracleFailure();
            else {
                uint256 sharePrice;
                if (useUpper)
                    sharePrice = latestAnswer > timeWeightedAverageAnswer ? latestAnswer : timeWeightedAverageAnswer;
                else sharePrice = latestAnswer < timeWeightedAverageAnswer ? latestAnswer : timeWeightedAverageAnswer;
                // Convert share price to totalAssets.
                _totalSupply = totalSupply;
                _totalAssets = sharePrice.mulDivDown(_totalSupply, 10 ** ORACLE_DECIMALS);
            }
        } else revert Cellar__OracleFailure();
    }
}

File 26 of 44 : ERC4626SharePriceOracle.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { ERC4626 } from "@solmate/mixins/ERC4626.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { Math } from "src/utils/Math.sol";
import { Owned } from "@solmate/auth/Owned.sol";
import { AutomationCompatibleInterface } from "@chainlink/contracts/src/v0.8/interfaces/AutomationCompatibleInterface.sol";
import { IRegistrar } from "src/interfaces/external/Chainlink/IRegistrar.sol";
import { IRegistry } from "src/interfaces/external/Chainlink/IRegistry.sol";
import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol";

contract ERC4626SharePriceOracle is AutomationCompatibleInterface {
    using Math for uint256;
    using SafeTransferLib for ERC20;

    // ========================================= STRUCTS =========================================

    struct Observation {
        uint64 timestamp;
        uint192 cumulative;
    }

    /**
     * @notice Use a struct for constructor args so we do not encounter stack too deep errors.
     */
    struct ConstructorArgs {
        ERC4626 _target;
        uint64 _heartbeat;
        uint64 _deviationTrigger;
        uint64 _gracePeriod;
        uint16 _observationsToUse;
        address _automationRegistry;
        address _automationRegistrar;
        address _automationAdmin;
        address _link;
        uint216 _startingAnswer;
        uint256 _allowedAnswerChangeLower;
        uint256 _allowedAnswerChangeUpper;
        address _sequencerUptimeFeed;
        uint64 _sequencerGracePeriod;
    }

    // ========================================= CONSTANTS =========================================
    /**
     * @notice Gas Limit to use for Upkeep created in `initialize`.
     * @dev Should be fairly constant between networks, but 50_000 is a safe limit in
     *      most situations.
     */
    uint32 public constant UPKEEP_GAS_LIMIT = 50_000;

    /**
     * @notice Decimals used to scale share price for internal calculations.
     */
    uint8 public constant decimals = 18;

    // ========================================= GLOBAL STATE =========================================
    /**
     * @notice The latest stored onchain answer.
     */
    uint216 public answer;

    /**
     * @notice Stores the index of observations with the pending Observation.
     */
    uint16 public currentIndex;

    /**
     * @notice The length of the observations array.
     * @dev `observations` will never change its length once set in the constructor.
     *      By saving this value here, we can take advantage of variable packing to make reads cheaper.
     * @dev This is not immutable to make it easier in the future to create oracles that can expand their observations.
     */
    uint16 public observationsLength;

    /**
     * @notice Triggered when answer provided by Chainlink Automation is extreme.
     * @dev true: No further upkeeps are allowed, `getLatest` and `getLatestAnswer` will return true error bools.
     *      false: Continue as normal.
     */
    bool public killSwitch;

    /**
     * @notice Stores the observations this contract uses to derive a
     *         time weighted average answer.
     */
    Observation[] public observations;

    /**
     * @notice The Automation V2 Forwarder address for this contract.
     */
    address public automationForwarder;

    /**
     * @notice keccak256 hash of the parameters used to create this upkeep.
     * @dev Only set if `initialize` leads to a pending upkeep.
     */
    bytes32 public pendingUpkeepParamHash;

    //============================== ERRORS ===============================

    error ERC4626SharePriceOracle__OnlyCallableByAutomationForwarder();
    error ERC4626SharePriceOracle__StalePerformData();
    error ERC4626SharePriceOracle__CumulativeTooLarge();
    error ERC4626SharePriceOracle__NoUpkeepConditionMet();
    error ERC4626SharePriceOracle__SharePriceTooLarge();
    error ERC4626SharePriceOracle__FuturePerformData();
    error ERC4626SharePriceOracle__ContractKillSwitch();
    error ERC4626SharePriceOracle__AlreadyInitialized();
    error ERC4626SharePriceOracle__ParamHashDiffers();
    error ERC4626SharePriceOracle__NoPendingUpkeepToHandle();

    //============================== EVENTS ===============================

    /**
     * @notice Emitted when performUpkeep is ran.
     * @param timeUpdated the time the answer was updated on chain
     * @param timeAnswerCalculated the time the answer was calculated in checkUpkeep
     * @param latestAnswer the new answer
     * @param timeWeightedAverageAnswer the new time weighted average answer
     * @param isNotSafeToUse bool
     *                       if true: `timeWeightedAverageAnswer` is illogical, use `latestAnswer`
     *                       if false: use `timeWeightedAverageAnswer`
     */
    event OracleUpdated(
        uint256 timeUpdated,
        uint256 timeAnswerCalculated,
        uint256 latestAnswer,
        uint256 timeWeightedAverageAnswer,
        bool isNotSafeToUse
    );

    /**
     * @notice Emitted when the oracles kill switch is activated.
     * @dev If this happens, then the proposed performData lead to extremely volatile share price,
     *      so we need to investigate why that happened, mitigate it, then launch a new share price oracle.
     */
    event KillSwitchActivated(uint256 reportedAnswer, uint256 minAnswer, uint256 maxAnswer);

    /**
     * @notice Emitted when the upkeep is registered.
     */
    event UpkeepRegistered(uint256 upkeepId, address forwarder);

    /**
     * @notice Emitted when a upkeep registration is left pending.
     */
    event UpkeepPending(bytes32 upkeepParamHash);

    //============================== IMMUTABLES ===============================

    /**
     * @notice Determines the minimum time for each observation, and is used to determine if an
     *         answer is stale.
     */
    uint64 public immutable heartbeat;

    /**
     * @notice Used to enforce that the summation of each observations delay used in
     *         a time weighed average calculation is less than the gracePeriod.
     * @dev Example: Using a 3 day TWAA with 1 hour grace period.
     *      When calculating the TWAA, the total time delta for completed observations must be greater than 3 days but less than
     *      3 days + 1hr. So one observation could be delayed 1 hr, or two observations could be
     *      delayed 30 min each.
     */
    uint64 public immutable gracePeriod;

    /**
     * @notice Number between 0 -> 10_000 that determines how far off the last saved answer
     *         can deviate from the current answer.
     * @dev This value should be reflective of the vaults expected maximum percent share
     *      price change during a heartbeat duration.
     * @dev
     *    -1_000 == 10%
     *    -100 == 1%
     *    -10 == 0.1%
     *    -1 == 0.01% or 1 bps
     */
    uint64 public immutable deviationTrigger;

    /**
     * @notice One share of target vault.
     */
    uint256 public immutable ONE_SHARE;

    /**
     * @notice The admin address for the Automation Upkeep.
     */
    address public immutable automationAdmin;

    /**
     * @notice Chainlink's Automation Registry contract address.
     * @notice For mainnet use 0x6593c7De001fC8542bB1703532EE1E5aA0D458fD.
     */
    address public immutable automationRegistry;

    /**
     * @notice Chainlink's Automation Registrar contract address.
     * @notice For mainnet use 0x6B0B234fB2f380309D47A7E9391E29E9a179395a.
     */
    address public immutable automationRegistrar;

    /**
     * @notice Link Token.
     * @notice For mainnet use 0x514910771AF9Ca656af840dff83E8264EcF986CA.
     */
    ERC20 public immutable link;

    /**
     * @notice ERC4626 target vault this contract is an oracle for.
     */
    ERC4626 public immutable target;

    /**
     * @notice Target vault decimals.
     */
    uint8 public immutable targetDecimals;

    /**
     * @notice Multiplier with 4 decimals that determines the acceptable lower band
     *         for a performUpkeep answer.
     */
    uint256 public immutable allowedAnswerChangeLower;

    /**
     * @notice Multiplier with 4 decimals that determines the acceptable upper band
     *         for a performUpkeep answer.
     */
    uint256 public immutable allowedAnswerChangeUpper;

    /**
     * @notice Address for the networks sequencer uptime feed.
     * @dev For oracles that do not rely on a sequencer being up, use address(0).
     */
    IChainlinkAggregator internal immutable sequencerUptimeFeed;

    /**
     * @notice The grace period to enforce after a sequencer comes back online.
     * @dev Calls to `getLatest` and `getLatestAnswer` will return a true for
     *      `isNotSafeToUse` if the sequencer is down, or if the time since the
     *      sequencer went back online is less than `sequencerGracePeriod`.
     */
    uint64 public immutable sequencerGracePeriod;

    /**
     * @notice TWAA Minimum Duration = `_observationsToUse` * `_heartbeat`.
     * @notice TWAA Maximum Duration = `_observationsToUse` * `_heartbeat` + `gracePeriod` + `_heartbeat`.
     * @notice TWAA calculations will use the current pending observation, and then `_observationsToUse` observations.
     */
    constructor(ConstructorArgs memory args) {
        target = args._target;
        targetDecimals = target.decimals();
        ONE_SHARE = 10 ** targetDecimals;
        heartbeat = args._heartbeat;
        deviationTrigger = args._deviationTrigger;
        gracePeriod = args._gracePeriod;
        // Add 1 to observations to use.
        args._observationsToUse = args._observationsToUse + 1;
        observationsLength = args._observationsToUse;

        // Grow Observations array to required length, and fill it with observations that use 1 for timestamp and cumulative.
        // That way the initial upkeeps won't need to change state from 0 which is more expensive.
        for (uint256 i; i < args._observationsToUse; ++i)
            observations.push(Observation({ timestamp: 1, cumulative: 1 }));

        // Set to args._startingAnswer so slot is dirty for first upkeep, and does not trigger kill switch.
        answer = args._startingAnswer;

        if (args._allowedAnswerChangeLower > 1e4) revert("Illogical Lower");
        allowedAnswerChangeLower = args._allowedAnswerChangeLower;
        if (args._allowedAnswerChangeUpper < 1e4) revert("Illogical Upper");
        allowedAnswerChangeUpper = args._allowedAnswerChangeUpper;

        automationRegistry = args._automationRegistry;
        automationRegistrar = args._automationRegistrar;
        automationAdmin = args._automationAdmin;
        link = ERC20(args._link);
        sequencerUptimeFeed = IChainlinkAggregator(args._sequencerUptimeFeed);
        sequencerGracePeriod = args._sequencerGracePeriod;
    }

    //============================== INITIALIZATION ===============================

    /**
     * @notice Should be called after contract creation.
     * @dev Creates a Chainlink Automation Upkeep, and set the `automationForwarder` address.
     */
    function initialize(uint96 initialUpkeepFunds) external {
        // This function is only callable once.
        if (automationForwarder != address(0) || pendingUpkeepParamHash != bytes32(0))
            revert ERC4626SharePriceOracle__AlreadyInitialized();

        link.safeTransferFrom(msg.sender, address(this), initialUpkeepFunds);

        // Create the upkeep.
        IRegistrar registrar = IRegistrar(automationRegistrar);
        IRegistry registry = IRegistry(automationRegistry);
        IRegistrar.RegistrationParams memory params = IRegistrar.RegistrationParams({
            name: string.concat(target.name(), " Share Price Oracle"),
            encryptedEmail: hex"",
            upkeepContract: address(this),
            gasLimit: UPKEEP_GAS_LIMIT,
            adminAddress: automationAdmin,
            triggerType: 0,
            checkData: hex"",
            triggerConfig: hex"",
            offchainConfig: hex"",
            amount: initialUpkeepFunds
        });

        link.safeApprove(automationRegistrar, initialUpkeepFunds);
        uint256 upkeepID = registrar.registerUpkeep(params);
        if (upkeepID > 0) {
            // Upkeep was successfully registered.
            address forwarder = registry.getForwarder(upkeepID);
            automationForwarder = forwarder;
            emit UpkeepRegistered(upkeepID, forwarder);
        } else {
            // Upkeep is pending.
            bytes32 paramHash = keccak256(
                abi.encode(
                    params.upkeepContract,
                    params.gasLimit,
                    params.adminAddress,
                    params.triggerType,
                    params.checkData,
                    params.offchainConfig
                )
            );
            pendingUpkeepParamHash = paramHash;
            emit UpkeepPending(paramHash);
        }
    }

    /**
     * @notice Finish setting forwarder address if `initialize` did not get an auto-approved upkeep.
     */
    function handlePendingUpkeep(uint256 _upkeepId) external {
        if (pendingUpkeepParamHash == bytes32(0) || automationForwarder != address(0))
            revert ERC4626SharePriceOracle__NoPendingUpkeepToHandle();

        IRegistry registry = IRegistry(automationRegistry);

        IRegistry.UpkeepInfo memory upkeepInfo = registry.getUpkeep(_upkeepId);
        // Build the param hash using upkeepInfo.
        // The upkeep id has 16 bytes of entropy, that need to be shifted out(16*8=128).
        // Then take the resulting number and only take the last byte of it to get the trigger type.
        uint8 triggerType = uint8(_upkeepId >> 128);
        bytes32 proposedParamHash = keccak256(
            abi.encode(
                upkeepInfo.target,
                upkeepInfo.executeGas,
                upkeepInfo.admin,
                triggerType,
                upkeepInfo.checkData,
                upkeepInfo.offchainConfig
            )
        );
        if (pendingUpkeepParamHash != proposedParamHash) revert ERC4626SharePriceOracle__ParamHashDiffers();

        // Hashes match, so finish initialization.
        address forwarder = registry.getForwarder(_upkeepId);
        automationForwarder = forwarder;
        emit UpkeepRegistered(_upkeepId, forwarder);
    }

    //============================== CHAINLINK AUTOMATION ===============================

    /**
     * @notice Leverages Automation V2 secure offchain computation to run expensive share price calculations offchain,
     *         then inject them onchain using `performUpkeep`.
     */
    function checkUpkeep(bytes calldata) external view returns (bool upkeepNeeded, bytes memory performData) {
        // Get target share price.
        uint216 sharePrice = _getTargetSharePrice();
        // Read state from one slot.
        uint256 _answer = answer;
        uint16 _currentIndex = currentIndex;
        uint16 _observationsLength = observationsLength;
        bool _killSwitch = killSwitch;

        if (!_killSwitch) {
            // See if we need to update because answer is stale or outside deviation.
            // Time since answer was last updated.
            uint256 timeDeltaCurrentAnswer = block.timestamp - observations[_currentIndex].timestamp;
            uint256 timeDeltaSincePreviousObservation = block.timestamp -
                observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp;
            uint64 _heartbeat = heartbeat;

            if (
                timeDeltaCurrentAnswer >= _heartbeat ||
                timeDeltaSincePreviousObservation >= _heartbeat ||
                sharePrice > _answer.mulDivDown(1e4 + deviationTrigger, 1e4) ||
                sharePrice < _answer.mulDivDown(1e4 - deviationTrigger, 1e4)
            ) {
                // We need to update answer.
                upkeepNeeded = true;
                performData = abi.encode(sharePrice, uint64(block.timestamp));
            }
        } // else no upkeep is needed
    }

    /**
     * @notice Save answer on chain, and update observations if needed.
     */
    function performUpkeep(bytes calldata performData) external {
        if (msg.sender != automationForwarder) revert ERC4626SharePriceOracle__OnlyCallableByAutomationForwarder();
        (uint216 sharePrice, uint64 currentTime) = abi.decode(performData, (uint216, uint64));

        // Verify atleast one of the upkeep conditions was met.
        bool upkeepConditionMet;

        // Read state from one slot.
        uint256 _answer = answer;
        uint16 _currentIndex = currentIndex;
        uint16 _observationsLength = observationsLength;
        bool _killSwitch = killSwitch;

        if (_killSwitch) revert ERC4626SharePriceOracle__ContractKillSwitch();

        // See if kill switch should be activated based on change between answers.
        if (_checkIfKillSwitchShouldBeTriggered(sharePrice, _answer)) return;

        // See if we are upkeeping because of deviation.
        if (
            sharePrice > uint256(_answer).mulDivDown(1e4 + deviationTrigger, 1e4) ||
            sharePrice < uint256(_answer).mulDivDown(1e4 - deviationTrigger, 1e4)
        ) upkeepConditionMet = true;

        // Update answer.
        answer = sharePrice;

        // Update current observation.
        Observation storage currentObservation = observations[_currentIndex];
        // Make sure time is larger than previous time.
        if (currentTime <= currentObservation.timestamp) revert ERC4626SharePriceOracle__StalePerformData();

        // Make sure time is not in the future.
        if (currentTime > block.timestamp) revert ERC4626SharePriceOracle__FuturePerformData();

        // See if we are updating because of staleness.
        uint256 timeDelta = currentTime - currentObservation.timestamp;
        if (timeDelta >= heartbeat) upkeepConditionMet = true;

        // Use the old answer to calculate cumulative.
        uint256 currentCumulative = currentObservation.cumulative + (_answer * timeDelta);
        if (currentCumulative > type(uint192).max) revert ERC4626SharePriceOracle__CumulativeTooLarge();
        currentObservation.cumulative = uint192(currentCumulative);
        currentObservation.timestamp = currentTime;

        uint256 timeDeltaSincePreviousObservation = currentTime -
            observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp;
        // See if we need to advance to the next cumulative.
        if (timeDeltaSincePreviousObservation >= heartbeat) {
            uint16 nextIndex = _getNextIndex(_currentIndex, _observationsLength);
            currentIndex = nextIndex;
            // Update memory variable for event.
            _currentIndex = nextIndex;
            // Update newest cumulative.
            Observation storage newObservation = observations[nextIndex];
            newObservation.cumulative = uint192(currentCumulative);
            newObservation.timestamp = currentTime;
            upkeepConditionMet = true;
        }

        if (!upkeepConditionMet) revert ERC4626SharePriceOracle__NoUpkeepConditionMet();

        (uint256 timeWeightedAverageAnswer, bool isNotSafeToUse) = _getTimeWeightedAverageAnswer(
            sharePrice,
            _currentIndex,
            _observationsLength
        );

        // See if kill switch should be activated based on change between proposed answer and time weighted average answer.
        if (!isNotSafeToUse && _checkIfKillSwitchShouldBeTriggered(sharePrice, timeWeightedAverageAnswer)) return;
        emit OracleUpdated(block.timestamp, currentTime, sharePrice, timeWeightedAverageAnswer, isNotSafeToUse);
    }

    //============================== ORACLE VIEW FUNCTIONS ===============================

    /**
     * @notice Get the latest answer, time weighted average answer, and bool indicating whether they can be safely used.
     */
    function getLatest() external view returns (uint256 ans, uint256 timeWeightedAverageAnswer, bool notSafeToUse) {
        // Read state from one slot.
        ans = answer;
        uint16 _currentIndex = currentIndex;
        uint16 _observationsLength = observationsLength;
        bool _killSwitch = killSwitch;

        if (_killSwitch) return (0, 0, true);
        if (_checkSequencer()) return (0, 0, true);

        // Check if answer is stale, if so set notSafeToUse to true, and return.
        uint256 timeDeltaSinceLastUpdated = block.timestamp - observations[currentIndex].timestamp;
        // Note add in the grace period here, because it can take time for the upkeep TX to go through.
        if (timeDeltaSinceLastUpdated > (heartbeat + gracePeriod)) return (0, 0, true);

        (timeWeightedAverageAnswer, notSafeToUse) = _getTimeWeightedAverageAnswer(
            ans,
            _currentIndex,
            _observationsLength
        );
        if (notSafeToUse) return (0, 0, true);
    }

    /**
     * @notice Get the latest answer, and bool indicating whether answer is safe to use or not.
     */
    function getLatestAnswer() external view returns (uint256, bool) {
        uint256 _answer = answer;
        bool _killSwitch = killSwitch;

        if (_killSwitch) return (0, true);
        if (_checkSequencer()) return (0, true);

        // Check if answer is stale, if so set notSafeToUse to true, and return.
        uint256 timeDeltaSinceLastUpdated = block.timestamp - observations[currentIndex].timestamp;
        // Note add in the grace period here, because it can take time for the upkeep TX to go through.
        if (timeDeltaSinceLastUpdated > (heartbeat + gracePeriod)) return (0, true);

        return (_answer, false);
    }

    //============================== INTERNAL HELPER FUNCTIONS ===============================

    /**
     * @notice Get the next index of observations array.
     */
    function _getNextIndex(uint16 _currentIndex, uint16 _length) internal pure returns (uint16 nextIndex) {
        nextIndex = (_currentIndex == _length - 1) ? 0 : _currentIndex + 1;
    }

    /**
     * @notice Get the previous index of observations array.
     */
    function _getPreviousIndex(uint16 _currentIndex, uint16 _length) internal pure returns (uint16 previousIndex) {
        previousIndex = (_currentIndex == 0) ? _length - 1 : _currentIndex - 1;
    }

    /**
     * @notice Use observations to get the time weighted average answer.
     */
    function _getTimeWeightedAverageAnswer(
        uint256 _answer,
        uint16 _currentIndex,
        uint16 _observationsLength
    ) internal view returns (uint256 timeWeightedAverageAnswer, bool notSafeToUse) {
        // Read observations from storage.
        Observation memory mostRecentlyCompletedObservation = observations[
            _getPreviousIndex(_currentIndex, _observationsLength)
        ];
        Observation memory oldestObservation = observations[_getNextIndex(_currentIndex, _observationsLength)];

        // Data is not set.
        if (oldestObservation.timestamp == 1) return (0, true);

        // Make sure that the old observations we are using are not too stale.
        uint256 timeDelta = mostRecentlyCompletedObservation.timestamp - oldestObservation.timestamp;
        /// @dev use _length - 2 because
        /// remove 1 because observations array stores the current pending observation.
        /// remove 1 because we are really interested in the time between observations.
        uint256 minDuration = heartbeat * (_observationsLength - 2);
        uint256 maxDuration = minDuration + gracePeriod;
        // Data is too new
        if (timeDelta < minDuration) return (0, true);
        // Data is too old
        if (timeDelta > maxDuration) return (0, true);

        Observation memory latestObservation = observations[_currentIndex];
        uint192 latestCumulative = latestObservation.cumulative +
            uint192((_answer * (block.timestamp - latestObservation.timestamp)));

        timeWeightedAverageAnswer =
            (latestCumulative - oldestObservation.cumulative) /
            (block.timestamp - oldestObservation.timestamp);
    }

    /**
     * @notice Get the target ERC4626's share price using totalAssets, and totalSupply.
     */
    function _getTargetSharePrice() internal view returns (uint216 sharePrice) {
        uint256 totalShares = target.totalSupply();
        // Get total Assets but scale it up to decimals decimals of precision.
        uint256 totalAssets = target.totalAssets().changeDecimals(targetDecimals, decimals);

        if (totalShares == 0) return 0;

        uint256 _sharePrice = ONE_SHARE.mulDivDown(totalAssets, totalShares);

        if (_sharePrice > type(uint216).max) revert ERC4626SharePriceOracle__SharePriceTooLarge();
        sharePrice = uint216(_sharePrice);
    }

    /**
     * @notice Activate the kill switch if `proposedAnswer` is extreme when compared to `answerToCompareAgainst`
     * @return bool indicating whether calling function should immediately exit or not.
     */
    function _checkIfKillSwitchShouldBeTriggered(
        uint256 proposedAnswer,
        uint256 answerToCompareAgainst
    ) internal returns (bool) {
        if (
            proposedAnswer < answerToCompareAgainst.mulDivDown(allowedAnswerChangeLower, 1e4) ||
            proposedAnswer > answerToCompareAgainst.mulDivDown(allowedAnswerChangeUpper, 1e4)
        ) {
            killSwitch = true;
            emit KillSwitchActivated(
                proposedAnswer,
                answerToCompareAgainst.mulDivDown(allowedAnswerChangeLower, 1e4),
                answerToCompareAgainst.mulDivDown(allowedAnswerChangeUpper, 1e4)
            );
            return true;
        }
        return false;
    }

    /**
     * @notice Checks if the sequencer is down, or if the grace period is not met.
     * @return bool indicating if the sequencer has a problem
     */
    function _checkSequencer() internal view returns (bool) {
        if (address(sequencerUptimeFeed) != address(0)) {
            (, int256 sequencerAnswer, uint256 startedAt, , ) = sequencerUptimeFeed.latestRoundData();

            // This check should make TXs from L1 to L2 revert if someone tried interacting with the cellar while the sequencer is down.
            // Answer == 0: Sequencer is up
            // Answer == 1: Sequencer is down
            if (sequencerAnswer == 1) {
                return true;
            }

            // Make sure the grace period has passed after the
            // sequencer is back up.
            uint256 timeSinceUp = block.timestamp - startedAt;
            if (timeSinceUp <= sequencerGracePeriod) {
                return true;
            }
        }

        // If we made it this far, the sequencer is fine, and or it is not set.
        return false;
    }
}

File 27 of 44 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

File 28 of 44 : AggregatorV2V3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";

interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}

File 29 of 44 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

File 30 of 44 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

            uint256 r = ratio;
            uint256 msb = 0;

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

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

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

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

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

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

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

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

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

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

}

File 32 of 44 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

File 33 of 44 : AutomationCompatibleInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AutomationCompatibleInterface {
  /**
   * @notice method that is simulated by the keepers to see if any work actually
   * needs to be performed. This method does does not actually need to be
   * executable, and since it is only ever simulated it can consume lots of gas.
   * @dev To ensure that it is never called, you may want to add the
   * cannotExecute modifier from KeeperBase to your implementation of this
   * method.
   * @param checkData specified in the upkeep registration so it is always the
   * same for a registered upkeep. This can easily be broken down into specific
   * arguments using `abi.decode`, so multiple upkeeps can be registered on the
   * same contract and easily differentiated by the contract.
   * @return upkeepNeeded boolean to indicate whether the keeper should call
   * performUpkeep or not.
   * @return performData bytes that the keeper should call performUpkeep with, if
   * upkeep is needed. If you would like to encode data to decode later, try
   * `abi.encode`.
   */
  function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);

  /**
   * @notice method that is actually executed by the keepers, via the registry.
   * The data returned by the checkUpkeep simulation will be passed into
   * this method to actually be executed.
   * @dev The input to this method should not be trusted, and the caller of the
   * method should not even be restricted to any single registry. Anyone should
   * be able call it, and the input should be validated, there is no guarantee
   * that the data passed in is the performData returned from checkUpkeep. This
   * could happen due to malicious keepers, racing keepers, or simply a state
   * change while the performUpkeep transaction is waiting for confirmation.
   * Always validate the data passed in.
   * @param performData is the data which was passed back from the checkData
   * simulation. If it is encoded, it can easily be decoded into other types by
   * calling `abi.decode`. This data should not be trusted, and should be
   * validated against the contract's current state.
   */
  function performUpkeep(bytes calldata performData) external;
}

File 34 of 44 : IRegistrar.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

interface IRegistrar {
    struct RegistrationParams {
        string name;
        bytes encryptedEmail;
        address upkeepContract;
        uint32 gasLimit;
        address adminAddress;
        uint8 triggerType;
        bytes checkData;
        bytes triggerConfig;
        bytes offchainConfig;
        uint96 amount;
    }

    enum AutoApproveType {
        DISABLED,
        ENABLED_SENDER_ALLOWLIST,
        ENABLED_ALL
    }

    function registerUpkeep(RegistrationParams calldata requestParams) external returns (uint256 id);

    function setTriggerConfig(
        uint8 triggerType,
        AutoApproveType autoApproveType,
        uint32 autoApproveMaxAllowed
    ) external;

    function owner() external view returns (address);

    function approve(
        string memory name,
        address upkeepContract,
        uint32 gasLimit,
        address adminAddress,
        uint8 triggerType,
        bytes calldata checkData,
        bytes memory triggerConfig,
        bytes calldata offchainConfig,
        bytes32 hash
    ) external;
}

File 35 of 44 : IRegistry.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

interface IRegistry {
    struct UpkeepInfo {
        address target;
        uint32 executeGas;
        bytes checkData;
        uint96 balance;
        address admin;
        uint64 maxValidBlocknumber;
        uint32 lastPerformBlockNumber;
        uint96 amountSpent;
        bool paused;
        bytes offchainConfig;
    }

    function getForwarder(uint256 upkeepID) external view returns (address forwarder);

    function getUpkeep(uint256 id) external view returns (UpkeepInfo memory upkeepInfo);
}

File 36 of 44 : AggregatorInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorInterface {
  function latestAnswer() external view returns (int256);

  function latestTimestamp() external view returns (uint256);

  function latestRound() external view returns (uint256);

  function getAnswer(uint256 roundId) external view returns (int256);

  function getTimestamp(uint256 roundId) external view returns (uint256);

  event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);

  event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}

File 37 of 44 : AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

File 38 of 44 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 42 of 44 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "remappings": [
    "@balancer/=lib/balancer-v2-monorepo/pkg/",
    "@chainlink/=lib/chainlink/",
    "@ds-test/=lib/forge-std/lib/ds-test/src/",
    "@forge-std/=lib/forge-std/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@solmate/=lib/solmate/src/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@uniswapV3C/=lib/v3-core/contracts/",
    "@uniswapV3P/=lib/v3-periphery/contracts/",
    "axelar-gmp-sdk-solidity/=lib/axelar-gmp-sdk-solidity/contracts/",
    "balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
    "chainlink/=lib/chainlink/integration-tests/contracts/ethereum/src/",
    "ds-test/=lib/forge-std/lib/ds-test/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/",
    "lib/balancer-v2-monorepo:@balancer-labs/=lib/balancer-v2-monorepo/../../node_modules/@balancer-labs/",
    "lib/balancer-v2-monorepo:ds-test/=lib/balancer-v2-monorepo/../../pvt/lib/forge-std/lib/ds-test/src/",
    "lib/balancer-v2-monorepo:forge-std/=lib/balancer-v2-monorepo/../../pvt/lib/forge-std/src/",
    "lib/forge-std:ds-test/=lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/solmate:ds-test/=lib/solmate/lib/ds-test/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract Registry","name":"_registry","type":"address"},{"internalType":"contract ERC20","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint32","name":"_holdingPosition","type":"uint32"},{"internalType":"bytes","name":"_holdingPositionConfig","type":"bytes"},{"internalType":"uint256","name":"_initialDeposit","type":"uint256"},{"internalType":"uint64","name":"_strategistPlatformCut","type":"uint64"},{"internalType":"uint192","name":"_shareSupplyCap","type":"uint192"},{"internalType":"address","name":"_balancerVault","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge","type":"error"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__AlternativeAssetNotSupported","type":"error"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__CallDataLengthNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"expectedAsset","type":"address"}],"name":"Cellar__AssetMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"Cellar__CallToAdaptorNotAllowed","type":"error"},{"inputs":[],"name":"Cellar__CallerNotBalancerVault","type":"error"},{"inputs":[],"name":"Cellar__ContractNotShutdown","type":"error"},{"inputs":[],"name":"Cellar__ContractShutdown","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__DebtMismatch","type":"error"},{"inputs":[],"name":"Cellar__ExpectedAddressDoesNotMatchActual","type":"error"},{"inputs":[],"name":"Cellar__ExternalInitiator","type":"error"},{"inputs":[],"name":"Cellar__FailedToForceOutPosition","type":"error"},{"inputs":[{"internalType":"address","name":"illiquidPosition","type":"address"}],"name":"Cellar__IlliquidWithdraw","type":"error"},{"inputs":[{"internalType":"uint256","name":"assetsOwed","type":"uint256"}],"name":"Cellar__IncompleteWithdraw","type":"error"},{"inputs":[],"name":"Cellar__InvalidFee","type":"error"},{"inputs":[],"name":"Cellar__InvalidFeeCut","type":"error"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"Cellar__InvalidHoldingPosition","type":"error"},{"inputs":[{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Cellar__InvalidRebalanceDeviation","type":"error"},{"inputs":[],"name":"Cellar__InvalidShareSupplyCap","type":"error"},{"inputs":[],"name":"Cellar__MinimumConstructorMintNotMet","type":"error"},{"inputs":[],"name":"Cellar__OracleFailure","type":"error"},{"inputs":[],"name":"Cellar__Paused","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionAlreadyUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"maxPositions","type":"uint256"}],"name":"Cellar__PositionArrayFull","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"},{"internalType":"uint256","name":"sharesRemaining","type":"uint256"}],"name":"Cellar__PositionNotEmpty","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionNotInCatalogue","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionNotUsed","type":"error"},{"inputs":[],"name":"Cellar__RemovingHoldingPosition","type":"error"},{"inputs":[],"name":"Cellar__SettingValueToRegistryIdZeroIsProhibited","type":"error"},{"inputs":[],"name":"Cellar__ShareSupplyCapExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Cellar__TotalAssetDeviatedOutsideRange","type":"error"},{"inputs":[{"internalType":"uint256","name":"current","type":"uint256"},{"internalType":"uint256","name":"expected","type":"uint256"}],"name":"Cellar__TotalSharesMustRemainConstant","type":"error"},{"inputs":[],"name":"Cellar__ZeroAssets","type":"error"},{"inputs":[],"name":"Cellar__ZeroShares","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"AdaptorCalled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"AdaptorCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"asset","type":"address"}],"name":"AlternativeAssetDropped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint32","name":"holdingPosition","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"depositFee","type":"uint32"}],"name":"AlternativeAssetUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"depositAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"MultiAssetDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"positionId","type":"uint32"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"PositionCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"newPosition1","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newPosition2","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"index2","type":"uint256"}],"name":"PositionSwapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldDeviation","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"RebalanceDeviationChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newOracle","type":"address"}],"name":"SharePriceOracleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isShutdown","type":"bool"}],"name":"ShutdownChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPayoutAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newPayoutAddress","type":"address"}],"name":"StrategistPayoutAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"oldPlatformCut","type":"uint64"},{"indexed":false,"internalType":"uint64","name":"newPlatformCut","type":"uint64"}],"name":"StrategistPlatformCutChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"addAdaptorToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bytes","name":"configurationData","type":"bytes"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"addPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"addPositionToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"name":"alternativeAssetData","outputs":[{"internalType":"bool","name":"isSupported","type":"bool"},{"internalType":"uint32","name":"holdingPosition","type":"uint32"},{"internalType":"uint32","name":"depositFee","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"blockExternalReceiver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"checkTotalAssets","type":"bool"},{"internalType":"uint16","name":"allowableRange","type":"uint16"},{"internalType":"address","name":"expectedPriceRouter","type":"address"}],"name":"cachePriceRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"adaptor","type":"address"},{"internalType":"bytes[]","name":"callData","type":"bytes[]"}],"internalType":"struct Cellar.AdaptorCall[]","name":"data","type":"tuple[]"}],"name":"callOnAdaptor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint192","name":"_newShareSupplyCap","type":"uint192"}],"name":"decreaseShareSupplyCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"_alternativeAsset","type":"address"}],"name":"dropAlternativeAssetData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeData","outputs":[{"internalType":"uint64","name":"strategistPlatformCut","type":"uint64"},{"internalType":"uint64","name":"platformFee","type":"uint64"},{"internalType":"uint64","name":"lastAccrual","type":"uint64"},{"internalType":"address","name":"strategistPayoutAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"forcePositionOut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCreditPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"holdingPosition","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ignorePause","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint192","name":"_newShareSupplyCap","type":"uint192"}],"name":"increaseShareSupplyCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"initiateShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"isPositionUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isShutdown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liftShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"locked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"depositAsset","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"multiAssetDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"depositAsset","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewMultiAssetDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceRouter","outputs":[{"internalType":"contract PriceRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256[]","name":"feeAmounts","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"receiveFlashLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"registry","outputs":[{"internalType":"contract Registry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"removeAdaptorFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"removePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"removePositionFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"_alternativeAsset","type":"address"},{"internalType":"uint32","name":"_alternativeHoldingPosition","type":"uint32"},{"internalType":"uint32","name":"_alternativeAssetFee","type":"uint32"}],"name":"setAlternativeAssetData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"setHoldingPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"setRebalanceDeviation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_registryId","type":"uint256"},{"internalType":"contract ERC4626SharePriceOracle","name":"_sharePriceOracle","type":"address"}],"name":"setSharePriceOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"payout","type":"address"}],"name":"setStrategistPayoutAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"cut","type":"uint64"}],"name":"setStrategistPlatformCut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sharePriceOracle","outputs":[{"internalType":"contract ERC4626SharePriceOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shareSupplyCap","outputs":[{"internalType":"uint192","name":"","type":"uint192"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index1","type":"uint32"},{"internalType":"uint32","name":"index2","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"swapPositions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleIgnorePause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssetsWithdrawable","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101c0604052670a688906bd8b000061014052662386f26fc10000610160525f6101808190526101a052600f80546001600160c01b0319166e2386f26fc100000a688906bd8b0000179055601080546001600160a01b0319169055660110d9316ec00060115534801562000071575f80fd5b506040516200738c3803806200738c833981016040819052620000949162000ff9565b8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a89898989898989898989338888888181846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000101573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200012791906200111e565b5f620001348482620011cc565b506001620001438382620011cc565b5060ff81166080524660a052620001596200033b565b60c052505050506001600160a01b0391821660e05250600680546001600160a01b03191691831691821790556040515f905f8051602062007345833981519152908290a3506001600160a01b038916610100819052604051635c9fcd8560e11b81526002600482015263b93f9b0a90602401602060405180830381865afa158015620001e7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200020d919062001294565b600880546001600160a01b0319166001600160a01b03929092169190911790556200023885620003d5565b620002465f8686826200049c565b620002518562000765565b600780546001600160c01b0319166001600160c01b0383161790556127108310156200029057604051632d0d251960e11b815260040160405180910390fd5b620002a76001600160a01b0389168b30866200087b565b620002b333846200090c565b620002bf858462000977565b600f80546001600160401b0319166001600160401b038416179055620002e58a62000a0d565b5050505050505050505050505050505050505050806001600160a01b0316610120816001600160a01b03168152505050505050505050505050505050505050505050505050505050505050505050505062001516565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f6040516200036d9190620012b2565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b620003df62000a91565b61010051604051635159d87f60e11b815263ffffffff831660048201526001600160a01b039091169063a2b3b0fe906024015f6040518083038186803b15801562000428575f80fd5b505afa1580156200043b573d5f803e3d5ffd5b5050505063ffffffff81165f818152600d6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910160405180910390a150565b620004a662000a91565b620004b062000ade565b63ffffffff83165f908152600b602052604090205460ff1615620004f45760405163335894fb60e11b815263ffffffff841660048201526024015b60405180910390fd5b63ffffffff83165f908152600d602052604090205460ff166200053357604051631f9db01d60e31b815263ffffffff84166004820152602401620004eb565b610100516040516385ae5d5760e01b815263ffffffff851660048201525f91829182916001600160a01b0316906385ae5d57906024015f60405180830381865afa15801562000584573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052620005ad91908101906200132c565b92509250925083151582151514620005e157604051632b1d0bd360e11b815263ffffffff87166004820152602401620004eb565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b0319909316931692909217178155915190919060018201906200065c9082620011cc565b5060608201516002820190620006739082620011cc565b509050508115620006ba57600a54602011620006a65760405163f025236d60e01b815260206004820152602401620004eb565b620006b4600a888862000b0a565b620006f0565b600954602011620006e25760405163f025236d60e01b815260206004820152602401620004eb565b620006f06009888862000b0a565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb90620007549088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b6200076f62000a91565b63ffffffff81165f908152600b602052604090205460ff16620007ae576040516370abe85960e01b815263ffffffff82166004820152602401620004eb565b60e0516001600160a01b0316620007c58262000cdf565b6001600160a01b0316146200080f5760e051620007e28262000cdf565b60405163298473c760e11b81526001600160a01b03928316600482015291166024820152604401620004eb565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff16156200085657604051630a42c0f960e41b815263ffffffff82166004820152602401620004eb565b6007805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080620009055760405162461bcd60e51b815260206004820152601460248201527f5452414e534645525f46524f4d5f4641494c45440000000000000000000000006044820152606401620004eb565b5050505050565b8060025f8282546200091f9190620013aa565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b039092169162000a07916369445c3160e01b91620009c491869160018201916002019060240162001441565b60408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b039384161790526001600160a01b0384169162000d7116565b50505050565b6006546001600160a01b0316331462000a585760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401620004eb565b600680546001600160a01b0319166001600160a01b03831690811790915560405133905f8051602062007345833981519152905f90a350565b6006546001600160a01b0316331462000adc5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401620004eb565b565b600754600160c81b900460ff161562000adc576040516337a5332d60e11b815260040160405180910390fd5b8254801562000c9f57838062000b226001846200146f565b8154811062000b355762000b3562001485565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a909204909316021790559062000b9890836200146f565b90505b8363ffffffff1681111562000c4b578462000bb86001836200146f565b8154811062000bcb5762000bcb62001485565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1685828154811062000c045762000c0462001485565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808062000c429062001499565b91505062000b9b565b5081848463ffffffff168154811062000c685762000c6862001485565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff16021790555062000a07565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf9162000d289160010190600401620014b1565b602060405180830381865afa15801562000d44573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000d6a919062001294565b9392505050565b606062000d998383604051806060016040528060278152602001620073656027913962000da2565b90505b92915050565b60605f80856001600160a01b03168560405162000dc09190620014c5565b5f60405180830381855af49150503d805f811462000dfa576040519150601f19603f3d011682016040523d82523d5f602084013e62000dff565b606091505b50909250905062000e138683838762000e1d565b9695505050505050565b6060831562000e905782515f0362000e88576001600160a01b0385163b62000e885760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401620004eb565b508162000e9c565b62000e9c838362000ea4565b949350505050565b81511562000eb55781518083602001fd5b8060405162461bcd60e51b8152600401620004eb9190620014e2565b6001600160a01b038116811462000ee6575f80fd5b50565b805162000ef68162000ed1565b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b8381101562000f2b57818101518382015260200162000f11565b50505f910152565b5f82601f83011262000f43575f80fd5b81516001600160401b038082111562000f605762000f6062000efb565b604051601f8301601f19908116603f0116810190828211818310171562000f8b5762000f8b62000efb565b8160405283815286602085880101111562000fa4575f80fd5b62000e1384602083016020890162000f0f565b805163ffffffff8116811462000ef6575f80fd5b80516001600160401b038116811462000ef6575f80fd5b80516001600160c01b038116811462000ef6575f80fd5b5f805f805f805f805f805f6101608c8e03121562001015575f80fd5b620010208c62000ee9565b9a506200103060208d0162000ee9565b99506200104060408d0162000ee9565b60608d01519099506001600160401b038111156200105c575f80fd5b6200106a8e828f0162000f33565b60808e015190995090506001600160401b0381111562001088575f80fd5b620010968e828f0162000f33565b975050620010a760a08d0162000fb7565b60c08d01519096506001600160401b03811115620010c3575f80fd5b620010d18e828f0162000f33565b95505060e08c01519350620010ea6101008d0162000fcb565b9250620010fb6101208d0162000fe2565b91506200110c6101408d0162000ee9565b90509295989b509295989b9093969950565b5f602082840312156200112f575f80fd5b815160ff8116811462000d6a575f80fd5b600181811c908216806200115557607f821691505b6020821081036200117457634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115620011c7575f81815260208120601f850160051c81016020861015620011a25750805b601f850160051c820191505b81811015620011c357828155600101620011ae565b5050505b505050565b81516001600160401b03811115620011e857620011e862000efb565b6200120081620011f9845462001140565b846200117a565b602080601f83116001811462001236575f84156200121e5750858301515b5f19600386901b1c1916600185901b178555620011c3565b5f85815260208120601f198616915b82811015620012665788860151825594840194600190910190840162001245565b50858210156200128457878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f60208284031215620012a5575f80fd5b815162000d6a8162000ed1565b5f808354620012c18162001140565b60018281168015620012dc5760018114620012f25762001320565b60ff198416875282151583028701945062001320565b875f526020805f205f5b85811015620013175781548a820152908401908201620012fc565b50505082870194505b50929695505050505050565b5f805f606084860312156200133f575f80fd5b83516200134c8162000ed1565b6020850151909350801515811462001362575f80fd5b60408501519092506001600160401b038111156200137e575f80fd5b6200138c8682870162000f33565b9150509250925092565b634e487b7160e01b5f52601160045260245ffd5b8082018082111562000d9c5762000d9c62001396565b5f8154620013ce8162001140565b808552602060018381168015620013ee5760018114620014095762001436565b60ff1985168884015283151560051b88018301955062001436565b865f52825f205f5b858110156200142e5781548a820186015290830190840162001411565b890184019650505b505050505092915050565b838152606060208201525f6200145b6060830185620013c0565b828103604084015262000e138185620013c0565b8181038181111562000d9c5762000d9c62001396565b634e487b7160e01b5f52603260045260245ffd5b5f81620014aa57620014aa62001396565b505f190190565b602081525f62000d996020830184620013c0565b5f8251620014d881846020870162000f0f565b9190910192915050565b602081525f82518060208401526200150281604085016020870162000f0f565b601f01601f19169190910160400192915050565b60805160a05160c05160e0516101005161012051615d69620015dc5f395f8181612df60152612e8501525f81816108eb0152818161174a01528181611aa1015281816121b001528181612483015281816127530152818161315401526141f401525f81816106a201528181610f4001528181610f8101528181611d4c015281816120a50152818161336a0152818161361d0152818161393d01528181613e53015261478201525f61145c01525f61142c01525f818161060b01526147fe0152615d695ff3fe608060405260043610610419575f3560e01c8063855bccb311610220578063b5292a9911610129578063d446bbcc116100b3578063e753e60011610078578063e753e60014610d46578063ef8b30f714610bff578063f04f270714610dc7578063f2fde38b14610de6578063f5743bc914610e05575f80fd5b8063d446bbcc14610c7c578063d505accf14610cb3578063d7d4bf4514610cd2578063d905777e14610cf1578063dd62ed3e14610d10575f80fd5b8063c63d75b6116100f9578063c63d75b614610be0578063c6e6f59214610bff578063ce96cb7714610c1e578063cf30901214610c3d578063d1e8840414610c5d575f80fd5b8063b5292a9914610b63578063ba08765214610b82578063bf86d69014610ba1578063c588d8d614610bc1575f80fd5b8063a373e3ff116101aa578063b0646e271161017a578063b0646e2714610ad3578063b0a75d3614610af2578063b187bd2614610b11578063b3d7f6b914610b25578063b460af9414610b44575f80fd5b8063a373e3ff14610a6d578063a8144e4814610a81578063a9059cbb14610a95578063ac9650d814610ab4575f80fd5b806395d89b41116101f057806395d89b41146109c35780639955a9d4146109d75780639959af94146109f65780639c5f00c214610a16578063a07bee0b14610a4e575f80fd5b8063855bccb3146109385780638da5cb5b1461095757806393bbeac01461097657806394bf804d146109a4575f80fd5b80633d8ab1e5116103225780635e2c576e116102ac57806370a082311161027c57806370a082311461087c57806371e99dc2146108a75780637ab92915146108bb5780637b103999146108da5780637ecebe001461090d575f80fd5b80635e2c576e146107bf5780635f6b88a0146107d35780636419111e146107f25780636e553f651461085d575f80fd5b80634cdad506116102f25780634cdad5061461048d5780634e84befe14610743578063501eb4fe14610762578063530a371414610781578063575bbce6146107a0575f80fd5b80633d8ab1e5146106c45780633e3382ba146106e3578063402d267d146107045780634c4602da14610723575f80fd5b8063196e8285116103a3578063313ce56711610373578063313ce567146105fa57806333e15be21461063f5780633644e5151461065e578063379e0b131461067257806338d52e0f14610691575f80fd5b8063196e828514610566578063217bb34d1461059d57806323b872dd146105bc5780632b91c5de146105db575f80fd5b8063095ea7b3116103e9578063095ea7b3146104ac5780630a28a477146104db5780630a680e18146104fa578063150b7a021461050e57806318160ddd14610551575f80fd5b806301e1d1141461042457806306fdde031461044b5780630780fd3a1461046c57806307a2d13a1461048d575f80fd5b3661042057005b5f80fd5b34801561042f575f80fd5b50610438610e24565b6040519081526020015b60405180910390f35b348015610456575f80fd5b5061045f610e6e565b6040516104429190614cb1565b348015610477575f80fd5b5061048b610486366004614cdb565b610ef9565b005b348015610498575f80fd5b506104386104a7366004614cf4565b61103f565b3480156104b7575f80fd5b506104cb6104c6366004614d1f565b611062565b6040519015158152602001610442565b3480156104e6575f80fd5b506104386104f5366004614cf4565b6110ce565b348015610505575f80fd5b5061048b6110e9565b348015610519575f80fd5b50610538610528366004614e2d565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610442565b34801561055c575f80fd5b5061043860025481565b348015610571575f80fd5b50601254610585906001600160a01b031681565b6040516001600160a01b039091168152602001610442565b3480156105a8575f80fd5b5061048b6105b7366004614e94565b611143565b3480156105c7575f80fd5b506104cb6105d6366004614eaf565b6111aa565b3480156105e6575f80fd5b506104386105f5366004614eed565b611284565b348015610605575f80fd5b5061062d7f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff9091168152602001610442565b34801561064a575f80fd5b5061048b610659366004614f39565b61134e565b348015610669575f80fd5b50610438611429565b34801561067d575f80fd5b5061048b61068c366004614f6e565b61147e565b34801561069c575f80fd5b506105857f000000000000000000000000000000000000000000000000000000000000000081565b3480156106cf575f80fd5b5061048b6106de366004614e94565b611723565b3480156106ee575f80fd5b506106f76117fa565b6040516104429190614fa7565b34801561070f575f80fd5b5061043861071e366004614e94565b61187b565b34801561072e575f80fd5b506007546104cb90600160d81b900460ff1681565b34801561074e575f80fd5b5061048b61075d366004615037565b611917565b34801561076d575f80fd5b5061048b61077c366004614cdb565b611a7e565b34801561078c575f80fd5b5061048b61079b366004614cf4565b611b56565b3480156107ab575f80fd5b5061048b6107ba366004615075565b611bde565b3480156107ca575f80fd5b5061048b611c38565b3480156107de575f80fd5b5061048b6107ed366004614e94565b611ca7565b3480156107fd575f80fd5b5061083961080c366004614e94565b60136020525f908152604090205460ff81169063ffffffff61010082048116916501000000000090041683565b60408051931515845263ffffffff9283166020850152911690820152606001610442565b348015610868575f80fd5b5061043861087736600461509b565b611d05565b348015610887575f80fd5b50610438610896366004614e94565b60036020525f908152604090205481565b3480156108b2575f80fd5b506106f7611d9a565b3480156108c6575f80fd5b506104386108d5366004614d1f565b611df6565b3480156108e5575f80fd5b506105857f000000000000000000000000000000000000000000000000000000000000000081565b348015610918575f80fd5b50610438610927366004614e94565b60056020525f908152604090205481565b348015610943575f80fd5b5061048b6109523660046150be565b611e42565b348015610962575f80fd5b50600654610585906001600160a01b031681565b348015610981575f80fd5b506104cb610990366004614cf4565b600b6020525f908152604090205460ff1681565b3480156109af575f80fd5b506104386109be36600461509b565b611feb565b3480156109ce575f80fd5b5061045f6120ef565b3480156109e2575f80fd5b5061048b6109f1366004615100565b6120fc565b348015610a01575f80fd5b506007546104cb90600160d01b900460ff1681565b348015610a21575f80fd5b50600754610a3990600160e01b900463ffffffff1681565b60405163ffffffff9091168152602001610442565b348015610a59575f80fd5b5061048b610a68366004614f6e565b6123c2565b348015610a78575f80fd5b5061048b61251d565b348015610a8c575f80fd5b5061043861255d565b348015610aa0575f80fd5b506104cb610aaf366004614d1f565b61259a565b348015610abf575f80fd5b5061048b610ace366004615037565b6125fd565b348015610ade575f80fd5b5061048b610aed366004615075565b612682565b348015610afd575f80fd5b5061048b610b0c366004614e94565b6126ba565b348015610b1c575f80fd5b506104cb61272b565b348015610b30575f80fd5b50610438610b3f366004614cf4565b6127c9565b348015610b4f575f80fd5b50610438610b5e36600461516c565b6127e5565b348015610b6e575f80fd5b5061048b610b7d3660046151a0565b612862565b348015610b8d575f80fd5b50610438610b9c36600461516c565b612906565b348015610bac575f80fd5b506007546104cb90600160c81b900460ff1681565b348015610bcc575f80fd5b5061048b610bdb3660046151c6565b61298d565b348015610beb575f80fd5b50610438610bfa366004614e94565b612a55565b348015610c0a575f80fd5b50610438610c19366004614cf4565b612ac9565b348015610c29575f80fd5b50610438610c38366004614e94565b612ae5565b348015610c48575f80fd5b506007546104cb90600160c01b900460ff1681565b348015610c68575f80fd5b5061048b610c77366004614cdb565b612b1b565b348015610c87575f80fd5b50600754610c9b906001600160c01b031681565b6040516001600160c01b039091168152602001610442565b348015610cbe575f80fd5b5061048b610ccd366004615207565b612b76565b348015610cdd575f80fd5b50600854610585906001600160a01b031681565b348015610cfc575f80fd5b50610438610d0b366004614e94565b612db4565b348015610d1b575f80fd5b50610438610d2a366004615273565b600460209081525f928352604080842090915290825290205481565b348015610d51575f80fd5b50600f54601054610d8e916001600160401b0380821692680100000000000000008304821692600160801b9004909116906001600160a01b031684565b604080516001600160401b039586168152938516602085015291909316908201526001600160a01b039091166060820152608001610442565b348015610dd2575f80fd5b5061048b610de136600461529f565b612deb565b348015610df1575f80fd5b5061048b610e00366004614e94565b612f33565b348015610e10575f80fd5b5061048b610e1f36600461509b565b612fa8565b5f610e2d61312e565b600754600160c01b900460ff1615610e605760405162461bcd60e51b8152600401610e5790615383565b60405180910390fd5b610e695f6131e5565b905090565b5f8054610e7a906153a7565b80601f0160208091040260200160405190810160405280929190818152602001828054610ea6906153a7565b8015610ef15780601f10610ec857610100808354040283529160200191610ef1565b820191905f5260205f20905b815481529060010190602001808311610ed457829003601f168201915b505050505081565b610f01613690565b63ffffffff81165f908152600b602052604090205460ff16610f3e576040516370abe85960e01b815263ffffffff82166004820152602401610e57565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610f71826136ba565b6001600160a01b031614610fd5577f0000000000000000000000000000000000000000000000000000000000000000610fa9826136ba565b60405163298473c760e11b81526001600160a01b03928316600482015291166024820152604401610e57565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff161561101a57604051630a42c0f960e41b815263ffffffff82166004820152602401610e57565b6007805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f805f61104b5f613747565b9150915061105a84838361385b565b949350505050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906110bc9086815260200190565b60405180910390a35060015b92915050565b5f805f6110da5f613747565b9150915061105a848383613867565b6110f1613690565b6110f9613873565b6007805460ff60c81b1916600160c81b179055604051600181527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c906020015b60405180910390a1565b61114b613690565b6001600160a01b0381165f81815260136020908152604091829020805468ffffffffffffffffff1916905590519182527f741bf5c2d606526029e0f199a3ddf6c7ebafa7edb2e1405174105f458195e67991015b60405180910390a150565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f198114611203576111df83826153f3565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f908152600360205260408120805485929061122a9084906153f3565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615d14833981519152906112719087815260200190565b60405180910390a3506001949350505050565b6007545f90600160c01b900460ff16156112b05760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f80806112d0878761389e565b9250925092506112e487878585858a6139f4565b604080516001600160a01b038a81168252602082018a905291810183905291955086169033907f385ba312edecbeeae57aca70f4fde3d83578697795291e74b1b4edb37d7291bf9060600160405180910390a350506007805460ff60c01b19169055509392505050565b611356613690565b5f8161139e5760098363ffffffff168154811061137557611375615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff166113dc565b600a8363ffffffff16815481106113b7576113b7615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90505f6113e882613a84565b9050801561141857604051631c7b946d60e31b815263ffffffff8316600482015260248101829052604401610e57565b611423848385613b0a565b50505050565b5f7f0000000000000000000000000000000000000000000000000000000000000000461461145957610e69613bec565b507f000000000000000000000000000000000000000000000000000000000000000090565b611486613690565b5f8082156115af57600a8463ffffffff16815481106114a7576114a7615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff16815481106114e6576114e6615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff168154811061152757611527615406565b905f5260205f209060089182820401919006600402600a8863ffffffff168154811061155557611555615406565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050506116cc565b60098463ffffffff16815481106115c8576115c8615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16915060098563ffffffff168154811061160757611607615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169050818160098763ffffffff168154811061164857611648615406565b905f5260205f20906008918282040191900660040260098863ffffffff168154811061167657611676615406565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b61172b613690565b604051636777140560e11b81526001600160a01b0382811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063ceee280a906024015f6040518083038186803b15801561178a575f80fd5b505afa15801561179c573d5f803e3d5ffd5b505050506001600160a01b0381165f818152600e6020908152604091829020805460ff191660019081179091558251938452908301527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a910161119f565b6060600a80548060200260200160405190810160405280929190818152602001828054801561187157602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116118345790505b5050505050905090565b6007545f90600160c81b900460ff161561189657505f919050565b6007546001600160c01b03166002600160c01b031981016118ba57505f1992915050565b5f806118c66001613747565b91509150826001600160c01b031681106118e457505f949350505050565b5f6118f8826001600160c01b0386166153f3565b905061190581848461385b565b9695505050505050565b505050919050565b600754600160c01b900460ff16156119415760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b17905561195c613690565b611964613873565b61196c61312e565b6007805460ff60d81b1916600160d81b1790555f80808061198c816131e5565b90506119b7601154670de0b6b3a76400006119a791906153f3565b8290670de0b6b3a7640000613c84565b93506119d2601154670de0b6b3a76400006119a7919061541a565b60025490935091506119ee90506119e98587615568565b613cb1565b5f6119f85f6131e5565b905083811080611a0757508281115b15611a365760405163628cc47560e11b8152600481018290526024810185905260448101849052606401610e57565b6002548214611a6657600254604051632b40145960e21b8152600481019190915260248101839052604401610e57565b50506007805463ff0000ff60c01b1916905550505050565b611a86613690565b604051635159d87f60e11b815263ffffffff821660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a2b3b0fe906024015f6040518083038186803b158015611ae9575f80fd5b505afa158015611afb573d5f803e3d5ffd5b5050505063ffffffff81165f818152600d6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910161119f565b611b5e613690565b67016345785d8a0000811115611b98576040516302d2a90f60e51b81526004810182905267016345785d8a00006024820152604401610e57565b601180549082905560408051828152602081018490527fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff91015b60405180910390a15050565b611be6613690565b6007546001600160c01b039081169082161115611c16576040516334f1ec1b60e01b815260040160405180910390fd5b600780546001600160c01b0319166001600160c01b0392909216919091179055565b611c40613690565b600754600160c81b900460ff16611c6a5760405163ec7165bf60e01b815260040160405180910390fd5b6007805460ff60c81b191690556040515f81527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c90602001611139565b611caf613690565b6001600160a01b0381165f818152600e60209081526040808320805460ff191690558051938452908301919091527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a910161119f565b6007545f90600160c01b900460ff1615611d315760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790819055611d86907f00000000000000000000000000000000000000000000000000000000000000009085908190819063ffffffff600160e01b90910416876139f4565b6007805460ff60c01b191690559392505050565b60606009805480602002602001604051908101604052809291908181526020018280548015611871575f918252602091829020805463ffffffff1684529082028301929091600491018084116118345790505050505050905090565b5f805f611e03858561389e565b50915091505f80611e146001613747565b9092509050611e3783611e2781876153f3565b611e31908561541a565b83613e36565b979650505050505050565b611e4a613690565b63ffffffff82165f908152600b602052604090205460ff16611e87576040516370abe85960e01b815263ffffffff83166004820152602401610e57565b826001600160a01b0316611e9a836136ba565b6001600160a01b031614611eb25782610fa9836136ba565b63ffffffff82165f908152600c6020526040902054600160a01b900460ff1615611ef757604051630a42c0f960e41b815263ffffffff83166004820152602401610e57565b6298968063ffffffff82161115611f2157604051632e3a13e960e21b815260040160405180910390fd5b60408051606080820183526001825263ffffffff85811660208085018281528784168688018181526001600160a01b038c165f818152601386528a902098518954945192518816650100000000000268ffffffff000000000019939098166101000264ffffffff00199115159190911664ffffffffff19909516949094179390931716949094179095558551948552840152928201929092527f2682afad81f7b7a2141b8d3c671b3efc09ac3dac73f06a5cd8e4714ae8864c1b91015b60405180910390a1505050565b6007545f90600160c01b900460ff16156120175760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f806120366001613747565b91509150612045858383613e42565b9250825f0361206757604051639768300560e01b815260040160405180910390fd5b6007546001600160c01b031661207d868361541a565b111561209c5760405163adea3dfd60e01b815260040160405180910390fd5b6007546120da907f000000000000000000000000000000000000000000000000000000000000000090600160e01b900463ffffffff16858888613e4e565b50506007805460ff60c01b1916905592915050565b60018054610e7a906153a7565b612104613690565b61210c613873565b63ffffffff83165f908152600b602052604090205460ff161561214a5760405163335894fb60e11b815263ffffffff84166004820152602401610e57565b63ffffffff83165f908152600d602052604090205460ff1661218757604051631f9db01d60e31b815263ffffffff84166004820152602401610e57565b6040516385ae5d5760e01b815263ffffffff841660048201525f90819081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906385ae5d57906024015f60405180830381865afa1580156121f4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261221b9190810190615574565b9250925092508315158215151461224d57604051632b1d0bd360e11b815263ffffffff87166004820152602401610e57565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b0319909316931692909217178155915190919060018201906122c69082615652565b50606082015160028201906122db9082615652565b50905050811561231c57600a5460201161230b5760405163f025236d60e01b815260206004820152602401610e57565b612317600a8888613ef2565b61234e565b6009546020116123425760405163f025236d60e01b815260206004820152602401610e57565b61234e60098888613ef2565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb906123b19088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b6123ca613690565b5f816124125760098463ffffffff16815481106123e9576123e9615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612450565b600a8463ffffffff168154811061242b5761242b615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff161415806124f457506040516321a0f75360e01b815263ffffffff841660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906321a0f75390602401602060405180830381865afa1580156124d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124f4919061570d565b156125125760405163d4db0b7960e01b815260040160405180910390fd5b611423848484613b0a565b612525613690565b600754600160d01b900460ff1661253d57600161253f565b5f5b60078054911515600160d01b0260ff60d01b19909216919091179055565b5f61256661312e565b600754600160c01b900460ff16156125905760405162461bcd60e51b8152600401610e5790615383565b610e6960016131e5565b335f908152600360205260408120805483919083906125ba9084906153f3565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615d14833981519152906110bc9086815260200190565b5f5b8181101561267d5761266a83838381811061261c5761261c615406565b905060200281019061262e9190615728565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506140af9050565b50806126758161576a565b9150506125ff565b505050565b61268a613690565b6007546001600160c01b039081169082161015611c16576040516334f1ec1b60e01b815260040160405180910390fd5b6126c2613690565b601054604080516001600160a01b03928316815291831660208301527f51dbb5a65bb22737861a63ec12ba6ce78a98631e9404b0567a2eaf7a06fc544d910160405180910390a1601080546001600160a01b0319166001600160a01b0392909216919091179055565b6007545f90600160d01b900460ff166127c457604051630ad85dff60e41b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063ad85dff090602401602060405180830381865afa1580156127a0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e69919061570d565b505f90565b5f805f6127d66001613747565b9150915061105a848383613e42565b6007545f90600160c01b900460ff16156128115760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f8061282f81613747565b9150915061283e868383613867565b925061284c868487876140d4565b50506007805460ff60c01b191690559392505050565b61286a613690565b670de0b6b3a76400006001600160401b038216111561289c57604051633d0203e560e01b815260040160405180910390fd5b600f54604080516001600160401b03928316815291831660208301527fb5cc994a260a85a42d6588668221571ae0a14f0a28f9e4817a5195262102c868910160405180910390a1600f805467ffffffffffffffff19166001600160401b0392909216919091179055565b6007545f90600160c01b900460ff16156129325760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f8061295081613747565b9150915061295f86838361385b565b9250825f0361298157604051639768300560e01b815260040160405180910390fd5b61284c838787876140d4565b612995613690565b5f8084156129da575f6129a6610e24565b90506129c56129b786612710615782565b829061ffff166127106141aa565b92506129d66129b7866127106157a4565b9150505b6129e56002846141c8565b600880546001600160a01b0319166001600160a01b0385161790555f612a09610e24565b90508515612a4d5782811080612a1e57508181115b15612a4d5760405163628cc47560e11b8152600481018290526024810184905260448101839052606401610e57565b505050505050565b6007545f90600160c81b900460ff1615612a7057505f919050565b6007546001600160c01b03166002600160c01b03198101612a9457505f1992915050565b6002546001600160c01b038216811015612ac057612abb816001600160c01b0384166153f3565b61105a565b5f949350505050565b5f805f612ad66001613747565b9150915061105a848383613e36565b6007545f90600160c01b900460ff1615612b115760405162461bcd60e51b8152600401610e5790615383565b6110c8825f6142a6565b612b23613690565b63ffffffff81165f818152600d60209081526040808320805460ff191690558051938452908301919091527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910161119f565b42841015612bc65760405162461bcd60e51b815260206004820152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606401610e57565b5f6001612bd1611429565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e08301909152805192019190912061190160f01b6101008301526101028201929092526101228101919091526101420160408051601f1981840301815282825280516020918201205f84529083018083525260ff871690820152606081018590526080810184905260a0016020604051602081039080840390855afa158015612cd9573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811615801590612d0f5750876001600160a01b0316816001600160a01b0316145b612d4c5760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610e57565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050505050565b6007545f90600160c01b900460ff1615612de05760405162461bcd60e51b8152600401610e5790615383565b6110c88260016142a6565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612e3457604051633cf941a360e01b815260040160405180910390fd5b600754600160d81b900460ff16612e5e576040516304a246dd60e51b815260040160405180910390fd5b5f612e6b828401846157bf565b9050612e7681613cb1565b5f5b86811015612f2757612f177f0000000000000000000000000000000000000000000000000000000000000000878784818110612eb657612eb6615406565b905060200201358a8a85818110612ecf57612ecf615406565b90506020020135612ee0919061541a565b8c8c85818110612ef257612ef2615406565b9050602002016020810190612f079190614e94565b6001600160a01b03169190614320565b612f208161576a565b9050612e78565b50505050505050505050565b6006546001600160a01b03163314612f5d5760405162461bcd60e51b8152600401610e5790615803565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a350565b6006546001600160a01b03163314612fd25760405162461bcd60e51b8152600401610e5790615803565b612fdc82826141c8565b601260ff16816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561301d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130419190615829565b60ff161415806130c25750306001600160a01b0316816001600160a01b031663d4b839926040518163ffffffff1660e01b8152600401602060405180830381865afa158015613092573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130b69190615844565b6001600160a01b031614155b156130e05760405163229e78bb60e01b815260040160405180910390fd5b601280546001600160a01b0319166001600160a01b0383169081179091556040519081527f51b1b17228af00bd72d43ecec4334e09b3584633abf6ef363a9fde05dfa73f8890602001611bd2565b600754600160d01b900460ff166131e357604051630ad85dff60e41b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063ad85dff090602401602060405180830381865afa1580156131a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131c5919061570d565b156131e357604051630f301f8f60e41b815260040160405180910390fd5b565b6009545f9081816001600160401b0381111561320357613203614d49565b60405190808252806020026020018201604052801561322c578160200160208202803683370190505b5090505f826001600160401b0381111561324857613248614d49565b604051908082528060200260200182016040528015613271578160200160208202803683370190505b50905084156133d8575f5b8381101561333d575f6009828154811061329857613298615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506132c781614394565b8383815181106132d9576132d9615406565b60200260200101818152505f036132f0575061332d565b6132f9816136ba565b84838151811061330b5761330b615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6133368161576a565b905061327c565b5060085460405163b333a17560e01b81526001600160a01b039091169063b333a1759061339290859085907f0000000000000000000000000000000000000000000000000000000000000000906004016158cf565b602060405180830381865afa1580156133ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133d1919061590c565b935061190f565b600a545f816001600160401b038111156133f4576133f4614d49565b60405190808252806020026020018201604052801561341d578160200160208202803683370190505b5090505f826001600160401b0381111561343957613439614d49565b604051908082528060200260200182016040528015613462578160200160208202803683370190505b5090505f5b86811015613528575f6009828154811061348357613483615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506134b281613a84565b8683815181106134c4576134c4615406565b60200260200101818152505f036134db5750613518565b6134e4816136ba565b8783815181106134f6576134f6615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6135218161576a565b9050613467565b505f5b838110156135ec575f600a828154811061354757613547615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061357681613a84565b83838151811061358857613588615406565b60200260200101818152505f0361359f57506135dc565b6135a8816136ba565b8483815181106135ba576135ba615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6135e58161576a565b905061352b565b50600854604051637563738b60e11b81526001600160a01b039091169063eac6e716906136459088908890879087907f000000000000000000000000000000000000000000000000000000000000000090600401615923565b602060405180830381865afa158015613660573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613684919061590c565b98975050505050505050565b6006546001600160a01b031633146131e35760405162461bcd60e51b8152600401610e5790615803565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf916137019160010190600401615a03565b602060405180830381865afa15801561371c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137409190615844565b9392505050565b6012545f9081906001600160a01b0316801561383c575f805f836001600160a01b031663c36af4606040518163ffffffff1660e01b8152600401606060405180830381865afa15801561379c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137c09190615a15565b92509250925080156137e55760405163229e78bb60e01b815260040160405180910390fd5b5f8715613802578284116137f957826137fb565b835b9050613814565b82841061380f5782613811565b835b90505b6002549550613831866138296012600a615b20565b8391906141aa565b965050505050613855565b60405163229e78bb60e01b815260040160405180910390fd5b50915091565b5f61105a8484846141aa565b5f61105a848385613c84565b600754600160c81b900460ff16156131e3576040516337a5332d60e11b815260040160405180910390fd5b6001600160a01b0382165f9081526013602090815260408083208151606081018352905460ff8116151580835263ffffffff6101008304811695840195909552650100000000009091049093169181019190915282918291906139145760405163217feaeb60e01b815260040160405180910390fd5b60085460405163151d4a5960e31b81526001600160a01b038881166004830152602482018890527f0000000000000000000000000000000000000000000000000000000000000000811660448301529091169063a8ea52c890606401602060405180830381865afa15801561398b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139af919061590c565b93506139e381604001516305f5e1006139c89190615b2e565b63ffffffff166305f5e100866141aa9092919063ffffffff16565b925080602001519150509250925092565b5f805f613a016001613747565b9092509050613a1486611e27818a6153f3565b9250825f03613a365760405163426f153760e11b815260040160405180910390fd5b6007546001600160c01b0316613a4c848361541a565b1115613a6b5760405163adea3dfd60e01b815260040160405180910390fd5b613a7889868a8688613e4e565b50509695505050505050565b63ffffffff81165f908152600c602052604080822080549151637841536560e01b81526001600160a01b03909216918291637841536591613acb9160010190600401615a03565b602060405180830381865afa158015613ae6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613740919061590c565b60075463ffffffff600160e01b909104811690831603613b3d576040516319ded73160e21b815260040160405180910390fd5b8015613b5357613b4e600a84614449565b613b5e565b613b5e600984614449565b63ffffffff82165f908152600b60209081526040808320805460ff19169055600c909152812080546001600160a81b031916815590613ba06001830182614c12565b613bad600283015f614c12565b50506040805163ffffffff8085168252851660208201527fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd519101611fde565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051613c1c9190615b4b565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b828202811515841585830485141716613c9b575f80fd5b6001826001830304018115150290509392505050565b5f5b8151811015613e32575f828281518110613ccf57613ccf615406565b602090810291909101810151516001600160a01b0381165f908152600e90925260409091205490915060ff16613d2357604051635df6b61760e11b81526001600160a01b0382166004820152602401610e57565b5f5b838381518110613d3757613d37615406565b60200260200101516020015151811015613e1f57613d9d848481518110613d6057613d60615406565b6020026020010151602001518281518110613d7d57613d7d615406565b6020026020010151836001600160a01b03166140af90919063ffffffff16565b507f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf48382858581518110613dd257613dd2615406565b6020026020010151602001518381518110613def57613def615406565b6020026020010151604051613e05929190615bbd565b60405180910390a180613e178161576a565b915050613d25565b505080613e2b9061576a565b9050613cb3565b5050565b5f61105a8483856141aa565b5f61105a848484613c84565b613e7a7f0000000000000000000000000000000000000000000000000000000000000000848484614588565b613e8f6001600160a01b038616333086614598565b613e998183614617565b60408051848152602081018490526001600160a01b0383169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a3613eeb8484848461466e565b5050505050565b8254801561406f578380613f076001846153f3565b81548110613f1757613f17615406565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a9092049093160217905590613f7890836153f3565b90505b8363ffffffff1681111561401f5784613f956001836153f3565b81548110613fa557613fa5615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16858281548110613fdb57613fdb615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061401790615be0565b915050613f7b565b5081848463ffffffff168154811061403957614039615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550611423565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b60606137408383604051806060016040528060278152602001615ced60279139614678565b6140e084848484614590565b336001600160a01b0382161461414b576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146141495761412584826153f3565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b61415581846146e2565b60408051858152602081018590526001600160a01b03808416929085169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a46114238483614741565b8282028115158415858304851417166141c1575f80fd5b0492915050565b815f036141e857604051632db38d0560e01b815260040160405180910390fd5b806001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b93f9b0a846040518263ffffffff1660e01b815260040161424091815260200190565b602060405180830381865afa15801561425b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061427f9190615844565b6001600160a01b031614613e3257604051634ee204d760e01b815260040160405180910390fd5b5f6142af61312e565b5f806142ba5f613747565b6001600160a01b0387165f90815260036020526040812054929450909250906142e490848461385b565b90505f6142f160016131e5565b9050808211156143015780614303565b815b9450851561431657611e37858585613e36565b5050505092915050565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806114235760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610e57565b63ffffffff81165f908152600c6020526040812054600160a01b900460ff16156143bf57505f919050565b63ffffffff82165f908152600c60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d29161440a91600182019160020190600401615bf5565b602060405180830381865afa158015614425573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110c8919061590c565b815463ffffffff821681116144965760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610e57565b63ffffffff82165b6144a96001836153f3565b81101561454657836144bc82600161541a565b815481106144cc576144cc615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1684828154811061450257614502615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061453e9061576a565b91505061449e565b508280548061455757614557615c22565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b614590613873565b61142361312e565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080613eeb5760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610e57565b8060025f828254614628919061541a565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615d1483398151915291015b60405180910390a35050565b6114238484614a96565b60605f80856001600160a01b0316856040516146949190615c36565b5f60405180830381855af49150503d805f81146146cc576040519150601f19603f3d011682016040523d82523d5f602084013e6146d1565b606091505b509150915061190586838387614b22565b6001600160a01b0382165f90815260036020526040812080548392906147099084906153f3565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615d1483398151915290602001614662565b61476860405180608001604052805f81526020015f81526020015f81526020015f81525090565b600854604051630226614760e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015290911690630226614790602401602060405180830381865afa1580156147d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906147f4919061590c565b60408201526148247f0000000000000000000000000000000000000000000000000000000000000000600a615b20565b60608201526009545f5b81811015614a73575f6009828154811061484a5761484a615406565b5f9182526020822060088204015460079091166004026101000a900463ffffffff16915061487782614394565b9050805f03614887575050614a63565b5f614891836136ba565b600854604051630226614760e01b81526001600160a01b038084166004830152929350911690630226614790602401602060405180830381865afa1580156148db573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906148ff919061590c565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614943573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906149679190615829565b61497290600a615b20565b6020870181905286515f91829161499c9161499587670de0b6b3a7640000615c51565b91906141aa565b90506149bb88606001518960400151836141aa9092919063ffffffff16565b91506149cf670de0b6b3a764000083615c68565b9150505f89821115614a32575f6149fd89604001518a606001518d670de0b6b3a76400006149959190615c51565b60208a01518a51919250614a13918391906141aa565b9150614a27670de0b6b3a764000083615c68565b91505f9a5050614a41565b5082614a3e828b6153f3565b99505b614a4c85828b614b9a565b895f03614a5d575050505050614a73565b50505050505b614a6c8161576a565b905061482e565b5083156114235760405163cc5ea39b60e01b815260048101859052602401610e57565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b0390921691611423916369445c3160e01b91614ae0918691600182019160020190602401615c87565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b038316906140af565b60608315614b905782515f03614b89576001600160a01b0385163b614b895760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610e57565b508161105a565b61105a8383614be8565b63ffffffff83165f908152600c602052604090819020805491516001600160a01b0390921691613eeb9163c9111bd760e01b91614ae091879187916001810191600290910190602401615cb1565b815115614bf85781518083602001fd5b8060405162461bcd60e51b8152600401610e579190614cb1565b508054614c1e906153a7565b5f825580601f10614c2d575050565b601f0160209004905f5260205f2090810190614c499190614c4c565b50565b5b80821115614c60575f8155600101614c4d565b5090565b5f5b83811015614c7e578181015183820152602001614c66565b50505f910152565b5f8151808452614c9d816020860160208601614c64565b601f01601f19169290920160200192915050565b602081525f6137406020830184614c86565b803563ffffffff81168114614cd6575f80fd5b919050565b5f60208284031215614ceb575f80fd5b61374082614cc3565b5f60208284031215614d04575f80fd5b5035919050565b6001600160a01b0381168114614c49575f80fd5b5f8060408385031215614d30575f80fd5b8235614d3b81614d0b565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b0381118282101715614d7f57614d7f614d49565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614dad57614dad614d49565b604052919050565b5f6001600160401b03821115614dcd57614dcd614d49565b50601f01601f191660200190565b5f82601f830112614dea575f80fd5b8135614dfd614df882614db5565b614d85565b818152846020838601011115614e11575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215614e40575f80fd5b8435614e4b81614d0b565b93506020850135614e5b81614d0b565b92506040850135915060608501356001600160401b03811115614e7c575f80fd5b614e8887828801614ddb565b91505092959194509250565b5f60208284031215614ea4575f80fd5b813561374081614d0b565b5f805f60608486031215614ec1575f80fd5b8335614ecc81614d0b565b92506020840135614edc81614d0b565b929592945050506040919091013590565b5f805f60608486031215614eff575f80fd5b8335614f0a81614d0b565b9250602084013591506040840135614f2181614d0b565b809150509250925092565b8015158114614c49575f80fd5b5f8060408385031215614f4a575f80fd5b614f5383614cc3565b91506020830135614f6381614f2c565b809150509250929050565b5f805f60608486031215614f80575f80fd5b614f8984614cc3565b9250614f9760208501614cc3565b91506040840135614f2181614f2c565b602080825282518282018190525f9190848201906040850190845b81811015614fe457835163ffffffff1683529284019291840191600101614fc2565b50909695505050505050565b5f8083601f840112615000575f80fd5b5081356001600160401b03811115615016575f80fd5b6020830191508360208260051b8501011115615030575f80fd5b9250929050565b5f8060208385031215615048575f80fd5b82356001600160401b0381111561505d575f80fd5b61506985828601614ff0565b90969095509350505050565b5f60208284031215615085575f80fd5b81356001600160c01b0381168114613740575f80fd5b5f80604083850312156150ac575f80fd5b823591506020830135614f6381614d0b565b5f805f606084860312156150d0575f80fd5b83356150db81614d0b565b92506150e960208501614cc3565b91506150f760408501614cc3565b90509250925092565b5f805f8060808587031215615113575f80fd5b61511c85614cc3565b935061512a60208601614cc3565b925060408501356001600160401b03811115615144575f80fd5b61515087828801614ddb565b925050606085013561516181614f2c565b939692955090935050565b5f805f6060848603121561517e575f80fd5b83359250602084013561519081614d0b565b91506040840135614f2181614d0b565b5f602082840312156151b0575f80fd5b81356001600160401b0381168114613740575f80fd5b5f805f606084860312156151d8575f80fd5b83356151e381614f2c565b9250602084013561ffff81168114615190575f80fd5b60ff81168114614c49575f80fd5b5f805f805f805f60e0888a03121561521d575f80fd5b873561522881614d0b565b9650602088013561523881614d0b565b955060408801359450606088013593506080880135615256816151f9565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615284575f80fd5b823561528f81614d0b565b91506020830135614f6381614d0b565b5f805f805f805f806080898b0312156152b6575f80fd5b88356001600160401b03808211156152cc575f80fd5b6152d88c838d01614ff0565b909a50985060208b01359150808211156152f0575f80fd5b6152fc8c838d01614ff0565b909850965060408b0135915080821115615314575f80fd5b6153208c838d01614ff0565b909650945060608b0135915080821115615338575f80fd5b818b0191508b601f83011261534b575f80fd5b813581811115615359575f80fd5b8c602082850101111561536a575f80fd5b6020830194508093505050509295985092959890939650565b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b600181811c908216806153bb57607f821691505b6020821081036153d957634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b818103818111156110c8576110c86153df565b634e487b7160e01b5f52603260045260245ffd5b808201808211156110c8576110c86153df565b5f6001600160401b0382111561544557615445614d49565b5060051b60200190565b5f61545c614df88461542d565b8381529050602080820190600585901b84018681111561547a575f80fd5b845b8181101561555d576001600160401b038082351115615499575f80fd5b813587016040818b0312156154ac575f80fd5b6154b4614d5d565b6154be8235614d0b565b8135815285820135838111156154d2575f80fd5b8083019250508a601f8301126154e6575f80fd5b81356154f4614df88261542d565b81815260059190911b8301870190878101908d831115615512575f80fd5b8885015b8381101561554757868135111561552b575f80fd5b61553a8f8b8335890101614ddb565b8352918901918901615516565b508389015250508652505092820192820161547c565b505050509392505050565b5f61374036848461544f565b5f805f60608486031215615586575f80fd5b835161559181614d0b565b60208501519093506155a281614f2c565b60408501519092506001600160401b038111156155bd575f80fd5b8401601f810186136155cd575f80fd5b80516155db614df882614db5565b8181528760208385010111156155ef575f80fd5b615600826020830160208601614c64565b8093505050509250925092565b601f82111561267d575f81815260208120601f850160051c810160208610156156335750805b601f850160051c820191505b81811015612a4d5782815560010161563f565b81516001600160401b0381111561566b5761566b614d49565b61567f8161567984546153a7565b8461560d565b602080601f8311600181146156b2575f841561569b5750858301515b5f19600386901b1c1916600185901b178555612a4d565b5f85815260208120601f198616915b828110156156e0578886015182559484019460019091019084016156c1565b50858210156156fd57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f6020828403121561571d575f80fd5b815161374081614f2c565b5f808335601e1984360301811261573d575f80fd5b8301803591506001600160401b03821115615756575f80fd5b602001915036819003821315615030575f80fd5b5f6001820161577b5761577b6153df565b5060010190565b61ffff82811682821603908082111561579d5761579d6153df565b5092915050565b61ffff81811683821601908082111561579d5761579d6153df565b5f602082840312156157cf575f80fd5b81356001600160401b038111156157e4575f80fd5b8201601f810184136157f4575f80fd5b61105a8482356020840161544f565b6020808252600c908201526b15539055551213d49256915160a21b604082015260600190565b5f60208284031215615839575f80fd5b8151613740816151f9565b5f60208284031215615854575f80fd5b815161374081614d0b565b5f8151808452602080850194508084015f5b838110156158965781516001600160a01b031687529582019590820190600101615871565b509495945050505050565b5f8151808452602080850194508084015f5b83811015615896578151875295820195908201906001016158b3565b606081525f6158e1606083018661585f565b82810360208401526158f381866158a1565b91505060018060a01b0383166040830152949350505050565b5f6020828403121561591c575f80fd5b5051919050565b60a081525f61593560a083018861585f565b828103602084015261594781886158a1565b9050828103604084015261595b818761585f565b9050828103606084015261596f81866158a1565b91505060018060a01b03831660808301529695505050505050565b5f8154615996816153a7565b8085526020600183811680156159b357600181146159cd576159f8565b60ff1985168884015283151560051b8801830195506159f8565b865f52825f205f5b858110156159f05781548a82018601529083019084016159d5565b890184019650505b505050505092915050565b602081525f613740602083018461598a565b5f805f60608486031215615a27575f80fd5b83519250602084015191506040840151614f2181614f2c565b600181815b80851115615a7a57815f1904821115615a6057615a606153df565b80851615615a6d57918102915b93841c9390800290615a45565b509250929050565b5f82615a90575060016110c8565b81615a9c57505f6110c8565b8160018114615ab25760028114615abc57615ad8565b60019150506110c8565b60ff841115615acd57615acd6153df565b50506001821b6110c8565b5060208310610133831016604e8410600b8410161715615afb575081810a6110c8565b615b058383615a40565b805f1904821115615b1857615b186153df565b029392505050565b5f61374060ff841683615a82565b63ffffffff82811682821603908082111561579d5761579d6153df565b5f808354615b58816153a7565b60018281168015615b705760018114615b8557615bb1565b60ff1984168752821515830287019450615bb1565b875f526020805f205f5b85811015615ba85781548a820152908401908201615b8f565b50505082870194505b50929695505050505050565b6001600160a01b03831681526040602082018190525f9061105a90830184614c86565b5f81615bee57615bee6153df565b505f190190565b604081525f615c07604083018561598a565b8281036020840152615c19818561598a565b95945050505050565b634e487b7160e01b5f52603160045260245ffd5b5f8251615c47818460208701614c64565b9190910192915050565b80820281158282048414176110c8576110c86153df565b5f82615c8257634e487b7160e01b5f52601260045260245ffd5b500490565b838152606060208201525f615c9f606083018561598a565b8281036040840152611905818561598a565b8481526001600160a01b03841660208201526080604082018190525f90615cda9083018561598a565b8281036060840152611e37818561598a56fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122038a4640d22c096bd2f0ec8bbdbbdf889726baa52b404f752396a365216b03c2964736f6c634300081500338be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564000000000000000000000000eef7b7205caf2bcd71437d9acde3874c3388c138000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee44476000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000005af3107a40000000000000000000000000000000000000000000000000000b1a2bc2ec5000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000000000000000000000000000000000000000000a547572626f2045455448000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009547572626f45455448000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x608060405260043610610419575f3560e01c8063855bccb311610220578063b5292a9911610129578063d446bbcc116100b3578063e753e60011610078578063e753e60014610d46578063ef8b30f714610bff578063f04f270714610dc7578063f2fde38b14610de6578063f5743bc914610e05575f80fd5b8063d446bbcc14610c7c578063d505accf14610cb3578063d7d4bf4514610cd2578063d905777e14610cf1578063dd62ed3e14610d10575f80fd5b8063c63d75b6116100f9578063c63d75b614610be0578063c6e6f59214610bff578063ce96cb7714610c1e578063cf30901214610c3d578063d1e8840414610c5d575f80fd5b8063b5292a9914610b63578063ba08765214610b82578063bf86d69014610ba1578063c588d8d614610bc1575f80fd5b8063a373e3ff116101aa578063b0646e271161017a578063b0646e2714610ad3578063b0a75d3614610af2578063b187bd2614610b11578063b3d7f6b914610b25578063b460af9414610b44575f80fd5b8063a373e3ff14610a6d578063a8144e4814610a81578063a9059cbb14610a95578063ac9650d814610ab4575f80fd5b806395d89b41116101f057806395d89b41146109c35780639955a9d4146109d75780639959af94146109f65780639c5f00c214610a16578063a07bee0b14610a4e575f80fd5b8063855bccb3146109385780638da5cb5b1461095757806393bbeac01461097657806394bf804d146109a4575f80fd5b80633d8ab1e5116103225780635e2c576e116102ac57806370a082311161027c57806370a082311461087c57806371e99dc2146108a75780637ab92915146108bb5780637b103999146108da5780637ecebe001461090d575f80fd5b80635e2c576e146107bf5780635f6b88a0146107d35780636419111e146107f25780636e553f651461085d575f80fd5b80634cdad506116102f25780634cdad5061461048d5780634e84befe14610743578063501eb4fe14610762578063530a371414610781578063575bbce6146107a0575f80fd5b80633d8ab1e5146106c45780633e3382ba146106e3578063402d267d146107045780634c4602da14610723575f80fd5b8063196e8285116103a3578063313ce56711610373578063313ce567146105fa57806333e15be21461063f5780633644e5151461065e578063379e0b131461067257806338d52e0f14610691575f80fd5b8063196e828514610566578063217bb34d1461059d57806323b872dd146105bc5780632b91c5de146105db575f80fd5b8063095ea7b3116103e9578063095ea7b3146104ac5780630a28a477146104db5780630a680e18146104fa578063150b7a021461050e57806318160ddd14610551575f80fd5b806301e1d1141461042457806306fdde031461044b5780630780fd3a1461046c57806307a2d13a1461048d575f80fd5b3661042057005b5f80fd5b34801561042f575f80fd5b50610438610e24565b6040519081526020015b60405180910390f35b348015610456575f80fd5b5061045f610e6e565b6040516104429190614cb1565b348015610477575f80fd5b5061048b610486366004614cdb565b610ef9565b005b348015610498575f80fd5b506104386104a7366004614cf4565b61103f565b3480156104b7575f80fd5b506104cb6104c6366004614d1f565b611062565b6040519015158152602001610442565b3480156104e6575f80fd5b506104386104f5366004614cf4565b6110ce565b348015610505575f80fd5b5061048b6110e9565b348015610519575f80fd5b50610538610528366004614e2d565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610442565b34801561055c575f80fd5b5061043860025481565b348015610571575f80fd5b50601254610585906001600160a01b031681565b6040516001600160a01b039091168152602001610442565b3480156105a8575f80fd5b5061048b6105b7366004614e94565b611143565b3480156105c7575f80fd5b506104cb6105d6366004614eaf565b6111aa565b3480156105e6575f80fd5b506104386105f5366004614eed565b611284565b348015610605575f80fd5b5061062d7f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff9091168152602001610442565b34801561064a575f80fd5b5061048b610659366004614f39565b61134e565b348015610669575f80fd5b50610438611429565b34801561067d575f80fd5b5061048b61068c366004614f6e565b61147e565b34801561069c575f80fd5b506105857f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b3480156106cf575f80fd5b5061048b6106de366004614e94565b611723565b3480156106ee575f80fd5b506106f76117fa565b6040516104429190614fa7565b34801561070f575f80fd5b5061043861071e366004614e94565b61187b565b34801561072e575f80fd5b506007546104cb90600160d81b900460ff1681565b34801561074e575f80fd5b5061048b61075d366004615037565b611917565b34801561076d575f80fd5b5061048b61077c366004614cdb565b611a7e565b34801561078c575f80fd5b5061048b61079b366004614cf4565b611b56565b3480156107ab575f80fd5b5061048b6107ba366004615075565b611bde565b3480156107ca575f80fd5b5061048b611c38565b3480156107de575f80fd5b5061048b6107ed366004614e94565b611ca7565b3480156107fd575f80fd5b5061083961080c366004614e94565b60136020525f908152604090205460ff81169063ffffffff61010082048116916501000000000090041683565b60408051931515845263ffffffff9283166020850152911690820152606001610442565b348015610868575f80fd5b5061043861087736600461509b565b611d05565b348015610887575f80fd5b50610438610896366004614e94565b60036020525f908152604090205481565b3480156108b2575f80fd5b506106f7611d9a565b3480156108c6575f80fd5b506104386108d5366004614d1f565b611df6565b3480156108e5575f80fd5b506105857f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee4447681565b348015610918575f80fd5b50610438610927366004614e94565b60056020525f908152604090205481565b348015610943575f80fd5b5061048b6109523660046150be565b611e42565b348015610962575f80fd5b50600654610585906001600160a01b031681565b348015610981575f80fd5b506104cb610990366004614cf4565b600b6020525f908152604090205460ff1681565b3480156109af575f80fd5b506104386109be36600461509b565b611feb565b3480156109ce575f80fd5b5061045f6120ef565b3480156109e2575f80fd5b5061048b6109f1366004615100565b6120fc565b348015610a01575f80fd5b506007546104cb90600160d01b900460ff1681565b348015610a21575f80fd5b50600754610a3990600160e01b900463ffffffff1681565b60405163ffffffff9091168152602001610442565b348015610a59575f80fd5b5061048b610a68366004614f6e565b6123c2565b348015610a78575f80fd5b5061048b61251d565b348015610a8c575f80fd5b5061043861255d565b348015610aa0575f80fd5b506104cb610aaf366004614d1f565b61259a565b348015610abf575f80fd5b5061048b610ace366004615037565b6125fd565b348015610ade575f80fd5b5061048b610aed366004615075565b612682565b348015610afd575f80fd5b5061048b610b0c366004614e94565b6126ba565b348015610b1c575f80fd5b506104cb61272b565b348015610b30575f80fd5b50610438610b3f366004614cf4565b6127c9565b348015610b4f575f80fd5b50610438610b5e36600461516c565b6127e5565b348015610b6e575f80fd5b5061048b610b7d3660046151a0565b612862565b348015610b8d575f80fd5b50610438610b9c36600461516c565b612906565b348015610bac575f80fd5b506007546104cb90600160c81b900460ff1681565b348015610bcc575f80fd5b5061048b610bdb3660046151c6565b61298d565b348015610beb575f80fd5b50610438610bfa366004614e94565b612a55565b348015610c0a575f80fd5b50610438610c19366004614cf4565b612ac9565b348015610c29575f80fd5b50610438610c38366004614e94565b612ae5565b348015610c48575f80fd5b506007546104cb90600160c01b900460ff1681565b348015610c68575f80fd5b5061048b610c77366004614cdb565b612b1b565b348015610c87575f80fd5b50600754610c9b906001600160c01b031681565b6040516001600160c01b039091168152602001610442565b348015610cbe575f80fd5b5061048b610ccd366004615207565b612b76565b348015610cdd575f80fd5b50600854610585906001600160a01b031681565b348015610cfc575f80fd5b50610438610d0b366004614e94565b612db4565b348015610d1b575f80fd5b50610438610d2a366004615273565b600460209081525f928352604080842090915290825290205481565b348015610d51575f80fd5b50600f54601054610d8e916001600160401b0380821692680100000000000000008304821692600160801b9004909116906001600160a01b031684565b604080516001600160401b039586168152938516602085015291909316908201526001600160a01b039091166060820152608001610442565b348015610dd2575f80fd5b5061048b610de136600461529f565b612deb565b348015610df1575f80fd5b5061048b610e00366004614e94565b612f33565b348015610e10575f80fd5b5061048b610e1f36600461509b565b612fa8565b5f610e2d61312e565b600754600160c01b900460ff1615610e605760405162461bcd60e51b8152600401610e5790615383565b60405180910390fd5b610e695f6131e5565b905090565b5f8054610e7a906153a7565b80601f0160208091040260200160405190810160405280929190818152602001828054610ea6906153a7565b8015610ef15780601f10610ec857610100808354040283529160200191610ef1565b820191905f5260205f20905b815481529060010190602001808311610ed457829003601f168201915b505050505081565b610f01613690565b63ffffffff81165f908152600b602052604090205460ff16610f3e576040516370abe85960e01b815263ffffffff82166004820152602401610e57565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316610f71826136ba565b6001600160a01b031614610fd5577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610fa9826136ba565b60405163298473c760e11b81526001600160a01b03928316600482015291166024820152604401610e57565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff161561101a57604051630a42c0f960e41b815263ffffffff82166004820152602401610e57565b6007805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f805f61104b5f613747565b9150915061105a84838361385b565b949350505050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906110bc9086815260200190565b60405180910390a35060015b92915050565b5f805f6110da5f613747565b9150915061105a848383613867565b6110f1613690565b6110f9613873565b6007805460ff60c81b1916600160c81b179055604051600181527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c906020015b60405180910390a1565b61114b613690565b6001600160a01b0381165f81815260136020908152604091829020805468ffffffffffffffffff1916905590519182527f741bf5c2d606526029e0f199a3ddf6c7ebafa7edb2e1405174105f458195e67991015b60405180910390a150565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f198114611203576111df83826153f3565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f908152600360205260408120805485929061122a9084906153f3565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615d14833981519152906112719087815260200190565b60405180910390a3506001949350505050565b6007545f90600160c01b900460ff16156112b05760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f80806112d0878761389e565b9250925092506112e487878585858a6139f4565b604080516001600160a01b038a81168252602082018a905291810183905291955086169033907f385ba312edecbeeae57aca70f4fde3d83578697795291e74b1b4edb37d7291bf9060600160405180910390a350506007805460ff60c01b19169055509392505050565b611356613690565b5f8161139e5760098363ffffffff168154811061137557611375615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff166113dc565b600a8363ffffffff16815481106113b7576113b7615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90505f6113e882613a84565b9050801561141857604051631c7b946d60e31b815263ffffffff8316600482015260248101829052604401610e57565b611423848385613b0a565b50505050565b5f7f0000000000000000000000000000000000000000000000000000000000000001461461145957610e69613bec565b507ff55eace1f921b8f4bfee49068101fe798c0a659b45781492a38bc89657af46e190565b611486613690565b5f8082156115af57600a8463ffffffff16815481106114a7576114a7615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff16815481106114e6576114e6615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff168154811061152757611527615406565b905f5260205f209060089182820401919006600402600a8863ffffffff168154811061155557611555615406565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050506116cc565b60098463ffffffff16815481106115c8576115c8615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16915060098563ffffffff168154811061160757611607615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169050818160098763ffffffff168154811061164857611648615406565b905f5260205f20906008918282040191900660040260098863ffffffff168154811061167657611676615406565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b61172b613690565b604051636777140560e11b81526001600160a01b0382811660048301527f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee44476169063ceee280a906024015f6040518083038186803b15801561178a575f80fd5b505afa15801561179c573d5f803e3d5ffd5b505050506001600160a01b0381165f818152600e6020908152604091829020805460ff191660019081179091558251938452908301527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a910161119f565b6060600a80548060200260200160405190810160405280929190818152602001828054801561187157602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116118345790505b5050505050905090565b6007545f90600160c81b900460ff161561189657505f919050565b6007546001600160c01b03166002600160c01b031981016118ba57505f1992915050565b5f806118c66001613747565b91509150826001600160c01b031681106118e457505f949350505050565b5f6118f8826001600160c01b0386166153f3565b905061190581848461385b565b9695505050505050565b505050919050565b600754600160c01b900460ff16156119415760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b17905561195c613690565b611964613873565b61196c61312e565b6007805460ff60d81b1916600160d81b1790555f80808061198c816131e5565b90506119b7601154670de0b6b3a76400006119a791906153f3565b8290670de0b6b3a7640000613c84565b93506119d2601154670de0b6b3a76400006119a7919061541a565b60025490935091506119ee90506119e98587615568565b613cb1565b5f6119f85f6131e5565b905083811080611a0757508281115b15611a365760405163628cc47560e11b8152600481018290526024810185905260448101849052606401610e57565b6002548214611a6657600254604051632b40145960e21b8152600481019190915260248101839052604401610e57565b50506007805463ff0000ff60c01b1916905550505050565b611a86613690565b604051635159d87f60e11b815263ffffffff821660048201527f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee444766001600160a01b03169063a2b3b0fe906024015f6040518083038186803b158015611ae9575f80fd5b505afa158015611afb573d5f803e3d5ffd5b5050505063ffffffff81165f818152600d6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910161119f565b611b5e613690565b67016345785d8a0000811115611b98576040516302d2a90f60e51b81526004810182905267016345785d8a00006024820152604401610e57565b601180549082905560408051828152602081018490527fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff91015b60405180910390a15050565b611be6613690565b6007546001600160c01b039081169082161115611c16576040516334f1ec1b60e01b815260040160405180910390fd5b600780546001600160c01b0319166001600160c01b0392909216919091179055565b611c40613690565b600754600160c81b900460ff16611c6a5760405163ec7165bf60e01b815260040160405180910390fd5b6007805460ff60c81b191690556040515f81527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c90602001611139565b611caf613690565b6001600160a01b0381165f818152600e60209081526040808320805460ff191690558051938452908301919091527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a910161119f565b6007545f90600160c01b900460ff1615611d315760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790819055611d86907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29085908190819063ffffffff600160e01b90910416876139f4565b6007805460ff60c01b191690559392505050565b60606009805480602002602001604051908101604052809291908181526020018280548015611871575f918252602091829020805463ffffffff1684529082028301929091600491018084116118345790505050505050905090565b5f805f611e03858561389e565b50915091505f80611e146001613747565b9092509050611e3783611e2781876153f3565b611e31908561541a565b83613e36565b979650505050505050565b611e4a613690565b63ffffffff82165f908152600b602052604090205460ff16611e87576040516370abe85960e01b815263ffffffff83166004820152602401610e57565b826001600160a01b0316611e9a836136ba565b6001600160a01b031614611eb25782610fa9836136ba565b63ffffffff82165f908152600c6020526040902054600160a01b900460ff1615611ef757604051630a42c0f960e41b815263ffffffff83166004820152602401610e57565b6298968063ffffffff82161115611f2157604051632e3a13e960e21b815260040160405180910390fd5b60408051606080820183526001825263ffffffff85811660208085018281528784168688018181526001600160a01b038c165f818152601386528a902098518954945192518816650100000000000268ffffffff000000000019939098166101000264ffffffff00199115159190911664ffffffffff19909516949094179390931716949094179095558551948552840152928201929092527f2682afad81f7b7a2141b8d3c671b3efc09ac3dac73f06a5cd8e4714ae8864c1b91015b60405180910390a1505050565b6007545f90600160c01b900460ff16156120175760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f806120366001613747565b91509150612045858383613e42565b9250825f0361206757604051639768300560e01b815260040160405180910390fd5b6007546001600160c01b031661207d868361541a565b111561209c5760405163adea3dfd60e01b815260040160405180910390fd5b6007546120da907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600160e01b900463ffffffff16858888613e4e565b50506007805460ff60c01b1916905592915050565b60018054610e7a906153a7565b612104613690565b61210c613873565b63ffffffff83165f908152600b602052604090205460ff161561214a5760405163335894fb60e11b815263ffffffff84166004820152602401610e57565b63ffffffff83165f908152600d602052604090205460ff1661218757604051631f9db01d60e31b815263ffffffff84166004820152602401610e57565b6040516385ae5d5760e01b815263ffffffff841660048201525f90819081906001600160a01b037f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee4447616906385ae5d57906024015f60405180830381865afa1580156121f4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261221b9190810190615574565b9250925092508315158215151461224d57604051632b1d0bd360e11b815263ffffffff87166004820152602401610e57565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b0319909316931692909217178155915190919060018201906122c69082615652565b50606082015160028201906122db9082615652565b50905050811561231c57600a5460201161230b5760405163f025236d60e01b815260206004820152602401610e57565b612317600a8888613ef2565b61234e565b6009546020116123425760405163f025236d60e01b815260206004820152602401610e57565b61234e60098888613ef2565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb906123b19088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b6123ca613690565b5f816124125760098463ffffffff16815481106123e9576123e9615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612450565b600a8463ffffffff168154811061242b5761242b615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff161415806124f457506040516321a0f75360e01b815263ffffffff841660048201527f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee444766001600160a01b0316906321a0f75390602401602060405180830381865afa1580156124d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124f4919061570d565b156125125760405163d4db0b7960e01b815260040160405180910390fd5b611423848484613b0a565b612525613690565b600754600160d01b900460ff1661253d57600161253f565b5f5b60078054911515600160d01b0260ff60d01b19909216919091179055565b5f61256661312e565b600754600160c01b900460ff16156125905760405162461bcd60e51b8152600401610e5790615383565b610e6960016131e5565b335f908152600360205260408120805483919083906125ba9084906153f3565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615d14833981519152906110bc9086815260200190565b5f5b8181101561267d5761266a83838381811061261c5761261c615406565b905060200281019061262e9190615728565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506140af9050565b50806126758161576a565b9150506125ff565b505050565b61268a613690565b6007546001600160c01b039081169082161015611c16576040516334f1ec1b60e01b815260040160405180910390fd5b6126c2613690565b601054604080516001600160a01b03928316815291831660208301527f51dbb5a65bb22737861a63ec12ba6ce78a98631e9404b0567a2eaf7a06fc544d910160405180910390a1601080546001600160a01b0319166001600160a01b0392909216919091179055565b6007545f90600160d01b900460ff166127c457604051630ad85dff60e41b81523060048201527f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee444766001600160a01b03169063ad85dff090602401602060405180830381865afa1580156127a0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e69919061570d565b505f90565b5f805f6127d66001613747565b9150915061105a848383613e42565b6007545f90600160c01b900460ff16156128115760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f8061282f81613747565b9150915061283e868383613867565b925061284c868487876140d4565b50506007805460ff60c01b191690559392505050565b61286a613690565b670de0b6b3a76400006001600160401b038216111561289c57604051633d0203e560e01b815260040160405180910390fd5b600f54604080516001600160401b03928316815291831660208301527fb5cc994a260a85a42d6588668221571ae0a14f0a28f9e4817a5195262102c868910160405180910390a1600f805467ffffffffffffffff19166001600160401b0392909216919091179055565b6007545f90600160c01b900460ff16156129325760405162461bcd60e51b8152600401610e5790615383565b6007805460ff60c01b1916600160c01b1790555f8061295081613747565b9150915061295f86838361385b565b9250825f0361298157604051639768300560e01b815260040160405180910390fd5b61284c838787876140d4565b612995613690565b5f8084156129da575f6129a6610e24565b90506129c56129b786612710615782565b829061ffff166127106141aa565b92506129d66129b7866127106157a4565b9150505b6129e56002846141c8565b600880546001600160a01b0319166001600160a01b0385161790555f612a09610e24565b90508515612a4d5782811080612a1e57508181115b15612a4d5760405163628cc47560e11b8152600481018290526024810184905260448101839052606401610e57565b505050505050565b6007545f90600160c81b900460ff1615612a7057505f919050565b6007546001600160c01b03166002600160c01b03198101612a9457505f1992915050565b6002546001600160c01b038216811015612ac057612abb816001600160c01b0384166153f3565b61105a565b5f949350505050565b5f805f612ad66001613747565b9150915061105a848383613e36565b6007545f90600160c01b900460ff1615612b115760405162461bcd60e51b8152600401610e5790615383565b6110c8825f6142a6565b612b23613690565b63ffffffff81165f818152600d60209081526040808320805460ff191690558051938452908301919091527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910161119f565b42841015612bc65760405162461bcd60e51b815260206004820152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606401610e57565b5f6001612bd1611429565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e08301909152805192019190912061190160f01b6101008301526101028201929092526101228101919091526101420160408051601f1981840301815282825280516020918201205f84529083018083525260ff871690820152606081018590526080810184905260a0016020604051602081039080840390855afa158015612cd9573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811615801590612d0f5750876001600160a01b0316816001600160a01b0316145b612d4c5760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610e57565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050505050565b6007545f90600160c01b900460ff1615612de05760405162461bcd60e51b8152600401610e5790615383565b6110c88260016142a6565b336001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c81614612e3457604051633cf941a360e01b815260040160405180910390fd5b600754600160d81b900460ff16612e5e576040516304a246dd60e51b815260040160405180910390fd5b5f612e6b828401846157bf565b9050612e7681613cb1565b5f5b86811015612f2757612f177f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8878784818110612eb657612eb6615406565b905060200201358a8a85818110612ecf57612ecf615406565b90506020020135612ee0919061541a565b8c8c85818110612ef257612ef2615406565b9050602002016020810190612f079190614e94565b6001600160a01b03169190614320565b612f208161576a565b9050612e78565b50505050505050505050565b6006546001600160a01b03163314612f5d5760405162461bcd60e51b8152600401610e5790615803565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a350565b6006546001600160a01b03163314612fd25760405162461bcd60e51b8152600401610e5790615803565b612fdc82826141c8565b601260ff16816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561301d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130419190615829565b60ff161415806130c25750306001600160a01b0316816001600160a01b031663d4b839926040518163ffffffff1660e01b8152600401602060405180830381865afa158015613092573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130b69190615844565b6001600160a01b031614155b156130e05760405163229e78bb60e01b815260040160405180910390fd5b601280546001600160a01b0319166001600160a01b0383169081179091556040519081527f51b1b17228af00bd72d43ecec4334e09b3584633abf6ef363a9fde05dfa73f8890602001611bd2565b600754600160d01b900460ff166131e357604051630ad85dff60e41b81523060048201527f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee444766001600160a01b03169063ad85dff090602401602060405180830381865afa1580156131a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131c5919061570d565b156131e357604051630f301f8f60e41b815260040160405180910390fd5b565b6009545f9081816001600160401b0381111561320357613203614d49565b60405190808252806020026020018201604052801561322c578160200160208202803683370190505b5090505f826001600160401b0381111561324857613248614d49565b604051908082528060200260200182016040528015613271578160200160208202803683370190505b50905084156133d8575f5b8381101561333d575f6009828154811061329857613298615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506132c781614394565b8383815181106132d9576132d9615406565b60200260200101818152505f036132f0575061332d565b6132f9816136ba565b84838151811061330b5761330b615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6133368161576a565b905061327c565b5060085460405163b333a17560e01b81526001600160a01b039091169063b333a1759061339290859085907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906004016158cf565b602060405180830381865afa1580156133ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133d1919061590c565b935061190f565b600a545f816001600160401b038111156133f4576133f4614d49565b60405190808252806020026020018201604052801561341d578160200160208202803683370190505b5090505f826001600160401b0381111561343957613439614d49565b604051908082528060200260200182016040528015613462578160200160208202803683370190505b5090505f5b86811015613528575f6009828154811061348357613483615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506134b281613a84565b8683815181106134c4576134c4615406565b60200260200101818152505f036134db5750613518565b6134e4816136ba565b8783815181106134f6576134f6615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6135218161576a565b9050613467565b505f5b838110156135ec575f600a828154811061354757613547615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061357681613a84565b83838151811061358857613588615406565b60200260200101818152505f0361359f57506135dc565b6135a8816136ba565b8483815181106135ba576135ba615406565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6135e58161576a565b905061352b565b50600854604051637563738b60e11b81526001600160a01b039091169063eac6e716906136459088908890879087907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401615923565b602060405180830381865afa158015613660573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613684919061590c565b98975050505050505050565b6006546001600160a01b031633146131e35760405162461bcd60e51b8152600401610e5790615803565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf916137019160010190600401615a03565b602060405180830381865afa15801561371c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137409190615844565b9392505050565b6012545f9081906001600160a01b0316801561383c575f805f836001600160a01b031663c36af4606040518163ffffffff1660e01b8152600401606060405180830381865afa15801561379c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137c09190615a15565b92509250925080156137e55760405163229e78bb60e01b815260040160405180910390fd5b5f8715613802578284116137f957826137fb565b835b9050613814565b82841061380f5782613811565b835b90505b6002549550613831866138296012600a615b20565b8391906141aa565b965050505050613855565b60405163229e78bb60e01b815260040160405180910390fd5b50915091565b5f61105a8484846141aa565b5f61105a848385613c84565b600754600160c81b900460ff16156131e3576040516337a5332d60e11b815260040160405180910390fd5b6001600160a01b0382165f9081526013602090815260408083208151606081018352905460ff8116151580835263ffffffff6101008304811695840195909552650100000000009091049093169181019190915282918291906139145760405163217feaeb60e01b815260040160405180910390fd5b60085460405163151d4a5960e31b81526001600160a01b038881166004830152602482018890527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811660448301529091169063a8ea52c890606401602060405180830381865afa15801561398b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139af919061590c565b93506139e381604001516305f5e1006139c89190615b2e565b63ffffffff166305f5e100866141aa9092919063ffffffff16565b925080602001519150509250925092565b5f805f613a016001613747565b9092509050613a1486611e27818a6153f3565b9250825f03613a365760405163426f153760e11b815260040160405180910390fd5b6007546001600160c01b0316613a4c848361541a565b1115613a6b5760405163adea3dfd60e01b815260040160405180910390fd5b613a7889868a8688613e4e565b50509695505050505050565b63ffffffff81165f908152600c602052604080822080549151637841536560e01b81526001600160a01b03909216918291637841536591613acb9160010190600401615a03565b602060405180830381865afa158015613ae6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613740919061590c565b60075463ffffffff600160e01b909104811690831603613b3d576040516319ded73160e21b815260040160405180910390fd5b8015613b5357613b4e600a84614449565b613b5e565b613b5e600984614449565b63ffffffff82165f908152600b60209081526040808320805460ff19169055600c909152812080546001600160a81b031916815590613ba06001830182614c12565b613bad600283015f614c12565b50506040805163ffffffff8085168252851660208201527fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd519101611fde565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051613c1c9190615b4b565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b828202811515841585830485141716613c9b575f80fd5b6001826001830304018115150290509392505050565b5f5b8151811015613e32575f828281518110613ccf57613ccf615406565b602090810291909101810151516001600160a01b0381165f908152600e90925260409091205490915060ff16613d2357604051635df6b61760e11b81526001600160a01b0382166004820152602401610e57565b5f5b838381518110613d3757613d37615406565b60200260200101516020015151811015613e1f57613d9d848481518110613d6057613d60615406565b6020026020010151602001518281518110613d7d57613d7d615406565b6020026020010151836001600160a01b03166140af90919063ffffffff16565b507f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf48382858581518110613dd257613dd2615406565b6020026020010151602001518381518110613def57613def615406565b6020026020010151604051613e05929190615bbd565b60405180910390a180613e178161576a565b915050613d25565b505080613e2b9061576a565b9050613cb3565b5050565b5f61105a8483856141aa565b5f61105a848484613c84565b613e7a7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2848484614588565b613e8f6001600160a01b038616333086614598565b613e998183614617565b60408051848152602081018490526001600160a01b0383169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a3613eeb8484848461466e565b5050505050565b8254801561406f578380613f076001846153f3565b81548110613f1757613f17615406565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a9092049093160217905590613f7890836153f3565b90505b8363ffffffff1681111561401f5784613f956001836153f3565b81548110613fa557613fa5615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16858281548110613fdb57613fdb615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061401790615be0565b915050613f7b565b5081848463ffffffff168154811061403957614039615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550611423565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b60606137408383604051806060016040528060278152602001615ced60279139614678565b6140e084848484614590565b336001600160a01b0382161461414b576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146141495761412584826153f3565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b61415581846146e2565b60408051858152602081018590526001600160a01b03808416929085169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a46114238483614741565b8282028115158415858304851417166141c1575f80fd5b0492915050565b815f036141e857604051632db38d0560e01b815260040160405180910390fd5b806001600160a01b03167f000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee444766001600160a01b031663b93f9b0a846040518263ffffffff1660e01b815260040161424091815260200190565b602060405180830381865afa15801561425b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061427f9190615844565b6001600160a01b031614613e3257604051634ee204d760e01b815260040160405180910390fd5b5f6142af61312e565b5f806142ba5f613747565b6001600160a01b0387165f90815260036020526040812054929450909250906142e490848461385b565b90505f6142f160016131e5565b9050808211156143015780614303565b815b9450851561431657611e37858585613e36565b5050505092915050565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806114235760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610e57565b63ffffffff81165f908152600c6020526040812054600160a01b900460ff16156143bf57505f919050565b63ffffffff82165f908152600c60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d29161440a91600182019160020190600401615bf5565b602060405180830381865afa158015614425573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110c8919061590c565b815463ffffffff821681116144965760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610e57565b63ffffffff82165b6144a96001836153f3565b81101561454657836144bc82600161541a565b815481106144cc576144cc615406565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1684828154811061450257614502615406565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061453e9061576a565b91505061449e565b508280548061455757614557615c22565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b614590613873565b61142361312e565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080613eeb5760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610e57565b8060025f828254614628919061541a565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615d1483398151915291015b60405180910390a35050565b6114238484614a96565b60605f80856001600160a01b0316856040516146949190615c36565b5f60405180830381855af49150503d805f81146146cc576040519150601f19603f3d011682016040523d82523d5f602084013e6146d1565b606091505b509150915061190586838387614b22565b6001600160a01b0382165f90815260036020526040812080548392906147099084906153f3565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615d1483398151915290602001614662565b61476860405180608001604052805f81526020015f81526020015f81526020015f81525090565b600854604051630226614760e01b81526001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28116600483015290911690630226614790602401602060405180830381865afa1580156147d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906147f4919061590c565b60408201526148247f0000000000000000000000000000000000000000000000000000000000000012600a615b20565b60608201526009545f5b81811015614a73575f6009828154811061484a5761484a615406565b5f9182526020822060088204015460079091166004026101000a900463ffffffff16915061487782614394565b9050805f03614887575050614a63565b5f614891836136ba565b600854604051630226614760e01b81526001600160a01b038084166004830152929350911690630226614790602401602060405180830381865afa1580156148db573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906148ff919061590c565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614943573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906149679190615829565b61497290600a615b20565b6020870181905286515f91829161499c9161499587670de0b6b3a7640000615c51565b91906141aa565b90506149bb88606001518960400151836141aa9092919063ffffffff16565b91506149cf670de0b6b3a764000083615c68565b9150505f89821115614a32575f6149fd89604001518a606001518d670de0b6b3a76400006149959190615c51565b60208a01518a51919250614a13918391906141aa565b9150614a27670de0b6b3a764000083615c68565b91505f9a5050614a41565b5082614a3e828b6153f3565b99505b614a4c85828b614b9a565b895f03614a5d575050505050614a73565b50505050505b614a6c8161576a565b905061482e565b5083156114235760405163cc5ea39b60e01b815260048101859052602401610e57565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b0390921691611423916369445c3160e01b91614ae0918691600182019160020190602401615c87565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b038316906140af565b60608315614b905782515f03614b89576001600160a01b0385163b614b895760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610e57565b508161105a565b61105a8383614be8565b63ffffffff83165f908152600c602052604090819020805491516001600160a01b0390921691613eeb9163c9111bd760e01b91614ae091879187916001810191600290910190602401615cb1565b815115614bf85781518083602001fd5b8060405162461bcd60e51b8152600401610e579190614cb1565b508054614c1e906153a7565b5f825580601f10614c2d575050565b601f0160209004905f5260205f2090810190614c499190614c4c565b50565b5b80821115614c60575f8155600101614c4d565b5090565b5f5b83811015614c7e578181015183820152602001614c66565b50505f910152565b5f8151808452614c9d816020860160208601614c64565b601f01601f19169290920160200192915050565b602081525f6137406020830184614c86565b803563ffffffff81168114614cd6575f80fd5b919050565b5f60208284031215614ceb575f80fd5b61374082614cc3565b5f60208284031215614d04575f80fd5b5035919050565b6001600160a01b0381168114614c49575f80fd5b5f8060408385031215614d30575f80fd5b8235614d3b81614d0b565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b0381118282101715614d7f57614d7f614d49565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614dad57614dad614d49565b604052919050565b5f6001600160401b03821115614dcd57614dcd614d49565b50601f01601f191660200190565b5f82601f830112614dea575f80fd5b8135614dfd614df882614db5565b614d85565b818152846020838601011115614e11575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215614e40575f80fd5b8435614e4b81614d0b565b93506020850135614e5b81614d0b565b92506040850135915060608501356001600160401b03811115614e7c575f80fd5b614e8887828801614ddb565b91505092959194509250565b5f60208284031215614ea4575f80fd5b813561374081614d0b565b5f805f60608486031215614ec1575f80fd5b8335614ecc81614d0b565b92506020840135614edc81614d0b565b929592945050506040919091013590565b5f805f60608486031215614eff575f80fd5b8335614f0a81614d0b565b9250602084013591506040840135614f2181614d0b565b809150509250925092565b8015158114614c49575f80fd5b5f8060408385031215614f4a575f80fd5b614f5383614cc3565b91506020830135614f6381614f2c565b809150509250929050565b5f805f60608486031215614f80575f80fd5b614f8984614cc3565b9250614f9760208501614cc3565b91506040840135614f2181614f2c565b602080825282518282018190525f9190848201906040850190845b81811015614fe457835163ffffffff1683529284019291840191600101614fc2565b50909695505050505050565b5f8083601f840112615000575f80fd5b5081356001600160401b03811115615016575f80fd5b6020830191508360208260051b8501011115615030575f80fd5b9250929050565b5f8060208385031215615048575f80fd5b82356001600160401b0381111561505d575f80fd5b61506985828601614ff0565b90969095509350505050565b5f60208284031215615085575f80fd5b81356001600160c01b0381168114613740575f80fd5b5f80604083850312156150ac575f80fd5b823591506020830135614f6381614d0b565b5f805f606084860312156150d0575f80fd5b83356150db81614d0b565b92506150e960208501614cc3565b91506150f760408501614cc3565b90509250925092565b5f805f8060808587031215615113575f80fd5b61511c85614cc3565b935061512a60208601614cc3565b925060408501356001600160401b03811115615144575f80fd5b61515087828801614ddb565b925050606085013561516181614f2c565b939692955090935050565b5f805f6060848603121561517e575f80fd5b83359250602084013561519081614d0b565b91506040840135614f2181614d0b565b5f602082840312156151b0575f80fd5b81356001600160401b0381168114613740575f80fd5b5f805f606084860312156151d8575f80fd5b83356151e381614f2c565b9250602084013561ffff81168114615190575f80fd5b60ff81168114614c49575f80fd5b5f805f805f805f60e0888a03121561521d575f80fd5b873561522881614d0b565b9650602088013561523881614d0b565b955060408801359450606088013593506080880135615256816151f9565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615284575f80fd5b823561528f81614d0b565b91506020830135614f6381614d0b565b5f805f805f805f806080898b0312156152b6575f80fd5b88356001600160401b03808211156152cc575f80fd5b6152d88c838d01614ff0565b909a50985060208b01359150808211156152f0575f80fd5b6152fc8c838d01614ff0565b909850965060408b0135915080821115615314575f80fd5b6153208c838d01614ff0565b909650945060608b0135915080821115615338575f80fd5b818b0191508b601f83011261534b575f80fd5b813581811115615359575f80fd5b8c602082850101111561536a575f80fd5b6020830194508093505050509295985092959890939650565b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b600181811c908216806153bb57607f821691505b6020821081036153d957634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b818103818111156110c8576110c86153df565b634e487b7160e01b5f52603260045260245ffd5b808201808211156110c8576110c86153df565b5f6001600160401b0382111561544557615445614d49565b5060051b60200190565b5f61545c614df88461542d565b8381529050602080820190600585901b84018681111561547a575f80fd5b845b8181101561555d576001600160401b038082351115615499575f80fd5b813587016040818b0312156154ac575f80fd5b6154b4614d5d565b6154be8235614d0b565b8135815285820135838111156154d2575f80fd5b8083019250508a601f8301126154e6575f80fd5b81356154f4614df88261542d565b81815260059190911b8301870190878101908d831115615512575f80fd5b8885015b8381101561554757868135111561552b575f80fd5b61553a8f8b8335890101614ddb565b8352918901918901615516565b508389015250508652505092820192820161547c565b505050509392505050565b5f61374036848461544f565b5f805f60608486031215615586575f80fd5b835161559181614d0b565b60208501519093506155a281614f2c565b60408501519092506001600160401b038111156155bd575f80fd5b8401601f810186136155cd575f80fd5b80516155db614df882614db5565b8181528760208385010111156155ef575f80fd5b615600826020830160208601614c64565b8093505050509250925092565b601f82111561267d575f81815260208120601f850160051c810160208610156156335750805b601f850160051c820191505b81811015612a4d5782815560010161563f565b81516001600160401b0381111561566b5761566b614d49565b61567f8161567984546153a7565b8461560d565b602080601f8311600181146156b2575f841561569b5750858301515b5f19600386901b1c1916600185901b178555612a4d565b5f85815260208120601f198616915b828110156156e0578886015182559484019460019091019084016156c1565b50858210156156fd57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f6020828403121561571d575f80fd5b815161374081614f2c565b5f808335601e1984360301811261573d575f80fd5b8301803591506001600160401b03821115615756575f80fd5b602001915036819003821315615030575f80fd5b5f6001820161577b5761577b6153df565b5060010190565b61ffff82811682821603908082111561579d5761579d6153df565b5092915050565b61ffff81811683821601908082111561579d5761579d6153df565b5f602082840312156157cf575f80fd5b81356001600160401b038111156157e4575f80fd5b8201601f810184136157f4575f80fd5b61105a8482356020840161544f565b6020808252600c908201526b15539055551213d49256915160a21b604082015260600190565b5f60208284031215615839575f80fd5b8151613740816151f9565b5f60208284031215615854575f80fd5b815161374081614d0b565b5f8151808452602080850194508084015f5b838110156158965781516001600160a01b031687529582019590820190600101615871565b509495945050505050565b5f8151808452602080850194508084015f5b83811015615896578151875295820195908201906001016158b3565b606081525f6158e1606083018661585f565b82810360208401526158f381866158a1565b91505060018060a01b0383166040830152949350505050565b5f6020828403121561591c575f80fd5b5051919050565b60a081525f61593560a083018861585f565b828103602084015261594781886158a1565b9050828103604084015261595b818761585f565b9050828103606084015261596f81866158a1565b91505060018060a01b03831660808301529695505050505050565b5f8154615996816153a7565b8085526020600183811680156159b357600181146159cd576159f8565b60ff1985168884015283151560051b8801830195506159f8565b865f52825f205f5b858110156159f05781548a82018601529083019084016159d5565b890184019650505b505050505092915050565b602081525f613740602083018461598a565b5f805f60608486031215615a27575f80fd5b83519250602084015191506040840151614f2181614f2c565b600181815b80851115615a7a57815f1904821115615a6057615a606153df565b80851615615a6d57918102915b93841c9390800290615a45565b509250929050565b5f82615a90575060016110c8565b81615a9c57505f6110c8565b8160018114615ab25760028114615abc57615ad8565b60019150506110c8565b60ff841115615acd57615acd6153df565b50506001821b6110c8565b5060208310610133831016604e8410600b8410161715615afb575081810a6110c8565b615b058383615a40565b805f1904821115615b1857615b186153df565b029392505050565b5f61374060ff841683615a82565b63ffffffff82811682821603908082111561579d5761579d6153df565b5f808354615b58816153a7565b60018281168015615b705760018114615b8557615bb1565b60ff1984168752821515830287019450615bb1565b875f526020805f205f5b85811015615ba85781548a820152908401908201615b8f565b50505082870194505b50929695505050505050565b6001600160a01b03831681526040602082018190525f9061105a90830184614c86565b5f81615bee57615bee6153df565b505f190190565b604081525f615c07604083018561598a565b8281036020840152615c19818561598a565b95945050505050565b634e487b7160e01b5f52603160045260245ffd5b5f8251615c47818460208701614c64565b9190910192915050565b80820281158282048414176110c8576110c86153df565b5f82615c8257634e487b7160e01b5f52601260045260245ffd5b500490565b838152606060208201525f615c9f606083018561598a565b8281036040840152611905818561598a565b8481526001600160a01b03841660208201526080604082018190525f90615cda9083018561598a565b8281036060840152611e37818561598a56fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122038a4640d22c096bd2f0ec8bbdbbdf889726baa52b404f752396a365216b03c2964736f6c63430008150033

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

000000000000000000000000eef7b7205caf2bcd71437d9acde3874c3388c138000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee44476000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000005af3107a40000000000000000000000000000000000000000000000000000b1a2bc2ec5000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000000000000000000000000000000000000000000a547572626f2045455448000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009547572626f45455448000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _owner (address): 0xeeF7b7205CAF2Bcd71437D9acDE3874C3388c138
Arg [1] : _registry (address): 0xEED68C267E9313a6ED6ee08de08c9F68dee44476
Arg [2] : _asset (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [3] : _name (string): Turbo EETH
Arg [4] : _symbol (string): TurboEETH
Arg [5] : _holdingPosition (uint32): 1
Arg [6] : _holdingPositionConfig (bytes): 0x0000000000000000000000000000000000000000000000000000000000000000
Arg [7] : _initialDeposit (uint256): 100000000000000
Arg [8] : _strategistPlatformCut (uint64): 800000000000000000
Arg [9] : _shareSupplyCap (uint192): 6277101735386680763835789423207666416102355444464034512895
Arg [10] : _balancerVault (address): 0xBA12222222228d8Ba445958a75a0704d566BF2C8

-----Encoded View---------------
17 Constructor Arguments found :
Arg [0] : 000000000000000000000000eef7b7205caf2bcd71437d9acde3874c3388c138
Arg [1] : 000000000000000000000000eed68c267e9313a6ed6ee08de08c9f68dee44476
Arg [2] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000160
Arg [4] : 00000000000000000000000000000000000000000000000000000000000001a0
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [6] : 00000000000000000000000000000000000000000000000000000000000001e0
Arg [7] : 00000000000000000000000000000000000000000000000000005af3107a4000
Arg [8] : 0000000000000000000000000000000000000000000000000b1a2bc2ec500000
Arg [9] : 0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff
Arg [10] : 000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8
Arg [11] : 000000000000000000000000000000000000000000000000000000000000000a
Arg [12] : 547572626f204545544800000000000000000000000000000000000000000000
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000009
Arg [14] : 547572626f454554480000000000000000000000000000000000000000000000
Arg [15] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [16] : 0000000000000000000000000000000000000000000000000000000000000000


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.