ETH Price: $3,064.63 (+5.83%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Advanced mode:
Parent Transaction Hash Method Block
From
To
View All Internal Transactions
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

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

Contract Source Code Verified (Exact Match)

Contract Name:
YieldOptimizerFacet

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
File 1 of 28 : YieldOptimizerFacet.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IMetaMorpho} from "../interfaces/morpho/IMetaMorpho.sol";
import {IMorpho, Id, MarketParams, Market} from "../interfaces/morpho/IMorpho.sol";
import {IIrm} from "../interfaces/morpho/IIrm.sol";
import {MarketParamsLib} from "../interfaces/morpho/MarketParamsLib.sol";
import {MathLib, WAD} from "../interfaces/morpho/MathLib.sol";
import {UtilsLib} from "../interfaces/morpho/UtilsLib.sol";
import {SharesMathLib} from "../interfaces/morpho/SharesMathLib.sol";
import {IMerklDistributor} from "../interfaces/morpho/IMerklDistributor.sol";
import {IComet} from "../interfaces/compound/IComet.sol";
import {IClaimable} from "../interfaces/compound/IClaimable.sol";
import {IPool} from "../interfaces/aave/IPool.sol";

import {LibDiamond} from "../libraries/LibDiamond.sol";
import {LibYieldOptimizer} from "../libraries/LibYieldOptimizer.sol";

contract YieldOptimizerFacet {
    using Address for address;
    using SafeERC20 for IERC20;
    using Math for uint256;
    using MathLib for uint256;
    using MathLib for uint128;
    using UtilsLib for uint256;
    using SharesMathLib for uint256;
    using MarketParamsLib for MarketParams;

    /**
     * @notice Supported DeFi protocols for yield optimization
     * @dev Each protocol represents a different lending/borrowing platform
     */
    enum Protocol {
        MORPHO,
        COMET,
        AAVE,
        SPARK
    }

    /**
     * @notice Emitted when a module function is successfully executed
     * @param moduleId Unique identifier of the module
     * @param facet Address of the facet contract handling the call
     * @param selector Function selector being executed
     * @param data Arbitrary encoded data for off-chain indexing
     */
    event ModuleEvent(bytes32 indexed moduleId, address indexed facet, bytes4 indexed selector, bytes data);

    /**
     * @notice Thrown when caller is neither an authorized keeper nor the vault owner
     */
    error OnlyKeeperOrOwner();

    /**
     * @notice Thrown when attempting to optimize before the cooldown period expires
     * @param current The current block timestamp
     * @param required The minimum timestamp required to proceed
     */
    error CooldownNotExpired(uint256 current, uint256 required);

    /**
     * @notice Thrown when the protocol lacks sufficient liquidity for the requested operation
     * @param liquidity The available liquidity in the protocol
     * @param required The required liquidity for the operation
     */
    error InsufficientLiquidity(uint256 liquidity, uint256 required);

    /**
     * @notice Thrown when attempting to withdraw from a protocol with no position
     */
    error NoPosition();

    /**
     * @notice Thrown when function receives zero amount, mismatched array lengths, or invalid protocol
     */
    error InvalidParameters();

    /**
     * @notice Thrown when attempting to interact with a protocol not in the Protocol enum
     */
    error UnsupportedProtocol();

    /**
     * @notice Thrown when a withdrawal operation from a protocol reverts or returns false
     */
    error WithdrawFailed();

    /**
     * @notice Thrown when the vault lacks sufficient balance for the requested operation
     */
    error InsufficientBalance();

    /**
     * @notice Thrown when interest accrual on a lending protocol fails
     */
    error AccrueInterestFailed();

    /**
     * @notice Thrown when attempting to claim rewards but the claimable amount is zero
     */
    error NoRewardsToClaim();

    bytes32 public constant MODULE_ID = keccak256("smartsafe.facet.yieldoptimizer");

    address public constant BASE_TOKEN = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;

    // Morpho
    address public constant META_MORPHO = 0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB;
    address public constant MERKL_DISTRIBUTOR = 0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae;
    // Compound
    address public constant COMET = 0xc3d688B66703497DAA19211EEdff47f25384cdc3;
    address public constant COMET_REWARDS = 0x1B0e765F6224C21223AeA2af16c1C46E38885a40;
    // Aave
    address public constant AAVE_POOL = 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2;
    address public constant AAVE_BASE_TOKEN = 0x98C23E9d8f34FEFb1B7BD6a91B7FF122F4e16F5c;
    // Spark
    address public constant SPARK_POOL = 0xC13e21B648A5Ee794902342038FF3aDAB66BE987;
    address public constant SPARK_BASE_TOKEN = 0x377C3bd93f2a2984E1E7bE6A5C22c525eD4A4815;

    uint128 internal constant DEFAULT_MIN_LIQUIDITY = 50_000_000e6; // 50M USDC (6 decimals)
    uint16 internal constant DEFAULT_MIN_BPS = 200; // 2%
    uint64 internal constant DEFAULT_COOLDOWN = 4 hours;

    modifier onlyOwner() {
        LibDiamond.enforceIsContractOwner();
        _;
    }

    modifier onlyKeeperOrOwner() {
        address owner_ = LibDiamond.contractOwner();
        if (msg.sender != owner_ && !LibYieldOptimizer.isKeeper(msg.sender)) {
            revert OnlyKeeperOrOwner();
        }
        _;
    }

    function yieldOptimizer_setConfig(uint128 minLiquidityThreshold, uint16 minBpsThreshold, uint64 cooldown)
        external
        onlyOwner
    {
        LibYieldOptimizer.setConfig(
            LibYieldOptimizer.Config({
                minLiquidityThreshold: minLiquidityThreshold,
                minBpsThreshold: minBpsThreshold,
                cooldown: cooldown
            })
        );

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_setConfig.selector);
        emit ModuleEvent(
            MODULE_ID,
            facet,
            this.yieldOptimizer_setConfig.selector,
            abi.encode(minLiquidityThreshold, minBpsThreshold, cooldown)
        );
    }

    function yieldOptimizer_setKeeper(address keeper, bool allowed) external onlyOwner {
        if (keeper == address(0)) {
            revert InvalidParameters();
        }

        bool changed = LibYieldOptimizer.setKeeper(keeper, allowed);

        if (changed) {
            address facet = LibDiamond.facetAddress(this.yieldOptimizer_setKeeper.selector);
            emit ModuleEvent(MODULE_ID, facet, this.yieldOptimizer_setKeeper.selector, abi.encode(keeper, allowed));
        }
    }

    function yieldOptimizer_deposit(Protocol protocol, uint256 amount) external onlyKeeperOrOwner {
        if (amount == 0) revert InvalidParameters();

        _enforceLiquidity(protocol);

        uint256 balance = IERC20(BASE_TOKEN).balanceOf(address(this));
        if (balance < amount) revert InsufficientBalance();

        _depositProtocol(protocol, amount);

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_deposit.selector);
        emit ModuleEvent(MODULE_ID, facet, this.yieldOptimizer_deposit.selector, abi.encode(protocol, amount));
    }

    function yieldOptimizer_withdraw(Protocol protocol) external onlyKeeperOrOwner returns (uint256 withdrawn) {
        withdrawn = _withdrawProtocol(protocol);

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_withdraw.selector);
        emit ModuleEvent(MODULE_ID, facet, this.yieldOptimizer_withdraw.selector, abi.encode(protocol, withdrawn));
    }

    function yieldOptimizer_optimizeYield(Protocol from, Protocol to) external onlyKeeperOrOwner {
        if (from == to) revert InvalidParameters();

        _enforceCooldown();

        uint256 withdrawn = _withdrawProtocol(from);
        _depositProtocol(to, withdrawn);

        LibYieldOptimizer.setLastExecuted(block.timestamp);

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_optimizeYield.selector);
        emit ModuleEvent(MODULE_ID, facet, this.yieldOptimizer_optimizeYield.selector, abi.encode(from, to, withdrawn));
    }

    function yieldOptimizer_claimComp() external onlyOwner {
        IClaimable.RewardOwed memory rewardOwed = IClaimable(COMET_REWARDS).getRewardOwed(COMET, address(this));
        if (rewardOwed.owed == 0) {
            revert NoRewardsToClaim();
        }
        IClaimable(COMET_REWARDS).claim(COMET, address(this), true);

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_claimComp.selector);
        emit ModuleEvent(MODULE_ID, facet, this.yieldOptimizer_claimComp.selector, abi.encode(rewardOwed.owed));
    }

    function yieldOptimizer_claimMorpho(
        address[] calldata accounts,
        address[] calldata rewards,
        uint256[] calldata claimables,
        bytes32[][] calldata proofs
    ) external onlyOwner {
        IMerklDistributor(MERKL_DISTRIBUTOR).claim(accounts, rewards, claimables, proofs);

        address facet = LibDiamond.facetAddress(this.yieldOptimizer_claimMorpho.selector);
        emit ModuleEvent(
            MODULE_ID, facet, this.yieldOptimizer_claimMorpho.selector, abi.encode(accounts, rewards, claimables)
        );
    }

    function yieldOptimizer_getOwedComp() external returns (IClaimable.RewardOwed memory) {
        IClaimable.RewardOwed memory rewardOwed = IClaimable(COMET_REWARDS).getRewardOwed(COMET, address(this));
        return rewardOwed;
    }

    function yieldOptimizer_getConfig() external view returns (LibYieldOptimizer.Config memory) {
        return _getConfig();
    }

    function yieldOptimizer_getLiquidity(Protocol protocol) external view returns (uint256 liquidity) {
        return _computeLiquidity(protocol);
    }

    function yieldOptimizer_getLiquidities() external view returns (uint256[] memory liquidities) {
        liquidities = new uint256[](4);
        for (uint256 i; i < 4; i++) {
            liquidities[i] = _computeLiquidity(Protocol(i));
        }
    }

    function yieldOptimizer_getPosition(Protocol protocol) external view returns (uint256 position) {
        return _computePosition(protocol);
    }

    function yieldOptimizer_getPositions() external view returns (uint256[] memory positions) {
        positions = new uint256[](4);
        for (uint256 i; i < 4; i++) {
            positions[i] = _computePosition(Protocol(i));
        }
    }

    function yieldOptimizer_isKeeper(address account) external view returns (bool) {
        return LibYieldOptimizer.isKeeper(account);
    }

    function yieldOptimizer_getKeeperCount() external view returns (uint256) {
        return LibYieldOptimizer.getKeeperCount();
    }

    function yieldOptimizer_lastOptimizationTimestamp() external view returns (uint256) {
        return LibYieldOptimizer.getLastExecuted();
    }

    function yieldOptimizer_canExecuteOptimization() external view returns (bool) {
        return _timeUntilNextOptimization() == 0;
    }

    function yieldOptimizer_getTimeUntilNextOptimization() external view returns (uint256) {
        return _timeUntilNextOptimization();
    }

    function _enforceLiquidity(Protocol protocol) internal view {
        LibYieldOptimizer.Config memory config = _getConfig();
        uint256 liquidity = _computeLiquidity(protocol);
        if (liquidity < config.minLiquidityThreshold) {
            revert InsufficientLiquidity(liquidity, config.minLiquidityThreshold);
        }
    }

    function _enforceCooldown() internal view {
        uint256 remaining = _timeUntilNextOptimization();
        if (remaining != 0) {
            uint256 required = block.timestamp + remaining;
            revert CooldownNotExpired(block.timestamp, required);
        }
    }

    function _timeUntilNextOptimization() internal view returns (uint256) {
        uint256 last = LibYieldOptimizer.getLastExecuted();
        if (last == 0) {
            return 0;
        }

        uint64 cooldown = _getConfig().cooldown;
        uint256 nextAllowed = last + cooldown;
        if (block.timestamp >= nextAllowed) {
            return 0;
        }
        return nextAllowed - block.timestamp;
    }

    function _getConfig() internal view returns (LibYieldOptimizer.Config memory config) {
        config = LibYieldOptimizer.getConfig();
        if (config.minLiquidityThreshold == 0) {
            config.minLiquidityThreshold = DEFAULT_MIN_LIQUIDITY;
        }
        if (config.minBpsThreshold == 0) {
            config.minBpsThreshold = DEFAULT_MIN_BPS;
        }
        if (config.cooldown == 0) {
            config.cooldown = DEFAULT_COOLDOWN;
        }
    }

    function _computeLiquidity(Protocol protocol) internal view returns (uint256 liquidity) {
        if (protocol == Protocol.MORPHO) {
            IMetaMorpho metaMorpho = IMetaMorpho(META_MORPHO);
            IMorpho morpho = metaMorpho.MORPHO();
            uint256 length = metaMorpho.withdrawQueueLength();
            uint256 availableLiquidity;

            for (uint256 index; index < length; index++) {
                Id id = metaMorpho.withdrawQueue(index);
                MarketParams memory marketParams = morpho.idToMarketParams(id);
                (uint256 totalSupplyAssets,, uint256 totalBorrowAssets,) = _expectedMarketBalances(morpho, marketParams);
                availableLiquidity += totalSupplyAssets - totalBorrowAssets;
            }
            liquidity = Math.min(availableLiquidity, IERC20(BASE_TOKEN).balanceOf(address(morpho)));
        } else if (protocol == Protocol.COMET) {
            liquidity = IERC20(BASE_TOKEN).balanceOf(COMET);
        } else if (protocol == Protocol.AAVE) {
            liquidity = IERC20(BASE_TOKEN).balanceOf(AAVE_BASE_TOKEN);
        } else if (protocol == Protocol.SPARK) {
            liquidity = IERC20(BASE_TOKEN).balanceOf(SPARK_BASE_TOKEN);
        } else {
            revert UnsupportedProtocol();
        }
    }

    function _expectedMarketBalances(IMorpho morpho, MarketParams memory marketParams)
        internal
        view
        returns (uint256, uint256, uint256, uint256)
    {
        Id id = marketParams.id();
        Market memory market = morpho.market(id);

        uint256 elapsed = block.timestamp - market.lastUpdate;

        // Skipped if elapsed == 0 or totalBorrowAssets == 0 because interest would be null, or if irm == address(0).
        if (elapsed != 0 && market.totalBorrowAssets != 0 && marketParams.irm != address(0)) {
            uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(marketParams, market);
            uint256 interest = market.totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
            market.totalBorrowAssets += interest.toUint128();
            market.totalSupplyAssets += interest.toUint128();

            if (market.fee != 0) {
                uint256 feeAmount = interest.wMulDown(market.fee);
                // The fee amount is subtracted from the total supply in this calculation to compensate for the fact
                // that total supply is already updated.
                uint256 feeShares =
                    feeAmount.toSharesDown(market.totalSupplyAssets - feeAmount, market.totalSupplyShares);
                market.totalSupplyShares += feeShares.toUint128();
            }
        }

        return (market.totalSupplyAssets, market.totalSupplyShares, market.totalBorrowAssets, market.totalBorrowShares);
    }

    function _computePosition(Protocol protocol) internal view returns (uint256 position) {
        if (protocol == Protocol.MORPHO) {
            (position,,) = _maxWithdraw(address(this));
        } else if (protocol == Protocol.COMET) {
            position = IComet(COMET).balanceOf(address(this));
        } else if (protocol == Protocol.AAVE) {
            position = IERC20(AAVE_BASE_TOKEN).balanceOf(address(this));
        } else if (protocol == Protocol.SPARK) {
            position = IERC20(SPARK_BASE_TOKEN).balanceOf(address(this));
        } else {
            revert UnsupportedProtocol();
        }
    }

    function _maxWithdraw(address owner)
        internal
        view
        returns (uint256 assets, uint256 newTotalSupply, uint256 newTotalAssets)
    {
        uint256 feeShares;
        (feeShares, newTotalAssets) = _accruedFeeShares();
        newTotalSupply = IERC20(META_MORPHO).totalSupply() + feeShares;

        assets = _convertToAssetsWithTotals(
            IERC20(META_MORPHO).balanceOf(owner), newTotalSupply, newTotalAssets, Math.Rounding.Floor
        );
    }

    function _accruedFeeShares() internal view returns (uint256 feeShares, uint256 newTotalAssets) {
        newTotalAssets = IMetaMorpho(META_MORPHO).totalAssets();

        uint256 totalInterest = newTotalAssets.zeroFloorSub(IMetaMorpho(META_MORPHO).lastTotalAssets());
        if (totalInterest != 0 && IMetaMorpho(META_MORPHO).fee() != 0) {
            // It is acknowledged that `feeAssets` may be rounded down to 0 if `totalInterest * fee < WAD`.
            uint256 feeAssets = totalInterest.mulDiv(IMetaMorpho(META_MORPHO).fee(), WAD);
            // The fee assets is subtracted from the total assets in this calculation to compensate for the fact
            // that total assets is already increased by the total interest (including the fee assets).
            feeShares = _convertToSharesWithTotals(
                feeAssets, IERC20(META_MORPHO).totalSupply(), newTotalAssets - feeAssets, Math.Rounding.Floor
            );
        }
    }

    function _convertToAssetsWithTotals(
        uint256 shares,
        uint256 newTotalSupply,
        uint256 newTotalAssets,
        Math.Rounding rounding
    ) internal view returns (uint256) {
        return shares.mulDiv(newTotalAssets + 1, newTotalSupply + 10 ** _decimalsOffset(), rounding);
    }

    function _convertToSharesWithTotals(
        uint256 assets,
        uint256 newTotalSupply,
        uint256 newTotalAssets,
        Math.Rounding rounding
    ) internal view returns (uint256) {
        return assets.mulDiv(newTotalSupply + 10 ** _decimalsOffset(), newTotalAssets + 1, rounding);
    }

    function _decimalsOffset() internal view returns (uint8) {
        return IMetaMorpho(META_MORPHO).DECIMALS_OFFSET();
    }

    function _depositProtocol(Protocol protocol, uint256 amount) internal {
        if (protocol == Protocol.MORPHO) {
            IERC20(BASE_TOKEN).approve(META_MORPHO, 0);
            IERC20(BASE_TOKEN).approve(META_MORPHO, amount);
            IMetaMorpho(META_MORPHO).deposit(amount, address(this));
        } else if (protocol == Protocol.COMET) {
            IERC20(BASE_TOKEN).approve(COMET, 0);
            IERC20(BASE_TOKEN).approve(COMET, amount);
            IComet(COMET).supply(BASE_TOKEN, amount);
        } else if (protocol == Protocol.AAVE) {
            IERC20(BASE_TOKEN).approve(AAVE_POOL, 0);
            IERC20(BASE_TOKEN).approve(AAVE_POOL, amount);
            IPool(AAVE_POOL).supply(BASE_TOKEN, amount, address(this), 0);
        } else if (protocol == Protocol.SPARK) {
            IERC20(BASE_TOKEN).approve(SPARK_POOL, 0);
            IERC20(BASE_TOKEN).approve(SPARK_POOL, amount);
            IPool(SPARK_POOL).supply(BASE_TOKEN, amount, address(this), 0);
        } else {
            revert UnsupportedProtocol();
        }
    }

    function _withdrawProtocol(Protocol protocol) internal returns (uint256 withdrawn) {
        uint256 position = _computePosition(protocol);
        if (position == 0) {
            revert NoPosition();
        }

        uint256 liquidity = _computeLiquidity(protocol);
        if (liquidity == 0) {
            revert InsufficientLiquidity(0, position);
        }

        uint256 withdrawable = Math.min(position, liquidity);
        bool withdrawAll = liquidity >= position;
        uint256 beforeBalance = IERC20(BASE_TOKEN).balanceOf(address(this));

        if (protocol == Protocol.MORPHO) {
            IMetaMorpho metaMorpho = IMetaMorpho(META_MORPHO);
            uint256 shares = IERC20(META_MORPHO).balanceOf(address(this));
            if (shares == 0) {
                revert NoPosition();
            }
            if (withdrawAll) {
                uint256 maxRedeem = metaMorpho.maxRedeem(address(this));
                uint256 sharesToRedeem = Math.min(shares, maxRedeem);
                metaMorpho.redeem(sharesToRedeem, address(this), address(this));
            } else {
                uint256 maxWithdraw = metaMorpho.maxWithdraw(address(this));
                uint256 assetsToWithdraw = Math.min(withdrawable, maxWithdraw);
                metaMorpho.withdraw(assetsToWithdraw, address(this), address(this));
            }
        } else if (protocol == Protocol.COMET) {
            uint256 amount = withdrawAll ? type(uint256).max : withdrawable;
            IComet(COMET).withdraw(BASE_TOKEN, amount);
        } else if (protocol == Protocol.AAVE) {
            uint256 amount = withdrawAll ? type(uint256).max : withdrawable;
            IPool(AAVE_POOL).withdraw(BASE_TOKEN, amount, address(this));
        } else if (protocol == Protocol.SPARK) {
            uint256 amount = withdrawAll ? type(uint256).max : withdrawable;
            IPool(SPARK_POOL).withdraw(BASE_TOKEN, amount, address(this));
        } else {
            revert UnsupportedProtocol();
        }

        uint256 afterBalance = IERC20(BASE_TOKEN).balanceOf(address(this));

        if (afterBalance < beforeBalance) revert WithdrawFailed();

        unchecked {
            withdrawn = afterBalance - beforeBalance;
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        bool success = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        bool success = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

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

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

File 3 of 28 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

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

            // Shift in bits from high into low.
            low |= high * twos;

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

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

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

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

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

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

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

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

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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

import {IMorpho, Id} from "./IMorpho.sol";

interface IMetaMorpho {
    function DECIMALS_OFFSET() external view returns (uint8);

    function MORPHO() external view returns (IMorpho);

    function lastTotalAssets() external view returns (uint256);

    function fee() external view returns (uint96);

    function withdrawQueue(uint256 index) external view returns (Id);

    function withdrawQueueLength() external view returns (uint256);

    function totalAssets() external view returns (uint256 assets);

    function maxWithdraw(address owner) external view returns (uint256 assets);

    function maxRedeem(address owner) external view returns (uint256);

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

    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

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

type Id is bytes32;

struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

interface IMorpho {
    function idToMarketParams(Id id) external view returns (MarketParams memory);

    function market(Id id) external view returns (Market memory m);

    function accrueInterest(MarketParams memory marketParams) external;
}

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

import {MarketParams, Market} from "./IMorpho.sol";

/// @title IIrm
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
interface IIrm {
    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);

    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
    /// storage.
    /// @dev Assumes that `market` corresponds to `marketParams`.
    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}

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

import {Id, MarketParams} from "./IMorpho.sol";

/// @title MarketParamsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to convert a market to its id.
library MarketParamsLib {
    /// @notice The length of the data used to compute the id of a market.
    /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
    uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;

    /// @notice Returns the id of the market `marketParams`.
    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
        assembly ("memory-safe") {
            marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
        }
    }
}

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

uint256 constant WAD = 1e18;

/// @title MathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
    /// @dev Returns (`x` * `y`) / `WAD` rounded down.
    function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded down.
    function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded up.
    function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y);
    }

    /// @dev Returns (`x` * `y`) / `d` rounded down.
    function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y) / d;
    }

    /// @dev Returns (`x` * `y`) / `d` rounded up.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y + (d - 1)) / d;
    }

    /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
    /// continuous compound interest rate.
    function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
        uint256 firstTerm = x * n;
        uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
        uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);

        return firstTerm + secondTerm + thirdTerm;
    }
}

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

/// @title UtilsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library exposing helpers.
/// @dev Inspired by https://github.com/morpho-org/morpho-utils.
library UtilsLib {
    /// @dev Returns true if there is exactly one zero among `x` and `y`.
    function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
        assembly {
            z := xor(iszero(x), iszero(y))
        }
    }

    /// @dev Returns the min of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns `x` safely cast to uint128.
    function toUint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max, "max uint128 exceeded");
        return uint128(x);
    }

    /// @dev Returns max(0, x - y).
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }
}

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

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

/// @title SharesMathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
    using MathLib for uint256;

    /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
    /// high precision computations.
    /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
    /// stays low enough not to inflate these assets to a significant value.
    /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
    uint256 internal constant VIRTUAL_SHARES = 1e6;

    /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
    /// empty.
    uint256 internal constant VIRTUAL_ASSETS = 1;

    /// @dev Calculates the value of `assets` quoted in shares, rounding down.
    function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
    }

    /// @dev Calculates the value of `shares` quoted in assets, rounding down.
    function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
    }

    /// @dev Calculates the value of `assets` quoted in shares, rounding up.
    function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
    }

    /// @dev Calculates the value of `shares` quoted in assets, rounding up.
    function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
        return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
    }
}

File 13 of 28 : IMerklDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IMerklDistributor {
    function claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs
    ) external;
}

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

interface IComet {
    function baseTrackingSupplySpeed() external view returns (uint256);

    function baseToken() external view returns (address);

    function supply(address asset, uint256 amount) external;

    function withdraw(address asset, uint256 amount) external;

    function getUtilization() external view returns (uint256);

    function getSupplyRate(uint256 utilization) external view returns (uint64);

    function totalSupply() external view returns (uint256);

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

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

interface IClaimable {
    struct RewardOwed {
        address token;
        uint256 owed;
    }

    function claim(address comet, address src, bool shouldAccrue) external;

    function getRewardOwed(address comet, address account) external returns (RewardOwed memory);
}

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

interface IPool {
    struct ReserveData {
        //stores the reserve configuration
        ReserveConfigurationMap configuration;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        //the current supply rate. Expressed in ray
        uint128 currentLiquidityRate;
        //variable borrow index. Expressed in ray
        uint128 variableBorrowIndex;
        //the current variable borrow rate. Expressed in ray
        uint128 currentVariableBorrowRate;
        //the current stable borrow rate. Expressed in ray
        uint128 currentStableBorrowRate;
        //timestamp of last update
        uint40 lastUpdateTimestamp;
        //the id of the reserve. Represents the position in the list of the active reserves
        uint16 id;
        //aToken address
        address aTokenAddress;
        //stableDebtToken address
        address stableDebtTokenAddress;
        //variableDebtToken address
        address variableDebtTokenAddress;
        //address of the interest rate strategy
        address interestRateStrategyAddress;
        //the current treasury balance, scaled
        uint128 accruedToTreasury;
        //the outstanding unbacked aTokens minted through the bridging feature
        uint128 unbacked;
        //the outstanding debt borrowed against this asset in isolation mode
        uint128 isolationModeTotalDebt;
    }

    struct ReserveConfigurationMap {
        //bit 0-15: LTV
        //bit 16-31: Liq. threshold
        //bit 32-47: Liq. bonus
        //bit 48-55: Decimals
        //bit 56: reserve is active
        //bit 57: reserve is frozen
        //bit 58: borrowing is enabled
        //bit 59: stable rate borrowing enabled
        //bit 60: asset is paused
        //bit 61: borrowing in isolation mode is enabled
        //bit 62-63: reserved
        //bit 64-79: reserve factor
        //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap
        //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap
        //bit 152-167 liquidation protocol fee
        //bit 168-175 eMode category
        //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
        //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
        //bit 252-255 unused
        uint256 data;
    }

    function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

    function withdraw(address asset, uint256 amount, address to) external returns (uint256);

    function getReserveData(address asset) external view returns (ReserveData memory);
}

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

import {IDiamond} from "../interfaces/diamond/IDiamond.sol";
import {IDiamondCut} from "../interfaces/diamond/IDiamondCut.sol";

library LibDiamond {
    bytes32 internal constant DIAMOND_STORAGE_POSITION = keccak256("smartsafe.storage.diamond");

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);

    error OwnableInvalidOwner(address owner);
    error NotContractOwner(address _user, address _contractOwner);
    error NoSelectorsGivenToAdd();
    error NoSelectorsProvidedForFacetForCut(address _facetAddress);
    error CannotAddSelectorsToZeroAddress(bytes4[] _selectors);
    error NoBytecodeAtAddress(address _contractAddress, string _message);
    error IncorrectFacetCutAction(uint8 _action);
    error CannotAddFunctionToDiamondThatAlreadyExists(bytes4 _selector);
    error CannotReplaceFunctionsFromFacetWithZeroAddress(bytes4[] _selectors);
    error CannotReplaceImmutableFunction(bytes4 _selector);
    error CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(bytes4 _selector);
    error CannotReplaceFunctionThatDoesNotExists(bytes4 _selector);
    error RemoveFacetAddressMustBeZeroAddress(address _facetAddress);
    error CannotRemoveFunctionThatDoesNotExist(bytes4 _selector);
    error CannotRemoveImmutableFunction(bytes4 _selector);
    error InitializationFunctionReverted(address _initializationContractAddress, bytes _calldata);

    struct FacetAddressAndSelectorPosition {
        address facetAddress;
        uint16 selectorPosition;
    }

    struct DiamondStorage {
        // function selector => facet address and selector position in selectors array
        mapping(bytes4 => FacetAddressAndSelectorPosition) facetAddressAndSelectorPosition;
        bytes4[] selectors;
        // owner of the contract
        address contractOwner;
    }

    function diamondStorage() internal pure returns (DiamondStorage storage ds) {
        bytes32 position = DIAMOND_STORAGE_POSITION;
        assembly {
            ds.slot := position
        }
    }

    function setContractOwner(address _newOwner) internal {
        if (_newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        DiamondStorage storage ds = diamondStorage();
        address previousOwner = ds.contractOwner;
        ds.contractOwner = _newOwner;
        emit OwnershipTransferred(previousOwner, _newOwner);
    }

    function contractOwner() internal view returns (address) {
        return diamondStorage().contractOwner;
    }

    function enforceIsContractOwner() internal view {
        if (msg.sender != diamondStorage().contractOwner) {
            revert NotContractOwner(msg.sender, diamondStorage().contractOwner);
        }
    }

    // Internal function version of diamondCut
    function diamondCut(IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata) internal {
        for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
            bytes4[] memory functionSelectors = _diamondCut[facetIndex].functionSelectors;
            address _facetAddress = _diamondCut[facetIndex].facetAddress;
            if (functionSelectors.length == 0) {
                revert NoSelectorsProvidedForFacetForCut(_facetAddress);
            }
            IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
            if (action == IDiamond.FacetCutAction.Add) {
                addFunctions(_facetAddress, functionSelectors);
            } else if (action == IDiamond.FacetCutAction.Replace) {
                replaceFunctions(_facetAddress, functionSelectors);
            } else if (action == IDiamond.FacetCutAction.Remove) {
                removeFunctions(_facetAddress, functionSelectors);
            } else {
                revert IncorrectFacetCutAction(uint8(action));
            }
        }
        emit DiamondCut(_diamondCut, _init, _calldata);
        initializeDiamondCut(_init, _calldata);
    }

    function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
        if (_facetAddress == address(0)) {
            revert CannotAddSelectorsToZeroAddress(_functionSelectors);
        }
        DiamondStorage storage ds = diamondStorage();
        uint16 selectorCount = uint16(ds.selectors.length);
        enforceHasContractCode(_facetAddress, "LibDiamondCut: Add facet has no code");
        for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
            bytes4 selector = _functionSelectors[selectorIndex];
            address oldFacetAddress = ds.facetAddressAndSelectorPosition[selector].facetAddress;
            if (oldFacetAddress != address(0)) {
                revert CannotAddFunctionToDiamondThatAlreadyExists(selector);
            }
            ds.facetAddressAndSelectorPosition[selector] = FacetAddressAndSelectorPosition(_facetAddress, selectorCount);
            ds.selectors.push(selector);
            selectorCount++;
        }
    }

    function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
        DiamondStorage storage ds = diamondStorage();
        if (_facetAddress == address(0)) {
            revert CannotReplaceFunctionsFromFacetWithZeroAddress(_functionSelectors);
        }
        enforceHasContractCode(_facetAddress, "LibDiamondCut: Replace facet has no code");
        for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
            bytes4 selector = _functionSelectors[selectorIndex];
            address oldFacetAddress = ds.facetAddressAndSelectorPosition[selector].facetAddress;
            // can't replace immutable functions -- functions defined directly in the diamond in this case
            if (oldFacetAddress == address(this)) {
                revert CannotReplaceImmutableFunction(selector);
            }
            if (oldFacetAddress == _facetAddress) {
                revert CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(selector);
            }
            if (oldFacetAddress == address(0)) {
                revert CannotReplaceFunctionThatDoesNotExists(selector);
            }
            // replace old facet address
            ds.facetAddressAndSelectorPosition[selector].facetAddress = _facetAddress;
        }
    }

    function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
        DiamondStorage storage ds = diamondStorage();
        uint256 selectorCount = ds.selectors.length;
        if (_facetAddress != address(0)) {
            revert RemoveFacetAddressMustBeZeroAddress(_facetAddress);
        }
        for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
            bytes4 selector = _functionSelectors[selectorIndex];
            FacetAddressAndSelectorPosition memory oldFacetAddressAndSelectorPosition =
                ds.facetAddressAndSelectorPosition[selector];
            if (oldFacetAddressAndSelectorPosition.facetAddress == address(0)) {
                revert CannotRemoveFunctionThatDoesNotExist(selector);
            }

            // can't remove immutable functions -- functions defined directly in the diamond
            if (oldFacetAddressAndSelectorPosition.facetAddress == address(this)) {
                revert CannotRemoveImmutableFunction(selector);
            }
            // replace selector with last selector
            selectorCount--;
            if (oldFacetAddressAndSelectorPosition.selectorPosition != selectorCount) {
                bytes4 lastSelector = ds.selectors[selectorCount];
                ds.selectors[oldFacetAddressAndSelectorPosition.selectorPosition] = lastSelector;
                ds.facetAddressAndSelectorPosition[lastSelector].selectorPosition =
                    oldFacetAddressAndSelectorPosition.selectorPosition;
            }
            // delete last selector
            ds.selectors.pop();
            delete ds.facetAddressAndSelectorPosition[selector];
        }
    }

    function initializeDiamondCut(address _init, bytes memory _calldata) internal {
        if (_init == address(0)) {
            return;
        }
        enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
        (bool success, bytes memory error) = _init.delegatecall(_calldata);
        if (!success) {
            if (error.length > 0) {
                // bubble up error
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(error)
                    revert(add(32, error), returndata_size)
                }
            } else {
                revert InitializationFunctionReverted(_init, _calldata);
            }
        }
    }

    function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
        uint256 contractSize;
        assembly {
            contractSize := extcodesize(_contract)
        }
        if (contractSize == 0) {
            revert NoBytecodeAtAddress(_contract, _errorMessage);
        }
    }

    function facetAddress(bytes4 _selector) internal view returns (address facetAddress_) {
        facetAddress_ = diamondStorage().facetAddressAndSelectorPosition[_selector].facetAddress;
    }
}

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

library LibYieldOptimizer {

    bytes32 internal constant STORAGE_POSITION = keccak256("smartsafe.storage.yieldoptimizer");

    struct Config {
        uint128 minLiquidityThreshold;
        uint16 minBpsThreshold;
        uint64 cooldown;
    }

    struct Layout {
        Config config;
        mapping(address => bool) keepers;
        uint256 keeperCount;
        uint256 lastExecuted;
    }

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_POSITION;
        assembly {
            l.slot := slot
        }
    }

    function getConfig() internal view returns (Config memory) {
        return layout().config;
    }

    function setConfig(Config memory config) internal {
        layout().config = config;
    }

    function isKeeper(address account) internal view returns (bool) {
        return layout().keepers[account];
    }

    function setKeeper(address account, bool allowed) internal returns (bool changed) {
        Layout storage l = layout();
        bool current = l.keepers[account];

        if (allowed) {
            if (current) return false;
            l.keepers[account] = true;
            unchecked {
                l.keeperCount += 1;
            }
            return true;
        }

        if (!current) return false;
        l.keepers[account] = false;
        unchecked {
            l.keeperCount -= 1;
        }
        return true;
    }

    function getKeeperCount() internal view returns (uint256) {
        return layout().keeperCount;
    }

    function getLastExecuted() internal view returns (uint256) {
        return layout().lastExecuted;
    }

    function setLastExecuted(uint256 timestamp) internal {
        layout().lastExecuted = timestamp;
    }
}

File 19 of 28 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

File 22 of 28 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool 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.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @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
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        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
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        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
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        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
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        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
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        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
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        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
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        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
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        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
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        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
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        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
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        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
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        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
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        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
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        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
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        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
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        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
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        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
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        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
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        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
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        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
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        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
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        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
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        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
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        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
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        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
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        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
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        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
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        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
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        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
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        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
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        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
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @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
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @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
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @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
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @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
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @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
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @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
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @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
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @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
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @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
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @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
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @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
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @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
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @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
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @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
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @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
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @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
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @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
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @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
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @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
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @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
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @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
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @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
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @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
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @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
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @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
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @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
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @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
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @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
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @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
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @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
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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

pragma solidity >=0.6.2;

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

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

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

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

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

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

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

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

File 24 of 28 : IDiamond.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

/**
 * @title IDiamond
 * @dev Standard interface for adding/replacing/removing diamond facets
 */
interface IDiamond {
    enum FacetCutAction {
        Add,
        Replace,
        Remove
    }
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

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

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

/**
 * @title IDiamondCut
 * @dev Standard interface for adding/replacing/removing diamond facets
 */
interface IDiamondCut is IDiamond {
    /**
     * @notice Add, replace, or remove any number of functions and optionally execute a function with delegatecall
     * @param _diamondCut Facet changes to apply
     * @param _init Address of delegatecall target for initialization
     * @param _calldata Calldata supplied to the initialization function
     */
    function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata) external;
}

File 26 of 28 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

File 27 of 28 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

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

pragma solidity >=0.4.16;

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

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@forge-std/=lib/forge-std/src/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"AccrueInterestFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"current","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"CooldownNotExpired","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"InsufficientLiquidity","type":"error"},{"inputs":[],"name":"InvalidParameters","type":"error"},{"inputs":[],"name":"NoPosition","type":"error"},{"inputs":[],"name":"NoRewardsToClaim","type":"error"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_contractOwner","type":"address"}],"name":"NotContractOwner","type":"error"},{"inputs":[],"name":"OnlyKeeperOrOwner","type":"error"},{"inputs":[],"name":"UnsupportedProtocol","type":"error"},{"inputs":[],"name":"WithdrawFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"moduleId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"facet","type":"address"},{"indexed":true,"internalType":"bytes4","name":"selector","type":"bytes4"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ModuleEvent","type":"event"},{"inputs":[],"name":"AAVE_BASE_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AAVE_POOL","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASE_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"COMET","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"COMET_REWARDS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MERKL_DISTRIBUTOR","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"META_MORPHO","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MODULE_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SPARK_BASE_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SPARK_POOL","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_canExecuteOptimization","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_claimComp","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"address[]","name":"rewards","type":"address[]"},{"internalType":"uint256[]","name":"claimables","type":"uint256[]"},{"internalType":"bytes32[][]","name":"proofs","type":"bytes32[][]"}],"name":"yieldOptimizer_claimMorpho","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum YieldOptimizerFacet.Protocol","name":"protocol","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"yieldOptimizer_deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"yieldOptimizer_getConfig","outputs":[{"components":[{"internalType":"uint128","name":"minLiquidityThreshold","type":"uint128"},{"internalType":"uint16","name":"minBpsThreshold","type":"uint16"},{"internalType":"uint64","name":"cooldown","type":"uint64"}],"internalType":"struct LibYieldOptimizer.Config","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_getKeeperCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_getLiquidities","outputs":[{"internalType":"uint256[]","name":"liquidities","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum YieldOptimizerFacet.Protocol","name":"protocol","type":"uint8"}],"name":"yieldOptimizer_getLiquidity","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_getOwedComp","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"owed","type":"uint256"}],"internalType":"struct IClaimable.RewardOwed","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum YieldOptimizerFacet.Protocol","name":"protocol","type":"uint8"}],"name":"yieldOptimizer_getPosition","outputs":[{"internalType":"uint256","name":"position","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_getPositions","outputs":[{"internalType":"uint256[]","name":"positions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_getTimeUntilNextOptimization","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"yieldOptimizer_isKeeper","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldOptimizer_lastOptimizationTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum YieldOptimizerFacet.Protocol","name":"from","type":"uint8"},{"internalType":"enum YieldOptimizerFacet.Protocol","name":"to","type":"uint8"}],"name":"yieldOptimizer_optimizeYield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"minLiquidityThreshold","type":"uint128"},{"internalType":"uint16","name":"minBpsThreshold","type":"uint16"},{"internalType":"uint64","name":"cooldown","type":"uint64"}],"name":"yieldOptimizer_setConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"keeper","type":"address"},{"internalType":"bool","name":"allowed","type":"bool"}],"name":"yieldOptimizer_setKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum YieldOptimizerFacet.Protocol","name":"protocol","type":"uint8"}],"name":"yieldOptimizer_withdraw","outputs":[{"internalType":"uint256","name":"withdrawn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

608060405234801561000f575f80fd5b506137dc8061001d5f395ff3fe608060405234801561000f575f80fd5b50600436106101bb575f3560e01c80636c3289b0116100f3578063d0120e0a11610093578063ee537c251161006e578063ee537c25146103d7578063ef58211c14610417578063f17c425e1461042a578063fecbe1c31461043d575f80fd5b8063d0120e0a14610395578063e702a367146103b0578063ed2f21f5146103c3575f80fd5b80638ccb1f12116100ce5780638ccb1f1214610341578063b140764f1461035c578063b7065d471461036f578063c530624914610382575f80fd5b80636c3289b01461031657806374a5b4a814610331578063888166b714610339575f80fd5b80632f09f4961161015e57806352a460d71161013957806352a460d7146102cd57806353e0ac09146102e057806363e2d3da146102fb5780636758f59a14610303575f80fd5b80632f09f496146102815780633acb3949146102ad5780634736a5c7146102b5575f80fd5b806320ea564e1161019957806320ea564e14610216578063210663e414610237578063219461ed1461024b5780632517b92b14610266575f80fd5b806308a01675146101bf5780631c8c463b146101f75780631f3257ed1461020c575b5f80fd5b6101da7387870bca3f3fd6335c3f4ce8392d69350b4fa4e281565b6040516001600160a01b0390911681526020015b60405180910390f35b6101ff610451565b6040516101ee9190612e07565b6102146104c2565b005b610229610224366004612e58565b610680565b6040519081526020016101ee565b6101da5f8051602061374783398151915281565b6101da733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6101da73c3d688b66703497daa19211eedff47f25384cdc381565b610289610690565b6040805182516001600160a01b0316815260209283015192810192909252016101ee565b6101ff610730565b6102bd61079d565b60405190151581526020016101ee565b6102146102db366004612e71565b6107ac565b6101da73377c3bd93f2a2984e1e7be6a5c22c525ed4a481581565b610229610905565b610229610311366004612e58565b610933565b6101da7398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c81565b610229610a0e565b610229610a37565b6101da73c13e21b648a5ee794902342038ff3adab66be98781565b61022961036a366004612e58565b610a40565b61021461037d366004612ee9565b610a4a565b610214610390366004612fc4565b610b57565b6101da731b0e765f6224c21223aea2af16c1c46e38885a4081565b6102146103be36600461300f565b610c23565b6102295f8051602061376783398151915281565b6103df610d3b565b6040805182516001600160801b0316815260208084015161ffff1690820152918101516001600160401b0316908201526060016101ee565b610214610425366004613068565b610d5f565b6102bd610438366004613090565b610ec7565b6101da5f8051602061372783398151915281565b60408051600480825260a08201909252606091602082016080803683370190505090505f5b60048110156104be57610499816003811115610494576104946130ab565b610ed1565b8282815181106104ab576104ab6130bf565b6020908102919091010152600101610476565b5090565b6104ca6112d6565b6040516320f0656b60e11b815273c3d688b66703497daa19211eedff47f25384cdc360048201523060248201525f90731b0e765f6224c21223aea2af16c1c46e38885a40906341e0cad69060440160408051808303815f875af1158015610533573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061055791906130d3565b905080602001515f0361057d576040516373380d9960e01b815260040160405180910390fd5b604051635b81a7bf60e11b815273c3d688b66703497daa19211eedff47f25384cdc3600482015230602482015260016044820152731b0e765f6224c21223aea2af16c1c46e38885a409063b7034f7e906064015f604051808303815f87803b1580156105e7575f80fd5b505af11580156105f9573d5f803e3d5ffd5b505050505f61060e631f3257ed60e01b611361565b602080840151604051929350631f3257ed60e01b926001600160a01b038516925f80516020613767833981519152925f805160206137878339815191529261065a920190815260200190565b60408051601f198184030181529082905261067491613134565b60405180910390a45050565b5f61068a826113a4565b92915050565b604080518082019091525f80825260208201526040516320f0656b60e11b815273c3d688b66703497daa19211eedff47f25384cdc360048201523060248201525f90731b0e765f6224c21223aea2af16c1c46e38885a40906341e0cad69060440160408051808303815f875af115801561070c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068a91906130d3565b60408051600480825260a08201909252606091602082016080803683370190505090505f5b60048110156104be57610778816003811115610773576107736130ab565b6113a4565b82828151811061078a5761078a6130bf565b6020908102919091010152600101610755565b5f6107a66114c1565b15919050565b5f6107b5611542565b9050336001600160a01b038216148015906107d657506107d433611570565b155b156107f457604051636ed04f9360e11b815260040160405180910390fd5b816003811115610806576108066130ab565b836003811115610818576108186130ab565b0361083657604051630e52390960e41b815260040160405180910390fd5b61083e6115ac565b5f610848846115f0565b90506108548382611bd6565b61087c427fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c3155565b5f61088d6352a460d760e01b611361565b90506352a460d760e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f805160206137878339815191528888876040516020016108dc939291906131a0565b60408051601f19818403018152908290526108f691613134565b60405180910390a45050505050565b5f61092e7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c305490565b905090565b5f8061093d611542565b9050336001600160a01b0382161480159061095e575061095c33611570565b155b1561097c57604051636ed04f9360e11b815260040160405180910390fd5b610985836115f0565b91505f6109986333ac7acd60e11b611361565b9050636758f59a60e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f8051602061378783398151915287876040516020016109e59291906131c9565b60408051601f19818403018152908290526109ff91613134565b60405180910390a45050919050565b5f61092e7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c315490565b5f61092e6114c1565b5f61068a82610ed1565b610a526112d6565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c090610a97908b908b908b908b908b908b908b908b9060040161325b565b5f604051808303815f87803b158015610aae575f80fd5b505af1158015610ac0573d5f803e3d5ffd5b505050505f610ad563b7065d4760e01b611361565b905063b7065d4760e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f805160206137878339815191528c8c8c8c8c8c604051602001610b2a96959493929190613336565b60408051601f1981840301815290829052610b4491613134565b60405180910390a4505050505050505050565b610b5f6112d6565b6001600160a01b038216610b8657604051630e52390960e41b815260040160405180910390fd5b5f610b9183836121fa565b90508015610c1e575f610baa63c530624960e01b611361565b604080516001600160a01b0387811660208301528615159282019290925291925063c530624960e01b91908316905f80516020613767833981519152905f80516020613787833981519152906060015b60408051601f1981840301815290829052610c1491613134565b60405180910390a4505b505050565b610c2b6112d6565b604080516060810182526001600160801b03851680825261ffff8516602083018190526001600160401b038516929093018290527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e805471ffffffffffffffffffffffffffffffffffff1916909117600160801b9093029290921767ffffffffffffffff60901b1916600160901b9091021790555f610cd063e702a36760e01b611361565b604080516001600160801b038716602082015261ffff8616918101919091526001600160401b038416606082015290915063e702a36760e01b906001600160a01b038316905f80516020613767833981519152905f8051602061378783398151915290608001610bfa565b604080516060810182525f808252602082018190529181019190915261092e6122eb565b5f610d68611542565b9050336001600160a01b03821614801590610d895750610d8733611570565b155b15610da757604051636ed04f9360e11b815260040160405180910390fd5b815f03610dc757604051630e52390960e41b815260040160405180910390fd5b610dd0836123dd565b6040516370a0823160e01b81523060048201525f905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015610e18573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e3c919061337e565b905082811015610e5f57604051631e9acf1760e31b815260040160405180910390fd5b610e698484611bd6565b5f610e7a633bd6084760e21b611361565b905063ef58211c60e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f8051602061378783398151915288886040516020016108dc9291906131c9565b5f61068a82611570565b5f80826003811115610ee557610ee56130ab565b03611166575f5f8051602061372783398151915290505f816001600160a01b0316633acb56246040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f38573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f5c9190613395565b90505f826001600160a01b03166333f91ebb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f9b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fbf919061337e565b90505f805b828110156110dd576040516362518ddf60e01b8152600481018290525f906001600160a01b038716906362518ddf90602401602060405180830381865afa158015611011573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611035919061337e565b604051632c3c915760e01b8152600481018290529091505f906001600160a01b03871690632c3c91579060240160a060405180830381865afa15801561107d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a191906133b0565b90505f806110af8884612435565b50925050915080826110c1919061345e565b6110cb9087613471565b95505060019093019250610fc4915050565b506040516370a0823160e01b81526001600160a01b038416600482015261115c9082905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015611133573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611157919061337e565b61272b565b9695505050505050565b600182600381111561117a5761117a6130ab565b036111fe576040516370a0823160e01b815273c3d688b66703497daa19211eedff47f25384cdc360048201525f80516020613747833981519152906370a08231906024015b602060405180830381865afa1580156111da573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068a919061337e565b6002826003811115611212576112126130ab565b0361125b576040516370a0823160e01b81527398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c60048201525f80516020613747833981519152906370a08231906024016111bf565b600382600381111561126f5761126f6130ab565b036112b8576040516370a0823160e01b815273377c3bd93f2a2984e1e7be6a5c22c525ed4a481560048201525f80516020613747833981519152906370a08231906024016111bf565b60405163743f26e160e01b815260040160405180910390fd5b919050565b7f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f456600201546001600160a01b0316331461135f577f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f45854604051600162bed83560e01b031981523360048201526001600160a01b0390911660248201526044015b60405180910390fd5b565b6001600160e01b0319165f9081527f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f45660205260409020546001600160a01b031690565b5f808260038111156113b8576113b86130ab565b036113d1576113c63061273d565b509091506112d19050565b60018260038111156113e5576113e56130ab565b03611421576040516370a0823160e01b815230600482015273c3d688b66703497daa19211eedff47f25384cdc3906370a08231906024016111bf565b6002826003811115611435576114356130ab565b03611471576040516370a0823160e01b81523060048201527398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c906370a08231906024016111bf565b6003826003811115611485576114856130ab565b036112b8576040516370a0823160e01b815230600482015273377c3bd93f2a2984e1e7be6a5c22c525ed4a4815906370a08231906024016111bf565b5f806114eb7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c315490565b9050805f036114fb575f91505090565b5f6115046122eb565b6040015190505f61151e6001600160401b03831684613471565b9050804210611530575f935050505090565b61153a428261345e565b935050505090565b7f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f458546001600160a01b031690565b6001600160a01b03165f9081527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2f602052604090205460ff1690565b5f6115b56114c1565b905080156115ed575f6115c88242613471565b60405163b388f18d60e01b815242600482015260248101829052909150604401611356565b50565b5f806115fb836113a4565b9050805f0361161d57604051632afc3c0d60e21b815260040160405180910390fd5b5f61162784610ed1565b9050805f036116525760405163a17e11d560e01b81525f600482015260248101839052604401611356565b5f61165d838361272b565b6040516370a0823160e01b815230600482015290915083831015905f905f80516020613747833981519152906370a0823190602401602060405180830381865afa1580156116ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116d1919061337e565b90505f8760038111156116e6576116e66130ab565b0361196e576040516370a0823160e01b81523060048201525f80516020613727833981519152905f9082906370a0823190602401602060405180830381865afa158015611735573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611759919061337e565b9050805f0361177b57604051632afc3c0d60e21b815260040160405180910390fd5b831561187657604051636c82bbbf60e11b81523060048201525f906001600160a01b0384169063d905777e90602401602060405180830381865afa1580156117c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e9919061337e565b90505f6117f6838361272b565b604051635d043b2960e11b815260048101829052306024820181905260448201529091506001600160a01b0385169063ba087652906064016020604051808303815f875af115801561184a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186e919061337e565b505050611967565b60405163ce96cb7760e01b81523060048201525f906001600160a01b0384169063ce96cb7790602401602060405180830381865afa1580156118ba573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118de919061337e565b90505f6118eb878361272b565b604051632d182be560e21b815260048101829052306024820181905260448201529091506001600160a01b0385169063b460af94906064016020604051808303815f875af115801561193f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611963919061337e565b5050505b5050611b3c565b6001876003811115611982576119826130ab565b03611a08575f826119935783611996565b5f195b60405163f3fef3a360e01b815290915073c3d688b66703497daa19211eedff47f25384cdc39063f3fef3a3906119df905f80516020613747833981519152908590600401613484565b5f604051808303815f87803b1580156119f6575f80fd5b505af1158015611963573d5f803e3d5ffd5b6002876003811115611a1c57611a1c6130ab565b03611ac0575f82611a2d5783611a30565b5f195b604051631a4ca37b60e21b81525f805160206137478339815191526004820152602481018290523060448201529091507387870bca3f3fd6335c3f4ce8392d69350b4fa4e2906369328dec906064015b6020604051808303815f875af1158015611a9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611967919061337e565b6003876003811115611ad457611ad46130ab565b036112b8575f82611ae55783611ae8565b5f195b604051631a4ca37b60e21b81525f8051602061374783398151915260048201526024810182905230604482015290915073c13e21b648a5ee794902342038ff3adab66be987906369328dec90606401611a80565b6040516370a0823160e01b81523060048201525f905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015611b84573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba8919061337e565b905081811015611bcb57604051631d42c86760e21b815260040160405180910390fd5b039695505050505050565b5f826003811115611be957611be96130ab565b03611d605760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611c2d905f80516020613727833981519152905f90600401613484565b6020604051808303815f875af1158015611c49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c6d919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611cad905f80516020613727833981519152908590600401613484565b6020604051808303815f875af1158015611cc9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ced919061349d565b50604051636e553f6560e01b8152600481018290523060248201525f8051602061372783398151915290636e553f65906044016020604051808303815f875af1158015611d3c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c1e919061337e565b6001826003811115611d7457611d746130ab565b03611efe5760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611dbf9073c3d688b66703497daa19211eedff47f25384cdc3905f90600401613484565b6020604051808303815f875af1158015611ddb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dff919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611e469073c3d688b66703497daa19211eedff47f25384cdc3908590600401613484565b6020604051808303815f875af1158015611e62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e86919061349d565b50604051631e573fb760e31b815273c3d688b66703497daa19211eedff47f25384cdc39063f2b9fdb890611ecd905f80516020613747833981519152908590600401613484565b5f604051808303815f87803b158015611ee4575f80fd5b505af1158015611ef6573d5f803e3d5ffd5b505050505050565b6002826003811115611f1257611f126130ab565b0361207c5760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611f5d907387870bca3f3fd6335c3f4ce8392d69350b4fa4e2905f90600401613484565b6020604051808303815f875af1158015611f79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f9d919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611fe4907387870bca3f3fd6335c3f4ce8392d69350b4fa4e2908590600401613484565b6020604051808303815f875af1158015612000573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612024919061349d565b5060405163617ba03760e01b81525f805160206137478339815191526004820152602481018290523060448201525f60648201527387870bca3f3fd6335c3f4ce8392d69350b4fa4e29063617ba03790608401611ecd565b6003826003811115612090576120906130ab565b036112b85760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b3906120db9073c13e21b648a5ee794902342038ff3adab66be987905f90600401613484565b6020604051808303815f875af11580156120f7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061211b919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b3906121629073c13e21b648a5ee794902342038ff3adab66be987908590600401613484565b6020604051808303815f875af115801561217e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121a2919061349d565b5060405163617ba03760e01b81525f805160206137478339815191526004820152602481018290523060448201525f606482015273c13e21b648a5ee794902342038ff3adab66be9879063617ba03790608401611ecd565b6001600160a01b0382165f9081527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2f60205260408120547fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e9060ff1683156122a457801561226c575f9250505061068a565b506001600160a01b0384165f90815260018281016020526040909120805460ff1916821790556002909101805482019055905061068a565b806122b3575f9250505061068a565b506001600160a01b0384165f90815260018083016020526040909120805460ff19169055600290910180545f19019055905092915050565b604080516060810182525f8082526020820181905291810191909152612388604080516060810182525f80825260208201819052918101919091527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e6040805160608101825291546001600160801b0381168352600160801b810461ffff166020840152600160901b90046001600160401b031690820152919050565b80519091506001600160801b03165f036123a657652d79883d200081525b806020015161ffff165f036123bd5760c860208201525b80604001516001600160401b03165f036123da5761384060408201525b90565b5f6123e66122eb565b90505f6123f283610ed1565b82519091506001600160801b0316811015610c1e57815160405163a17e11d560e01b8152600481018390526001600160801b039091166024820152604401611356565b5f805f805f6124458660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa15801561248d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124b191906134b8565b90505f81608001516001600160801b0316426124cd919061345e565b905080158015906124ea575060408201516001600160801b031615155b8015612502575060608801516001600160a01b031615155b156126f7576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa1580156125d1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125f5919061337e565b90505f6126196126058385612855565b60408601516001600160801b0316906128b3565b9050612624816128c7565b84604001818151612635919061356c565b6001600160801b031690525061264a816128c7565b8451859061265990839061356c565b6001600160801b0390811690915260a0860151161590506126f4575f6126958560a001516001600160801b0316836128b390919063ffffffff16565b90505f6126c982875f01516001600160801b03166126b3919061345e565b60208801518491906001600160801b0316612916565b90506126d4816128c7565b866020018181516126e5919061356c565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f8282188284100282185b9392505050565b5f805f80612749612942565b8093508192505050805f805160206137278339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561279b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127bf919061337e565b6127c99190613471565b6040516370a0823160e01b81526001600160a01b038716600482015290935061284b905f80516020613727833981519152906370a0823190602401602060405180830381865afa15801561281f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612843919061337e565b84845f612bce565b9350509193909250565b5f806128618385613593565b90505f612881828061287c670de0b6b3a76400006002613593565b612c0c565b90505f61289c828461287c670de0b6b3a76400006003613593565b9050806128a98385613471565b61115c9190613471565b5f6127368383670de0b6b3a7640000612c0c565b5f6001600160801b038211156104be5760405162461bcd60e51b81526020600482015260146024820152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b6044820152606401611356565b5f61293a612927620f424084613471565b612932600186613471565b869190612c0c565b949350505050565b5f805f805160206137278339815191526001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561298d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b1919061337e565b90505f612a2e5f805160206137278339815191526001600160a01b031663568efc076040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a00573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a24919061337e565b8084039084110290565b90508015801590612ab357505f805160206137278339815191526001600160a01b031663ddca3f436040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a83573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aa791906135aa565b6001600160601b031615155b15612bc9575f612b425f805160206137278339815191526001600160a01b031663ddca3f436040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b05573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b2991906135aa565b83906001600160601b0316670de0b6b3a7640000612c22565b9050612bc5815f805160206137278339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b91573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb5919061337e565b612bbf848761345e565b5f612cd2565b9350505b509091565b5f612c03612bdd846001613471565b612be5612cfe565b612bf090600a6136b0565b612bfa9087613471565b87919085612d6c565b95945050505050565b5f81612c188486613593565b61293a91906136d2565b5f805f612c2f8686612dae565b91509150815f03612c5357838181612c4957612c496136be565b0492505050612736565b818411612c6a57612c6a6003851502601118612dca565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f612c03612cde612cfe565b612ce990600a6136b0565b612cf39086613471565b612bfa856001613471565b5f5f805160206137278339815191526001600160a01b031663aea70acc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d48573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092e91906136e5565b5f612d99612d7983612ddb565b8015612d9457505f8480612d8f57612d8f6136be565b868809115b151590565b612da4868686612c22565b612c039190613471565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b5f6002826003811115612df057612df06130ab565b612dfa9190613705565b60ff166001149050919050565b602080825282518282018190525f9190848201906040850190845b81811015612e3e57835183529284019291840191600101612e22565b50909695505050505050565b8035600481106112d1575f80fd5b5f60208284031215612e68575f80fd5b61273682612e4a565b5f8060408385031215612e82575f80fd5b612e8b83612e4a565b9150612e9960208401612e4a565b90509250929050565b5f8083601f840112612eb2575f80fd5b5081356001600160401b03811115612ec8575f80fd5b6020830191508360208260051b8501011115612ee2575f80fd5b9250929050565b5f805f805f805f806080898b031215612f00575f80fd5b88356001600160401b0380821115612f16575f80fd5b612f228c838d01612ea2565b909a50985060208b0135915080821115612f3a575f80fd5b612f468c838d01612ea2565b909850965060408b0135915080821115612f5e575f80fd5b612f6a8c838d01612ea2565b909650945060608b0135915080821115612f82575f80fd5b50612f8f8b828c01612ea2565b999c989b5096995094979396929594505050565b6001600160a01b03811681146115ed575f80fd5b80151581146115ed575f80fd5b5f8060408385031215612fd5575f80fd5b8235612fe081612fa3565b91506020830135612ff081612fb7565b809150509250929050565b6001600160801b03811681146115ed575f80fd5b5f805f60608486031215613021575f80fd5b833561302c81612ffb565b9250602084013561ffff81168114613042575f80fd5b915060408401356001600160401b038116811461305d575f80fd5b809150509250925092565b5f8060408385031215613079575f80fd5b61308283612e4a565b946020939093013593505050565b5f602082840312156130a0575f80fd5b813561273681612fa3565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f604082840312156130e3575f80fd5b604051604081018181106001600160401b038211171561311157634e487b7160e01b5f52604160045260245ffd5b604052825161311f81612fa3565b81526020928301519281019290925250919050565b5f602080835283518060208501525f5b8181101561316057858101830151858201604001528201613144565b505f604082860101526040601f19601f8301168501019250505092915050565b6004811061319c57634e487b7160e01b5f52602160045260245ffd5b9052565b606081016131ae8286613180565b6131bb6020830185613180565b826040830152949350505050565b604081016131d78285613180565b8260208301529392505050565b8183525f60208085019450825f5b8581101561322057813561320581612fa3565b6001600160a01b0316875295820195908201906001016131f2565b509495945050505050565b8183525f6001600160fb1b03831115613242575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f61326e608083018a8c6131e4565b602083820381850152613282828a8c6131e4565b9150838203604085015261329782888a61322b565b84810360608601528581529150808201600586811b84018301885f5b8981101561332157868303601f190185528135368c9003601e190181126132d8575f80fd5b8b0186810190356001600160401b038111156132f2575f80fd5b80861b3603821315613302575f80fd5b61330d85828461322b565b9688019694505050908501906001016132b3565b50909f9e505050505050505050505050505050565b606081525f61334960608301888a6131e4565b828103602084015261335c8187896131e4565b9050828103604084015261337181858761322b565b9998505050505050505050565b5f6020828403121561338e575f80fd5b5051919050565b5f602082840312156133a5575f80fd5b815161273681612fa3565b5f60a082840312156133c0575f80fd5b60405160a081018181106001600160401b03821117156133ee57634e487b7160e01b5f52604160045260245ffd5b60405282516133fc81612fa3565b8152602083015161340c81612fa3565b6020820152604083015161341f81612fa3565b6040820152606083015161343281612fa3565b60608201526080928301519281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561068a5761068a61344a565b8082018082111561068a5761068a61344a565b6001600160a01b03929092168252602082015260400190565b5f602082840312156134ad575f80fd5b815161273681612fb7565b5f60c082840312156134c8575f80fd5b60405160c081018181106001600160401b03821117156134f657634e487b7160e01b5f52604160045260245ffd5b604052825161350481612ffb565b8152602083015161351481612ffb565b6020820152604083015161352781612ffb565b6040820152606083015161353a81612ffb565b6060820152608083015161354d81612ffb565b608082015260a083015161356081612ffb565b60a08201529392505050565b6001600160801b0381811683821601908082111561358c5761358c61344a565b5092915050565b808202811582820484141761068a5761068a61344a565b5f602082840312156135ba575f80fd5b81516001600160601b0381168114612736575f80fd5b600181815b8085111561360a57815f19048211156135f0576135f061344a565b808516156135fd57918102915b93841c93908002906135d5565b509250929050565b5f826136205750600161068a565b8161362c57505f61068a565b8160018114613642576002811461364c57613668565b600191505061068a565b60ff84111561365d5761365d61344a565b50506001821b61068a565b5060208310610133831016604e8410600b841016171561368b575081810a61068a565b61369583836135d0565b805f19048211156136a8576136a861344a565b029392505050565b5f61273660ff841683613612565b634e487b7160e01b5f52601260045260245ffd5b5f826136e0576136e06136be565b500490565b5f602082840312156136f5575f80fd5b815160ff81168114612736575f80fd5b5f60ff831680613717576137176136be565b8060ff8416069150509291505056fe000000000000000000000000beef01735c132ada46aa9aa4c54623caa92a64cb000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4819dcce294f3f733802db88fa2ed6e61b236e4bc1c64033b1bdbdea45ebd5b6f5ab77c5852209a3e1fa0ff26f5df3855bab424a731e449d854807254ac995898ea2646970667358221220aeb56e6621b156d2d35d4eac82b2141c29f6c5611d22d21c3277de55c238a37664736f6c63430008180033

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106101bb575f3560e01c80636c3289b0116100f3578063d0120e0a11610093578063ee537c251161006e578063ee537c25146103d7578063ef58211c14610417578063f17c425e1461042a578063fecbe1c31461043d575f80fd5b8063d0120e0a14610395578063e702a367146103b0578063ed2f21f5146103c3575f80fd5b80638ccb1f12116100ce5780638ccb1f1214610341578063b140764f1461035c578063b7065d471461036f578063c530624914610382575f80fd5b80636c3289b01461031657806374a5b4a814610331578063888166b714610339575f80fd5b80632f09f4961161015e57806352a460d71161013957806352a460d7146102cd57806353e0ac09146102e057806363e2d3da146102fb5780636758f59a14610303575f80fd5b80632f09f496146102815780633acb3949146102ad5780634736a5c7146102b5575f80fd5b806320ea564e1161019957806320ea564e14610216578063210663e414610237578063219461ed1461024b5780632517b92b14610266575f80fd5b806308a01675146101bf5780631c8c463b146101f75780631f3257ed1461020c575b5f80fd5b6101da7387870bca3f3fd6335c3f4ce8392d69350b4fa4e281565b6040516001600160a01b0390911681526020015b60405180910390f35b6101ff610451565b6040516101ee9190612e07565b6102146104c2565b005b610229610224366004612e58565b610680565b6040519081526020016101ee565b6101da5f8051602061374783398151915281565b6101da733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6101da73c3d688b66703497daa19211eedff47f25384cdc381565b610289610690565b6040805182516001600160a01b0316815260209283015192810192909252016101ee565b6101ff610730565b6102bd61079d565b60405190151581526020016101ee565b6102146102db366004612e71565b6107ac565b6101da73377c3bd93f2a2984e1e7be6a5c22c525ed4a481581565b610229610905565b610229610311366004612e58565b610933565b6101da7398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c81565b610229610a0e565b610229610a37565b6101da73c13e21b648a5ee794902342038ff3adab66be98781565b61022961036a366004612e58565b610a40565b61021461037d366004612ee9565b610a4a565b610214610390366004612fc4565b610b57565b6101da731b0e765f6224c21223aea2af16c1c46e38885a4081565b6102146103be36600461300f565b610c23565b6102295f8051602061376783398151915281565b6103df610d3b565b6040805182516001600160801b0316815260208084015161ffff1690820152918101516001600160401b0316908201526060016101ee565b610214610425366004613068565b610d5f565b6102bd610438366004613090565b610ec7565b6101da5f8051602061372783398151915281565b60408051600480825260a08201909252606091602082016080803683370190505090505f5b60048110156104be57610499816003811115610494576104946130ab565b610ed1565b8282815181106104ab576104ab6130bf565b6020908102919091010152600101610476565b5090565b6104ca6112d6565b6040516320f0656b60e11b815273c3d688b66703497daa19211eedff47f25384cdc360048201523060248201525f90731b0e765f6224c21223aea2af16c1c46e38885a40906341e0cad69060440160408051808303815f875af1158015610533573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061055791906130d3565b905080602001515f0361057d576040516373380d9960e01b815260040160405180910390fd5b604051635b81a7bf60e11b815273c3d688b66703497daa19211eedff47f25384cdc3600482015230602482015260016044820152731b0e765f6224c21223aea2af16c1c46e38885a409063b7034f7e906064015f604051808303815f87803b1580156105e7575f80fd5b505af11580156105f9573d5f803e3d5ffd5b505050505f61060e631f3257ed60e01b611361565b602080840151604051929350631f3257ed60e01b926001600160a01b038516925f80516020613767833981519152925f805160206137878339815191529261065a920190815260200190565b60408051601f198184030181529082905261067491613134565b60405180910390a45050565b5f61068a826113a4565b92915050565b604080518082019091525f80825260208201526040516320f0656b60e11b815273c3d688b66703497daa19211eedff47f25384cdc360048201523060248201525f90731b0e765f6224c21223aea2af16c1c46e38885a40906341e0cad69060440160408051808303815f875af115801561070c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068a91906130d3565b60408051600480825260a08201909252606091602082016080803683370190505090505f5b60048110156104be57610778816003811115610773576107736130ab565b6113a4565b82828151811061078a5761078a6130bf565b6020908102919091010152600101610755565b5f6107a66114c1565b15919050565b5f6107b5611542565b9050336001600160a01b038216148015906107d657506107d433611570565b155b156107f457604051636ed04f9360e11b815260040160405180910390fd5b816003811115610806576108066130ab565b836003811115610818576108186130ab565b0361083657604051630e52390960e41b815260040160405180910390fd5b61083e6115ac565b5f610848846115f0565b90506108548382611bd6565b61087c427fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c3155565b5f61088d6352a460d760e01b611361565b90506352a460d760e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f805160206137878339815191528888876040516020016108dc939291906131a0565b60408051601f19818403018152908290526108f691613134565b60405180910390a45050505050565b5f61092e7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c305490565b905090565b5f8061093d611542565b9050336001600160a01b0382161480159061095e575061095c33611570565b155b1561097c57604051636ed04f9360e11b815260040160405180910390fd5b610985836115f0565b91505f6109986333ac7acd60e11b611361565b9050636758f59a60e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f8051602061378783398151915287876040516020016109e59291906131c9565b60408051601f19818403018152908290526109ff91613134565b60405180910390a45050919050565b5f61092e7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c315490565b5f61092e6114c1565b5f61068a82610ed1565b610a526112d6565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c090610a97908b908b908b908b908b908b908b908b9060040161325b565b5f604051808303815f87803b158015610aae575f80fd5b505af1158015610ac0573d5f803e3d5ffd5b505050505f610ad563b7065d4760e01b611361565b905063b7065d4760e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f805160206137878339815191528c8c8c8c8c8c604051602001610b2a96959493929190613336565b60408051601f1981840301815290829052610b4491613134565b60405180910390a4505050505050505050565b610b5f6112d6565b6001600160a01b038216610b8657604051630e52390960e41b815260040160405180910390fd5b5f610b9183836121fa565b90508015610c1e575f610baa63c530624960e01b611361565b604080516001600160a01b0387811660208301528615159282019290925291925063c530624960e01b91908316905f80516020613767833981519152905f80516020613787833981519152906060015b60408051601f1981840301815290829052610c1491613134565b60405180910390a4505b505050565b610c2b6112d6565b604080516060810182526001600160801b03851680825261ffff8516602083018190526001600160401b038516929093018290527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e805471ffffffffffffffffffffffffffffffffffff1916909117600160801b9093029290921767ffffffffffffffff60901b1916600160901b9091021790555f610cd063e702a36760e01b611361565b604080516001600160801b038716602082015261ffff8616918101919091526001600160401b038416606082015290915063e702a36760e01b906001600160a01b038316905f80516020613767833981519152905f8051602061378783398151915290608001610bfa565b604080516060810182525f808252602082018190529181019190915261092e6122eb565b5f610d68611542565b9050336001600160a01b03821614801590610d895750610d8733611570565b155b15610da757604051636ed04f9360e11b815260040160405180910390fd5b815f03610dc757604051630e52390960e41b815260040160405180910390fd5b610dd0836123dd565b6040516370a0823160e01b81523060048201525f905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015610e18573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e3c919061337e565b905082811015610e5f57604051631e9acf1760e31b815260040160405180910390fd5b610e698484611bd6565b5f610e7a633bd6084760e21b611361565b905063ef58211c60e01b6001600160e01b031916816001600160a01b03165f805160206137678339815191525f8051602061378783398151915288886040516020016108dc9291906131c9565b5f61068a82611570565b5f80826003811115610ee557610ee56130ab565b03611166575f5f8051602061372783398151915290505f816001600160a01b0316633acb56246040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f38573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f5c9190613395565b90505f826001600160a01b03166333f91ebb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f9b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fbf919061337e565b90505f805b828110156110dd576040516362518ddf60e01b8152600481018290525f906001600160a01b038716906362518ddf90602401602060405180830381865afa158015611011573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611035919061337e565b604051632c3c915760e01b8152600481018290529091505f906001600160a01b03871690632c3c91579060240160a060405180830381865afa15801561107d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a191906133b0565b90505f806110af8884612435565b50925050915080826110c1919061345e565b6110cb9087613471565b95505060019093019250610fc4915050565b506040516370a0823160e01b81526001600160a01b038416600482015261115c9082905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015611133573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611157919061337e565b61272b565b9695505050505050565b600182600381111561117a5761117a6130ab565b036111fe576040516370a0823160e01b815273c3d688b66703497daa19211eedff47f25384cdc360048201525f80516020613747833981519152906370a08231906024015b602060405180830381865afa1580156111da573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068a919061337e565b6002826003811115611212576112126130ab565b0361125b576040516370a0823160e01b81527398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c60048201525f80516020613747833981519152906370a08231906024016111bf565b600382600381111561126f5761126f6130ab565b036112b8576040516370a0823160e01b815273377c3bd93f2a2984e1e7be6a5c22c525ed4a481560048201525f80516020613747833981519152906370a08231906024016111bf565b60405163743f26e160e01b815260040160405180910390fd5b919050565b7f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f456600201546001600160a01b0316331461135f577f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f45854604051600162bed83560e01b031981523360048201526001600160a01b0390911660248201526044015b60405180910390fd5b565b6001600160e01b0319165f9081527f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f45660205260409020546001600160a01b031690565b5f808260038111156113b8576113b86130ab565b036113d1576113c63061273d565b509091506112d19050565b60018260038111156113e5576113e56130ab565b03611421576040516370a0823160e01b815230600482015273c3d688b66703497daa19211eedff47f25384cdc3906370a08231906024016111bf565b6002826003811115611435576114356130ab565b03611471576040516370a0823160e01b81523060048201527398c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c906370a08231906024016111bf565b6003826003811115611485576114856130ab565b036112b8576040516370a0823160e01b815230600482015273377c3bd93f2a2984e1e7be6a5c22c525ed4a4815906370a08231906024016111bf565b5f806114eb7fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c315490565b9050805f036114fb575f91505090565b5f6115046122eb565b6040015190505f61151e6001600160401b03831684613471565b9050804210611530575f935050505090565b61153a428261345e565b935050505090565b7f58da5b78f5c49ca84d5bba341c06bce7ec8aea952db936d0a51a1c7c5d79f458546001600160a01b031690565b6001600160a01b03165f9081527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2f602052604090205460ff1690565b5f6115b56114c1565b905080156115ed575f6115c88242613471565b60405163b388f18d60e01b815242600482015260248101829052909150604401611356565b50565b5f806115fb836113a4565b9050805f0361161d57604051632afc3c0d60e21b815260040160405180910390fd5b5f61162784610ed1565b9050805f036116525760405163a17e11d560e01b81525f600482015260248101839052604401611356565b5f61165d838361272b565b6040516370a0823160e01b815230600482015290915083831015905f905f80516020613747833981519152906370a0823190602401602060405180830381865afa1580156116ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116d1919061337e565b90505f8760038111156116e6576116e66130ab565b0361196e576040516370a0823160e01b81523060048201525f80516020613727833981519152905f9082906370a0823190602401602060405180830381865afa158015611735573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611759919061337e565b9050805f0361177b57604051632afc3c0d60e21b815260040160405180910390fd5b831561187657604051636c82bbbf60e11b81523060048201525f906001600160a01b0384169063d905777e90602401602060405180830381865afa1580156117c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e9919061337e565b90505f6117f6838361272b565b604051635d043b2960e11b815260048101829052306024820181905260448201529091506001600160a01b0385169063ba087652906064016020604051808303815f875af115801561184a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186e919061337e565b505050611967565b60405163ce96cb7760e01b81523060048201525f906001600160a01b0384169063ce96cb7790602401602060405180830381865afa1580156118ba573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118de919061337e565b90505f6118eb878361272b565b604051632d182be560e21b815260048101829052306024820181905260448201529091506001600160a01b0385169063b460af94906064016020604051808303815f875af115801561193f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611963919061337e565b5050505b5050611b3c565b6001876003811115611982576119826130ab565b03611a08575f826119935783611996565b5f195b60405163f3fef3a360e01b815290915073c3d688b66703497daa19211eedff47f25384cdc39063f3fef3a3906119df905f80516020613747833981519152908590600401613484565b5f604051808303815f87803b1580156119f6575f80fd5b505af1158015611963573d5f803e3d5ffd5b6002876003811115611a1c57611a1c6130ab565b03611ac0575f82611a2d5783611a30565b5f195b604051631a4ca37b60e21b81525f805160206137478339815191526004820152602481018290523060448201529091507387870bca3f3fd6335c3f4ce8392d69350b4fa4e2906369328dec906064015b6020604051808303815f875af1158015611a9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611967919061337e565b6003876003811115611ad457611ad46130ab565b036112b8575f82611ae55783611ae8565b5f195b604051631a4ca37b60e21b81525f8051602061374783398151915260048201526024810182905230604482015290915073c13e21b648a5ee794902342038ff3adab66be987906369328dec90606401611a80565b6040516370a0823160e01b81523060048201525f905f80516020613747833981519152906370a0823190602401602060405180830381865afa158015611b84573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba8919061337e565b905081811015611bcb57604051631d42c86760e21b815260040160405180910390fd5b039695505050505050565b5f826003811115611be957611be96130ab565b03611d605760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611c2d905f80516020613727833981519152905f90600401613484565b6020604051808303815f875af1158015611c49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c6d919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611cad905f80516020613727833981519152908590600401613484565b6020604051808303815f875af1158015611cc9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ced919061349d565b50604051636e553f6560e01b8152600481018290523060248201525f8051602061372783398151915290636e553f65906044016020604051808303815f875af1158015611d3c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c1e919061337e565b6001826003811115611d7457611d746130ab565b03611efe5760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611dbf9073c3d688b66703497daa19211eedff47f25384cdc3905f90600401613484565b6020604051808303815f875af1158015611ddb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dff919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611e469073c3d688b66703497daa19211eedff47f25384cdc3908590600401613484565b6020604051808303815f875af1158015611e62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e86919061349d565b50604051631e573fb760e31b815273c3d688b66703497daa19211eedff47f25384cdc39063f2b9fdb890611ecd905f80516020613747833981519152908590600401613484565b5f604051808303815f87803b158015611ee4575f80fd5b505af1158015611ef6573d5f803e3d5ffd5b505050505050565b6002826003811115611f1257611f126130ab565b0361207c5760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611f5d907387870bca3f3fd6335c3f4ce8392d69350b4fa4e2905f90600401613484565b6020604051808303815f875af1158015611f79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f9d919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b390611fe4907387870bca3f3fd6335c3f4ce8392d69350b4fa4e2908590600401613484565b6020604051808303815f875af1158015612000573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612024919061349d565b5060405163617ba03760e01b81525f805160206137478339815191526004820152602481018290523060448201525f60648201527387870bca3f3fd6335c3f4ce8392d69350b4fa4e29063617ba03790608401611ecd565b6003826003811115612090576120906130ab565b036112b85760405163095ea7b360e01b81525f805160206137478339815191529063095ea7b3906120db9073c13e21b648a5ee794902342038ff3adab66be987905f90600401613484565b6020604051808303815f875af11580156120f7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061211b919061349d565b5060405163095ea7b360e01b81525f805160206137478339815191529063095ea7b3906121629073c13e21b648a5ee794902342038ff3adab66be987908590600401613484565b6020604051808303815f875af115801561217e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121a2919061349d565b5060405163617ba03760e01b81525f805160206137478339815191526004820152602481018290523060448201525f606482015273c13e21b648a5ee794902342038ff3adab66be9879063617ba03790608401611ecd565b6001600160a01b0382165f9081527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2f60205260408120547fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e9060ff1683156122a457801561226c575f9250505061068a565b506001600160a01b0384165f90815260018281016020526040909120805460ff1916821790556002909101805482019055905061068a565b806122b3575f9250505061068a565b506001600160a01b0384165f90815260018083016020526040909120805460ff19169055600290910180545f19019055905092915050565b604080516060810182525f8082526020820181905291810191909152612388604080516060810182525f80825260208201819052918101919091527fd889dcd6a8adf978a15d14e5190acdc0773d19c32c6617082a300e17aae31c2e6040805160608101825291546001600160801b0381168352600160801b810461ffff166020840152600160901b90046001600160401b031690820152919050565b80519091506001600160801b03165f036123a657652d79883d200081525b806020015161ffff165f036123bd5760c860208201525b80604001516001600160401b03165f036123da5761384060408201525b90565b5f6123e66122eb565b90505f6123f283610ed1565b82519091506001600160801b0316811015610c1e57815160405163a17e11d560e01b8152600481018390526001600160801b039091166024820152604401611356565b5f805f805f6124458660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa15801561248d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124b191906134b8565b90505f81608001516001600160801b0316426124cd919061345e565b905080158015906124ea575060408201516001600160801b031615155b8015612502575060608801516001600160a01b031615155b156126f7576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa1580156125d1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125f5919061337e565b90505f6126196126058385612855565b60408601516001600160801b0316906128b3565b9050612624816128c7565b84604001818151612635919061356c565b6001600160801b031690525061264a816128c7565b8451859061265990839061356c565b6001600160801b0390811690915260a0860151161590506126f4575f6126958560a001516001600160801b0316836128b390919063ffffffff16565b90505f6126c982875f01516001600160801b03166126b3919061345e565b60208801518491906001600160801b0316612916565b90506126d4816128c7565b866020018181516126e5919061356c565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f8282188284100282185b9392505050565b5f805f80612749612942565b8093508192505050805f805160206137278339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561279b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127bf919061337e565b6127c99190613471565b6040516370a0823160e01b81526001600160a01b038716600482015290935061284b905f80516020613727833981519152906370a0823190602401602060405180830381865afa15801561281f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612843919061337e565b84845f612bce565b9350509193909250565b5f806128618385613593565b90505f612881828061287c670de0b6b3a76400006002613593565b612c0c565b90505f61289c828461287c670de0b6b3a76400006003613593565b9050806128a98385613471565b61115c9190613471565b5f6127368383670de0b6b3a7640000612c0c565b5f6001600160801b038211156104be5760405162461bcd60e51b81526020600482015260146024820152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b6044820152606401611356565b5f61293a612927620f424084613471565b612932600186613471565b869190612c0c565b949350505050565b5f805f805160206137278339815191526001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561298d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b1919061337e565b90505f612a2e5f805160206137278339815191526001600160a01b031663568efc076040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a00573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a24919061337e565b8084039084110290565b90508015801590612ab357505f805160206137278339815191526001600160a01b031663ddca3f436040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a83573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aa791906135aa565b6001600160601b031615155b15612bc9575f612b425f805160206137278339815191526001600160a01b031663ddca3f436040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b05573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b2991906135aa565b83906001600160601b0316670de0b6b3a7640000612c22565b9050612bc5815f805160206137278339815191526001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b91573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb5919061337e565b612bbf848761345e565b5f612cd2565b9350505b509091565b5f612c03612bdd846001613471565b612be5612cfe565b612bf090600a6136b0565b612bfa9087613471565b87919085612d6c565b95945050505050565b5f81612c188486613593565b61293a91906136d2565b5f805f612c2f8686612dae565b91509150815f03612c5357838181612c4957612c496136be565b0492505050612736565b818411612c6a57612c6a6003851502601118612dca565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f612c03612cde612cfe565b612ce990600a6136b0565b612cf39086613471565b612bfa856001613471565b5f5f805160206137278339815191526001600160a01b031663aea70acc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d48573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092e91906136e5565b5f612d99612d7983612ddb565b8015612d9457505f8480612d8f57612d8f6136be565b868809115b151590565b612da4868686612c22565b612c039190613471565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b5f6002826003811115612df057612df06130ab565b612dfa9190613705565b60ff166001149050919050565b602080825282518282018190525f9190848201906040850190845b81811015612e3e57835183529284019291840191600101612e22565b50909695505050505050565b8035600481106112d1575f80fd5b5f60208284031215612e68575f80fd5b61273682612e4a565b5f8060408385031215612e82575f80fd5b612e8b83612e4a565b9150612e9960208401612e4a565b90509250929050565b5f8083601f840112612eb2575f80fd5b5081356001600160401b03811115612ec8575f80fd5b6020830191508360208260051b8501011115612ee2575f80fd5b9250929050565b5f805f805f805f806080898b031215612f00575f80fd5b88356001600160401b0380821115612f16575f80fd5b612f228c838d01612ea2565b909a50985060208b0135915080821115612f3a575f80fd5b612f468c838d01612ea2565b909850965060408b0135915080821115612f5e575f80fd5b612f6a8c838d01612ea2565b909650945060608b0135915080821115612f82575f80fd5b50612f8f8b828c01612ea2565b999c989b5096995094979396929594505050565b6001600160a01b03811681146115ed575f80fd5b80151581146115ed575f80fd5b5f8060408385031215612fd5575f80fd5b8235612fe081612fa3565b91506020830135612ff081612fb7565b809150509250929050565b6001600160801b03811681146115ed575f80fd5b5f805f60608486031215613021575f80fd5b833561302c81612ffb565b9250602084013561ffff81168114613042575f80fd5b915060408401356001600160401b038116811461305d575f80fd5b809150509250925092565b5f8060408385031215613079575f80fd5b61308283612e4a565b946020939093013593505050565b5f602082840312156130a0575f80fd5b813561273681612fa3565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f604082840312156130e3575f80fd5b604051604081018181106001600160401b038211171561311157634e487b7160e01b5f52604160045260245ffd5b604052825161311f81612fa3565b81526020928301519281019290925250919050565b5f602080835283518060208501525f5b8181101561316057858101830151858201604001528201613144565b505f604082860101526040601f19601f8301168501019250505092915050565b6004811061319c57634e487b7160e01b5f52602160045260245ffd5b9052565b606081016131ae8286613180565b6131bb6020830185613180565b826040830152949350505050565b604081016131d78285613180565b8260208301529392505050565b8183525f60208085019450825f5b8581101561322057813561320581612fa3565b6001600160a01b0316875295820195908201906001016131f2565b509495945050505050565b8183525f6001600160fb1b03831115613242575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f61326e608083018a8c6131e4565b602083820381850152613282828a8c6131e4565b9150838203604085015261329782888a61322b565b84810360608601528581529150808201600586811b84018301885f5b8981101561332157868303601f190185528135368c9003601e190181126132d8575f80fd5b8b0186810190356001600160401b038111156132f2575f80fd5b80861b3603821315613302575f80fd5b61330d85828461322b565b9688019694505050908501906001016132b3565b50909f9e505050505050505050505050505050565b606081525f61334960608301888a6131e4565b828103602084015261335c8187896131e4565b9050828103604084015261337181858761322b565b9998505050505050505050565b5f6020828403121561338e575f80fd5b5051919050565b5f602082840312156133a5575f80fd5b815161273681612fa3565b5f60a082840312156133c0575f80fd5b60405160a081018181106001600160401b03821117156133ee57634e487b7160e01b5f52604160045260245ffd5b60405282516133fc81612fa3565b8152602083015161340c81612fa3565b6020820152604083015161341f81612fa3565b6040820152606083015161343281612fa3565b60608201526080928301519281019290925250919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561068a5761068a61344a565b8082018082111561068a5761068a61344a565b6001600160a01b03929092168252602082015260400190565b5f602082840312156134ad575f80fd5b815161273681612fb7565b5f60c082840312156134c8575f80fd5b60405160c081018181106001600160401b03821117156134f657634e487b7160e01b5f52604160045260245ffd5b604052825161350481612ffb565b8152602083015161351481612ffb565b6020820152604083015161352781612ffb565b6040820152606083015161353a81612ffb565b6060820152608083015161354d81612ffb565b608082015260a083015161356081612ffb565b60a08201529392505050565b6001600160801b0381811683821601908082111561358c5761358c61344a565b5092915050565b808202811582820484141761068a5761068a61344a565b5f602082840312156135ba575f80fd5b81516001600160601b0381168114612736575f80fd5b600181815b8085111561360a57815f19048211156135f0576135f061344a565b808516156135fd57918102915b93841c93908002906135d5565b509250929050565b5f826136205750600161068a565b8161362c57505f61068a565b8160018114613642576002811461364c57613668565b600191505061068a565b60ff84111561365d5761365d61344a565b50506001821b61068a565b5060208310610133831016604e8410600b841016171561368b575081810a61068a565b61369583836135d0565b805f19048211156136a8576136a861344a565b029392505050565b5f61273660ff841683613612565b634e487b7160e01b5f52601260045260245ffd5b5f826136e0576136e06136be565b500490565b5f602082840312156136f5575f80fd5b815160ff81168114612736575f80fd5b5f60ff831680613717576137176136be565b8060ff8416069150509291505056fe000000000000000000000000beef01735c132ada46aa9aa4c54623caa92a64cb000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4819dcce294f3f733802db88fa2ed6e61b236e4bc1c64033b1bdbdea45ebd5b6f5ab77c5852209a3e1fa0ff26f5df3855bab424a731e449d854807254ac995898ea2646970667358221220aeb56e6621b156d2d35d4eac82b2141c29f6c5611d22d21c3277de55c238a37664736f6c63430008180033

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

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