ETH Price: $2,950.83 (-0.17%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Transfer236914262025-10-30 16:35:1186 days ago1761842111IN
0x87869357...d89ce618d
0 ETH0.000085511.65062198
Initialize Pool ...236914112025-10-30 16:31:5986 days ago1761841919IN
0x87869357...d89ce618d
1.00000198 ETH0.000335560.61595669

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Method Block
From
To
Modify Liquiditi...236914112025-10-30 16:31:5986 days ago1761841919
0x87869357...d89ce618d
1.00000198 ETH
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

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xa802b0c3...9084c6A98
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
MemeStrategy

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 39 : MemeStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&-MEMS2025-&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&                         &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%    %%%%%%%%#    %%    &&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%    %%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%    %%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%            ,%%%%%%    &&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%            ,%%%%%%%%%%    &&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    &&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%    %%%%%%%%    &&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&    %%%%%%%%%%%%%%%%%%%%%    %%%%%%%%    &&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&                     &&&&        &&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

      ╔═══════════════════════════════════════════════════════════════╗
      ║               MEMESTRATEGY | MEMS - by Yokai Works            ║
      ║            The Perpetual Meme Token Flipping Machine          ║
      ╚═══════════════════════════════════════════════════════════════╝
*/

import {Ownable} from "solady/auth/Ownable.sol";
import {ERC20} from "solady/tokens/ERC20.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {IWETH} from "./interfaces/IWETH.sol";
import {IMemeStrategyHook} from "./interfaces/IMemeStrategyHook.sol";
import {IUniswapV2Router} from "./interfaces/IUniswapV2Router.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
    function transfer(address, uint256) external;
    function approve(address, uint256) external;
    function decimals() external view returns (uint8);
}

interface IUnlockCallback {
    function unlockCallback(
        bytes calldata data
    ) external returns (bytes memory);
}

/// @title MemeStrategy - The Perpetual Meme Token Flipping Machine
/// @author YokaiWorks (https://yokai.works/)
/// @notice MEMS is an innovative DeFi protocol that combines automated meme token trading
///         through a queue-based system, dynamic fee collection via a Uniswap V4 hook with
///         a 3-phase fee system, a buyback and burn mechanism that automatically uses profits
///         to repurchase and burn MEMS tokens, and treasury operations that allocate 80% of
///         fees to the strategy while 20% goes to the treasury as rake.
/// @dev Uses Uniswap V2 Router for meme token swaps (with fee-on-transfer support),
///      V4 unlock pattern for MEMS buyback & burn
contract MemeStrategy is ERC20, Ownable, ReentrancyGuard, IUnlockCallback {
    using CurrencyLibrary for Currency;

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                   STRUCTS                                    */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    struct MemeToken {
        address v2Router;
        bool isWhitelisted;
    }

    struct QueuedPurchase {
        uint256 queueId;
        address targetAddress;
        uint256 ethAmount;
        uint256 targetMultiplier;
        uint256 maxSlippage;
        uint256 targetEntryPrice;
        uint256 queuedAt;
        bool executed;
        bool exists;
        bool executeToTreasury; // If true, use executeSaleToTreasury(); if false, use executeSale()
    }

    struct Purchase {
        uint256 purchaseId;
        address tokenAddress;      // Token address
        uint256 tokenAmount;       // Amount of tokens received
        uint256 buyPricePerUnit;   // ETH per token
        uint256 targetPrice;       // Calculated from targetMultiplier
        uint256 ethSpent;          // Native ETH spent
        uint256 timestamp;
        bool sold;
        uint256 soldPrice;
        uint256 soldTimestamp;
        bool isProfit;
        uint256 profitOrLoss;
        uint256 slippageUsed;
        bool executeToTreasury; // If true, must use executeSaleToTreasury(); if false, must use executeSale()
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                  CONSTANTS                                   */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    IPoolManager private immutable POOL_MANAGER;
    IPositionManager private immutable POSM;
    IAllowanceTransfer private immutable PERMIT2;
    IWETH private immutable WETH;

    uint256 public constant MAX_SUPPLY = 1_000_000_000 * 1e18;
    uint256 public constant BPS_BASE = 10_000;
    uint256 public constant MIN_MULTIPLIER = 200;      // 2% min
    uint256 public constant MAX_MULTIPLIER = 990_000;  // 9900% max (100x total return)
    uint256 public constant MAX_SLIPPAGE = 5_000;      // 50% max
    uint256 public constant MAX_BATCH_SIZE = 50;

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                STATE VARIABLES                               */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    // Trading Control (Anti-Snipe)
    bool public tradingEnabled;

    // Access Control (Operators)
    mapping(address => bool) public operators;

    // Fee Management
    uint256 public executorReward;

    // Slippage Protection
    uint256 public maxSaleSlippage;  // Max slippage when selling meme tokens
    uint256 public maxBuybackSlippage; // Max slippage when buying back MEMS tokens (default: 500 = 5%)
    uint256 public minForceSellBPS; // Min return % of original cost in forceSell (default: 5000 = 50%)

    // Pool Configuration
    address public hookAddress;
    bool public poolInitialized;     // Track if pool has been initialized

    // Purchase Tracking
    uint256 public totalPurchases;
    uint256 public totalQueues;
    mapping(uint256 => Purchase) public purchases;
    mapping(address => MemeToken) public whitelistedTokens;

    // Queue System (Backend-Managed FIFO)
    // Backend listens to events and maintains queue order off-chain
    // Contract only stores by ID for gas efficiency
    mapping(uint256 => QueuedPurchase) public queuedPurchases;
    uint256 public nextQueueId = 1;     // Auto-incrementing ID counter
    uint256 public activeQueueCount;    // Number of items currently in queue

    // Statistics
    uint256 public totalProfit;
    uint256 public totalLoss;
    uint256 public totalTokensBurned;
    uint256 public successfulFlips;  // Used for phase transition (successfulFlips == 0)
    uint256 public failedFlips;

    // Pause State
    bool public paused;

    // Risk Management
    uint256 public maxSinglePurchase;
    uint256 public minSpikeThreshold; // Min ETH to trigger fee spikes
    uint256 public maxQueueSize;      // Max queue items (0 = unlimited, for spam/risk management)
    mapping(address => bool) public approvedRouters;

    // Module System (inline, replaces external ModuleManager)
    mapping(address => bool) public whitelistedModules;

    // Active Purchases Tracking (Backend-Managed)
    // Backend listens to TokenPurchaseExecuted and TokenSaleExecuted events
    // to maintain list of active purchases off-chain for gas efficiency
    uint256 public activePurchaseCount;

    // Callback Protection
    bool private _unlockInProgress;

    // Force Operation Protection (prevents cross-function reentrancy)
    bool private _forceOperationInProgress;

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                    EVENTS                                    */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    // Access Control Events
    event TradingEnabled(uint256 timestamp);
    event OperatorAdded(address indexed operator);
    event OperatorRemoved(address indexed operator);

    // Whitelist Events
    event MemeTokenWhitelisted(address indexed token, address indexed router);
    event MemeTokenDelisted(address indexed token);

    // Queue Events
    event TokenPurchaseQueued(
        uint256 indexed queueId,
        address indexed tokenAddress,
        address router,
        uint256 ethAmount,
        uint256 targetMultiplier,
        uint256 maxSlippage,
        uint256 targetEntryPrice,
        address indexed queuedBy,
        uint256 treasuryBalance,
        uint256 timestamp
    );
    event QueueCleared(uint256 indexed queueId);
    event QueueRemoved(uint256 indexed queueId);

    // Execution Events
    event TokenPurchaseExecuted(
        uint256 indexed purchaseId,
        uint256 indexed queueId,
        address indexed tokenAddress,
        address executor,
        uint256 ethSpent,
        uint256 tokenAmount,
        uint8 tokenDecimals,
        uint256 buyPricePerToken,
        uint256 targetPrice,
        uint256 targetMultiplier,
        uint256 slippageUsed,
        bool executeToTreasury,
        uint256 timestamp
    );

    event TokenSaleExecuted(
        uint256 indexed purchaseId,
        address indexed tokenAddress,
        address indexed executor,
        uint256 tokenAmount,
        uint256 ethReceived,
        uint256 ethSpent,
        bool isProfit,
        uint256 profitOrLossAmount,
        uint256 memsBurned,
        uint256 executorReward,
        uint256 buyPrice,
        uint256 sellPrice,
        uint256 holdingDuration,
        bool isFirstSale,
        bool toTreasury,
        uint256 timestamp
    );

    event ForceSold(
        uint256 indexed purchaseId,
        uint256 ethReceived,
        bool isProfit,
        uint256 amount,
        uint256 tokensBurned,
        bool toTreasury
    );
    event ForceBurn(
        address indexed initiator,
        uint256 ethUsed,
        uint256 tokensBurned,
        uint256 timestamp
    );

    // System Events
    event FeesAdded(uint256 amount, uint256 newTotal, address indexed from);
    event TokensBurned(uint256 ethSpent, uint256 amount, uint256 totalBurned);
    event EmergencyETHWithdraw(uint256 amount, address indexed to);
    event EmergencyWithdraw(address indexed token, uint256 amount, address to);
    event ModuleAdded(address indexed module);
    event ModuleRemoved(address indexed module);

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                   ERRORS                                     */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    error OnlyOwnerOrOperator();
    error NotAuthorized();
    error InvalidAmount();
    error TokenNotWhitelisted();
    error NoQueueExists();
    error PurchaseNotFound();
    error AlreadyProcessed();
    error WrongExecutionFunction();
    error TargetNotReached();
    error ContractPaused();
    error InvalidAddress();
    error CannotWithdrawStrategyToken();
    error RouterNotApproved();
    error PoolLiquidityTooLow();
    error InvalidCurrency();
    error RouterWETHMismatch();
    error NoV2Liquidity();
    error ModuleNotWhitelisted();
    error PriceCalculationOverflow();
    error ForceOperationInProgress();
    error QueueFull();

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                  MODIFIERS                                   */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    modifier whenNotPaused() {
        if (paused) revert ContractPaused();
        _;
    }

    modifier validSlippage(uint256 slippage) {
        if (slippage > MAX_SLIPPAGE) revert InvalidAmount();
        _;
    }

    modifier onlyOwnerOrOperator() {
        if (msg.sender != owner() && !operators[msg.sender])
            revert OnlyOwnerOrOperator();
        _;
    }

    modifier noForceOperationReentrancy() {
        if (_forceOperationInProgress) revert ForceOperationInProgress();
        _forceOperationInProgress = true;
        _;
        _forceOperationInProgress = false;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                 CONSTRUCTOR                                  */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    constructor(
        address _owner,
        address _posm,
        address _permit2,
        address _weth
    ) {
        if (_weth == address(0)) revert InvalidAddress();
        
        POSM = IPositionManager(_posm);
        POOL_MANAGER = POSM.poolManager();
        PERMIT2 = IAllowanceTransfer(_permit2);
        WETH = IWETH(_weth);

        _initializeOwner(_owner);

        // Set defaults
        executorReward = 0.01 ether;
        maxSaleSlippage = 500; // 5%
        maxBuybackSlippage = 500; // 5% - slippage protection for MEMS buybacks
        maxSinglePurchase = 50 ether; // Global max per purchase
        minSpikeThreshold = 2 ether; // Min ETH to trigger fee spikes
        minForceSellBPS = 5000; // 50% - force sell must return at least 50% of original cost
        maxQueueSize = 0; // Unlimited by default (set to limit for spam/risk management)
    }

    /// @notice Returns the name of the token
    function name() public pure override returns (string memory) {
        return "MemeStrategy";
    }

    /// @notice Returns the symbol of the token
    function symbol() public pure override returns (string memory) {
        return "MEMS";
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          SAFE MATH HELPERS                                   */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Safely calculate price per token with overflow protection
    /// @dev Uses checked arithmetic to prevent overflow in (amount * precision) / tokens
    /// @param ethAmount Amount of ETH spent (in wei)
    /// @param tokenAmount Amount of tokens received (in token's base units)
    /// @param tokenAddress Address of the token to get decimals
    /// @return pricePerToken Price in wei per full token (e.g., for 9 decimals: wei per 1e9 base units)
    function _safePriceCalculation(
        uint256 ethAmount,
        uint256 tokenAmount,
        address tokenAddress
    ) internal view returns (uint256 pricePerToken) {
        if (tokenAmount == 0) revert InvalidAmount();

        // Get token decimals
        uint8 decimals = IERC20(tokenAddress).decimals();
        uint256 decimalMultiplier = 10 ** decimals;

        // Check if multiplication would overflow
        if (ethAmount > type(uint256).max / decimalMultiplier) revert PriceCalculationOverflow();

        // Calculate price per full token: (ethAmount * 10^decimals) / tokenAmount
        // This gives us wei per full token
        pricePerToken = (ethAmount * decimalMultiplier) / tokenAmount;

        return pricePerToken;
    }

    /// @notice Safely calculate target price with multiplier
    /// @dev Prevents overflow in (price * multiplier) calculation
    /// @param basePrice Base price per token
    /// @param multiplierBPS Target multiplier in basis points (10000 = 100%)
    /// @return targetPrice Target price including multiplier
    function _safeTargetPriceCalculation(
        uint256 basePrice,
        uint256 multiplierBPS
    ) internal pure returns (uint256 targetPrice) {
        // Calculate total multiplier (base + target)
        uint256 totalMultiplier = BPS_BASE + multiplierBPS;

        // Check if multiplication would overflow
        if (basePrice > type(uint256).max / totalMultiplier) revert PriceCalculationOverflow();

        // Safe to multiply now
        targetPrice = (basePrice * totalMultiplier) / BPS_BASE;

        return targetPrice;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          ADMIN - ACCESS CONTROL                              */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Initialize V4 pool and add initial liquidity (one-time, owner only)
    /// @dev Atomically initializes pool and adds liquidity. LP NFT sent to owner.
    ///      Uses ONLY msg.value for ETH (preserves any treasury ETH already accrued)
    /// @param _hook Hook address for the pool
    /// @param liquidity Amount of liquidity to add
    /// @param sqrtPriceX96 Starting price (79228162514264337593543950336 for 1:1)
    /// @param tickLower Lower tick for position (e.g., -887220)
    /// @param tickUpper Upper tick for position (e.g., 887220)
    function initializePoolAndAddLiquidity(
        address _hook,
        uint128 liquidity,
        uint160 sqrtPriceX96,
        int24 tickLower,
        int24 tickUpper
    ) external payable onlyOwner nonReentrant {
        if (poolInitialized) revert AlreadyProcessed();
        if (_hook == address(0)) revert InvalidAddress();
        if (liquidity == 0) revert InvalidAmount();
        if (msg.value == 0) revert InvalidAmount();

        uint256 amount0Max = msg.value;
        uint256 amount1Max = MAX_SUPPLY;

        _mint(address(this), MAX_SUPPLY);
        hookAddress = _hook;
        PoolKey memory strategyPoolKey = PoolKey({
            currency0: Currency.wrap(address(0)),       // Native ETH (v1.1)
            currency1: Currency.wrap(address(this)),    // MEMS token
            fee: 0,                                     // 0% pool fee (hook collects via deltas)
            tickSpacing: 60,
            hooks: IHooks(_hook)
        });

        // Validate PoolKey configuration
        if (Currency.unwrap(strategyPoolKey.currency0) != address(0))
            revert InvalidCurrency();
        if (Currency.unwrap(strategyPoolKey.currency1) != address(this))
            revert InvalidCurrency();

        // 1. Initialize the pool
        POSM.initializePool(strategyPoolKey, sqrtPriceX96);

        // 2. Approve MEMS to Permit2 and PositionManager (temporary)
        approve(address(PERMIT2), type(uint256).max);
        PERMIT2.approve(address(this), address(POSM), type(uint160).max, uint48(block.timestamp + 300));

        bytes memory actions = abi.encodePacked(uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR));

        bytes[] memory mintParams = new bytes[](2);
        mintParams[0] = abi.encode(strategyPoolKey, tickLower, tickUpper, liquidity, amount0Max, amount1Max, owner(), "");
        mintParams[1] = abi.encode(strategyPoolKey.currency0, strategyPoolKey.currency1);
        POSM.modifyLiquidities{value: amount0Max}(abi.encode(actions, mintParams), block.timestamp + 300);

        // 3. Revoke Permit2 approval for tighter security (only needed during initialization)
        // approve(address(PERMIT2), 0);

        poolInitialized = true;
        // Pool initialized
    }

    /// @notice Enable token transfers (one-time, irreversible)
    /// @dev Call this in bundle launch to open trading (owner or operator)
    function enableTrading() external onlyOwnerOrOperator {
        if (tradingEnabled) revert AlreadyProcessed();
        tradingEnabled = true;
        emit TradingEnabled(block.timestamp);
    }

    /// @notice Add operator for day-to-day operations
    function addOperator(address _operator) external onlyOwner {
        if (_operator == address(0)) revert InvalidAddress();
        if (!operators[_operator]) {
            operators[_operator] = true;
            emit OperatorAdded(_operator);
        }
    }

    /// @notice Remove operator
    function removeOperator(address _operator) external onlyOwner {
        if (operators[_operator]) {
            operators[_operator] = false;
            emit OperatorRemoved(_operator);
        }
    }


    /// @notice Override transfer to enforce trading enabled
    /// @dev Allows transfers before trading for:
    ///      - Owner transfers
    ///      - Contract-initiated transfers (pool initialization)
    ///      - Transfers to/from POSM and POOL_MANAGER (liquidity operations)
    ///      - Burning (to == address(0))
    /// @notice Override transfer to enforce trading enabled
    /// @dev Before trading enabled, ONLY these senders are allowed:
    ///      - Owner
    ///      - Contract itself (for pool initialization)
    ///      - POSM (for liquidity operations)
    ///      - POOL_MANAGER (for pool operations)
    ///      Also allows burning (to == address(0))
    function transfer(
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        if (!tradingEnabled) {
            // Whitelist: only specific senders can transfer before trading
            bool isAllowedSender =
                msg.sender == owner() ||
                msg.sender == address(this) ||
                msg.sender == address(POSM) ||
                msg.sender == address(POOL_MANAGER);

            // Allow burning
            bool isBurn = to == address(0);

            // Restrict POOL_MANAGER destinations before trading enabled (anti-snipe)
            // Prevents swaps to random users while allowing liquidity operations
            if (msg.sender == address(POOL_MANAGER)) {
                bool isAllowedDestination =
                    to == address(POOL_MANAGER) ||
                    to == address(POSM) ||
                    to == owner() ||
                    to == address(this) ||
                    to == address(0); // burning
                
                if (!isAllowedDestination) {
                    revert ContractPaused();
                }
            }

            if (!isAllowedSender && !isBurn) {
                revert ContractPaused();
            }
        }
        return super.transfer(to, amount);
    }

    /// @notice Override transferFrom to enforce trading enabled
    /// @dev Before trading enabled, ONLY these are allowed:
    ///      - POSM or POOL_MANAGER as caller (for liquidity operations)
    ///      - Owner as sender (owner-initiated transfers)
    ///      - Contract as sender (contract-initiated transfers)
    ///      - Minting/burning (from/to == address(0))
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        if (!tradingEnabled) {
            // Whitelist: POSM and POOL_MANAGER can call transferFrom
            bool isAllowedCaller =
                msg.sender == address(POSM) ||
                msg.sender == address(POOL_MANAGER);

            // Whitelist: Owner and contract can be the 'from' address
            bool isAllowedFrom =
                from == owner() ||
                from == address(this);

            // Allow minting/burning
            bool isMintOrBurn = from == address(0) || to == address(0);

            // Restrict POOL_MANAGER destinations before trading enabled (anti-snipe)
            // Prevents swaps to random users while allowing liquidity operations
            if (msg.sender == address(POOL_MANAGER)) {
                bool isAllowedDestination =
                    to == address(POOL_MANAGER) ||
                    to == address(POSM) ||
                    to == owner() ||
                    to == address(this) ||
                    to == address(0); // burning
                
                if (!isAllowedDestination) {
                    revert ContractPaused();
                }
            }

            if (!isAllowedCaller && !isAllowedFrom && !isMintOrBurn) {
                revert ContractPaused();
            }
        }
        return super.transferFrom(from, to, amount);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                            ADMIN - WHITELIST MANAGEMENT                      */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Add meme token to whitelist
    /// @param _token Token address
    /// @param _v2Router Router address (typically Universal Router)
    function addMemeToken(
        address _token,
        address _v2Router
    ) external onlyOwnerOrOperator {
        if (_token == address(0) || _v2Router == address(0))
            revert InvalidAddress();
        if (!approvedRouters[_v2Router]) revert RouterNotApproved();

        if (!whitelistedTokens[_token].isWhitelisted) {
            whitelistedTokens[_token] = MemeToken({
                v2Router: _v2Router,
                isWhitelisted: true
            });

            emit MemeTokenWhitelisted(_token, _v2Router);
        }
    }

    /// @notice Remove meme token from whitelist
    function removeMemeToken(address _token) external onlyOwnerOrOperator {
        if (!whitelistedTokens[_token].isWhitelisted)
            revert TokenNotWhitelisted();
        whitelistedTokens[_token].isWhitelisted = false;
        emit MemeTokenDelisted(_token);
    }

    /// @notice Update V2 router for whitelisted token
    /// @param _token Token address
    /// @param _newRouter New V2 router address
    function updateTokenRouter(
        address _token,
        address _newRouter
    ) external onlyOwner {
        if (_newRouter == address(0)) revert InvalidAddress();
        if (!approvedRouters[_newRouter]) revert RouterNotApproved();
        if (!whitelistedTokens[_token].isWhitelisted)
            revert TokenNotWhitelisted();

        whitelistedTokens[_token].v2Router = _newRouter;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                            ADMIN - QUEUE MANAGEMENT                          */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Queue meme token purchase with custom target (FIFO)
    /// @param _token Token address (must be whitelisted)
    /// @param _ethAmount ETH to spend (native)
    /// @param _targetMultiplier Target profit in BPS (10000 = 100% = 2x)
    /// @param _maxSlippage Max slippage in BPS
    /// @param _targetEntryPrice Max price to pay per token (in ETH, 1e18 precision), 0 = execute at any price
    function queueMemePurchase(
        address _token,
        uint256 _ethAmount,
        uint256 _targetMultiplier,
        uint256 _maxSlippage,
        uint256 _targetEntryPrice,
        bool _executeToTreasury
    )
        external
        onlyOwnerOrOperator
        validSlippage(_maxSlippage)
        returns (uint256 queueId)
    {
        MemeToken memory tokenInfo = whitelistedTokens[_token];
        if (!tokenInfo.isWhitelisted) revert TokenNotWhitelisted();
        if (_ethAmount == 0) revert InvalidAmount();
        if (_ethAmount > maxSinglePurchase) revert InvalidAmount();
        if (_targetMultiplier < MIN_MULTIPLIER || _targetMultiplier > MAX_MULTIPLIER)
            revert InvalidAmount();
        if (maxQueueSize > 0 && activeQueueCount >= maxQueueSize) revert QueueFull();

        // Assign unique queue ID (backend will manage FIFO order)
        queueId = nextQueueId++;
        totalQueues++;

        queuedPurchases[queueId] = QueuedPurchase({
            queueId: queueId,
            targetAddress: _token,
            ethAmount: _ethAmount,
            targetMultiplier: _targetMultiplier,
            maxSlippage: _maxSlippage,
            targetEntryPrice: _targetEntryPrice,
            queuedAt: block.timestamp,
            executed: false,
            exists: true,
            executeToTreasury: _executeToTreasury
        });

        activeQueueCount++;

        emit TokenPurchaseQueued(
            queueId,
            _token,
            tokenInfo.v2Router,
            _ethAmount,
            _targetMultiplier,
            _maxSlippage,
            _targetEntryPrice,
            msg.sender,
            address(this).balance,
            block.timestamp
        );

        return queueId;
    }

    /// @notice Force immediate meme token purchase (bypasses queue)
    /// @dev Useful for time-sensitive opportunities, does NOT affect FIFO queue
    function forceBuyMeme(
        address _token,
        uint256 _ethAmount,
        uint256 _targetMultiplier,
        uint256 _maxSlippage,
        bool _executeToTreasury
    )
        external
        onlyOwnerOrOperator
        nonReentrant
        whenNotPaused
        returns (uint256 purchaseId)
    {
        MemeToken memory tokenInfo = whitelistedTokens[_token];
        if (!tokenInfo.isWhitelisted) revert TokenNotWhitelisted();
        if (_ethAmount == 0) revert InvalidAmount();
        if (_ethAmount > maxSinglePurchase) revert InvalidAmount();
        if (_targetMultiplier < 1_000 || _targetMultiplier > MAX_MULTIPLIER)
            revert InvalidAmount();

        // Check sufficient ETH for purchase + executor reward
        uint256 totalSpend = _ethAmount + executorReward;
        if (address(this).balance < totalSpend) revert InsufficientBalance();

        // Execute immediately (bypasses FIFO queue)
        purchaseId = _executeMemeTokenPurchase(
            _token,
            _ethAmount,
            _targetMultiplier,
            _maxSlippage,
            0, // queueId = 0 (bypassed queue)
            _executeToTreasury
        );

        // Pay executor reward
        SafeTransferLib.safeTransferETH(msg.sender, executorReward);

        return purchaseId;
    }

    /// @notice Remove specific queue item by ID (backend determines which to clear)
    /// @param queueId The specific queue ID to clear
    /// @dev Renamed from clearQueue - backend now specifies which ID to clear
    function clearQueue(uint256 queueId) external onlyOwnerOrOperator {
        QueuedPurchase storage queue = queuedPurchases[queueId];

        if (!queue.exists || queue.executed) revert NoQueueExists();

        // Delete queue item
        delete queuedPurchases[queueId];
        activeQueueCount--;
        
        emit QueueCleared(queueId);
    }

    /// @notice Remove any queued purchase by queue ID
    /// @param queueId The queue ID to remove
    /// @dev Backend determines which queue item to remove (no on-chain iteration needed)
    function removeQueuedPurchase(uint256 queueId) external onlyOwnerOrOperator {
        QueuedPurchase storage queue = queuedPurchases[queueId];

        // Validate queue item exists and not executed
        if (!queue.exists || queue.executed) {
            revert NoQueueExists();
        }

        // Delete queue item (full delete)
        delete queuedPurchases[queueId];
        activeQueueCount--;
        
        emit QueueRemoved(queueId);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                         ADMIN - SYSTEM CONFIGURATION                         */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    function setExecutorReward(uint256 _reward) external onlyOwner {
        if (_reward == 0) revert InvalidAmount();
        if (_reward > 1 ether) revert InvalidAmount(); // Sanity check: max 1 ETH reward
        executorReward = _reward;
    }

    function setMaxSaleSlippage(
        uint256 _slippage
    ) external onlyOwner validSlippage(_slippage) {
        maxSaleSlippage = _slippage;
    }

    function setMinForceSellBPS(uint256 _minBPS) external onlyOwner {
        if (_minBPS > BPS_BASE) revert InvalidAmount();
        minForceSellBPS = _minBPS;
    }

    function setMaxBuybackSlippage(
        uint256 _slippage
    ) external onlyOwner validSlippage(_slippage) {
        maxBuybackSlippage = _slippage;
    }

    function setHookAddress(address _hook) external onlyOwner {
        if (_hook == address(0)) revert InvalidAddress();
        hookAddress = _hook;
    }

    function addApprovedRouter(address _router) external onlyOwner {
        if (_router == address(0)) revert InvalidAddress();

        if (!approvedRouters[_router]) {
            // Validate router's WETH matches our WETH (prevents cross-chain mismatches)
            try IUniswapV2Router(_router).WETH() returns (address routerWETH) {
                if (routerWETH != address(WETH)) revert RouterWETHMismatch();
            } catch {
                // Router doesn't implement WETH() - skip validation (non-V2 router)
            }

            approvedRouters[_router] = true;
        }
    }

    function removeApprovedRouter(address _router) external onlyOwner {
        if (approvedRouters[_router]) {
            approvedRouters[_router] = false;
        }
    }

    function setMaxSinglePurchase(uint256 _max) external onlyOwner {
        if (_max == 0) revert InvalidAmount();
        maxSinglePurchase = _max;
    }

    function setMinSpikeThreshold(uint256 _threshold) external onlyOwner {
        if (_threshold == 0) revert InvalidAmount();
        minSpikeThreshold = _threshold;
    }

    /// @notice Set maximum queue size (0 = unlimited)
    /// @dev No technical limit since O(1) operations, but useful for spam/risk management
    /// @param _maxSize Maximum queue items (0 for unlimited)
    function setMaxQueueSize(uint256 _maxSize) external onlyOwner {
        maxQueueSize = _maxSize;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                        ADMIN - MODULE MANAGEMENT                             */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Add a module contract to the whitelist
    /// @dev Modules can receive funding (push) or pull funds from treasury
    /// @param _module Address of the module contract
    function addModule(address _module) external onlyOwner {
        if (_module == address(0)) revert InvalidAddress();
        if (whitelistedModules[_module]) revert AlreadyProcessed();

        whitelistedModules[_module] = true;
        emit ModuleAdded(_module);
    }

    /// @notice Remove a module contract from the whitelist
    /// @param _module Address of the module contract to remove
    function removeModule(address _module) external onlyOwner {
        if (!whitelistedModules[_module]) revert ModuleNotWhitelisted();

        whitelistedModules[_module] = false;
        emit ModuleRemoved(_module);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                           ADMIN - EMERGENCY FUNCTIONS                        */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    function pause() external onlyOwner {
        paused = true;
    }

    function unpause() external onlyOwner {
        paused = false;
    }

    /// @notice Force sell token regardless of target price
    /// @param _purchaseId Purchase ID to sell
    /// @param _slippageBPS Slippage tolerance in basis points (e.g., 500 = 5%)
    function forceSell(
        uint256 _purchaseId,
        uint256 _slippageBPS
    ) external onlyOwner nonReentrant noForceOperationReentrancy returns (uint256 amountOut) {
        Purchase storage purchase = purchases[_purchaseId];
        if (purchase.purchaseId == 0) revert PurchaseNotFound();
        if (purchase.sold) revert AlreadyProcessed();
        if (_slippageBPS > BPS_BASE) revert InvalidAmount();

        // Verify we have enough tokens for this specific purchase
        IERC20 token = IERC20(purchase.tokenAddress);
        uint256 amountToSell = purchase.tokenAmount;
        uint256 balance = token.balanceOf(address(this));
        if (balance < amountToSell) revert InsufficientBalance();

        MemeToken memory tokenInfo = whitelistedTokens[purchase.tokenAddress];
        IUniswapV2Router v2Router = IUniswapV2Router(tokenInfo.v2Router);

        // Calculate minAmountOut with slippage and safety checks
        uint256 _minAmountOut = _calculateMinAmountOut(
            amountToSell,
            purchase.tokenAddress,
            tokenInfo.v2Router,
            _slippageBPS,
            purchase.ethSpent
        );

        // Build path: Token → ETH
        address[] memory path = new address[](2);
        path[0] = purchase.tokenAddress;
        path[1] = address(WETH);

        // ═══════════════════════════════════════════════════════════════════════
        // CRITICAL: Update state BEFORE external calls (reentrancy protection)
        // ═══════════════════════════════════════════════════════════════════════

        // Mark as sold immediately to prevent reentrancy
        purchase.sold = true;
        purchase.soldTimestamp = block.timestamp;

        // Remove from active purchases BEFORE external calls
        _removeActivePurchase();

        // ═══════════════════════════════════════════════════════════════════════
        // Now safe to make external calls to potentially malicious token
        // ═══════════════════════════════════════════════════════════════════════

        // Safe approve pattern: set to 0 first, then set amount
        token.approve(address(v2Router), 0);
        token.approve(address(v2Router), amountToSell);

        uint256 ethBefore = address(this).balance;
        v2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            amountToSell,
            _minAmountOut,
            path,
            address(this),
            block.timestamp + 300
        );

        // Get actual ETH received (critical for fee-on-transfer tokens)
        uint256 ethAfter = address(this).balance;
        amountOut = ethAfter - ethBefore;

        // Note: All proceeds go directly to buyback, so no net change to currentFeesETH
        // (we receive ETH from sale, then immediately spend it on buyback)

        // Calculate profit or loss (force sells are usually at a loss)
        bool isProfit = amountOut > purchase.ethSpent;
        uint256 profitOrLoss = isProfit
            ? amountOut - purchase.ethSpent
            : purchase.ethSpent - amountOut;

        // Buyback and burn (no executor reward for admin force sells)
        // Calculate minimum tokens out with slippage protection
        uint256 minTokensOut = _calculateMinTokensFromETH(amountOut, maxBuybackSlippage);
        uint256 tokensBurned = _buyAndBurnTokens(amountOut, minTokensOut);

        // Update remaining purchase details (use safe calculation)
        purchase.soldPrice = _safePriceCalculation(amountOut, amountToSell, purchase.tokenAddress);
        purchase.isProfit = isProfit;
        purchase.profitOrLoss = profitOrLoss;

        // Update stats
        if (!isProfit) {
            totalLoss += profitOrLoss;
            failedFlips++;
        } else {
            // Rare: force sell at profit
            totalProfit += profitOrLoss;
            successfulFlips++;
        }

        emit ForceSold(
            _purchaseId,
            amountOut,
            isProfit,
            profitOrLoss,
            tokensBurned,
            false // toTreasury: false for regular forceSell with buyback
        );
    }

    /// @notice Force sell to treasury WITHOUT immediate buyback
    /// @dev ETH stays in treasury for later manual buyback, useful for managing timing
    /// @param _purchaseId Purchase ID to force sell
    /// @param _slippageBPS Slippage tolerance in basis points (e.g., 500 = 5%)
    function forceSellToTreasury(
        uint256 _purchaseId,
        uint256 _slippageBPS
    ) external onlyOwner nonReentrant noForceOperationReentrancy returns (uint256 amountOut) {
        Purchase storage purchase = purchases[_purchaseId];
        if (purchase.purchaseId == 0) revert PurchaseNotFound();
        if (purchase.sold) revert AlreadyProcessed();
        if (_slippageBPS > BPS_BASE) revert InvalidAmount();

        // Verify we have enough tokens for this specific purchase
        IERC20 token = IERC20(purchase.tokenAddress);
        uint256 amountToSell = purchase.tokenAmount;
        uint256 balance = token.balanceOf(address(this));
        if (balance < amountToSell) revert InsufficientBalance();

        MemeToken memory tokenInfo = whitelistedTokens[purchase.tokenAddress];
        IUniswapV2Router v2Router = IUniswapV2Router(tokenInfo.v2Router);

        // Calculate minAmountOut with slippage and safety checks
        uint256 _minAmountOut = _calculateMinAmountOut(
            amountToSell,
            purchase.tokenAddress,
            tokenInfo.v2Router,
            _slippageBPS,
            purchase.ethSpent
        );

        // Build path: Token → ETH
        address[] memory path = new address[](2);
        path[0] = purchase.tokenAddress;
        path[1] = address(WETH);

        // ═══════════════════════════════════════════════════════════════════════
        // CRITICAL: Update state BEFORE external calls (reentrancy protection)
        // ═══════════════════════════════════════════════════════════════════════

        // Mark as sold immediately to prevent reentrancy
        purchase.sold = true;
        purchase.soldTimestamp = block.timestamp;

        // Remove from active purchases BEFORE external calls
        _removeActivePurchase();

        // ═══════════════════════════════════════════════════════════════════════
        // Now safe to make external calls to potentially malicious token
        // ═══════════════════════════════════════════════════════════════════════

        // Safe approve pattern: set to 0 first, then set amount
        token.approve(address(v2Router), 0);
        token.approve(address(v2Router), amountToSell);

        uint256 ethBefore = address(this).balance;
        v2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            amountToSell,
            _minAmountOut,
            path,
            address(this),
            block.timestamp + 300
        );

        // Get actual ETH received (critical for fee-on-transfer tokens)
        uint256 ethAfter = address(this).balance;
        amountOut = ethAfter - ethBefore;

        // ETH stays in treasury (address(this).balance) for later manual buyback
        // No immediate buyback - owner can call forceBurn() later

        // Calculate profit or loss (force sells are usually at a loss)
        bool isProfit = amountOut > purchase.ethSpent;
        uint256 profitOrLoss = isProfit
            ? amountOut - purchase.ethSpent
            : purchase.ethSpent - amountOut;

        // Update remaining purchase details (use safe calculation)
        purchase.soldPrice = _safePriceCalculation(amountOut, amountToSell, purchase.tokenAddress);
        purchase.isProfit = isProfit;
        purchase.profitOrLoss = profitOrLoss;

        // Update stats
        if (!isProfit) {
            totalLoss += profitOrLoss;
            failedFlips++;
        } else {
            // Rare: force sell at profit
            totalProfit += profitOrLoss;
            successfulFlips++;
        }

        emit ForceSold(
            _purchaseId,
            amountOut,
            isProfit,
            profitOrLoss,
            0, // tokensBurned: 0 for treasury sales (no immediate buyback)
            true // toTreasury: true for treasury sales
        );
    }

    /// @notice Admin-only manual buyback and burn
    /// @dev Can trigger spike fees if amount >= minSpikeThreshold
    /// @param ethAmount Amount of ETH to spend on buyback
    /// @param slippageBPS Slippage tolerance in basis points (e.g., 500 = 5%)
    function forceBurn(
        uint256 ethAmount,
        uint256 slippageBPS
    ) external onlyOwner nonReentrant noForceOperationReentrancy validSlippage(slippageBPS) returns (uint256 tokensBurned) {
        if (ethAmount == 0) revert InvalidAmount();
        if (ethAmount > address(this).balance) revert InsufficientBalance();

        // Trigger spike fee if amount is large enough (Phase 2 only)
        if (successfulFlips > 0 && ethAmount >= minSpikeThreshold) {
            try IMemeStrategyHook(hookAddress).triggerFeeSpike(ethAmount) {
                // Spike triggered
            } catch {
                // Hook failure doesn't block burn execution
            }
        }

        // Calculate minimum tokens out with slippage protection
        uint256 minTokensOut = _calculateMinTokensFromETH(ethAmount, slippageBPS);

        // Execute buyback and burn with slippage protection
        tokensBurned = _buyAndBurnTokens(ethAmount, minTokensOut);

        emit ForceBurn(
            msg.sender,
            ethAmount,
            tokensBurned,
            block.timestamp
        );

        return tokensBurned;
    }

    function emergencyWithdrawTokens(
        address _token,
        uint256 _amount
    ) external onlyOwner {
        if (_token == address(this)) revert CannotWithdrawStrategyToken();
        SafeTransferLib.safeTransfer(_token, owner(), _amount);
        emit EmergencyWithdraw(_token, _amount, owner());
    }

    function emergencyWithdrawETH(uint256 _amount) external onlyOwner {
        if (_amount > address(this).balance) revert InsufficientBalance();
        SafeTransferLib.safeTransferETH(owner(), _amount);
        emit EmergencyETHWithdraw(_amount, owner());
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                         MODULE FUNDING (PUSH/PULL)                           */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Push ETH funds to a whitelisted module (owner-initiated)
    /// @param _module Module address to fund
    /// @param amount ETH amount to transfer
    /// @dev Only owner can push funds to modules
    function fundModule(address _module, uint256 amount) external onlyOwner nonReentrant {
        if (!whitelistedModules[_module]) revert ModuleNotWhitelisted();
        if (address(this).balance < amount) revert InsufficientBalance();
        SafeTransferLib.safeTransferETH(_module, amount);
    }

    /// @notice Allow whitelisted modules to pull funds from treasury
    /// @param amount ETH amount to pull
    /// @dev Can only be called by whitelisted modules
    function pullFundsFromTreasury(uint256 amount) external nonReentrant {
        if (!whitelistedModules[msg.sender]) revert ModuleNotWhitelisted();
        if (address(this).balance < amount) revert InsufficientBalance();
        SafeTransferLib.safeTransferETH(msg.sender, amount);
    }

    /// @notice Receive ETH from any source
    /// @dev All ETH sent to contract becomes available for treasury operations
    ///      Simplified accounting: address(this).balance is the source of truth
    receive() external payable {
        emit FeesAdded(msg.value, address(this).balance, msg.sender);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          PUBLIC - EXECUTION FUNCTIONS                        */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Execute a specific queued purchase by ID (backend specifies which to execute)
    /// @dev Backend maintains queue order and tells executor which ID to execute next
    ///      Only executes if current price is at or below targetEntryPrice (or if targetEntryPrice is 0)
    /// @param queueId The specific queue ID to execute
    function executeQueuedPurchase(uint256 queueId)
        external
        nonReentrant
        whenNotPaused
        returns (uint256 purchaseId)
    {
        // Direct access to queue by ID
        QueuedPurchase storage queueStorage = queuedPurchases[queueId];

        // Validate queue item exists and not executed
        if (!queueStorage.exists || queueStorage.executed) {
            revert NoQueueExists();
        }

        // Load into memory for execution
        QueuedPurchase memory queue = queueStorage;

        // Check target entry price if set (0 = no limit)
        if (queue.targetEntryPrice > 0) {
            MemeToken memory tokenInfo = whitelistedTokens[queue.targetAddress];
            IUniswapV2Router v2Router = IUniswapV2Router(tokenInfo.v2Router);

            // Build path for price check
            address[] memory path = new address[](2);
            path[0] = address(WETH);
            path[1] = queue.targetAddress;

            // Get current price per token
            try v2Router.getAmountsOut(1e18, path) returns (uint256[] memory amounts) {
                uint256 currentPricePerToken = amounts[1];

                // Safety: Prevent division by zero
                if (currentPricePerToken == 0) revert InvalidAmount();

                // Current price must be <= targetEntryPrice (more tokens per ETH = better)
                // targetEntryPrice is how much ETH per token we're willing to pay
                // We need to convert: if we spend 1 ETH, we get currentPricePerToken tokens
                // Price per token = 1e18 / currentPricePerToken
                // ✅ Use safe calculation to prevent overflow
                uint256 pricePerToken = _safePriceCalculation(1e18, currentPricePerToken, queue.targetAddress);

                if (pricePerToken > queue.targetEntryPrice) {
                    revert TargetNotReached(); // Price too high
                }
            } catch {
                revert NoV2Liquidity();
            }
        }

        // Check sufficient ETH
        uint256 totalSpend = queue.ethAmount + executorReward;
        if (address(this).balance < totalSpend) revert InsufficientBalance();

        // Execute meme token purchase
        purchaseId = _executeMemeTokenPurchase(
            queue.targetAddress,
            queue.ethAmount,
            queue.targetMultiplier,
            queue.maxSlippage,
            queue.queueId,
            queue.executeToTreasury
        );

        // Pay executor reward
        SafeTransferLib.safeTransferETH(msg.sender, executorReward);

        // Mark queue as executed and remove from queue
        queueStorage.executed = true;
        delete queuedPurchases[queueId];
        activeQueueCount--;
    }

    /// @notice Execute sale when target reached (anyone can call)
    /// @dev Standard execution: sells meme token and immediately buyback MEMS
    /// @param _purchaseId Purchase ID to sell
    function executeSale(
        uint256 _purchaseId
    ) external nonReentrant whenNotPaused returns (uint256 profit) {
        return _executeSaleInternal(_purchaseId, true); // true = do buyback
    }

    /// @notice Execute sale to treasury WITHOUT immediate buyback (unpredictable timing)
    /// @dev Same as executeSale() but ETH stays in treasury for later manual buyback
    /// @param _purchaseId Purchase ID to sell
    function executeSaleToTreasury(
        uint256 _purchaseId
    ) external nonReentrant whenNotPaused returns (uint256 profit) {
        return _executeSaleInternal(_purchaseId, false); // false = no buyback
    }

    /// @notice Internal sale execution logic (shared by executeSale and executeSaleToTreasury)
    /// @param _purchaseId Purchase ID to sell
    /// @param doBuyback Whether to immediately buyback and burn MEMS tokens
    function _executeSaleInternal(
        uint256 _purchaseId,
        bool doBuyback
    ) internal returns (uint256) {
        Purchase storage purchase = purchases[_purchaseId];
        if (purchase.purchaseId == 0) revert PurchaseNotFound();
        if (purchase.sold) revert AlreadyProcessed();

        // Validate correct execution function
        if (doBuyback && purchase.executeToTreasury) revert WrongExecutionFunction();
        if (!doBuyback && !purchase.executeToTreasury) revert WrongExecutionFunction();

        // Verify we have enough tokens for this specific purchase
        IERC20 token = IERC20(purchase.tokenAddress);
        uint256 amountToSell = purchase.tokenAmount;
        uint256 balance = token.balanceOf(address(this));
        if (balance < amountToSell) revert InsufficientBalance();

        // Get current price from V2 for target verification
        MemeToken memory tokenInfo = whitelistedTokens[purchase.tokenAddress];
        IUniswapV2Router v2Router = IUniswapV2Router(tokenInfo.v2Router);
        address[] memory path = new address[](2);
        path[0] = purchase.tokenAddress;
        path[1] = address(WETH);

        uint256[] memory expectedOut;
        try v2Router.getAmountsOut(amountToSell, path) returns (
            uint256[] memory amounts
        ) {
            expectedOut = amounts;
        } catch {
            revert TargetNotReached(); // If price query fails, can't verify target
        }

        // Use safe calculation for current price
        uint256 currentPrice = _safePriceCalculation(expectedOut[1], amountToSell, purchase.tokenAddress);

        // Verify target reached
        if (currentPrice < purchase.targetPrice) revert TargetNotReached();

        // Calculate min ETH out with slippage
        uint256 minETHOut = (expectedOut[1] * (BPS_BASE - maxSaleSlippage)) / BPS_BASE;

        // ═══════════════════════════════════════════════════════════════════════
        // Update state BEFORE external calls (reentrancy protection)
        // ═══════════════════════════════════════════════════════════════════════

        // Mark as sold immediately to prevent reentrancy
        purchase.sold = true;
        purchase.soldTimestamp = block.timestamp;

        // Remove from active purchases BEFORE external calls
        _removeActivePurchase();

        // Safe approve pattern: set to 0 first, then set amount
        token.approve(address(v2Router), 0);
        token.approve(address(v2Router), amountToSell);

        uint256 totalReceived = address(this).balance;
        v2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            amountToSell,
            minETHOut,
            path,
            address(this),
            block.timestamp + 300
        );

        // Get actual ETH received (critical for fee-on-transfer tokens)
        totalReceived = address(this).balance - totalReceived;

        // Calculate actual slippage
        uint256 actualSlippage = expectedOut[1] > totalReceived
            ? (((expectedOut[1] - totalReceived) * BPS_BASE) / expectedOut[1])
            : 0;

        // Verify we have enough to pay executor reward
        if (totalReceived < executorReward) revert InsufficientBalance();

        // Calculate profit or loss
        bool isProfit = totalReceived > purchase.ethSpent;
        uint256 profitOrLoss = isProfit
            ? totalReceived - purchase.ethSpent
            : purchase.ethSpent - totalReceived;

        // Execute buyback if requested
        uint256 tokensBurned = 0;
        if (doBuyback) {
            uint256 forBuyback = totalReceived - executorReward;
            // Calculate minimum tokens out with slippage protection
            uint256 minTokensOut = _calculateMinTokensFromETH(forBuyback, maxBuybackSlippage);
            tokensBurned = _buyAndBurnTokens(forBuyback, minTokensOut);
        }

        // Update remaining purchase details (use safe calculation)
        purchase.soldPrice = _safePriceCalculation(totalReceived, amountToSell, purchase.tokenAddress);
        purchase.isProfit = isProfit;
        purchase.profitOrLoss = profitOrLoss;
        purchase.slippageUsed = actualSlippage;

        // Capture first sale state before any updates
        bool isFirstSale = (isProfit && successfulFlips == 0);

        // Update stats
        if (isProfit) {
            totalProfit += profitOrLoss;

            // PHASE TRANSITION LOGIC
            if (isFirstSale) {
                // First profitable sale → Phase 2
                // Phase transition to Phase 2
                try IMemeStrategyHook(hookAddress).notifyFirstSale(totalReceived) {} catch {}

                // Also trigger spike fee on first sale if large enough (and doing buyback)
                if (doBuyback && totalReceived >= minSpikeThreshold) {
                    try IMemeStrategyHook(hookAddress).triggerFeeSpike(totalReceived) {} catch {}
                }
            } else if (doBuyback && totalReceived >= minSpikeThreshold) {
                // Subsequent sales with buyback → Trigger spikes
                try IMemeStrategyHook(hookAddress).triggerFeeSpike(totalReceived) {} catch {}
            }
            // NOTE: If no buyback (executeToTreasury), no spike trigger
            // Admin can trigger spike later via manual forceBurn()

            successfulFlips++; // Increment AFTER check
        } else {
            totalLoss += profitOrLoss;
            failedFlips++;
        }

        // Pay executor (ETH)
        SafeTransferLib.safeTransferETH(msg.sender, executorReward);

        // Emit sale event with explicit treasury flag
        emit TokenSaleExecuted(
            _purchaseId,
            purchase.tokenAddress,
            msg.sender,
            amountToSell,
            totalReceived,
            purchase.ethSpent,
            isProfit,
            profitOrLoss,
            tokensBurned,
            executorReward,
            purchase.buyPricePerUnit,
            purchase.soldPrice,
            block.timestamp - purchase.timestamp,
            isFirstSale,
            !doBuyback, // toTreasury: true if no buyback, false if buyback
            block.timestamp
        );

        return profitOrLoss;
    }

    /// @notice Receive ETH fees from hook
    function addFeesETH() external payable {
        if (msg.sender != hookAddress && msg.sender != owner())
            revert NotAuthorized();
        if (msg.value == 0) revert InvalidAmount();
        emit FeesAdded(msg.value, address(this).balance, msg.sender);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                         UNISWAP V4 UNLOCK CALLBACK                           */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Uniswap V4 unlock callback for atomic swap execution
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(POOL_MANAGER)) revert NotAuthorized();
        if (!_unlockInProgress) revert NotAuthorized();

        (bool zeroForOne, int256 amountSpecified) = abi.decode(
            data,
            (bool, int256)
        );

        PoolKey memory strategyPoolKey = PoolKey({
            currency0: Currency.wrap(address(0)),       // Native ETH (v1.1)
            currency1: Currency.wrap(address(this)),    // MEMS token
            fee: 0,                                     // 0% pool fee (hook collects via deltas)
            tickSpacing: 60,
            hooks: IHooks(hookAddress)
        });

        // Execute swap on the strategy pool (ETH/MEMS)
        BalanceDelta delta = POOL_MANAGER.swap(
            strategyPoolKey,
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: amountSpecified,
                sqrtPriceLimitX96: zeroForOne
                    ? TickMath.MIN_SQRT_PRICE + 1
                    : TickMath.MAX_SQRT_PRICE - 1
            }),
            "" // No hook data
        );

        // Settle and take based on swap direction
        if (zeroForOne) {
            // Buying MEMS with ETH
            // Negative amount0 = we owe ETH, positive amount1 = we receive tokens
            if (delta.amount0() < 0) {
                // Pay ETH to pool (currency0 should be native ETH)
                if (strategyPoolKey.currency0.isAddressZero()) {
                    POOL_MANAGER.settle{
                        value: uint256(int256(-delta.amount0()))
                    }();
                } else {
                    _settleV4(
                        strategyPoolKey.currency0,
                        uint256(int256(-delta.amount0()))
                    );
                }
            }
            if (delta.amount1() > 0) {
                _takeV4(
                    strategyPoolKey.currency1,
                    uint256(int256(delta.amount1()))
                );
            }
        } else {
            // Selling MEMS for ETH (future use case)
            if (delta.amount1() < 0) {
                _settleV4(
                    strategyPoolKey.currency1,
                    uint256(int256(-delta.amount1()))
                );
            }
            if (delta.amount0() > 0) {
                _takeV4(
                    strategyPoolKey.currency0,
                    uint256(int256(delta.amount0()))
                );
            }
        }

        return abi.encode(delta);
    }

    /// @notice Settle (pay) a currency to the PoolManager
    function _settleV4(Currency currency, uint256 amount) internal {
        if (currency.isAddressZero()) {
            // Native ETH
            POOL_MANAGER.settle{value: amount}();
        } else {
            // ERC20 - sync, transfer, settle
            POOL_MANAGER.sync(currency);
            SafeTransferLib.safeTransfer(
                Currency.unwrap(currency),
                address(POOL_MANAGER),
                amount
            );
            POOL_MANAGER.settle();
        }
    }

    /// @notice Take (receive) a currency from the PoolManager
    function _takeV4(Currency currency, uint256 amount) internal {
        POOL_MANAGER.take(currency, address(this), amount);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                            INTERNAL - CORE LOGIC                             */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    function _executeMemeTokenPurchase(
        address _token,
        uint256 _ethAmount,
        uint256 _targetMultiplier,
        uint256 _maxSlippage,
        uint256 queueId,
        bool executeToTreasury
    ) internal returns (uint256 purchaseId) {
        MemeToken memory tokenInfo = whitelistedTokens[_token];
        IUniswapV2Router v2Router = IUniswapV2Router(tokenInfo.v2Router);

        address[] memory path = new address[](2);
        path[0] = address(WETH);
        path[1] = _token;

        // Get quote with error handling
        uint256 expectedTokensFromQuote;
        try v2Router.getAmountsOut(_ethAmount, path) returns (
            uint256[] memory amounts
        ) {
            expectedTokensFromQuote = amounts[1];
        } catch {
            revert NoV2Liquidity();
        }

        uint256 minTokensOut = (expectedTokensFromQuote * (BPS_BASE - _maxSlippage)) / BPS_BASE;

        // Execute V2 swap: ETH → Token (supports fee-on-transfer tokens)
        uint256 balanceBefore = IERC20(_token).balanceOf(address(this));
        v2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
            value: _ethAmount
        }(minTokensOut, path, address(this), block.timestamp + 300);

        // Get balance after (critical for fee-on-transfer tokens)
        uint256 balanceAfter = IERC20(_token).balanceOf(address(this));
        uint256 actualReceived = balanceAfter - balanceBefore;

        // Calculate actual slippage
        uint256 actualSlippage = expectedTokensFromQuote > actualReceived
            ? (((expectedTokensFromQuote - actualReceived) * BPS_BASE) /
                expectedTokensFromQuote)
            : 0;

        // Calculate prices using per-queue multiplier with overflow protection
        // ✅ Use safe calculations to prevent overflow
        uint8 tokenDecimals = IERC20(_token).decimals();
        uint256 buyPricePerToken = _safePriceCalculation(_ethAmount, actualReceived, _token);
        uint256 targetPrice = _safeTargetPriceCalculation(buyPricePerToken, _targetMultiplier);

        // Create purchase record
        totalPurchases++;
        purchaseId = totalPurchases;

        purchases[purchaseId] = Purchase({
            purchaseId: purchaseId,
            tokenAddress: _token,
            tokenAmount: actualReceived,
            buyPricePerUnit: buyPricePerToken,
            targetPrice: targetPrice,
            ethSpent: _ethAmount,
            timestamp: block.timestamp,
            sold: false,
            soldPrice: 0,
            soldTimestamp: 0,
            isProfit: false,
            profitOrLoss: 0,
            slippageUsed: actualSlippage,
            executeToTreasury: executeToTreasury
        });

        // Add to active purchases
        _addActivePurchase();

        emit TokenPurchaseExecuted(
            purchaseId,
            queueId,
            _token,
            msg.sender,
            _ethAmount,
            actualReceived,
            tokenDecimals,
            buyPricePerToken,
            targetPrice,
            _targetMultiplier,
            actualSlippage,
            executeToTreasury,
            block.timestamp
        );
    }

    /// @notice Buy back and burn strategy tokens using ETH via Uniswap V4
    /// @param ethAmountIn Amount of ETH to spend on buyback
    /// @param minTokensOut Minimum MEMS tokens to receive (slippage protection, 0 = skip check)
    function _buyAndBurnTokens(uint256 ethAmountIn, uint256 minTokensOut) internal returns (uint256 tokensBurned) {
        if (ethAmountIn == 0) return 0;

        // Get balance before (safe to do before flag - view function)
        uint256 balanceBefore = balanceOf(address(this));

        // Determine swap direction (ETH is currency0, Strategy token is currency1)
        bool zeroForOne = true; // ETH → Strategy token

        require(ethAmountIn <= uint256(type(int256).max));
        int256 amountSpecified = -int256(ethAmountIn);

        _unlockInProgress = true;
        try POOL_MANAGER.unlock(abi.encode(zeroForOne, amountSpecified)) {} catch {
            _unlockInProgress = false;
            return 0;
        }
        _unlockInProgress = false;

        // Get balance after and calculate tokens received
        uint256 balanceAfter = balanceOf(address(this));
        tokensBurned = balanceAfter - balanceBefore;

        if (minTokensOut > 0 && tokensBurned < minTokensOut) revert InvalidAmount();
        _burn(address(this), tokensBurned);

        totalTokensBurned += tokensBurned;
        emit TokensBurned(ethAmountIn, tokensBurned, totalTokensBurned);
    }

    /// @dev Increment active purchase counter (backend tracks actual IDs via events)
    function _addActivePurchase() internal {
        activePurchaseCount++;
    }

    /// @dev Decrement active purchase counter (backend tracks actual IDs via events)
    function _removeActivePurchase() internal {
        if (activePurchaseCount > 0) {
            activePurchaseCount--;
        }
    }

    function _calculateMinAmountOut(uint256 amountToSell, address tokenAddress, address v2RouterAddress, uint256 slippageBPS, uint256 ethSpent) internal view returns (uint256) {
        address[] memory path = new address[](2);
        path[0] = tokenAddress;
        path[1] = address(WETH);

        try IUniswapV2Router(v2RouterAddress).getAmountsOut(amountToSell, path) returns (uint256[] memory amounts) {
            uint256 minOut = (amounts[1] * (BPS_BASE - slippageBPS)) / BPS_BASE;
            if (minOut < (ethSpent * minForceSellBPS) / BPS_BASE) revert InvalidAmount();
            return minOut;
        } catch {
            revert TargetNotReached();
        }
    }

    /// @notice Calculate min MEMS tokens from ETH with slippage
    function _calculateMinTokensFromETH(uint256 ethAmount, uint256 slippageBPS) internal view returns (uint256 minTokensOut) {
        if (ethAmount == 0) return 0;
        uint256 contractTokenBalance = balanceOf(address(this));
        uint256 contractETHBalance = address(this).balance;
        if (contractETHBalance == 0) return 0;

        if (ethAmount > type(uint256).max / contractTokenBalance) {
            minTokensOut = (ethAmount / contractETHBalance) * contractTokenBalance;
        } else {
            minTokensOut = (ethAmount * contractTokenBalance) / contractETHBalance;
        }
        minTokensOut = (minTokensOut * (BPS_BASE - slippageBPS)) / BPS_BASE;
    }

    function _calculateSpikeFeeBPS(uint256 ethAmount) internal view returns (uint256 feeBPS, bool spikeSkipped) {
        try IMemeStrategyHook(hookAddress).getTierForAmount(ethAmount) returns (
            uint256 tierFeePercent,
            uint256 /* decayHours */
        ) {
            // Get current active sell fee from hook
            try IMemeStrategyHook(hookAddress).getCurrentFee(false) returns (
                uint256 currentSellFee
            ) {
                // Spike is skipped if tier fee is NOT higher than current
                spikeSkipped = (tierFeePercent <= currentSellFee);
                return (tierFeePercent, spikeSkipped);
            } catch {
                // If getCurrentFee fails, return tier fee with skipped=false
                return (tierFeePercent, false);
            }
        } catch {
            // Fallback: return 0 with skipped=false if hook query fails
            return (0, false);
        }
    }

}

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

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

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

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

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

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

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

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

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

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

/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
///   minting and transferring zero tokens, as well as self-approvals.
///   For performance, this implementation WILL NOT revert for such actions.
///   Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
///   the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
///   change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The total supply has overflowed.
    error TotalSupplyOverflow();

    /// @dev The allowance has overflowed.
    error AllowanceOverflow();

    /// @dev The allowance has underflowed.
    error AllowanceUnderflow();

    /// @dev Insufficient balance.
    error InsufficientBalance();

    /// @dev Insufficient allowance.
    error InsufficientAllowance();

    /// @dev The permit is invalid.
    error InvalidPermit();

    /// @dev The permit has expired.
    error PermitExpired();

    /// @dev The allowance of Permit2 is fixed at infinity.
    error Permit2AllowanceIsFixedAtInfinity();

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

    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
    event Transfer(address indexed from, address indexed to, uint256 amount);

    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
    uint256 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
    uint256 private constant _APPROVAL_EVENT_SIGNATURE =
        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;

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

    /// @dev The storage slot for the total supply.
    uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;

    /// @dev The balance slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _BALANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let balanceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;

    /// @dev The allowance slot of (`owner`, `spender`) is given by:
    /// ```
    ///     mstore(0x20, spender)
    ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let allowanceSlot := keccak256(0x0c, 0x34)
    /// ```
    uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;

    /// @dev The nonce slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _NONCES_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let nonceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _NONCES_SLOT_SEED = 0x38377508;

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

    /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
    uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;

    /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
    bytes32 private constant _DOMAIN_TYPEHASH =
        0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    /// @dev `keccak256("1")`.
    /// If you need to use a different version, override `_versionHash`.
    bytes32 private constant _DEFAULT_VERSION_HASH =
        0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;

    /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
    bytes32 private constant _PERMIT_TYPEHASH =
        0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;

    /// @dev The canonical Permit2 address.
    /// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
    /// Enabled by default. To disable, override `_givePermit2InfiniteAllowance()`.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ERC20 METADATA                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the name of the token.
    function name() public view virtual returns (string memory);

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

    /// @dev Returns the decimals places of the token.
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

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

    /// @dev Returns the amount of tokens in existence.
    function totalSupply() public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_TOTAL_SUPPLY_SLOT)
        }
    }

    /// @dev Returns the amount of tokens owned by `owner`.
    function balanceOf(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
    function allowance(address owner, address spender)
        public
        view
        virtual
        returns (uint256 result)
    {
        if (_givePermit2InfiniteAllowance()) {
            if (spender == _PERMIT2) return type(uint256).max;
        }
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x34))
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
    ///
    /// Emits a {Approval} event.
    function approve(address spender, uint256 amount) public virtual returns (bool) {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && amount != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Transfer `amount` tokens from the caller to `to`.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    ///
    /// Emits a {Transfer} event.
    function transfer(address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(msg.sender, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, caller())
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(msg.sender, to, amount);
        return true;
    }

    /// @dev Transfers `amount` tokens from `from` to `to`.
    ///
    /// Note: Does not update the allowance if it is the maximum uint256 value.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
    ///
    /// Emits a {Transfer} event.
    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(from, to, amount);
        // Code duplication is for zero-cost abstraction if possible.
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                let from_ := shl(96, from)
                if iszero(eq(caller(), _PERMIT2)) {
                    // Compute the allowance slot and load its value.
                    mstore(0x20, caller())
                    mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                    let allowanceSlot := keccak256(0x0c, 0x34)
                    let allowance_ := sload(allowanceSlot)
                    // If the allowance is not the maximum uint256 value.
                    if not(allowance_) {
                        // Revert if the amount to be transferred exceeds the allowance.
                        if gt(amount, allowance_) {
                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                            revert(0x1c, 0x04)
                        }
                        // Subtract and store the updated allowance.
                        sstore(allowanceSlot, sub(allowance_, amount))
                    }
                }
                // Compute the balance slot and load its value.
                mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                let fromBalanceSlot := keccak256(0x0c, 0x20)
                let fromBalance := sload(fromBalanceSlot)
                // Revert if insufficient balance.
                if gt(amount, fromBalance) {
                    mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated balance.
                sstore(fromBalanceSlot, sub(fromBalance, amount))
                // Compute the balance slot of `to`.
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x20)
                // Add and store the updated balance of `to`.
                // Will not overflow because the sum of all user balances
                // cannot exceed the maximum uint256 value.
                sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                // Emit the {Transfer} event.
                mstore(0x20, amount)
                log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let from_ := shl(96, from)
                // Compute the allowance slot and load its value.
                mstore(0x20, caller())
                mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                let allowanceSlot := keccak256(0x0c, 0x34)
                let allowance_ := sload(allowanceSlot)
                // If the allowance is not the maximum uint256 value.
                if not(allowance_) {
                    // Revert if the amount to be transferred exceeds the allowance.
                    if gt(amount, allowance_) {
                        mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                        revert(0x1c, 0x04)
                    }
                    // Subtract and store the updated allowance.
                    sstore(allowanceSlot, sub(allowance_, amount))
                }
                // Compute the balance slot and load its value.
                mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                let fromBalanceSlot := keccak256(0x0c, 0x20)
                let fromBalance := sload(fromBalanceSlot)
                // Revert if insufficient balance.
                if gt(amount, fromBalance) {
                    mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated balance.
                sstore(fromBalanceSlot, sub(fromBalance, amount))
                // Compute the balance slot of `to`.
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x20)
                // Add and store the updated balance of `to`.
                // Will not overflow because the sum of all user balances
                // cannot exceed the maximum uint256 value.
                sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                // Emit the {Transfer} event.
                mstore(0x20, amount)
                log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
            }
        }
        _afterTokenTransfer(from, to, amount);
        return true;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          EIP-2612                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev For more performance, override to return the constant value
    /// of `keccak256(bytes(name()))` if `name()` will never change.
    function _constantNameHash() internal view virtual returns (bytes32 result) {}

    /// @dev If you need a different value, override this function.
    function _versionHash() internal view virtual returns (bytes32 result) {
        result = _DEFAULT_VERSION_HASH;
    }

    /// @dev For inheriting contracts to increment the nonce.
    function _incrementNonce(address owner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _NONCES_SLOT_SEED)
            mstore(0x00, owner)
            let nonceSlot := keccak256(0x0c, 0x20)
            sstore(nonceSlot, add(1, sload(nonceSlot)))
        }
    }

    /// @dev Returns the current nonce for `owner`.
    /// This value is used to compute the signature for EIP-2612 permit.
    function nonces(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the nonce slot and load its value.
            mstore(0x0c, _NONCES_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
    /// authorized by a signed approval by `owner`.
    ///
    /// Emits a {Approval} event.
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && value != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        bytes32 versionHash = _versionHash();
        /// @solidity memory-safe-assembly
        assembly {
            // Revert if the block timestamp is greater than `deadline`.
            if gt(timestamp(), deadline) {
                mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
                revert(0x1c, 0x04)
            }
            let m := mload(0x40) // Grab the free memory pointer.
            // Clean the upper 96 bits.
            owner := shr(96, shl(96, owner))
            spender := shr(96, shl(96, spender))
            // Compute the nonce slot and load its value.
            mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
            mstore(0x00, owner)
            let nonceSlot := keccak256(0x0c, 0x20)
            let nonceValue := sload(nonceSlot)
            // Prepare the domain separator.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), versionHash)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            mstore(0x2e, keccak256(m, 0xa0))
            // Prepare the struct hash.
            mstore(m, _PERMIT_TYPEHASH)
            mstore(add(m, 0x20), owner)
            mstore(add(m, 0x40), spender)
            mstore(add(m, 0x60), value)
            mstore(add(m, 0x80), nonceValue)
            mstore(add(m, 0xa0), deadline)
            mstore(0x4e, keccak256(m, 0xc0))
            // Prepare the ecrecover calldata.
            mstore(0x00, keccak256(0x2c, 0x42))
            mstore(0x20, and(0xff, v))
            mstore(0x40, r)
            mstore(0x60, s)
            let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
            // If the ecrecover fails, the returndatasize will be 0x00,
            // `owner` will be checked if it equals the hash at 0x00,
            // which evaluates to false (i.e. 0), and we will revert.
            // If the ecrecover succeeds, the returndatasize will be 0x20,
            // `owner` will be compared against the returned address at 0x20.
            if iszero(eq(mload(returndatasize()), owner)) {
                mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
                revert(0x1c, 0x04)
            }
            // Increment and store the updated nonce.
            sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
            // Compute the allowance slot and store the value.
            // The `owner` is already at slot 0x20.
            mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
            sstore(keccak256(0x2c, 0x34), value)
            // Emit the {Approval} event.
            log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero pointer.
        }
    }

    /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
    function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        bytes32 versionHash = _versionHash();
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Grab the free memory pointer.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), versionHash)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            result := keccak256(m, 0xa0)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL MINT FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Mints `amount` tokens to `to`, increasing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _mint(address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(address(0), to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
            let totalSupplyAfter := add(totalSupplyBefore, amount)
            // Revert if the total supply overflows.
            if lt(totalSupplyAfter, totalSupplyBefore) {
                mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                revert(0x1c, 0x04)
            }
            // Store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(address(0), to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL BURN FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Burns `amount` tokens from `from`, reducing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _burn(address from, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, address(0), amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, from)
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Subtract and store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
            // Emit the {Transfer} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
        }
        _afterTokenTransfer(from, address(0), amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL TRANSFER FUNCTIONS                 */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Moves `amount` of tokens from `from` to `to`.
    function _transfer(address from, address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL ALLOWANCE FUNCTIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        if (_givePermit2InfiniteAllowance()) {
            if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
        }
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if not(allowance_) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
    ///
    /// Emits a {Approval} event.
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        if (_givePermit2InfiniteAllowance()) {
            /// @solidity memory-safe-assembly
            assembly {
                // If `spender == _PERMIT2 && amount != type(uint256).max`.
                if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
                    mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @solidity memory-safe-assembly
        assembly {
            let owner_ := shl(96, owner)
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     HOOKS TO OVERRIDE                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Hook that is called before any transfer of tokens.
    /// This includes minting and burning.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /// @dev Hook that is called after any transfer of tokens.
    /// This includes minting and burning.
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}

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

    /// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
    ///
    /// This value should be kept constant after contract initialization,
    /// or else the actual allowance values may not match with the {Approval} events.
    /// For best performance, return a compile-time constant for zero-cost abstraction.
    function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
        return true;
    }
}

File 4 of 39 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

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

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
        }
        _;
    }
}

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

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

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` does not implement `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented :=
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";

import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";

/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
    INotifier,
    IImmutableState,
    IERC721Permit_v4,
    IEIP712_v4,
    IMulticall_v4,
    IPoolInitializer_v4,
    IUnorderedNonce,
    IPermit2Forwarder
{
    /// @notice Thrown when the caller is not approved to modify a position
    error NotApproved(address caller);
    /// @notice Thrown when the block.timestamp exceeds the user-provided deadline
    error DeadlinePassed(uint256 deadline);
    /// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
    /// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
    error PoolManagerMustBeLocked();

    /// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
    /// @dev This is the standard entrypoint for the PositionManager
    /// @param unlockData is an encoding of actions, and parameters for those actions
    /// @param deadline is the deadline for the batched actions to be executed
    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;

    /// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
    /// @dev This must be called by a contract that has already unlocked the v4 PoolManager
    /// @param actions the actions to perform
    /// @param params the parameters to provide for the actions
    function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;

    /// @notice Used to get the ID that will be used for the next minted liquidity position
    /// @return uint256 The next token ID
    function nextTokenId() external view returns (uint256);

    /// @notice Returns the liquidity of a position
    /// @param tokenId the ERC721 tokenId
    /// @return liquidity the position's liquidity, as a liquidityAmount
    /// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
    function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);

    /// @notice Returns the pool key and position info of a position
    /// @param tokenId the ERC721 tokenId
    /// @return poolKey the pool key of the position
    /// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
    function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);

    /// @notice Returns the position info of a position
    /// @param tokenId the ERC721 tokenId
    /// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
    function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}

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

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

/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
    /// @notice Thrown when an allowance on a token has expired.
    /// @param deadline The timestamp at which the allowed amount is no longer valid
    error AllowanceExpired(uint256 deadline);

    /// @notice Thrown when an allowance on a token has been depleted.
    /// @param amount The maximum amount allowed
    error InsufficientAllowance(uint256 amount);

    /// @notice Thrown when too many nonces are invalidated.
    error ExcessiveInvalidation();

    /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
    event NonceInvalidation(
        address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
    );

    /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
    event Approval(
        address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
    );

    /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
    event Permit(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint160 amount,
        uint48 expiration,
        uint48 nonce
    );

    /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
    event Lockdown(address indexed owner, address token, address spender);

    /// @notice The permit data for a token
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice The permit message signed for a single token allowance
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The permit message signed for multiple token allowances
    struct PermitBatch {
        // the permit data for multiple token allowances
        PermitDetails[] details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The saved permissions
    /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice A token spender pair.
    struct TokenSpenderPair {
        // the token the spender is approved
        address token;
        // the spender address
        address spender;
    }

    /// @notice Details for a token transfer.
    struct AllowanceTransferDetails {
        // the owner of the token
        address from;
        // the recipient of the token
        address to;
        // the amount of the token
        uint160 amount;
        // the token to be transferred
        address token;
    }

    /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
    /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
    /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
    function allowance(address user, address token, address spender)
        external
        view
        returns (uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Approves the spender to use up to amount of the specified token up until the expiration
    /// @param token The token to approve
    /// @param spender The spender address to approve
    /// @param amount The approved amount of the token
    /// @param expiration The timestamp at which the approval is no longer valid
    /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitSingle Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitBatch Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;

    /// @notice Transfer approved tokens from one address to another
    /// @param from The address to transfer from
    /// @param to The address of the recipient
    /// @param amount The amount of the token to transfer
    /// @param token The token address to transfer
    /// @dev Requires the from address to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(address from, address to, uint160 amount, address token) external;

    /// @notice Transfer approved tokens in a batch
    /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
    /// @dev Requires the from addresses to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;

    /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
    /// by batch revoking approvals
    /// @param approvals Array of approvals to revoke.
    function lockdown(TokenSpenderPair[] calldata approvals) external;

    /// @notice Invalidate nonces for a given (token, spender) pair
    /// @param token The token to invalidate nonces for
    /// @param spender The spender to invalidate nonces for
    /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
    /// @dev Can't invalidate more than 2**16 nonces per transaction.
    function invalidateNonces(address token, address spender, uint48 newNonce) external;
}

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

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

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

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

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

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

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

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

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

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

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

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

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

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

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

File 11 of 39 : PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

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

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

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

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

interface IWETH {
    function deposit() external payable;
    function withdraw(uint256) external;
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
    function balanceOf(address) external view returns (uint256);
    function approve(address, uint256) external returns (bool);
}

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

/// @title IMemeStrategyHook
/// @notice Interface for MemeStrategyHook phase transitions and fee spikes
interface IMemeStrategyHook {
    /// @notice Notify hook of first successful sale (Phase 1 → Phase 2 transition)
    /// @param saleAmount ETH amount from the first sale
    function notifyFirstSale(uint256 saleAmount) external;
    
    /// @notice Trigger fee spike on subsequent sales
    /// @param saleAmount ETH amount from the sale
    function triggerFeeSpike(uint256 saleAmount) external;
    
    /// @notice Get tier information for a given ETH amount
    /// @param ethAmount Amount of ETH to query
    /// @return feePercent Fee percentage in basis points
    /// @return decayHours Decay duration in hours
    function getTierForAmount(uint256 ethAmount) external view returns (uint256 feePercent, uint256 decayHours);
    
    /// @notice Get current active fee (with decay applied)
    /// @param isBuy True for buy fee, false for sell fee
    /// @return Current fee in basis points
    function getCurrentFee(bool isBuy) external view returns (uint256);
}

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

interface IUniswapV2Router {
    function swapExactETHForTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable returns (uint256[] memory amounts);

    function swapExactTokensForETH(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    
    // Fee-on-transfer token support (critical for meme tokens with taxes)
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;
    
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    
    function getAmountsOut(
        uint256 amountIn,
        address[] calldata path
    ) external view returns (uint256[] memory amounts);
    
    function WETH() external view returns (address);
}

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

File 17 of 39 : Actions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
    // pool actions
    // liquidity actions
    uint256 internal constant INCREASE_LIQUIDITY = 0x00;
    uint256 internal constant DECREASE_LIQUIDITY = 0x01;
    uint256 internal constant MINT_POSITION = 0x02;
    uint256 internal constant BURN_POSITION = 0x03;
    uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
    uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05;

    // swapping
    uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
    uint256 internal constant SWAP_EXACT_IN = 0x07;
    uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08;
    uint256 internal constant SWAP_EXACT_OUT = 0x09;

    // donate
    // note this is not supported in the position manager or router
    uint256 internal constant DONATE = 0x0a;

    // closing deltas on the pool manager
    // settling
    uint256 internal constant SETTLE = 0x0b;
    uint256 internal constant SETTLE_ALL = 0x0c;
    uint256 internal constant SETTLE_PAIR = 0x0d;
    // taking
    uint256 internal constant TAKE = 0x0e;
    uint256 internal constant TAKE_ALL = 0x0f;
    uint256 internal constant TAKE_PORTION = 0x10;
    uint256 internal constant TAKE_PAIR = 0x11;

    uint256 internal constant CLOSE_CURRENCY = 0x12;
    uint256 internal constant CLEAR_OR_TAKE = 0x13;
    uint256 internal constant SWEEP = 0x14;

    uint256 internal constant WRAP = 0x15;
    uint256 internal constant UNWRAP = 0x16;

    // minting/burning 6909s to close deltas
    // note this is not supported in the position manager or router
    uint256 internal constant MINT_6909 = 0x17;
    uint256 internal constant BURN_6909 = 0x18;
}

File 18 of 39 : PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";

/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
    // the lower and upper tick of the position
    int24 tickLower;
    int24 tickUpper;
    // how to modify the liquidity
    int256 liquidityDelta;
    // a value to set if you want unique liquidity positions at the same range
    bytes32 salt;
}

/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
    /// Whether to swap token0 for token1 or vice versa
    bool zeroForOne;
    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
    int256 amountSpecified;
    /// The sqrt price at which, if reached, the swap will stop executing
    uint160 sqrtPriceLimitX96;
}

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";

/**
 * @dev PositionInfo is a packed version of solidity structure.
 * Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
 *
 * Layout:
 * 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
 *
 * Fields in the direction from the least significant bit:
 *
 * A flag to know if the tokenId is subscribed to an address
 * uint8 hasSubscriber;
 *
 * The tickUpper of the position
 * int24 tickUpper;
 *
 * The tickLower of the position
 * int24 tickLower;
 *
 * The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
 * bytes25 poolId;
 *
 * Note: If more bits are needed, hasSubscriber can be a single bit.
 *
 */
type PositionInfo is uint256;

using PositionInfoLibrary for PositionInfo global;

library PositionInfoLibrary {
    PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);

    uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
    uint256 internal constant MASK_8_BITS = 0xFF;
    uint24 internal constant MASK_24_BITS = 0xFFFFFF;
    uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
    uint256 internal constant SET_SUBSCRIBE = 0x01;
    uint8 internal constant TICK_LOWER_OFFSET = 8;
    uint8 internal constant TICK_UPPER_OFFSET = 32;

    /// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
    function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
        assembly ("memory-safe") {
            _poolId := and(MASK_UPPER_200_BITS, info)
        }
    }

    function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
        assembly ("memory-safe") {
            _tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
        }
    }

    function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
        assembly ("memory-safe") {
            _tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
        }
    }

    function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
        assembly ("memory-safe") {
            _hasSubscriber := and(MASK_8_BITS, info)
        }
    }

    /// @dev this does not actually set any storage
    function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
        assembly ("memory-safe") {
            _info := or(info, SET_SUBSCRIBE)
        }
    }

    /// @dev this does not actually set any storage
    function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
        assembly ("memory-safe") {
            _info := and(info, SET_UNSUBSCRIBE)
        }
    }

    /// @notice Creates the default PositionInfo struct
    /// @dev Called when minting a new position
    /// @param _poolKey the pool key of the position
    /// @param _tickLower the lower tick of the position
    /// @param _tickUpper the upper tick of the position
    /// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
    function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
        internal
        pure
        returns (PositionInfo info)
    {
        bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
        assembly {
            info :=
                or(
                    or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
                    shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
                )
        }
    }
}

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

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

/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
    /// @notice Thrown when unsubscribing without a subscriber
    error NotSubscribed();
    /// @notice Thrown when a subscriber does not have code
    error NoCodeSubscriber();
    /// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
    error GasLimitTooLow();
    /// @notice Wraps the revert message of the subscriber contract on a reverting subscription
    error SubscriptionReverted(address subscriber, bytes reason);
    /// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
    error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
    /// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
    error BurnNotificationReverted(address subscriber, bytes reason);
    /// @notice Thrown when a tokenId already has a subscriber
    error AlreadySubscribed(uint256 tokenId, address subscriber);

    /// @notice Emitted on a successful call to subscribe
    event Subscription(uint256 indexed tokenId, address indexed subscriber);
    /// @notice Emitted on a successful call to unsubscribe
    event Unsubscription(uint256 indexed tokenId, address indexed subscriber);

    /// @notice Returns the subscriber for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @return subscriber the subscriber contract
    function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);

    /// @notice Enables the subscriber to receive notifications for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @param newSubscriber the address of the subscriber contract
    /// @param data caller-provided data that's forwarded to the subscriber contract
    /// @dev Calling subscribe when a position is already subscribed will revert
    /// @dev payable so it can be multicalled with NATIVE related actions
    /// @dev will revert if pool manager is locked
    function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;

    /// @notice Removes the subscriber from receiving notifications for a respective position
    /// @param tokenId the ERC721 tokenId
    /// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
    /// @dev payable so it can be multicalled with NATIVE related actions
    /// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
    /// @dev will revert if pool manager is locked
    function unsubscribe(uint256 tokenId) external payable;

    /// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
    /// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
    function unsubscribeGasLimit() external view returns (uint256);
}

File 21 of 39 : IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";

/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

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

/// @title IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
    error SignatureDeadlineExpired();
    error NoSelfPermit();
    error Unauthorized();

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
    /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
    /// @dev payable so it can be multicalled with NATIVE related actions
    function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
        external
        payable;

    /// @notice Set an operator with full permission to an owner's tokens via signature
    /// @param owner The address that is setting the operator
    /// @param operator The address that will be set as an operator for the owner
    /// @param approved The permission to set on the operator
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
    /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
    /// @dev payable so it can be multicalled with NATIVE related actions
    function permitForAll(
        address owner,
        address operator,
        bool approved,
        uint256 deadline,
        uint256 nonce,
        bytes calldata signature
    ) external payable;
}

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

/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
    /// @notice Returns the domain separator for the current chain.
    /// @return bytes32 The domain separator
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
    /// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";

/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
    /// @notice Initialize a Uniswap v4 Pool
    /// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
    /// @param key The PoolKey of the pool to initialize
    /// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
    /// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
    function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}

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

/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
    error NonceAlreadyUsed();

    /// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
    /// @dev word is at most type(uint248).max
    function nonces(address owner, uint256 word) external view returns (uint256);

    /// @notice Revoke a nonce by spending it, preventing it from being used again
    /// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
    /// @dev payable so it can be multicalled with native-token related actions
    function revokeNonce(uint256 nonce) external payable;
}

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

import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";

/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
    /// @notice allows forwarding a single permit to permit2
    /// @dev this function is payable to allow multicall with NATIVE based actions
    /// @param owner the owner of the tokens
    /// @param permitSingle the permit data
    /// @param signature the signature of the permit; abi.encodePacked(r, s, v)
    /// @return err the error returned by a reverting permit call, empty if successful
    function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
        external
        payable
        returns (bytes memory err);

    /// @notice allows forwarding batch permits to permit2
    /// @dev this function is payable to allow multicall with NATIVE based actions
    /// @param owner the owner of the tokens
    /// @param _permitBatch a batch of approvals
    /// @param signature the signature of the permit; abi.encodePacked(r, s, v)
    /// @return err the error returned by a reverting permit call, empty if successful
    function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
        external
        payable
        returns (bytes memory err);
}

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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

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

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

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

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

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

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

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

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

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

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

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

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

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

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

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

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

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

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

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

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

import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";

/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
    /// @notice Called when a position subscribes to this subscriber contract
    /// @param tokenId the token ID of the position
    /// @param data additional data passed in by the caller
    function notifySubscribe(uint256 tokenId, bytes memory data) external;

    /// @notice Called when a position unsubscribes from the subscriber
    /// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
    /// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
    /// @param tokenId the token ID of the position
    function notifyUnsubscribe(uint256 tokenId) external;

    /// @notice Called when a position is burned
    /// @param tokenId the token ID of the position
    /// @param owner the current owner of the tokenId
    /// @param info information about the position
    /// @param liquidity the amount of liquidity decreased in the position, may be 0
    /// @param feesAccrued the fees accrued by the position if liquidity was decreased
    function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
        external;

    /// @notice Called when a position modifies its liquidity or collects fees
    /// @param tokenId the token ID of the position
    /// @param liquidityChange the change in liquidity on the underlying position
    /// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
    /// @dev Note that feesAccrued can be artificially inflated by a malicious user
    /// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
    /// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
    function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}

Settings
{
  "remappings": [
    "solady/=lib/solady/src/",
    "permit2/=lib/permit2/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-router/=lib/v4-periphery/lib/v4-router/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_posm","type":"address"},{"internalType":"address","name":"_permit2","type":"address"},{"internalType":"address","name":"_weth","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AllowanceOverflow","type":"error"},{"inputs":[],"name":"AllowanceUnderflow","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"AlreadyProcessed","type":"error"},{"inputs":[],"name":"CannotWithdrawStrategyToken","type":"error"},{"inputs":[],"name":"ContractPaused","type":"error"},{"inputs":[],"name":"ForceOperationInProgress","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidCurrency","type":"error"},{"inputs":[],"name":"InvalidPermit","type":"error"},{"inputs":[],"name":"ModuleNotWhitelisted","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"NoQueueExists","type":"error"},{"inputs":[],"name":"NoV2Liquidity","type":"error"},{"inputs":[],"name":"NotAuthorized","type":"error"},{"inputs":[],"name":"OnlyOwnerOrOperator","type":"error"},{"inputs":[],"name":"Permit2AllowanceIsFixedAtInfinity","type":"error"},{"inputs":[],"name":"PermitExpired","type":"error"},{"inputs":[],"name":"PoolLiquidityTooLow","type":"error"},{"inputs":[],"name":"PriceCalculationOverflow","type":"error"},{"inputs":[],"name":"PurchaseNotFound","type":"error"},{"inputs":[],"name":"QueueFull","type":"error"},{"inputs":[],"name":"Reentrancy","type":"error"},{"inputs":[],"name":"RouterNotApproved","type":"error"},{"inputs":[],"name":"RouterWETHMismatch","type":"error"},{"inputs":[],"name":"TargetNotReached","type":"error"},{"inputs":[],"name":"TokenNotWhitelisted","type":"error"},{"inputs":[],"name":"TotalSupplyOverflow","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"WrongExecutionFunction","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"EmergencyETHWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"EmergencyWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotal","type":"uint256"},{"indexed":true,"internalType":"address","name":"from","type":"address"}],"name":"FeesAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"initiator","type":"address"},{"indexed":false,"internalType":"uint256","name":"ethUsed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokensBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"ForceBurn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"purchaseId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ethReceived","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isProfit","type":"bool"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokensBurned","type":"uint256"},{"indexed":false,"internalType":"bool","name":"toTreasury","type":"bool"}],"name":"ForceSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"MemeTokenDelisted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"router","type":"address"}],"name":"MemeTokenWhitelisted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"module","type":"address"}],"name":"ModuleAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"module","type":"address"}],"name":"ModuleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"OperatorAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"OperatorRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"queueId","type":"uint256"}],"name":"QueueCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"queueId","type":"uint256"}],"name":"QueueRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"purchaseId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"queueId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"address","name":"executor","type":"address"},{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"tokenDecimals","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"buyPricePerToken","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"targetPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"targetMultiplier","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"slippageUsed","type":"uint256"},{"indexed":false,"internalType":"bool","name":"executeToTreasury","type":"bool"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"TokenPurchaseExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"queueId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"address","name":"router","type":"address"},{"indexed":false,"internalType":"uint256","name":"ethAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"targetMultiplier","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"maxSlippage","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"targetEntryPrice","type":"uint256"},{"indexed":true,"internalType":"address","name":"queuedBy","type":"address"},{"indexed":false,"internalType":"uint256","name":"treasuryBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"TokenPurchaseQueued","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"purchaseId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":true,"internalType":"address","name":"executor","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ethReceived","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isProfit","type":"bool"},{"indexed":false,"internalType":"uint256","name":"profitOrLossAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"memsBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"executorReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"buyPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sellPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"holdingDuration","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isFirstSale","type":"bool"},{"indexed":false,"internalType":"bool","name":"toTreasury","type":"bool"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"TokenSaleExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ethSpent","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBurned","type":"uint256"}],"name":"TokensBurned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"TradingEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"BPS_BASE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"result","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_BATCH_SIZE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_MULTIPLIER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SLIPPAGE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_MULTIPLIER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activePurchaseCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activeQueueCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_router","type":"address"}],"name":"addApprovedRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"addFeesETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_v2Router","type":"address"}],"name":"addMemeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_module","type":"address"}],"name":"addModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_operator","type":"address"}],"name":"addOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"approvedRouters","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"queueId","type":"uint256"}],"name":"clearQueue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"emergencyWithdrawETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"emergencyWithdrawTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"enableTrading","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"queueId","type":"uint256"}],"name":"executeQueuedPurchase","outputs":[{"internalType":"uint256","name":"purchaseId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_purchaseId","type":"uint256"}],"name":"executeSale","outputs":[{"internalType":"uint256","name":"profit","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_purchaseId","type":"uint256"}],"name":"executeSaleToTreasury","outputs":[{"internalType":"uint256","name":"profit","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"executorReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"failedFlips","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"ethAmount","type":"uint256"},{"internalType":"uint256","name":"slippageBPS","type":"uint256"}],"name":"forceBurn","outputs":[{"internalType":"uint256","name":"tokensBurned","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_ethAmount","type":"uint256"},{"internalType":"uint256","name":"_targetMultiplier","type":"uint256"},{"internalType":"uint256","name":"_maxSlippage","type":"uint256"},{"internalType":"bool","name":"_executeToTreasury","type":"bool"}],"name":"forceBuyMeme","outputs":[{"internalType":"uint256","name":"purchaseId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_purchaseId","type":"uint256"},{"internalType":"uint256","name":"_slippageBPS","type":"uint256"}],"name":"forceSell","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_purchaseId","type":"uint256"},{"internalType":"uint256","name":"_slippageBPS","type":"uint256"}],"name":"forceSellToTreasury","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_module","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"fundModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"hookAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"initializePoolAndAddLiquidity","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"maxBuybackSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxQueueSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxSaleSlippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxSinglePurchase","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minForceSellBPS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minSpikeThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"nextQueueId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"operators","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolInitialized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"pullFundsFromTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"purchases","outputs":[{"internalType":"uint256","name":"purchaseId","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"internalType":"uint256","name":"buyPricePerUnit","type":"uint256"},{"internalType":"uint256","name":"targetPrice","type":"uint256"},{"internalType":"uint256","name":"ethSpent","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"bool","name":"sold","type":"bool"},{"internalType":"uint256","name":"soldPrice","type":"uint256"},{"internalType":"uint256","name":"soldTimestamp","type":"uint256"},{"internalType":"bool","name":"isProfit","type":"bool"},{"internalType":"uint256","name":"profitOrLoss","type":"uint256"},{"internalType":"uint256","name":"slippageUsed","type":"uint256"},{"internalType":"bool","name":"executeToTreasury","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_ethAmount","type":"uint256"},{"internalType":"uint256","name":"_targetMultiplier","type":"uint256"},{"internalType":"uint256","name":"_maxSlippage","type":"uint256"},{"internalType":"uint256","name":"_targetEntryPrice","type":"uint256"},{"internalType":"bool","name":"_executeToTreasury","type":"bool"}],"name":"queueMemePurchase","outputs":[{"internalType":"uint256","name":"queueId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"queuedPurchases","outputs":[{"internalType":"uint256","name":"queueId","type":"uint256"},{"internalType":"address","name":"targetAddress","type":"address"},{"internalType":"uint256","name":"ethAmount","type":"uint256"},{"internalType":"uint256","name":"targetMultiplier","type":"uint256"},{"internalType":"uint256","name":"maxSlippage","type":"uint256"},{"internalType":"uint256","name":"targetEntryPrice","type":"uint256"},{"internalType":"uint256","name":"queuedAt","type":"uint256"},{"internalType":"bool","name":"executed","type":"bool"},{"internalType":"bool","name":"exists","type":"bool"},{"internalType":"bool","name":"executeToTreasury","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_router","type":"address"}],"name":"removeApprovedRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"removeMemeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_module","type":"address"}],"name":"removeModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_operator","type":"address"}],"name":"removeOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"queueId","type":"uint256"}],"name":"removeQueuedPurchase","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_reward","type":"uint256"}],"name":"setExecutorReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"}],"name":"setHookAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_slippage","type":"uint256"}],"name":"setMaxBuybackSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxSize","type":"uint256"}],"name":"setMaxQueueSize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_slippage","type":"uint256"}],"name":"setMaxSaleSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_max","type":"uint256"}],"name":"setMaxSinglePurchase","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minBPS","type":"uint256"}],"name":"setMinForceSellBPS","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_threshold","type":"uint256"}],"name":"setMinSpikeThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"successfulFlips","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"totalLoss","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalProfit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalPurchases","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalQueues","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalTokensBurned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tradingEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_newRouter","type":"address"}],"name":"updateTokenRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"whitelistedModules","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"whitelistedTokens","outputs":[{"internalType":"address","name":"v2Router","type":"address"},{"internalType":"bool","name":"isWhitelisted","type":"bool"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

0x61010080604052346102175760808161614a8038038091610020828561023d565b8339810103126102175761003381610274565b9061004060208201610274565b90610059606061005260408401610274565b9201610274565b6001600c556001600160a01b031691821561022e576001600160a01b031660a081905260405163dc4c90d360e01b815290602090829060049082905afa908115610223575f916101dd575b506080526001600160a01b0390811660c05260e09190915216638b78c6d8198190555f7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08180a3662386f26fc100006002556101f46003556101f46004556802b5e3af16b1880000601455671bc16d674ec800006015556113886005555f601655604051615ec190816102898239608051818181611b6401528181611c4401528181613ea701528181614ffc015281816150e8015281816158190152818161586d015281816159290152615cb2015260a051818181611c0f01528181611c76015281816139e10152614f9d015260c05181613a38015260e051818181610a060152818161114c01528181611e5c01528181612428015281816127b801528181612f6601528181613343015281816146670152615a320152f35b90506020813d60201161021b575b816101f86020938361023d565b8101031261021757516001600160a01b0381168103610217575f6100a4565b5f80fd5b3d91506101eb565b6040513d5f823e3d90fd5b63e6c4247b60e01b5f5260045ffd5b601f909101601f19168101906001600160401b0382119082101761026057604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036102175756fe6080604052600436101561004d575b3615610018575f80fd5b476040519034825260208201527f318f8a239412df7b37584cdc970509562cc8ea85492a3cc8622124bb1f72980c60403392a2005b5f803560e01c806306fdde031461536e578063095ea7b3146152d25780630d457ee1146152b557806313e7c9d814615278578063180dff8d1461525157806318160ddd1461522c5780631dbbaa9e146151b45780631ea09eae146151975780631ed86f191461511657806323b872dd14614ea15780632569296214614e585780632dc7865714614e3b5780632f28c10e14614e1e57806331372c1a14614de8578063313ce56714614dcd57806332a3cf9614614da557806332cb6b0c14614d7f5780633644e51514614cf75780633687ccf414614cda5780633f4ba83a14614cb6578063445b1e4b14614c795780634586332214614c325780634ada218b14614c1157806354d1f13d14614bcd5780635962a94114614bb05780635c975abb14614b8e5780635d6a618d14614b715780636720699414614b545780636b15231414614b375780636b792c4b14614ac5578063706cd95c14614a9e57806370a0823114614a6c578063710c2583146147e0578063715018a61461479757806371a062441461473f57806371cde3991461472257806376db057214614705578063795bd1bd146146e85780637ac07b15146145d75780637c8ba8a6146145495780637caf60ff1461451f5780637ecebe00146144ed578063828586aa146144c35780638392fe31146143ef5780638456cb59146143c857806386001519146143ab5780638a6d930f1461430b5780638a8c523c146142875780638da5cb5b1461425b578063917bb998146141c357806391dd734614613e56578063920c156214613d8b578063941e56571461386457806394c5829a1461320457806394f665f614612e2c57806395d89b4114612de15780639870d7fe14612d4a5780639b1225c4146126a75780639e08ac25146126845780639eaa1b0914612667578063a0632461146125ec578063a106a41414611cec578063a3756ebb14611cad578063a9059cbb14611aa4578063ac8a584a14611a26578063af06b55914611939578063b98ad25514611913578063b9a62754146117cd578063bcbe22f7146117af578063c07e1498146116a4578063c445baa214611686578063cfdbf2541461166a578063d157e3011461164c578063d505accf14611480578063d57e551414611011578063dad0801d146108f1578063dadb2b601461085f578063daf9c21014610811578063dcd631c11461068e578063dd62ed3e14610659578063e3b682ea1461059d578063ed03e78c14610581578063f04e283e14610533578063f2fde38b146104f4578063f38b5611146104b9578063f7088bc61461049b578063f7d9cc1e1461047d578063f9759518146104605763fee81cf41461042b575061000e565b3461045d57602036600319011261045d576104446153ad565b9063389a75e1600c5252602080600c2054604051908152f35b80fd5b503461045d578060031936011261045d5760206040516113888152f35b503461045d578060031936011261045d576020601654604051908152f35b503461045d578060031936011261045d576020600254604051908152f35b503461045d57602036600319011261045d576004356104d661572a565b61138881116104e55760045580f35b63162908e360e11b8252600482fd5b50602036600319011261045d576105096153ad565b61051161572a565b8060601b156105265761052390615762565b80f35b637448fbae82526004601cfd5b50602036600319011261045d576105486153ad565b61055061572a565b63389a75e1600c528082526020600c20805442116105745790826105239255615762565b636f5e881883526004601cfd5b503461045d578060031936011261045d57602060405160c88152f35b503461045d57604036600319011261045d576105b76153ad565b6105bf6153c3565b6105c761572a565b6001600160a01b031690811561064a57818352601760205260ff6040842054161561063b576001600160a01b0316808352600a602052604083205460a01c60ff161561062c578252600a6020526040822080546001600160a01b031916909117905580f35b6307c241ad60e51b8352600483fd5b63119e93c560e11b8352600483fd5b63e6c4247b60e01b8352600483fd5b503461045d57604036600319011261045d5760206106866106786153ad565b6106806153c3565b906156ed565b604051908152f35b503461045d5761069d366153d9565b916106a661572a565b3068929eee149b4bd212685414610804573068929eee149b4bd2126855601a5460ff8160081c166107f55761ff00191661010017601a5561138883116107e65781156107e6574782116107d7576011541515806107cb575b610774575b5061071961071360209383615b9e565b82615c25565b604080519283526020830182905242908301529033907f10bf0e47b0d990f69b0852e8e187b46263ac183e4f0ceab61070037d6bb9023f90606090a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b6006546001600160a01b0316803b156107c7578180916024604051809481936319a1ccbb60e01b83528860048401525af16107b0575b50610703565b816107ba91615461565b805f1261045d57806107aa565b5080fd5b506015548210156106fe565b631e9acf1760e31b8152600490fd5b63162908e360e11b8152600490fd5b6379b60e8b60e01b8252600482fd5b63ab143c0690526004601cfd5b503461045d57602036600319011261045d5760409081906001600160a01b036108386153ad565b168152600a602052205460ff82519160018060a01b038116835260a01c1615156020820152f35b503461045d57602036600319011261045d576004353068929eee149b4bd2126854146108e4573068929eee149b4bd2126855338252601860205260ff604083205416156108d5578047106108c6576108b79033615746565b3868929eee149b4bd212685580f35b631e9acf1760e31b8252600482fd5b638fd1408d60e01b8252600482fd5b63ab143c0682526004601cfd5b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff601354166110025750805f52600960205260405f20805415610ff357600781019081549060ff8216610fe4575f9360ff600d8301541615610fd557600182019360018060a01b03855416936002840154946040516370a0823160e01b8152306004820152602081602481855afa8015610f3b5787915f91610fa0575b5010610f9157805f52600a60205260405f2090604051916109c2836153ef565b5491602060ff60018060a01b0385169485845260a01c161515910152604051906109ed606083615461565b60028252604036602084013780610a03836155a8565b527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610a37836155c9565b5260405163d06ca61f60e01b81525f8180610a56868d600484016159a8565b0381875afa5f9181610f6d575b50610a77576365be670760e11b5f5260045ffd5b94610a8c828a610a86896155c9565b51615b15565b600489015411610f5e57610a9f866155c9565b51600354612710036127108111610f4a57610abf612710916001936159c2565b049560ff1916179055426009880155610ad6615afc565b803b15610f465760405163095ea7b360e01b81528360048201525f60248201525f8160448183865af18015610f3b57610f26575b50808a913b156107c75760405163095ea7b360e01b81526001600160a01b0385166004820152602481018a90529082908290604490829084905af18015610eea57610f0d575b5050479261012c420192834211610ef95790818b9493923b15610ef5578492838b93610b946040519788968795869463791ac94760e01b8652309260048701615615565b03925af18015610eea57610ed1575b5050610baf904761564e565b9081610bba826155c9565b511115610ec957610bd482610bce836155c9565b5161564e565b906127108202918083046127101490151715610eb55790610bf7610bfe926155c9565b51906159d5565b905b6002548110610ea6576005840193845492838311809484825f14610e975790610c289161564e565b985b8054610c40906001600160a01b03168a87615b15565b9260088501938455610c6183600a87019060ff801983541691151516179055565b8a600b860155600c8501558195610e8c575b8115610e6657610c858a600e5461559b565b600e558a8615610e06576006546001600160a01b0316803b156107c7578180809260246040518094819363092ddc5160e41b83528d60048401525af1610df1575b5050610d9b575b9960209a5b610cdd60115461551b565b6011555b610ced60025433615746565b60018060a01b0390541697549160025492610d136006600388015496549701544261564e565b966040519b8c528d8c015260408b015260608a01528960808a015260a089015260c088015260e087015261010086015261012085015215156101408401526001610160840152426101808401527f249461fdf7d29ea7abe6bfc09b464051b9f83c048367693dca40c27c7fa83c466101a03394a43868929eee149b4bd2126855604051908152f35b6006548b906001600160a01b0316803b156107c75781906024604051809481936319a1ccbb60e01b83528b60048401525af1610dd8575b50610ccd565b610de38c8092615461565b610ded575f610dd2565b8a80fd5b81610dfb91615461565b61045d57805f610cc6565b610e14575b9960209a610cd2565b6006548b906001600160a01b0316803b156107c75781906024604051809481936319a1ccbb60e01b83528b60048401525af1610e51575b50610e0b565b610e5c8c8092615461565b610ded575f610e4b565b9960209a610e768b600f5461559b565b600f55610e8460125461551b565b601255610ce1565b601154159550610c73565b610ea09161564e565b98610c2a565b631e9acf1760e31b8752600487fd5b634e487b7160e01b88526011600452602488fd5b508590610c00565b81610edb91615461565b610ee657865f610ba3565b8680fd5b6040513d84823e3d90fd5b8480fd5b634e487b7160e01b8b52601160045260248bfd5b81610f1791615461565b610f2257885f610b50565b8880fd5b610f33919a505f90615461565b5f985f610b0a565b6040513d5f823e3d90fd5b5f80fd5b634e487b7160e01b5f52601160045260245ffd5b6365be670760e11b5f5260045ffd5b610f8a9192503d805f833e610f828183615461565b81019061565b565b905f610a63565b631e9acf1760e31b5f5260045ffd5b9150506020813d602011610fcd575b81610fbc60209383615461565b81010312610f46578690515f6109a2565b3d9150610faf565b63015a4da360e11b5f5260045ffd5b632bf773b360e11b5f5260045ffd5b634496e09960e01b5f5260045ffd5b63ab35696f60e01b8152600490fd5b503461045d57611020366153d9565b9061102961572a565b3068929eee149b4bd212685414611473573068929eee149b4bd2126855601a5460ff8160081c166114645761ff00191661010017601a55808352600960205260408320805415611455576007810180549060ff821661144657612710851161143757600183019160018060a01b03835416906002850154926040516370a0823160e01b8152306004820152602081602481875afa801561142c5785918b916113f7575b50106113e857828952600a6020526040892092604051936110ec856153ef565b5493602060ff60018060a01b0387169687845260a01c16151591015261111b60058801998a54908684896159f8565b9160016040519461112d606087615461565b60028652604036602088013783611143876155a8565b52818060a01b037f000000000000000000000000000000000000000000000000000000000000000016611175876155c9565b5260ff191617905542600988015561118b615afc565b803b156113cd5760405163095ea7b360e01b81528460048201528a60248201528a808260448183875af180156113c0576113d1575b5050803b156113cd5760405163095ea7b360e01b81526001600160a01b038516600482015260248101869052908a9081908390604490829084905af180156113c0576113a9575b5050479261012c420191824211610ef957908a9291813b156113a55783611248956040519687958694859363791ac94760e01b855230918d60048701615615565b03925af1801561139a57611383575b509560a0926112d37f749892656f0d55173a238548a9c4a0ddf8c8e0d39b19e5947a821a5a6f9b5f419593600b61129060209b4761564e565b9954808b1196908b881561137257906112a89161564e565b9384935b6112c28d6112bc60045482615b9e565b90615c25565b96545f1960018c1b0116908d615b15565b60088201556112f187600a83019060ff801983541691151516179055565b0155836113505761130481600f5461559b565b600f5561131260125461551b565b6012555b6040519388855289850152604084015260608301526080820152a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b61135c81600e5461559b565b600e5561136a60115461551b565b601155611316565b61137b9161564e565b9384936112ac565b8761138d91615461565b865f12610ee6575f611257565b6040513d8a823e3d90fd5b8380fd5b6113b291615461565b885f12610f22575f89611207565b50604051903d90823e3d90fd5b8980fd5b6113da91615461565b895f126113cd575f8a6111c0565b631e9acf1760e31b8952600489fd5b9150506020813d602011611424575b8161141360209383615461565b81010312610f46578490515f6110cc565b3d9150611406565b6040513d8c823e3d90fd5b63162908e360e11b8652600486fd5b632bf773b360e11b8652600486fd5b634496e09960e01b8452600484fd5b6379b60e8b60e01b8452600484fd5b63ab143c0683526004601cfd5b503461045d5760e036600319011261045d5761149a6153ad565b6114a26153c3565b604435606435906084359260ff84168403611648576001600160a01b0316936e22d473030f116ddee9f6b43ac78ba38518821915171561163b576114e4615483565b602081519101209280421161162e576040519160018060a01b03169465383775081901600e5285885260c06020600c20938454937f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252602082019788528460408301987fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc68a528b606085019a468c528c608087019330855260a08820602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988525252888a525260a082015220604e526042602c20885260ff1660205260a43560405260c43560605260208060808960015afa90853d5103611621570190556303faf4f960a51b84176040526034602c20557f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a380f35b63ddafbaef88526004601cfd5b631a15a3cc87526004601cfd5b633f68539a86526004601cfd5b8580fd5b503461045d578060031936011261045d576020601054604051908152f35b503461045d578060031936011261045d57602060405160328152f35b503461045d578060031936011261045d576020600d54604051908152f35b503461045d57602036600319011261045d57638b78c6d81954600435906001600160a01b031633141580611798575b61178957808252600b602052600760408320015460ff8160081c161590811561177e575b5061176f57808252600b60205261173a6040832060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b611745600d546156e1565b600d557f1c899aec6b677cce6148a2f50b400ad80179a5ca200b00fc7ce7f8405ff62d258280a280f35b6383c52cf760e01b8252600482fd5b60ff9150165f6116f7565b63089b7a0760e41b8252600482fd5b50338252600160205260ff604083205416156116d3565b503461045d578060031936011261045d576020600554604051908152f35b503461045d57604036600319011261045d576117e76153ad565b6117ef6153c3565b9060018060a01b03638b78c6d8195416331415806118fc575b6118ed576001600160a01b031690811580156118dc575b61064a576001600160a01b03168083526017602052604083205490919060ff161561063b57808352600a60205260ff604084205460a01c1615611860578280f35b60405161186c816153ef565b82815260016020808301918252838652600a9052604085209151825491516001600160a81b03199092166001600160a01b03919091161790151560a01b60ff60a01b161790557f670d89413ae6972219aaf1aeb3c8168012d92e210628e058e9f5ac8d64adfb3a8380a35f808280f35b506001600160a01b0381161561181f565b63089b7a0760e41b8352600483fd5b50338352600160205260ff60408420541615611808565b503461045d578060031936011261045d57602060ff60065460a01c166040519015158152f35b503461045d57602036600319011261045d57638b78c6d81954600435906001600160a01b031633141580611a0f575b61178957808252600b602052600760408320015460ff8160081c1615908115611a04575b5061176f57808252600b6020526119cf6040832060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b6119da600d546156e1565b600d557f6e7a8b064487ccb89997e2d58592a670e1737cfc714efcd1c5a47fef9b23685a8280a280f35b60ff9150165f61198c565b50338252600160205260ff60408320541615611968565b503461045d57602036600319011261045d57611a406153ad565b611a4861572a565b6001600160a01b03168082526001602052604082205460ff16611a69575080f35b808252600160205260408220805460ff191690557f80c0b871b97b595b16a7741c1b06fed0c6f6f558639f18ccbce50724325dc40d8280a280f35b503461045d57604036600319011261045d57611abe6153ad565b6024359160ff81541615611b2b575b6387a211a2600c523381526020600c208054808511611b1e578490039055526020600c20818154019055602052600c5160601c335f80516020615e6c833981519152602080a3602060405160018152f35b63f4d678b883526004601cfd5b638b78c6d819546001600160a01b03163381148015611ca4575b8015611c72575b8015611c40575b6001600160a01b03848116801593917f000000000000000000000000000000000000000000000000000000000000000016338114611bb5575b505050159081611bac575b5015611acd5763ab35696f60e01b8152600490fd5b9050155f611b97565b8114918215611c0d575b8215611c03575b508115611bf9575b508015611bf2575b15611be3575f8080611b8c565b63ab35696f60e01b8352600483fd5b5081611bd6565b905030145f611bce565b811491505f611bc6565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031682149250611bbf565b50337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031614611b53565b50337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031614611b4c565b50303314611b45565b503461045d57602036600319011261045d5760209060ff906040906001600160a01b03611cd86153ad565b168152601884522054166040519015158152f35b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff6013541661100257818152600b60205260408120916007830180549360ff8560081c16159485158096906125e2575b6125d357604051611d608161540b565b8254815260018060a01b0360018401541660208201818152600285015494604084019586526003810154926060850193845260048201549a608086019b8c52600583015490600660a0880194838652015460c088015260ff8816151560e088015261010087015260ff61012087019760101c16151587526123d3575b5050611dec85516002549061559b565b47106123c45760018060a01b039051169351905197519151925115155f98855f52600a60205260405f2060405190611e23826153ef565b5490602060ff60018060a01b0384169384845260a01c16151591015260405190611e4e606083615461565b6002825260403660208401377f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316611e8d836155a8565b5287611e98836155c9565b5260405163d06ca61f60e01b81525f8180611eb7868a600484016159a8565b0381855afa5f91816123a8575b50611ed857630b99e1d760e31b5f5260045ffd5b611ee1906155c9565b5195612710036127108111610f4a57611efd61271091886159c2565b6040516370a0823160e01b8152306004820152939190046020846024818d5afa938415610f3b575f94612374575b5061012c420192834211610f4a57803b15610f46575f9288611f71936040519687958694859363b6f9de9560e01b855260048501526080602485015260848401906155d9565b90306044840152606483015203925af18015610f3b5761235f575b506040516370a0823160e01b8152306004820152906020826024818b5afa8015612354578c90612320575b611fc1925061564e565b938481111561231857611fd4858261564e565b61271081029080820461271014901517156123045790611ff3916159d5565b905b60405163313ce56760e01b81529a60208c6004818b5afa9b8c156113c057819c6122d3575b50612026888787615b15565b9082612710019081612710116122bf5781156122ab57815f1904831161229c575061205190826159c2565b6127109004906007546120639061551b565b9c8d97886007558a87878b60405161207a81615444565b81815260208101948552604081018681528d60608301908a825260808401908c825260a0850190815260c085019042825260e08601925f84526101008701945f86526101208801965f88526101408901985f8a5261016081019a5f8c5261018082019c8d526101a082019d8e525f52600960205260405f209d8e91518255600160a01b600190039051169060010190600160a01b60019003166001600160601b0360a01b8254161790555160028d01555160038c01555160048b01555160058a0155516006890155511515600788019061215f919060ff801983541691151516179055565b516008870155516009860155511515600a850190612188919060ff801983541691151516179055565b51600b84015551600c83015551151590600d01906121b1919060ff801983541691151516179055565b6019546121bd9061551b565b601955604051973389526020890152604088015260ff166060870152608086015260a085015260c084015260e0830152610100820152426101208201526101407f99de35bc627d2b927519c1e6bf7bdd9a5a309af85385bd394ef9979015bab98491a460025461222d9033615746565b60ff1981541660011790558152600b602052604090206122769060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b600d54612282906156e1565b600d553868929eee149b4bd2126855604051908152602090f35b63eb54e4d360e01b8152600490fd5b634e487b7160e01b81526012600452602490fd5b634e487b7160e01b81526011600452602490fd5b6122f6919c5060203d6020116122fd575b6122ee8183615461565b8101906159df565b9a5f61201a565b503d6122e4565b634e487b7160e01b8c52601160045260248cfd5b508990611ff5565b506020823d60201161234c575b8161233a60209383615461565b81010312610f4657611fc19151611fb7565b3d915061232d565b6040513d8e823e3d90fd5b61236c919b505f90615461565b5f995f611f8c565b9093506020813d6020116123a0575b8161239060209383615461565b81010312610f465751925f611f2b565b3d9150612383565b6123bd9192503d805f833e610f828183615461565b905f611ec4565b631e9acf1760e31b8852600488fd5b8952600a6020526124a08960408120604051906123ef826153ef565b5490602060ff60018060a01b0384169384845260a01c1615159101526040519061241a606083615461565b6002825260403660208401377f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316612459836155a8565b5285516001600160a01b031661246e836155c9565b52604051808095819463d06ca61f60e01b8352670de0b6b3a764000060048401526040602484015260448301906155d9565b03915afa8a91816125b7575b506124c057630b99e1d760e31b8a5260048afd5b6124c9906155c9565b5180156125a857825160405163313ce56760e01b815290602090829060049082906001600160a01b03165afa8015610f3b5760ff915f91612589575b5016604d8111610f4a57600a0a90811561257557815f1904670de0b6b3a76400001161256657670de0b6b3a76400008281029290830403610f4a57612549916159d5565b905110612557575f80611ddc565b6365be670760e11b8852600488fd5b63eb54e4d360e01b5f5260045ffd5b634e487b7160e01b5f52601260045260245ffd5b6125a2915060203d6020116122fd576122ee8183615461565b5f612505565b63162908e360e11b8a5260048afd5b6125cc9192503d808d833e610f828183615461565b905f6124ac565b6383c52cf760e01b8552600485fd5b5060ff8116611d50565b503461045d57602036600319011261045d576126066153ad565b61260e61572a565b6001600160a01b03168082526018602052604082205460ff16156108d557808252601860205260408220805460ff191690557f0a1ee69f55c33d8467c69ca59ce2007a737a88603d75392972520bf67cb513b88280a280f35b503461045d578060031936011261045d5760206040516127108152f35b503461045d57602036600319011261045d5761269e61572a565b60043560165580f35b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff601354166110025750805f52600960205260405f20805415610ff3576007810180549060ff8216610fe45760ff600d84015416610fd5575f93600184019460018060a01b038654166002860154946040516370a0823160e01b8152306004820152602081602481865afa8015610f3b5787915f91612d15575b5010610f9157815f52600a60205260405f2060405190612774826153ef565b5490602060ff60018060a01b0384169384845260a01c1615159101526040519261279f606085615461565b600284526040366020860137806127b5856155a8565b527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166127e9856155c9565b5260405163d06ca61f60e01b81525f8180612808888d600484016159a8565b0381865afa5f9181612cf9575b50612829576365be670760e11b5f5260045ffd5b96612838828a610a868b6155c9565b60048b015411610f5e5761284b886155c9565b51600354612710036127108111610f4a5761286b612710916001936159c2565b049460ff19161790554260098a0155612882615afc565b803b15610f465760405163095ea7b360e01b81528260048201525f60248201525f8160448183865af18015610f3b57612ce4575b50803b15610ef55760405163095ea7b360e01b81526001600160a01b0383166004820152602481018990529085908290604490829084905af18015612cd957908591612cc4575b5050479261012c420192834211612cb057823b156116485791889186809461293d6040519788968795869463791ac94760e01b8652309260048701615615565b03925af18015612ca557908391612c90575b505061295b904761564e565b9283612966826155c9565b511115612c885761297a84610bce836155c9565b906127108202918083046127101490151715612c745790610bf761299d926155c9565b925b60025495868210612c6557908160056129d993019586546129e581851195869286845f14612c5657906129d19161564e565b9b5b8661564e565b6112bc60045482615b9e565b8b546129fb906001600160a01b03168b87615b15565b9260088501938455612a1c83600a87019060ff801983541691151516179055565b8b600b860155600c8501558195612c4b575b8115612c2657612a408b600e5461559b565b600e558515612bc2576006546001600160a01b0316803b15612ba9578780809260246040518094819363092ddc5160e41b83528c60048401525af1612bad575b5050601554851015612b58575b60209b5b612a9c60115461551b565b6011555b612aac60025433615746565b60018060a01b0390541698549160025492612ad26006600388015496549701544261564e565b966040519c8d528e8d015260408c015260608b01528a60808b015260a08a015260c089015260e08801526101008701526101208601521515610140850152610160840152426101808401527f249461fdf7d29ea7abe6bfc09b464051b9f83c048367693dca40c27c7fa83c466101a03394a43868929eee149b4bd2126855604051908152f35b6006546001600160a01b0316803b15612ba9578780916024604051809481936319a1ccbb60e01b83528b60048401525af1612b94575b50612a8d565b612b9f888092615461565b610ee6575f612b8e565b8780fd5b81612bb791615461565b610ee657865f612a80565b601554851015612bd5575b60209b612a91565b6006546001600160a01b0316803b15612ba9578780916024604051809481936319a1ccbb60e01b83528b60048401525af1612c11575b50612bcd565b612c1c888092615461565b610ee6575f612c0b565b60209b612c358c600f5461559b565b600f55612c4360125461551b565b601255612aa0565b601154159550612a2e565b612c5f9161564e565b9b6129d3565b631e9acf1760e31b8352600483fd5b634e487b7160e01b83526011600452602483fd5b50809261299f565b81612c9a91615461565b6107c757815f61294f565b6040513d85823e3d90fd5b634e487b7160e01b86526011600452602486fd5b81612cce91615461565b6113a557835f6128fd565b6040513d87823e3d90fd5b612cf19195505f90615461565b5f935f6128b6565b612d0e9192503d805f833e610f828183615461565b905f612815565b9150506020813d602011612d42575b81612d3160209383615461565b81010312610f46578690515f612755565b3d9150612d24565b503461045d57602036600319011261045d57612d646153ad565b612d6c61572a565b6001600160a01b03168015612dd257808252600160205260ff60408320541615612d94575080f35b808252600160205260408220600160ff198254161790557fac6fa858e9350a46cec16539926e0fde25b7629f84b5a72bffaae4df888ae86d8280a280f35b63e6c4247b60e01b8252600482fd5b503461045d578060031936011261045d57612e28604051612e03604082615461565b60048152634d454d5360e01b6020820152604051918291602083526020830190615389565b0390f35b503461045d57612e3b366153d9565b90612e4461572a565b3068929eee149b4bd212685414611473573068929eee149b4bd2126855601a5460ff8160081c166114645761ff00191661010017601a558083526009602052604083208054156114555760078101805460ff811661144657612710851161143757600183019060018060a01b03825416906002850154936040516370a0823160e01b8152306004820152602081602481875afa801561142c5786918b916131cf575b50106113e857828952600a602052604089209260405193612f06856153ef565b5493602060ff60018060a01b0387169687845260a01c161515910152612f3560058801998a549086848a6159f8565b91600160405194612f47606087615461565b60028652604036602088013783612f5d876155a8565b52818060a01b037f000000000000000000000000000000000000000000000000000000000000000016612f8f876155c9565b5260ff1916179055426009880155612fa5615afc565b803b156113cd5760405163095ea7b360e01b81528460048201528a60248201528a808260448183875af180156113c0576131b8575b5050803b156113cd5760405163095ea7b360e01b81526001600160a01b038516600482015260248101879052908a9081908390604490829084905af180156113c0576131a1575b5050479261012c420192834211610ef957908a9291813b156113a55760405163791ac94760e01b81529485938492869284926130639230918e60048701615615565b03925af1801561139a5761318a575b509560a0927f749892656f0d55173a238548a9c4a0ddf8c8e0d39b19e5947a821a5a6f9b5f419492600b6130a860209a4761564e565b9854946130d8868b11968b885f1461317957906130c49161564e565b9485945b545f1960018b1b0116908c615b15565b60088201556130f686600a83019060ff801983541691151516179055565b0155826131575761310981600f5461559b565b600f5561311760125461551b565b6012555b60405192878452888401526040830152606082015260016080820152a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b61316381600e5461559b565b600e5561317160115461551b565b60115561311b565b6131829161564e565b9485946130c8565b8761319491615461565b865f12610ee6575f613072565b6131aa91615461565b885f12610f22575f89613021565b6131c191615461565b895f126113cd575f8a612fda565b9150506020813d6020116131fc575b816131eb60209383615461565b81010312610f46578590515f612ee6565b3d91506131de565b503461045d5760a036600319011261045d5761321e6153ad565b9060243560443560843590811515809203610f4657638b78c6d819546001600160a01b03163314158061384d575b61383e573068929eee149b4bd212685414613831573068929eee149b4bd212685560ff601354166138225760018060a01b03851693848152600a6020526040812060ff6040519161329c836153ef565b546001600160a01b038116835260a01c161580156020909201919091526138135783156107e65760145484116107e6576103e882108015613807575b6107e6576132e86002548561559b565b47106107d757505f90845f52600a60205260405f20956040519661330b886153ef565b5496602060ff60018060a01b038a16998a845260a01c161515910152604051613335606082615461565b6002815260403660208301377f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316613374826155a8565b528661337f826155c9565b5260405163d06ca61f60e01b81525f818061339e858b600484016159a8565b03818c5afa5f91816137eb575b506133bf57630b99e1d760e31b5f5260045ffd5b6133c8906155c9565b5197606435612710036127108111610f4a576133e7612710918b6159c2565b6040516370a0823160e01b8152306004820152939190046020846024818d5afa938415610f3b575f946137b7575b5061012c420192834211610f4a57803b15610f46575f928a61345b936040519687958694859363b6f9de9560e01b855260048501526080602485015260848401906155d9565b90306044840152606483015203925af18015610f3b576137a2575b506040516370a0823160e01b8152306004820152906020826024818b5afa8015612cd957859061376e575b6134ab925061564e565b9687811115613767576134be888261564e565b612710810290808204612710149015171561375357906134dd916159d5565b925b60405163313ce56760e01b8152916020836004818b5afa928315610eea57829361372e575b50613510908988615b15565b9083612710019081612710116122bf5781156122ab57815f1904831161229c575061353b90826159c2565b61271090049160075461354d9061551b565b988960075560405161355e81615444565b8a815287878c60208401938d8552604081018681528d60608301908a825260808401908c825260a0850190815260c085019042825260e08601925f84526101008701945f86526101208801965f88526101408901985f8a5261016081019a5f8c5261018082019c8d526101a082019d8e525f52600960205260405f209d8e91518255600160a01b600190039051169060010190600160a01b60019003166001600160601b0360a01b8254161790555160028d01555160038c01555160048b01555160058a01555160068901555115156007880190613647919060ff801983541691151516179055565b516008870155516009860155511515600a850190613670919060ff801983541691151516179055565b51600b84015551600c83015551151590600d0190613699919060ff801983541691151516179055565b6019546136a59061551b565b601955604051973389526020890152604088015260ff166060870152608086015260a085015260c084015260e083015261010082015282426101208301527f99de35bc627d2b927519c1e6bf7bdd9a5a309af85385bd394ef9979015bab9846101405f93a46002546137179033615746565b3868929eee149b4bd2126855604051908152602090f35b61351091935061374c9060203d6020116122fd576122ee8183615461565b9290613504565b634e487b7160e01b85526011600452602485fd5b50826134df565b506020823d60201161379a575b8161378860209383615461565b81010312610f46576134ab91516134a1565b3d915061377b565b6137af9194505f90615461565b5f925f613476565b9093506020813d6020116137e3575b816137d360209383615461565b81010312610f465751925f613415565b3d91506137c6565b6138009192503d805f833e610f828183615461565b905f6133ab565b50620f1b3082116132d8565b6307c241ad60e51b8152600490fd5b63ab35696f60e01b8452600484fd5b63ab143c0684526004601cfd5b63089b7a0760e41b8452600484fd5b50338452600160205260ff6040852054161561324c565b60a0366003190112610f46576138786153ad565b602435906fffffffffffffffffffffffffffffffff8216809203610f46576044356001600160a01b0381169190829003610f4657606435908160020b809203610f4657608435908160020b809203610f46576138d261572a565b3068929eee149b4bd212685414613d7e573068929eee149b4bd212685560ff60065460a01c16610fe4576001600160a01b0316908115613d6f578415613d60573415613d60576805345cdf77eb68f44c546b033b2e3c9fd0803ce80000008101908110613d53576805345cdf77eb68f44c556387a211a2600c52305f526020600c206b033b2e3c9fd0803ce800000081540190556b033b2e3c9fd0803ce8000000602052600c5160601c5f5f80516020615e6c833981519152602080a3600680546001600160a01b03191683179055604051926139ae84615428565b5f80855230602086019081526040860191909152603c6060860152608085019390935260405163f702040560e01b8152947f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169390613a186004880187615529565b60a48701525a9560208160c4815f89819cf18015610f3b57613d1a575b507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031694613a6a866154ad565b5061012c420195864211610f4a57803b15610f46576040516387517c4560e01b8152306004820152602481018790526001600160a01b03604482015265ffffffffffff88166064820152905f908290608490829084905af18015610f3b57613d05575b50604051600160f91b6020820152600d60f81b60218201526002815292613af5602285615461565b60609460405199613b06878c615461565b60028b52601f1987018a5b888d838310613cf5575050505090613bfd9594939291638b78c6d819549160405193613b406020860187615529565b60c085015260e0840152610100830152346101208301526b033b2e3c9fd0803ce80000006101408301526001600160a01b0316610160820152610180808201526101a08082018a90528152613b976101c082615461565b613ba08a6155a8565b52613baa896155a8565b50519051604080516001600160a01b03938416602082015292909116828201528152613bd68482615461565b613bdf886155c9565b52613be9876155c9565b506040519260406020850152830190615389565b601f19828203016040830152855180825260208201916020808360051b83010198019287915b838310613cc8575050505050613c4381859603601f198101835282615461565b813b15613cc3578391613c749160405180958194829363dd46508f60e01b8452604060048501526044840190615389565b906024830152039134905af18015610eea57613cae575b506006805460ff60a01b1916600160a01b1790553868929eee149b4bd212685580f35b81613cb891615461565b61045d578082613c8b565b505050fd5b9091929398602080613ce6600193601f198682030187528d51615389565b9b019301930191939290613c23565b9060208381949301015201613b11565b613d129197505f90615461565b5f9588613acd565b6020813d602011613d4b575b81613d3360209383615461565b81010312610f4657518060020b810315613a35575f80fd5b3d9150613d26565b63e5cfe9575f526004601cfd5b63162908e360e11b5f5260045ffd5b63e6c4247b60e01b5f5260045ffd5b63ab143c065f526004601cfd5b34610f46576020366003190112610f4657613da46153ad565b638b78c6d819546001600160a01b031633141580613e3f575b613e30576001600160a01b03165f818152600a602052604090205460a01c60ff1615613e21575f818152600a60205260408120805460ff60a01b191690557fe6d4e8c78bb42602884e0e162c56ea85d4c168529e664f0f8352ab8d1aafb17e9080a2005b6307c241ad60e51b5f5260045ffd5b63089b7a0760e41b5f5260045ffd5b50335f52600160205260ff60405f20541615613dbd565b34610f46576020366003190112610f465760043567ffffffffffffffff8111610f465736602382011215610f4657806004013567ffffffffffffffff8111610f4657810190366024830111610f46577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691338390036141b45760ff601a5416156141b45760409082900312610f4657602481013580151591828203610f465760018060a01b03600654169160405191613f1783615428565b5f835260208301933085525f6040850152603c60608501526080840152815f14614199576401000276a4905b604051956060870187811067ffffffffffffffff8211176141855760405286526044602087019101358152604086019160018060a01b0316825260405195633cf3645360e21b8752613f986004880186615529565b51151560a48701525160c486015260018060a01b0390511660e48501526101206101048501525f610124850152602084610144815f895af1938415610f3b575f94614151575b50156140ed578260801d905f82600f0b12614052575b5050612e28925081600f0b5f8113614036575b50505b60405190602082015260208152614022604082615461565b604051918291602083526020830190615389565b905161404b91906001600160a01b0316615927565b8280614007565b516001600160a01b0316806140ce575061406d60209161556c565b600f0b93600460405180968193630476982d60e21b83525af1928315610f3b57612e289361409f575b505b8380613ff4565b6140c09060203d6020116140c7575b6140b88183615461565b81019061558c565b5083614096565b503d6140ae565b612e2894506140df6140e89261556c565b600f0b906157f0565b614098565b90612e28935082600f0b5f8112614133575b50508160801d600f0b5f8113614117575b505061400a565b905161412c91906001600160a01b0316615927565b8280614110565b6140df61414a9260018060a01b039051169161556c565b83806140ff565b9093506020813d60201161417d575b8161416d60209383615461565b81010312610f4657519285613fde565b3d9150614160565b634e487b7160e01b5f52604160045260245ffd5b73fffd8963efd1fc6a506488495d951d5263988d2590613f43565b63ea8e4eb560e01b5f5260045ffd5b34610f46576040366003190112610f46576141dc6153ad565b6024356141e761572a565b6001600160a01b0382169130831461424c578161422f7faaeda929aa102e867049528ec7cd2499e3a2f8846e736ae7935f234dfbf500d993604093638b78c6d819549061579f565b638b78c6d8195482519182526001600160a01b03166020820152a2005b63c03b13ef60e01b5f5260045ffd5b34610f46575f366003190112610f4657638b78c6d819546040516001600160a01b039091168152602090f35b34610f46575f366003190112610f4657638b78c6d819546001600160a01b0316331415806142f4575b613e30575f5460ff8116610fe45760019060ff1916175f557fb3da2db3dfc3778f99852546c6e9ab39ec253f9de7b0847afec61bd27878e9236020604051428152a1005b50335f52600160205260ff60405f205416156142b0565b34610f46576020366003190112610f46576004355f52600b60205261014060405f2060ff81549160018060a01b0360018201541690600281015460038201546004830154906005840154926007600686015495015495604051988952602089015260408801526060870152608086015260a085015260c0840152818116151560e0840152818160081c16151561010084015260101c161515610120820152f35b34610f46575f366003190112610f46576020600e54604051908152f35b34610f46575f366003190112610f46576143e061572a565b6013805460ff19166001179055005b34610f46576020366003190112610f46576004355f5260096020526101c060405f2080549060018060a01b03600182015416906002810154600382015460048301546005840154600685015460ff6007870154169060088701549260098801549460ff600a8a01541696600b8a01549860ff600d600c8d01549c0154169b60206040519e8f908152015260408d015260608c015260808b015260a08a015260c0890152151560e0880152610100870152610120860152151561014085015261016084015261018083015215156101a0820152f35b34610f46576020366003190112610f46576004356144df61572a565b6127108111613d6057600555005b34610f46576020366003190112610f46576145066153ad565b6338377508600c525f52602080600c2054604051908152f35b34610f46576020366003190112610f465760043561453b61572a565b6113888111613d6057600355005b34610f46576040366003190112610f46576145626153ad565b60243561456d61572a565b3068929eee149b4bd212685414613d7e573068929eee149b4bd21268556001600160a01b0382165f9081526018602052604090205460ff16156145c857804710610f91576145ba91615746565b3868929eee149b4bd2126855005b638fd1408d60e01b5f5260045ffd5b34610f46576020366003190112610f46576145f06153ad565b6145f861572a565b6001600160a01b03168015613d6f57805f52601760205260ff60405f2054161561461e57005b6040516315ab88c960e31b8152602081600481855afa5f91816146a4575b5061465d575b505f908152601760205260409020805460ff19166001179055005b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081169116036146955781614642565b633a2619c960e11b5f5260045ffd5b9091506020813d6020116146e0575b816146c060209383615461565b81010312610f4657516001600160a01b0381168103610f4657908361463c565b3d91506146b3565b34610f46575f366003190112610f46576020600354604051908152f35b34610f46575f366003190112610f46576020601454604051908152f35b34610f46575f366003190112610f46576020601954604051908152f35b34610f46576020366003190112610f46576147586153ad565b61476061572a565b6001600160a01b03165f8181526017602052604090205460ff1661478057005b5f908152601760205260409020805460ff19169055005b5f366003190112610f46576147aa61572a565b5f638b78c6d819547f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a35f638b78c6d81955005b34610f465760c0366003190112610f46576147f96153ad565b60243590604435606435926084359060a43593841515809503610f4657638b78c6d819546001600160a01b031633141580614a55575b613e30576113888611613d605760018060a01b031691825f52600a60205260405f209560ff60405197614861896153ef565b546001600160a01b038116895260a01c161580156020890152613e21578215613d60576014548311613d605760c885108015614a49575b613d60576016548015159081614a3c575b50614a2d57602096600c54966148be8861551b565b600c556148cc60085461551b565b600855604051906148dc8261540b565b8882528861499860078c8501948a8652604081018a8152606082018d8152608083018a815260a08401918c835260c085019342855260e086019a5f8c5261010087019960018b5261012088019b8c525f526020600b905260405f209651875560018060a01b03905116600187019060018060a01b03166001600160601b0360a01b8254161790555160028601555160038501555160048401555160058301555160068201550193511515849060ff801983541691151516179055565b518254915162ffff001990921690151560081b61ff00161790151560101b62ff000016179055600d546149ca9061551b565b600d5560018060a01b039051169447936040519687528887015260408601526060850152608084015260a08301524260c0830152827fdd0602ca2177d4659e08f6824ebc6f123ee4d8440e33aab9ba4e625f2eb32fcb60e03394a4604051908152f35b638acb5f2760e01b5f5260045ffd5b9050600d541015886148a9565b50620f1b308511614898565b50335f52600160205260ff60405f2054161561482f565b34610f46576020366003190112610f4657614a856153ad565b6387a211a2600c525f52602080600c2054604051908152f35b34610f46576020366003190112610f4657600435614aba61572a565b8015613d6057601555005b34610f46576020366003190112610f4657600435614ae161572a565b478111610f9157614af881638b78c6d81954615746565b638b78c6d819546040519182526001600160a01b0316907f9520fe2678e0516c00ad6efc90d2ee6857e665081c3fc5c80b83764400360e1090602090a2005b34610f46575f366003190112610f46576020601154604051908152f35b34610f46575f366003190112610f46576020601254604051908152f35b34610f46575f366003190112610f46576020604051620f1b308152f35b34610f46575f366003190112610f4657602060ff601354166040519015158152f35b34610f46575f366003190112610f46576020600754604051908152f35b5f366003190112610f465763389a75e1600c52335f525f6020600c2055337ffa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c925f80a2005b34610f46575f366003190112610f4657602060ff5f54166040519015158152f35b34610f46576020366003190112610f4657614c4b6153ad565b614c5361572a565b6001600160a01b03168015613d6f576001600160601b0360a01b60065416176006555f80f35b34610f46576020366003190112610f46576001600160a01b03614c9a6153ad565b165f526017602052602060ff60405f2054166040519015158152f35b34610f46575f366003190112610f4657614cce61572a565b6013805460ff19169055005b34610f46575f366003190112610f46576020600454604051908152f35b34610f46575f366003190112610f4657602060a0614d13615483565b828151910120604051907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252838201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015220604051908152f35b34610f46575f366003190112610f465760206040516b033b2e3c9fd0803ce80000008152f35b34610f46575f366003190112610f46576006546040516001600160a01b039091168152602090f35b34610f46575f366003190112610f4657602060405160128152f35b34610f46576020366003190112610f4657600435614e0461572a565b8015613d6057670de0b6b3a76400008111613d6057600255005b34610f46575f366003190112610f46576020601554604051908152f35b34610f46575f366003190112610f46576020600854604051908152f35b5f366003190112610f465763389a75e1600c52335f526202a30042016020600c2055337fdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d5f80a2005b34610f46576060366003190112610f4657614eba6153ad565b614ec26153c3565b6044359060ff5f541615614f9b575b8260601b6e22d473030f116ddee9f6b43ac78ba33303614f51575b6387a211a217600c526020600c208054808411614f445783900390555f526020600c20818154019055602052600c5160601c9060018060a01b03165f80516020615e6c833981519152602080a3602060405160018152f35b63f4d678b85f526004601cfd5b33602052637f5e9f208117600c526034600c20908154918219614f77575b509050614eec565b828511614f8e57846387a211a29303905585614f6f565b6313be252b5f526004601cfd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031633811480156150e4575b638b78c6d819546001600160a01b0386811691168181149390929184156150da575b159283156150c8575b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690338214615067575b50505015918261505e575b5081615055575b5015614ed1575b63ab35696f60e01b5f5260045ffd5b9050158461503f565b15915085615038565b6001600160a01b0387169182149283156150be575b5082156150b4575b5081156150aa575b81156150a1575b50156150465786808061502d565b90501587615093565b308114915061508c565b8114915088615084565b821492508961507c565b6001600160a01b038616159350614ffa565b3081149450614ff1565b50337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031614614fcf565b34610f46576020366003190112610f465761512f6153ad565b61513761572a565b6001600160a01b03168015613d6f57805f52601860205260ff60405f205416610fe457805f52601860205260405f20600160ff198254161790557fead6a006345da1073a106d5f32372d2d2204f46cb0b4bca8f5ebafcbbed12b8a5f80a2005b34610f46575f366003190112610f46576020600c54604051908152f35b5f366003190112610f46576006546001600160a01b031633141580615213575b6141b4573415613d6057476040519034825260208201527f318f8a239412df7b37584cdc970509562cc8ea85492a3cc8622124bb1f72980c60403392a2005b50638b78c6d819546001600160a01b03163314156151d4565b34610f46575f366003190112610f465760206805345cdf77eb68f44c54604051908152f35b34610f46576020366003190112610f465760043561526d61572a565b8015613d6057601455005b34610f46576020366003190112610f46576001600160a01b036152996153ad565b165f526001602052602060ff60405f2054166040519015158152f35b34610f46575f366003190112610f46576020600f54604051908152f35b34610f46576040366003190112610f46576152eb6153ad565b602435906001600160a01b0381166e22d473030f116ddee9f6b43ac78ba318821915171561536157602052637f5e9f20600c52335f52806034600c20555f52602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3602060405160018152f35b633f68539a5f526004601cfd5b34610f46575f366003190112610f4657612e28614022615483565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b0382168203610f4657565b602435906001600160a01b0382168203610f4657565b6040906003190112610f46576004359060243590565b6040810190811067ffffffffffffffff82111761418557604052565b610140810190811067ffffffffffffffff82111761418557604052565b60a0810190811067ffffffffffffffff82111761418557604052565b6101c0810190811067ffffffffffffffff82111761418557604052565b90601f8019910116810190811067ffffffffffffffff82111761418557604052565b60405190615492604083615461565b600c82526b4d656d65537472617465677960a01b6020830152565b6001600160a01b0381166e22d473030f116ddee9f6b43ac78ba3186001171561536157602052637f5e9f20600c52335f525f196034600c20555f195f52602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3600190565b5f198114610f4a5760010190565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b600f0b6f7fffffffffffffffffffffffffffffff198114610f4a575f0390565b90816020910312610f46575190565b91908201809211610f4a57565b8051156155b55760200190565b634e487b7160e01b5f52603260045260245ffd5b8051600110156155b55760400190565b90602080835192838152019201905f5b8181106155f65750505090565b82516001600160a01b03168452602093840193909201916001016155e9565b919260809361563a92979695978452602084015260a0604084015260a08301906155d9565b6001600160a01b0390951660608201520152565b91908203918211610f4a57565b602081830312610f465780519067ffffffffffffffff8211610f4657019080601f83011215610f465781519167ffffffffffffffff8311614185578260051b9060208201936156ad6040519586615461565b8452602080850192820101928311610f4657602001905b8282106156d15750505090565b81518152602091820191016156c4565b8015610f4a575f190190565b906001600160a01b0381166e22d473030f116ddee9f6b43ac78ba31461572357602052637f5e9f20600c525f526034600c205490565b50505f1990565b638b78c6d81954330361573957565b6382b429005f526004601cfd5b5f80809338935af11561575557565b63b12d13eb5f526004601cfd5b60018060a01b031680638b78c6d819547f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3638b78c6d81955565b919060145260345263a9059cbb60601b5f5260205f6044601082855af1908160015f511416156157d2575b50505f603452565b3b153d1710156157e3575f806157ca565b6390b8ec185f526004601cfd5b6001600160a01b03168061586b5750604051630476982d60e21b815290602090829060049082907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af18015610f3b576158505750565b6158689060203d6020116140c7576140b88183615461565b50565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691823b15610f4657604051632961046560e21b8152600481018390525f9290838160248183895af18015610f3b57615908575b50926158d860209282859661579f565b600460405180958193630476982d60e21b83525af19081156158fc57506158505750565b604051903d90823e3d90fd5b8491935060209261591c5f6158d893615461565b5f94925092506158c8565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691823b15610f4657604051630b0d9c0960e01b81526001600160a01b0390921660048301523060248301526044820152905f908290606490829084905af18015610f3b5761599c5750565b5f6159a691615461565b565b6040906159bf9392815281602082015201906155d9565b90565b81810292918115918404141715610f4a57565b8115612575570490565b90816020910312610f46575160ff81168103610f465790565b90615a78925f9260405192615a0e606085615461565b600284526040366020860137615a23846155a8565b6001600160a01b0391821690527f000000000000000000000000000000000000000000000000000000000000000016615a5b846155c9565b5260405180958194829363d06ca61f60e01b8452600484016159a8565b03916001600160a01b03165afa5f9181615ae0575b50615aa1576365be670760e11b5f5260045ffd5b615aaa906155c9565b519061271003906127108211610f4a57612710615acb8193615ad6936159c2565b0492600554906159c2565b048110613d605790565b615af59192503d805f833e610f828183615461565b905f615a8d565b60195480615b075750565b615b10906156e1565b601955565b918115613d605760405163313ce56760e01b815290602090829060049082906001600160a01b03165afa8015610f3b5760ff915f91615b7f575b5016604d8111610f4a57600a0a91821561257557825f19048111612566576159bf92615b7a916159c2565b6159d5565b615b98915060203d6020116122fd576122ee8183615461565b5f615b4f565b8015615c1f576387a211a2600c52305f526020600c20549047908115615c17578215612575575f19839004811115615c0457615be39291615bde916159d5565b6159c2565b905b61271003906127108211610f4a5761271091615c00916159c2565b0490565b615c1192615b7a916159c2565b90615be5565b505050505f90565b50505f90565b9190918015615e65576387a211a2600c908152305f5260209020546001600160ff1b038211610f4657600160ff1b8214610f4a57600160ff19601a541617601a55615cad5f60405160016020820152848203604082015260408152615c8b606082615461565b604051809381926348c8949160e01b8352602060048401526024830190615389565b0381837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af19081615dde575b50615cf9575050601a805460ff191690555f9150565b615d1d9060ff19601a5416601a556387a211a2600c52305f526020600c205461564e565b928015159081615dd4575b50613d60576387a211a2600c52305f526020600c2090815490818511614f44577fe25c13ab9b2aded7bb7d39d4829c2efb98edd820bd84d49234678cedc8b8fd5692858093039055816805345cdf77eb68f44c54036805345cdf77eb68f44c55815f525f305f80516020615e6c833981519152602083a3615dcf615dae8360105461559b565b80601055604051938493846040919493926060820195825260208201520152565b0390a1565b905083105f615d28565b3d805f833e615ded8183615461565b810190602081830312610f465780519067ffffffffffffffff8211610f46570181601f82011215610f465780519067ffffffffffffffff82116141855760405192615e42601f8401601f191660200185615461565b82845260208383010111610f4657815f9260208093018386015e83010152615ce3565b505f915056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220ee7a358ad3f350b718c1081454c98ff4839353675864329d256cd3bae2e09b0864736f6c634300081a0033000000000000000000000000f4605f32cbc9b825bd02f154d5e849b165f5db0c000000000000000000000000bd216513d74c8cf14cf4747e6aaa6420ff64ee9e000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2

Deployed Bytecode

0x6080604052600436101561004d575b3615610018575f80fd5b476040519034825260208201527f318f8a239412df7b37584cdc970509562cc8ea85492a3cc8622124bb1f72980c60403392a2005b5f803560e01c806306fdde031461536e578063095ea7b3146152d25780630d457ee1146152b557806313e7c9d814615278578063180dff8d1461525157806318160ddd1461522c5780631dbbaa9e146151b45780631ea09eae146151975780631ed86f191461511657806323b872dd14614ea15780632569296214614e585780632dc7865714614e3b5780632f28c10e14614e1e57806331372c1a14614de8578063313ce56714614dcd57806332a3cf9614614da557806332cb6b0c14614d7f5780633644e51514614cf75780633687ccf414614cda5780633f4ba83a14614cb6578063445b1e4b14614c795780634586332214614c325780634ada218b14614c1157806354d1f13d14614bcd5780635962a94114614bb05780635c975abb14614b8e5780635d6a618d14614b715780636720699414614b545780636b15231414614b375780636b792c4b14614ac5578063706cd95c14614a9e57806370a0823114614a6c578063710c2583146147e0578063715018a61461479757806371a062441461473f57806371cde3991461472257806376db057214614705578063795bd1bd146146e85780637ac07b15146145d75780637c8ba8a6146145495780637caf60ff1461451f5780637ecebe00146144ed578063828586aa146144c35780638392fe31146143ef5780638456cb59146143c857806386001519146143ab5780638a6d930f1461430b5780638a8c523c146142875780638da5cb5b1461425b578063917bb998146141c357806391dd734614613e56578063920c156214613d8b578063941e56571461386457806394c5829a1461320457806394f665f614612e2c57806395d89b4114612de15780639870d7fe14612d4a5780639b1225c4146126a75780639e08ac25146126845780639eaa1b0914612667578063a0632461146125ec578063a106a41414611cec578063a3756ebb14611cad578063a9059cbb14611aa4578063ac8a584a14611a26578063af06b55914611939578063b98ad25514611913578063b9a62754146117cd578063bcbe22f7146117af578063c07e1498146116a4578063c445baa214611686578063cfdbf2541461166a578063d157e3011461164c578063d505accf14611480578063d57e551414611011578063dad0801d146108f1578063dadb2b601461085f578063daf9c21014610811578063dcd631c11461068e578063dd62ed3e14610659578063e3b682ea1461059d578063ed03e78c14610581578063f04e283e14610533578063f2fde38b146104f4578063f38b5611146104b9578063f7088bc61461049b578063f7d9cc1e1461047d578063f9759518146104605763fee81cf41461042b575061000e565b3461045d57602036600319011261045d576104446153ad565b9063389a75e1600c5252602080600c2054604051908152f35b80fd5b503461045d578060031936011261045d5760206040516113888152f35b503461045d578060031936011261045d576020601654604051908152f35b503461045d578060031936011261045d576020600254604051908152f35b503461045d57602036600319011261045d576004356104d661572a565b61138881116104e55760045580f35b63162908e360e11b8252600482fd5b50602036600319011261045d576105096153ad565b61051161572a565b8060601b156105265761052390615762565b80f35b637448fbae82526004601cfd5b50602036600319011261045d576105486153ad565b61055061572a565b63389a75e1600c528082526020600c20805442116105745790826105239255615762565b636f5e881883526004601cfd5b503461045d578060031936011261045d57602060405160c88152f35b503461045d57604036600319011261045d576105b76153ad565b6105bf6153c3565b6105c761572a565b6001600160a01b031690811561064a57818352601760205260ff6040842054161561063b576001600160a01b0316808352600a602052604083205460a01c60ff161561062c578252600a6020526040822080546001600160a01b031916909117905580f35b6307c241ad60e51b8352600483fd5b63119e93c560e11b8352600483fd5b63e6c4247b60e01b8352600483fd5b503461045d57604036600319011261045d5760206106866106786153ad565b6106806153c3565b906156ed565b604051908152f35b503461045d5761069d366153d9565b916106a661572a565b3068929eee149b4bd212685414610804573068929eee149b4bd2126855601a5460ff8160081c166107f55761ff00191661010017601a5561138883116107e65781156107e6574782116107d7576011541515806107cb575b610774575b5061071961071360209383615b9e565b82615c25565b604080519283526020830182905242908301529033907f10bf0e47b0d990f69b0852e8e187b46263ac183e4f0ceab61070037d6bb9023f90606090a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b6006546001600160a01b0316803b156107c7578180916024604051809481936319a1ccbb60e01b83528860048401525af16107b0575b50610703565b816107ba91615461565b805f1261045d57806107aa565b5080fd5b506015548210156106fe565b631e9acf1760e31b8152600490fd5b63162908e360e11b8152600490fd5b6379b60e8b60e01b8252600482fd5b63ab143c0690526004601cfd5b503461045d57602036600319011261045d5760409081906001600160a01b036108386153ad565b168152600a602052205460ff82519160018060a01b038116835260a01c1615156020820152f35b503461045d57602036600319011261045d576004353068929eee149b4bd2126854146108e4573068929eee149b4bd2126855338252601860205260ff604083205416156108d5578047106108c6576108b79033615746565b3868929eee149b4bd212685580f35b631e9acf1760e31b8252600482fd5b638fd1408d60e01b8252600482fd5b63ab143c0682526004601cfd5b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff601354166110025750805f52600960205260405f20805415610ff357600781019081549060ff8216610fe4575f9360ff600d8301541615610fd557600182019360018060a01b03855416936002840154946040516370a0823160e01b8152306004820152602081602481855afa8015610f3b5787915f91610fa0575b5010610f9157805f52600a60205260405f2090604051916109c2836153ef565b5491602060ff60018060a01b0385169485845260a01c161515910152604051906109ed606083615461565b60028252604036602084013780610a03836155a8565b527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316610a37836155c9565b5260405163d06ca61f60e01b81525f8180610a56868d600484016159a8565b0381875afa5f9181610f6d575b50610a77576365be670760e11b5f5260045ffd5b94610a8c828a610a86896155c9565b51615b15565b600489015411610f5e57610a9f866155c9565b51600354612710036127108111610f4a57610abf612710916001936159c2565b049560ff1916179055426009880155610ad6615afc565b803b15610f465760405163095ea7b360e01b81528360048201525f60248201525f8160448183865af18015610f3b57610f26575b50808a913b156107c75760405163095ea7b360e01b81526001600160a01b0385166004820152602481018a90529082908290604490829084905af18015610eea57610f0d575b5050479261012c420192834211610ef95790818b9493923b15610ef5578492838b93610b946040519788968795869463791ac94760e01b8652309260048701615615565b03925af18015610eea57610ed1575b5050610baf904761564e565b9081610bba826155c9565b511115610ec957610bd482610bce836155c9565b5161564e565b906127108202918083046127101490151715610eb55790610bf7610bfe926155c9565b51906159d5565b905b6002548110610ea6576005840193845492838311809484825f14610e975790610c289161564e565b985b8054610c40906001600160a01b03168a87615b15565b9260088501938455610c6183600a87019060ff801983541691151516179055565b8a600b860155600c8501558195610e8c575b8115610e6657610c858a600e5461559b565b600e558a8615610e06576006546001600160a01b0316803b156107c7578180809260246040518094819363092ddc5160e41b83528d60048401525af1610df1575b5050610d9b575b9960209a5b610cdd60115461551b565b6011555b610ced60025433615746565b60018060a01b0390541697549160025492610d136006600388015496549701544261564e565b966040519b8c528d8c015260408b015260608a01528960808a015260a089015260c088015260e087015261010086015261012085015215156101408401526001610160840152426101808401527f249461fdf7d29ea7abe6bfc09b464051b9f83c048367693dca40c27c7fa83c466101a03394a43868929eee149b4bd2126855604051908152f35b6006548b906001600160a01b0316803b156107c75781906024604051809481936319a1ccbb60e01b83528b60048401525af1610dd8575b50610ccd565b610de38c8092615461565b610ded575f610dd2565b8a80fd5b81610dfb91615461565b61045d57805f610cc6565b610e14575b9960209a610cd2565b6006548b906001600160a01b0316803b156107c75781906024604051809481936319a1ccbb60e01b83528b60048401525af1610e51575b50610e0b565b610e5c8c8092615461565b610ded575f610e4b565b9960209a610e768b600f5461559b565b600f55610e8460125461551b565b601255610ce1565b601154159550610c73565b610ea09161564e565b98610c2a565b631e9acf1760e31b8752600487fd5b634e487b7160e01b88526011600452602488fd5b508590610c00565b81610edb91615461565b610ee657865f610ba3565b8680fd5b6040513d84823e3d90fd5b8480fd5b634e487b7160e01b8b52601160045260248bfd5b81610f1791615461565b610f2257885f610b50565b8880fd5b610f33919a505f90615461565b5f985f610b0a565b6040513d5f823e3d90fd5b5f80fd5b634e487b7160e01b5f52601160045260245ffd5b6365be670760e11b5f5260045ffd5b610f8a9192503d805f833e610f828183615461565b81019061565b565b905f610a63565b631e9acf1760e31b5f5260045ffd5b9150506020813d602011610fcd575b81610fbc60209383615461565b81010312610f46578690515f6109a2565b3d9150610faf565b63015a4da360e11b5f5260045ffd5b632bf773b360e11b5f5260045ffd5b634496e09960e01b5f5260045ffd5b63ab35696f60e01b8152600490fd5b503461045d57611020366153d9565b9061102961572a565b3068929eee149b4bd212685414611473573068929eee149b4bd2126855601a5460ff8160081c166114645761ff00191661010017601a55808352600960205260408320805415611455576007810180549060ff821661144657612710851161143757600183019160018060a01b03835416906002850154926040516370a0823160e01b8152306004820152602081602481875afa801561142c5785918b916113f7575b50106113e857828952600a6020526040892092604051936110ec856153ef565b5493602060ff60018060a01b0387169687845260a01c16151591015261111b60058801998a54908684896159f8565b9160016040519461112d606087615461565b60028652604036602088013783611143876155a8565b52818060a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216611175876155c9565b5260ff191617905542600988015561118b615afc565b803b156113cd5760405163095ea7b360e01b81528460048201528a60248201528a808260448183875af180156113c0576113d1575b5050803b156113cd5760405163095ea7b360e01b81526001600160a01b038516600482015260248101869052908a9081908390604490829084905af180156113c0576113a9575b5050479261012c420191824211610ef957908a9291813b156113a55783611248956040519687958694859363791ac94760e01b855230918d60048701615615565b03925af1801561139a57611383575b509560a0926112d37f749892656f0d55173a238548a9c4a0ddf8c8e0d39b19e5947a821a5a6f9b5f419593600b61129060209b4761564e565b9954808b1196908b881561137257906112a89161564e565b9384935b6112c28d6112bc60045482615b9e565b90615c25565b96545f1960018c1b0116908d615b15565b60088201556112f187600a83019060ff801983541691151516179055565b0155836113505761130481600f5461559b565b600f5561131260125461551b565b6012555b6040519388855289850152604084015260608301526080820152a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b61135c81600e5461559b565b600e5561136a60115461551b565b601155611316565b61137b9161564e565b9384936112ac565b8761138d91615461565b865f12610ee6575f611257565b6040513d8a823e3d90fd5b8380fd5b6113b291615461565b885f12610f22575f89611207565b50604051903d90823e3d90fd5b8980fd5b6113da91615461565b895f126113cd575f8a6111c0565b631e9acf1760e31b8952600489fd5b9150506020813d602011611424575b8161141360209383615461565b81010312610f46578490515f6110cc565b3d9150611406565b6040513d8c823e3d90fd5b63162908e360e11b8652600486fd5b632bf773b360e11b8652600486fd5b634496e09960e01b8452600484fd5b6379b60e8b60e01b8452600484fd5b63ab143c0683526004601cfd5b503461045d5760e036600319011261045d5761149a6153ad565b6114a26153c3565b604435606435906084359260ff84168403611648576001600160a01b0316936e22d473030f116ddee9f6b43ac78ba38518821915171561163b576114e4615483565b602081519101209280421161162e576040519160018060a01b03169465383775081901600e5285885260c06020600c20938454937f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252602082019788528460408301987fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc68a528b606085019a468c528c608087019330855260a08820602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988525252888a525260a082015220604e526042602c20885260ff1660205260a43560405260c43560605260208060808960015afa90853d5103611621570190556303faf4f960a51b84176040526034602c20557f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a380f35b63ddafbaef88526004601cfd5b631a15a3cc87526004601cfd5b633f68539a86526004601cfd5b8580fd5b503461045d578060031936011261045d576020601054604051908152f35b503461045d578060031936011261045d57602060405160328152f35b503461045d578060031936011261045d576020600d54604051908152f35b503461045d57602036600319011261045d57638b78c6d81954600435906001600160a01b031633141580611798575b61178957808252600b602052600760408320015460ff8160081c161590811561177e575b5061176f57808252600b60205261173a6040832060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b611745600d546156e1565b600d557f1c899aec6b677cce6148a2f50b400ad80179a5ca200b00fc7ce7f8405ff62d258280a280f35b6383c52cf760e01b8252600482fd5b60ff9150165f6116f7565b63089b7a0760e41b8252600482fd5b50338252600160205260ff604083205416156116d3565b503461045d578060031936011261045d576020600554604051908152f35b503461045d57604036600319011261045d576117e76153ad565b6117ef6153c3565b9060018060a01b03638b78c6d8195416331415806118fc575b6118ed576001600160a01b031690811580156118dc575b61064a576001600160a01b03168083526017602052604083205490919060ff161561063b57808352600a60205260ff604084205460a01c1615611860578280f35b60405161186c816153ef565b82815260016020808301918252838652600a9052604085209151825491516001600160a81b03199092166001600160a01b03919091161790151560a01b60ff60a01b161790557f670d89413ae6972219aaf1aeb3c8168012d92e210628e058e9f5ac8d64adfb3a8380a35f808280f35b506001600160a01b0381161561181f565b63089b7a0760e41b8352600483fd5b50338352600160205260ff60408420541615611808565b503461045d578060031936011261045d57602060ff60065460a01c166040519015158152f35b503461045d57602036600319011261045d57638b78c6d81954600435906001600160a01b031633141580611a0f575b61178957808252600b602052600760408320015460ff8160081c1615908115611a04575b5061176f57808252600b6020526119cf6040832060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b6119da600d546156e1565b600d557f6e7a8b064487ccb89997e2d58592a670e1737cfc714efcd1c5a47fef9b23685a8280a280f35b60ff9150165f61198c565b50338252600160205260ff60408320541615611968565b503461045d57602036600319011261045d57611a406153ad565b611a4861572a565b6001600160a01b03168082526001602052604082205460ff16611a69575080f35b808252600160205260408220805460ff191690557f80c0b871b97b595b16a7741c1b06fed0c6f6f558639f18ccbce50724325dc40d8280a280f35b503461045d57604036600319011261045d57611abe6153ad565b6024359160ff81541615611b2b575b6387a211a2600c523381526020600c208054808511611b1e578490039055526020600c20818154019055602052600c5160601c335f80516020615e6c833981519152602080a3602060405160018152f35b63f4d678b883526004601cfd5b638b78c6d819546001600160a01b03163381148015611ca4575b8015611c72575b8015611c40575b6001600160a01b03848116801593917f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a9016338114611bb5575b505050159081611bac575b5015611acd5763ab35696f60e01b8152600490fd5b9050155f611b97565b8114918215611c0d575b8215611c03575b508115611bf9575b508015611bf2575b15611be3575f8080611b8c565b63ab35696f60e01b8352600483fd5b5081611bd6565b905030145f611bce565b811491505f611bc6565b7f000000000000000000000000bd216513d74c8cf14cf4747e6aaa6420ff64ee9e6001600160a01b031682149250611bbf565b50337f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031614611b53565b50337f000000000000000000000000bd216513d74c8cf14cf4747e6aaa6420ff64ee9e6001600160a01b031614611b4c565b50303314611b45565b503461045d57602036600319011261045d5760209060ff906040906001600160a01b03611cd86153ad565b168152601884522054166040519015158152f35b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff6013541661100257818152600b60205260408120916007830180549360ff8560081c16159485158096906125e2575b6125d357604051611d608161540b565b8254815260018060a01b0360018401541660208201818152600285015494604084019586526003810154926060850193845260048201549a608086019b8c52600583015490600660a0880194838652015460c088015260ff8816151560e088015261010087015260ff61012087019760101c16151587526123d3575b5050611dec85516002549061559b565b47106123c45760018060a01b039051169351905197519151925115155f98855f52600a60205260405f2060405190611e23826153ef565b5490602060ff60018060a01b0384169384845260a01c16151591015260405190611e4e606083615461565b6002825260403660208401377f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316611e8d836155a8565b5287611e98836155c9565b5260405163d06ca61f60e01b81525f8180611eb7868a600484016159a8565b0381855afa5f91816123a8575b50611ed857630b99e1d760e31b5f5260045ffd5b611ee1906155c9565b5195612710036127108111610f4a57611efd61271091886159c2565b6040516370a0823160e01b8152306004820152939190046020846024818d5afa938415610f3b575f94612374575b5061012c420192834211610f4a57803b15610f46575f9288611f71936040519687958694859363b6f9de9560e01b855260048501526080602485015260848401906155d9565b90306044840152606483015203925af18015610f3b5761235f575b506040516370a0823160e01b8152306004820152906020826024818b5afa8015612354578c90612320575b611fc1925061564e565b938481111561231857611fd4858261564e565b61271081029080820461271014901517156123045790611ff3916159d5565b905b60405163313ce56760e01b81529a60208c6004818b5afa9b8c156113c057819c6122d3575b50612026888787615b15565b9082612710019081612710116122bf5781156122ab57815f1904831161229c575061205190826159c2565b6127109004906007546120639061551b565b9c8d97886007558a87878b60405161207a81615444565b81815260208101948552604081018681528d60608301908a825260808401908c825260a0850190815260c085019042825260e08601925f84526101008701945f86526101208801965f88526101408901985f8a5261016081019a5f8c5261018082019c8d526101a082019d8e525f52600960205260405f209d8e91518255600160a01b600190039051169060010190600160a01b60019003166001600160601b0360a01b8254161790555160028d01555160038c01555160048b01555160058a0155516006890155511515600788019061215f919060ff801983541691151516179055565b516008870155516009860155511515600a850190612188919060ff801983541691151516179055565b51600b84015551600c83015551151590600d01906121b1919060ff801983541691151516179055565b6019546121bd9061551b565b601955604051973389526020890152604088015260ff166060870152608086015260a085015260c084015260e0830152610100820152426101208201526101407f99de35bc627d2b927519c1e6bf7bdd9a5a309af85385bd394ef9979015bab98491a460025461222d9033615746565b60ff1981541660011790558152600b602052604090206122769060075f918281558260018201558260028201558260038201558260048201558260058201558260068201550155565b600d54612282906156e1565b600d553868929eee149b4bd2126855604051908152602090f35b63eb54e4d360e01b8152600490fd5b634e487b7160e01b81526012600452602490fd5b634e487b7160e01b81526011600452602490fd5b6122f6919c5060203d6020116122fd575b6122ee8183615461565b8101906159df565b9a5f61201a565b503d6122e4565b634e487b7160e01b8c52601160045260248cfd5b508990611ff5565b506020823d60201161234c575b8161233a60209383615461565b81010312610f4657611fc19151611fb7565b3d915061232d565b6040513d8e823e3d90fd5b61236c919b505f90615461565b5f995f611f8c565b9093506020813d6020116123a0575b8161239060209383615461565b81010312610f465751925f611f2b565b3d9150612383565b6123bd9192503d805f833e610f828183615461565b905f611ec4565b631e9acf1760e31b8852600488fd5b8952600a6020526124a08960408120604051906123ef826153ef565b5490602060ff60018060a01b0384169384845260a01c1615159101526040519061241a606083615461565b6002825260403660208401377f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316612459836155a8565b5285516001600160a01b031661246e836155c9565b52604051808095819463d06ca61f60e01b8352670de0b6b3a764000060048401526040602484015260448301906155d9565b03915afa8a91816125b7575b506124c057630b99e1d760e31b8a5260048afd5b6124c9906155c9565b5180156125a857825160405163313ce56760e01b815290602090829060049082906001600160a01b03165afa8015610f3b5760ff915f91612589575b5016604d8111610f4a57600a0a90811561257557815f1904670de0b6b3a76400001161256657670de0b6b3a76400008281029290830403610f4a57612549916159d5565b905110612557575f80611ddc565b6365be670760e11b8852600488fd5b63eb54e4d360e01b5f5260045ffd5b634e487b7160e01b5f52601260045260245ffd5b6125a2915060203d6020116122fd576122ee8183615461565b5f612505565b63162908e360e11b8a5260048afd5b6125cc9192503d808d833e610f828183615461565b905f6124ac565b6383c52cf760e01b8552600485fd5b5060ff8116611d50565b503461045d57602036600319011261045d576126066153ad565b61260e61572a565b6001600160a01b03168082526018602052604082205460ff16156108d557808252601860205260408220805460ff191690557f0a1ee69f55c33d8467c69ca59ce2007a737a88603d75392972520bf67cb513b88280a280f35b503461045d578060031936011261045d5760206040516127108152f35b503461045d57602036600319011261045d5761269e61572a565b60043560165580f35b503461045d57602036600319011261045d57600435903068929eee149b4bd212685414610804573068929eee149b4bd212685560ff601354166110025750805f52600960205260405f20805415610ff3576007810180549060ff8216610fe45760ff600d84015416610fd5575f93600184019460018060a01b038654166002860154946040516370a0823160e01b8152306004820152602081602481865afa8015610f3b5787915f91612d15575b5010610f9157815f52600a60205260405f2060405190612774826153ef565b5490602060ff60018060a01b0384169384845260a01c1615159101526040519261279f606085615461565b600284526040366020860137806127b5856155a8565b527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03166127e9856155c9565b5260405163d06ca61f60e01b81525f8180612808888d600484016159a8565b0381865afa5f9181612cf9575b50612829576365be670760e11b5f5260045ffd5b96612838828a610a868b6155c9565b60048b015411610f5e5761284b886155c9565b51600354612710036127108111610f4a5761286b612710916001936159c2565b049460ff19161790554260098a0155612882615afc565b803b15610f465760405163095ea7b360e01b81528260048201525f60248201525f8160448183865af18015610f3b57612ce4575b50803b15610ef55760405163095ea7b360e01b81526001600160a01b0383166004820152602481018990529085908290604490829084905af18015612cd957908591612cc4575b5050479261012c420192834211612cb057823b156116485791889186809461293d6040519788968795869463791ac94760e01b8652309260048701615615565b03925af18015612ca557908391612c90575b505061295b904761564e565b9283612966826155c9565b511115612c885761297a84610bce836155c9565b906127108202918083046127101490151715612c745790610bf761299d926155c9565b925b60025495868210612c6557908160056129d993019586546129e581851195869286845f14612c5657906129d19161564e565b9b5b8661564e565b6112bc60045482615b9e565b8b546129fb906001600160a01b03168b87615b15565b9260088501938455612a1c83600a87019060ff801983541691151516179055565b8b600b860155600c8501558195612c4b575b8115612c2657612a408b600e5461559b565b600e558515612bc2576006546001600160a01b0316803b15612ba9578780809260246040518094819363092ddc5160e41b83528c60048401525af1612bad575b5050601554851015612b58575b60209b5b612a9c60115461551b565b6011555b612aac60025433615746565b60018060a01b0390541698549160025492612ad26006600388015496549701544261564e565b966040519c8d528e8d015260408c015260608b01528a60808b015260a08a015260c089015260e08801526101008701526101208601521515610140850152610160840152426101808401527f249461fdf7d29ea7abe6bfc09b464051b9f83c048367693dca40c27c7fa83c466101a03394a43868929eee149b4bd2126855604051908152f35b6006546001600160a01b0316803b15612ba9578780916024604051809481936319a1ccbb60e01b83528b60048401525af1612b94575b50612a8d565b612b9f888092615461565b610ee6575f612b8e565b8780fd5b81612bb791615461565b610ee657865f612a80565b601554851015612bd5575b60209b612a91565b6006546001600160a01b0316803b15612ba9578780916024604051809481936319a1ccbb60e01b83528b60048401525af1612c11575b50612bcd565b612c1c888092615461565b610ee6575f612c0b565b60209b612c358c600f5461559b565b600f55612c4360125461551b565b601255612aa0565b601154159550612a2e565b612c5f9161564e565b9b6129d3565b631e9acf1760e31b8352600483fd5b634e487b7160e01b83526011600452602483fd5b50809261299f565b81612c9a91615461565b6107c757815f61294f565b6040513d85823e3d90fd5b634e487b7160e01b86526011600452602486fd5b81612cce91615461565b6113a557835f6128fd565b6040513d87823e3d90fd5b612cf19195505f90615461565b5f935f6128b6565b612d0e9192503d805f833e610f828183615461565b905f612815565b9150506020813d602011612d42575b81612d3160209383615461565b81010312610f46578690515f612755565b3d9150612d24565b503461045d57602036600319011261045d57612d646153ad565b612d6c61572a565b6001600160a01b03168015612dd257808252600160205260ff60408320541615612d94575080f35b808252600160205260408220600160ff198254161790557fac6fa858e9350a46cec16539926e0fde25b7629f84b5a72bffaae4df888ae86d8280a280f35b63e6c4247b60e01b8252600482fd5b503461045d578060031936011261045d57612e28604051612e03604082615461565b60048152634d454d5360e01b6020820152604051918291602083526020830190615389565b0390f35b503461045d57612e3b366153d9565b90612e4461572a565b3068929eee149b4bd212685414611473573068929eee149b4bd2126855601a5460ff8160081c166114645761ff00191661010017601a558083526009602052604083208054156114555760078101805460ff811661144657612710851161143757600183019060018060a01b03825416906002850154936040516370a0823160e01b8152306004820152602081602481875afa801561142c5786918b916131cf575b50106113e857828952600a602052604089209260405193612f06856153ef565b5493602060ff60018060a01b0387169687845260a01c161515910152612f3560058801998a549086848a6159f8565b91600160405194612f47606087615461565b60028652604036602088013783612f5d876155a8565b52818060a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216612f8f876155c9565b5260ff1916179055426009880155612fa5615afc565b803b156113cd5760405163095ea7b360e01b81528460048201528a60248201528a808260448183875af180156113c0576131b8575b5050803b156113cd5760405163095ea7b360e01b81526001600160a01b038516600482015260248101879052908a9081908390604490829084905af180156113c0576131a1575b5050479261012c420192834211610ef957908a9291813b156113a55760405163791ac94760e01b81529485938492869284926130639230918e60048701615615565b03925af1801561139a5761318a575b509560a0927f749892656f0d55173a238548a9c4a0ddf8c8e0d39b19e5947a821a5a6f9b5f419492600b6130a860209a4761564e565b9854946130d8868b11968b885f1461317957906130c49161564e565b9485945b545f1960018b1b0116908c615b15565b60088201556130f686600a83019060ff801983541691151516179055565b0155826131575761310981600f5461559b565b600f5561311760125461551b565b6012555b60405192878452888401526040830152606082015260016080820152a261ff0019601a5416601a553868929eee149b4bd2126855604051908152f35b61316381600e5461559b565b600e5561317160115461551b565b60115561311b565b6131829161564e565b9485946130c8565b8761319491615461565b865f12610ee6575f613072565b6131aa91615461565b885f12610f22575f89613021565b6131c191615461565b895f126113cd575f8a612fda565b9150506020813d6020116131fc575b816131eb60209383615461565b81010312610f46578590515f612ee6565b3d91506131de565b503461045d5760a036600319011261045d5761321e6153ad565b9060243560443560843590811515809203610f4657638b78c6d819546001600160a01b03163314158061384d575b61383e573068929eee149b4bd212685414613831573068929eee149b4bd212685560ff601354166138225760018060a01b03851693848152600a6020526040812060ff6040519161329c836153ef565b546001600160a01b038116835260a01c161580156020909201919091526138135783156107e65760145484116107e6576103e882108015613807575b6107e6576132e86002548561559b565b47106107d757505f90845f52600a60205260405f20956040519661330b886153ef565b5496602060ff60018060a01b038a16998a845260a01c161515910152604051613335606082615461565b6002815260403660208301377f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316613374826155a8565b528661337f826155c9565b5260405163d06ca61f60e01b81525f818061339e858b600484016159a8565b03818c5afa5f91816137eb575b506133bf57630b99e1d760e31b5f5260045ffd5b6133c8906155c9565b5197606435612710036127108111610f4a576133e7612710918b6159c2565b6040516370a0823160e01b8152306004820152939190046020846024818d5afa938415610f3b575f946137b7575b5061012c420192834211610f4a57803b15610f46575f928a61345b936040519687958694859363b6f9de9560e01b855260048501526080602485015260848401906155d9565b90306044840152606483015203925af18015610f3b576137a2575b506040516370a0823160e01b8152306004820152906020826024818b5afa8015612cd957859061376e575b6134ab925061564e565b9687811115613767576134be888261564e565b612710810290808204612710149015171561375357906134dd916159d5565b925b60405163313ce56760e01b8152916020836004818b5afa928315610eea57829361372e575b50613510908988615b15565b9083612710019081612710116122bf5781156122ab57815f1904831161229c575061353b90826159c2565b61271090049160075461354d9061551b565b988960075560405161355e81615444565b8a815287878c60208401938d8552604081018681528d60608301908a825260808401908c825260a0850190815260c085019042825260e08601925f84526101008701945f86526101208801965f88526101408901985f8a5261016081019a5f8c5261018082019c8d526101a082019d8e525f52600960205260405f209d8e91518255600160a01b600190039051169060010190600160a01b60019003166001600160601b0360a01b8254161790555160028d01555160038c01555160048b01555160058a01555160068901555115156007880190613647919060ff801983541691151516179055565b516008870155516009860155511515600a850190613670919060ff801983541691151516179055565b51600b84015551600c83015551151590600d0190613699919060ff801983541691151516179055565b6019546136a59061551b565b601955604051973389526020890152604088015260ff166060870152608086015260a085015260c084015260e083015261010082015282426101208301527f99de35bc627d2b927519c1e6bf7bdd9a5a309af85385bd394ef9979015bab9846101405f93a46002546137179033615746565b3868929eee149b4bd2126855604051908152602090f35b61351091935061374c9060203d6020116122fd576122ee8183615461565b9290613504565b634e487b7160e01b85526011600452602485fd5b50826134df565b506020823d60201161379a575b8161378860209383615461565b81010312610f46576134ab91516134a1565b3d915061377b565b6137af9194505f90615461565b5f925f613476565b9093506020813d6020116137e3575b816137d360209383615461565b81010312610f465751925f613415565b3d91506137c6565b6138009192503d805f833e610f828183615461565b905f6133ab565b50620f1b3082116132d8565b6307c241ad60e51b8152600490fd5b63ab35696f60e01b8452600484fd5b63ab143c0684526004601cfd5b63089b7a0760e41b8452600484fd5b50338452600160205260ff6040852054161561324c565b60a0366003190112610f46576138786153ad565b602435906fffffffffffffffffffffffffffffffff8216809203610f46576044356001600160a01b0381169190829003610f4657606435908160020b809203610f4657608435908160020b809203610f46576138d261572a565b3068929eee149b4bd212685414613d7e573068929eee149b4bd212685560ff60065460a01c16610fe4576001600160a01b0316908115613d6f578415613d60573415613d60576805345cdf77eb68f44c546b033b2e3c9fd0803ce80000008101908110613d53576805345cdf77eb68f44c556387a211a2600c52305f526020600c206b033b2e3c9fd0803ce800000081540190556b033b2e3c9fd0803ce8000000602052600c5160601c5f5f80516020615e6c833981519152602080a3600680546001600160a01b03191683179055604051926139ae84615428565b5f80855230602086019081526040860191909152603c6060860152608085019390935260405163f702040560e01b8152947f000000000000000000000000bd216513d74c8cf14cf4747e6aaa6420ff64ee9e6001600160a01b03169390613a186004880187615529565b60a48701525a9560208160c4815f89819cf18015610f3b57613d1a575b507f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba36001600160a01b031694613a6a866154ad565b5061012c420195864211610f4a57803b15610f46576040516387517c4560e01b8152306004820152602481018790526001600160a01b03604482015265ffffffffffff88166064820152905f908290608490829084905af18015610f3b57613d05575b50604051600160f91b6020820152600d60f81b60218201526002815292613af5602285615461565b60609460405199613b06878c615461565b60028b52601f1987018a5b888d838310613cf5575050505090613bfd9594939291638b78c6d819549160405193613b406020860187615529565b60c085015260e0840152610100830152346101208301526b033b2e3c9fd0803ce80000006101408301526001600160a01b0316610160820152610180808201526101a08082018a90528152613b976101c082615461565b613ba08a6155a8565b52613baa896155a8565b50519051604080516001600160a01b03938416602082015292909116828201528152613bd68482615461565b613bdf886155c9565b52613be9876155c9565b506040519260406020850152830190615389565b601f19828203016040830152855180825260208201916020808360051b83010198019287915b838310613cc8575050505050613c4381859603601f198101835282615461565b813b15613cc3578391613c749160405180958194829363dd46508f60e01b8452604060048501526044840190615389565b906024830152039134905af18015610eea57613cae575b506006805460ff60a01b1916600160a01b1790553868929eee149b4bd212685580f35b81613cb891615461565b61045d578082613c8b565b505050fd5b9091929398602080613ce6600193601f198682030187528d51615389565b9b019301930191939290613c23565b9060208381949301015201613b11565b613d129197505f90615461565b5f9588613acd565b6020813d602011613d4b575b81613d3360209383615461565b81010312610f4657518060020b810315613a35575f80fd5b3d9150613d26565b63e5cfe9575f526004601cfd5b63162908e360e11b5f5260045ffd5b63e6c4247b60e01b5f5260045ffd5b63ab143c065f526004601cfd5b34610f46576020366003190112610f4657613da46153ad565b638b78c6d819546001600160a01b031633141580613e3f575b613e30576001600160a01b03165f818152600a602052604090205460a01c60ff1615613e21575f818152600a60205260408120805460ff60a01b191690557fe6d4e8c78bb42602884e0e162c56ea85d4c168529e664f0f8352ab8d1aafb17e9080a2005b6307c241ad60e51b5f5260045ffd5b63089b7a0760e41b5f5260045ffd5b50335f52600160205260ff60405f20541615613dbd565b34610f46576020366003190112610f465760043567ffffffffffffffff8111610f465736602382011215610f4657806004013567ffffffffffffffff8111610f4657810190366024830111610f46577f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031691338390036141b45760ff601a5416156141b45760409082900312610f4657602481013580151591828203610f465760018060a01b03600654169160405191613f1783615428565b5f835260208301933085525f6040850152603c60608501526080840152815f14614199576401000276a4905b604051956060870187811067ffffffffffffffff8211176141855760405286526044602087019101358152604086019160018060a01b0316825260405195633cf3645360e21b8752613f986004880186615529565b51151560a48701525160c486015260018060a01b0390511660e48501526101206101048501525f610124850152602084610144815f895af1938415610f3b575f94614151575b50156140ed578260801d905f82600f0b12614052575b5050612e28925081600f0b5f8113614036575b50505b60405190602082015260208152614022604082615461565b604051918291602083526020830190615389565b905161404b91906001600160a01b0316615927565b8280614007565b516001600160a01b0316806140ce575061406d60209161556c565b600f0b93600460405180968193630476982d60e21b83525af1928315610f3b57612e289361409f575b505b8380613ff4565b6140c09060203d6020116140c7575b6140b88183615461565b81019061558c565b5083614096565b503d6140ae565b612e2894506140df6140e89261556c565b600f0b906157f0565b614098565b90612e28935082600f0b5f8112614133575b50508160801d600f0b5f8113614117575b505061400a565b905161412c91906001600160a01b0316615927565b8280614110565b6140df61414a9260018060a01b039051169161556c565b83806140ff565b9093506020813d60201161417d575b8161416d60209383615461565b81010312610f4657519285613fde565b3d9150614160565b634e487b7160e01b5f52604160045260245ffd5b73fffd8963efd1fc6a506488495d951d5263988d2590613f43565b63ea8e4eb560e01b5f5260045ffd5b34610f46576040366003190112610f46576141dc6153ad565b6024356141e761572a565b6001600160a01b0382169130831461424c578161422f7faaeda929aa102e867049528ec7cd2499e3a2f8846e736ae7935f234dfbf500d993604093638b78c6d819549061579f565b638b78c6d8195482519182526001600160a01b03166020820152a2005b63c03b13ef60e01b5f5260045ffd5b34610f46575f366003190112610f4657638b78c6d819546040516001600160a01b039091168152602090f35b34610f46575f366003190112610f4657638b78c6d819546001600160a01b0316331415806142f4575b613e30575f5460ff8116610fe45760019060ff1916175f557fb3da2db3dfc3778f99852546c6e9ab39ec253f9de7b0847afec61bd27878e9236020604051428152a1005b50335f52600160205260ff60405f205416156142b0565b34610f46576020366003190112610f46576004355f52600b60205261014060405f2060ff81549160018060a01b0360018201541690600281015460038201546004830154906005840154926007600686015495015495604051988952602089015260408801526060870152608086015260a085015260c0840152818116151560e0840152818160081c16151561010084015260101c161515610120820152f35b34610f46575f366003190112610f46576020600e54604051908152f35b34610f46575f366003190112610f46576143e061572a565b6013805460ff19166001179055005b34610f46576020366003190112610f46576004355f5260096020526101c060405f2080549060018060a01b03600182015416906002810154600382015460048301546005840154600685015460ff6007870154169060088701549260098801549460ff600a8a01541696600b8a01549860ff600d600c8d01549c0154169b60206040519e8f908152015260408d015260608c015260808b015260a08a015260c0890152151560e0880152610100870152610120860152151561014085015261016084015261018083015215156101a0820152f35b34610f46576020366003190112610f46576004356144df61572a565b6127108111613d6057600555005b34610f46576020366003190112610f46576145066153ad565b6338377508600c525f52602080600c2054604051908152f35b34610f46576020366003190112610f465760043561453b61572a565b6113888111613d6057600355005b34610f46576040366003190112610f46576145626153ad565b60243561456d61572a565b3068929eee149b4bd212685414613d7e573068929eee149b4bd21268556001600160a01b0382165f9081526018602052604090205460ff16156145c857804710610f91576145ba91615746565b3868929eee149b4bd2126855005b638fd1408d60e01b5f5260045ffd5b34610f46576020366003190112610f46576145f06153ad565b6145f861572a565b6001600160a01b03168015613d6f57805f52601760205260ff60405f2054161561461e57005b6040516315ab88c960e31b8152602081600481855afa5f91816146a4575b5061465d575b505f908152601760205260409020805460ff19166001179055005b6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281169116036146955781614642565b633a2619c960e11b5f5260045ffd5b9091506020813d6020116146e0575b816146c060209383615461565b81010312610f4657516001600160a01b0381168103610f4657908361463c565b3d91506146b3565b34610f46575f366003190112610f46576020600354604051908152f35b34610f46575f366003190112610f46576020601454604051908152f35b34610f46575f366003190112610f46576020601954604051908152f35b34610f46576020366003190112610f46576147586153ad565b61476061572a565b6001600160a01b03165f8181526017602052604090205460ff1661478057005b5f908152601760205260409020805460ff19169055005b5f366003190112610f46576147aa61572a565b5f638b78c6d819547f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a35f638b78c6d81955005b34610f465760c0366003190112610f46576147f96153ad565b60243590604435606435926084359060a43593841515809503610f4657638b78c6d819546001600160a01b031633141580614a55575b613e30576113888611613d605760018060a01b031691825f52600a60205260405f209560ff60405197614861896153ef565b546001600160a01b038116895260a01c161580156020890152613e21578215613d60576014548311613d605760c885108015614a49575b613d60576016548015159081614a3c575b50614a2d57602096600c54966148be8861551b565b600c556148cc60085461551b565b600855604051906148dc8261540b565b8882528861499860078c8501948a8652604081018a8152606082018d8152608083018a815260a08401918c835260c085019342855260e086019a5f8c5261010087019960018b5261012088019b8c525f526020600b905260405f209651875560018060a01b03905116600187019060018060a01b03166001600160601b0360a01b8254161790555160028601555160038501555160048401555160058301555160068201550193511515849060ff801983541691151516179055565b518254915162ffff001990921690151560081b61ff00161790151560101b62ff000016179055600d546149ca9061551b565b600d5560018060a01b039051169447936040519687528887015260408601526060850152608084015260a08301524260c0830152827fdd0602ca2177d4659e08f6824ebc6f123ee4d8440e33aab9ba4e625f2eb32fcb60e03394a4604051908152f35b638acb5f2760e01b5f5260045ffd5b9050600d541015886148a9565b50620f1b308511614898565b50335f52600160205260ff60405f2054161561482f565b34610f46576020366003190112610f4657614a856153ad565b6387a211a2600c525f52602080600c2054604051908152f35b34610f46576020366003190112610f4657600435614aba61572a565b8015613d6057601555005b34610f46576020366003190112610f4657600435614ae161572a565b478111610f9157614af881638b78c6d81954615746565b638b78c6d819546040519182526001600160a01b0316907f9520fe2678e0516c00ad6efc90d2ee6857e665081c3fc5c80b83764400360e1090602090a2005b34610f46575f366003190112610f46576020601154604051908152f35b34610f46575f366003190112610f46576020601254604051908152f35b34610f46575f366003190112610f46576020604051620f1b308152f35b34610f46575f366003190112610f4657602060ff601354166040519015158152f35b34610f46575f366003190112610f46576020600754604051908152f35b5f366003190112610f465763389a75e1600c52335f525f6020600c2055337ffa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c925f80a2005b34610f46575f366003190112610f4657602060ff5f54166040519015158152f35b34610f46576020366003190112610f4657614c4b6153ad565b614c5361572a565b6001600160a01b03168015613d6f576001600160601b0360a01b60065416176006555f80f35b34610f46576020366003190112610f46576001600160a01b03614c9a6153ad565b165f526017602052602060ff60405f2054166040519015158152f35b34610f46575f366003190112610f4657614cce61572a565b6013805460ff19169055005b34610f46575f366003190112610f46576020600454604051908152f35b34610f46575f366003190112610f4657602060a0614d13615483565b828151910120604051907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8252838201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015220604051908152f35b34610f46575f366003190112610f465760206040516b033b2e3c9fd0803ce80000008152f35b34610f46575f366003190112610f46576006546040516001600160a01b039091168152602090f35b34610f46575f366003190112610f4657602060405160128152f35b34610f46576020366003190112610f4657600435614e0461572a565b8015613d6057670de0b6b3a76400008111613d6057600255005b34610f46575f366003190112610f46576020601554604051908152f35b34610f46575f366003190112610f46576020600854604051908152f35b5f366003190112610f465763389a75e1600c52335f526202a30042016020600c2055337fdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d5f80a2005b34610f46576060366003190112610f4657614eba6153ad565b614ec26153c3565b6044359060ff5f541615614f9b575b8260601b6e22d473030f116ddee9f6b43ac78ba33303614f51575b6387a211a217600c526020600c208054808411614f445783900390555f526020600c20818154019055602052600c5160601c9060018060a01b03165f80516020615e6c833981519152602080a3602060405160018152f35b63f4d678b85f526004601cfd5b33602052637f5e9f208117600c526034600c20908154918219614f77575b509050614eec565b828511614f8e57846387a211a29303905585614f6f565b6313be252b5f526004601cfd5b7f000000000000000000000000bd216513d74c8cf14cf4747e6aaa6420ff64ee9e6001600160a01b031633811480156150e4575b638b78c6d819546001600160a01b0386811691168181149390929184156150da575b159283156150c8575b7f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031690338214615067575b50505015918261505e575b5081615055575b5015614ed1575b63ab35696f60e01b5f5260045ffd5b9050158461503f565b15915085615038565b6001600160a01b0387169182149283156150be575b5082156150b4575b5081156150aa575b81156150a1575b50156150465786808061502d565b90501587615093565b308114915061508c565b8114915088615084565b821492508961507c565b6001600160a01b038616159350614ffa565b3081149450614ff1565b50337f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031614614fcf565b34610f46576020366003190112610f465761512f6153ad565b61513761572a565b6001600160a01b03168015613d6f57805f52601860205260ff60405f205416610fe457805f52601860205260405f20600160ff198254161790557fead6a006345da1073a106d5f32372d2d2204f46cb0b4bca8f5ebafcbbed12b8a5f80a2005b34610f46575f366003190112610f46576020600c54604051908152f35b5f366003190112610f46576006546001600160a01b031633141580615213575b6141b4573415613d6057476040519034825260208201527f318f8a239412df7b37584cdc970509562cc8ea85492a3cc8622124bb1f72980c60403392a2005b50638b78c6d819546001600160a01b03163314156151d4565b34610f46575f366003190112610f465760206805345cdf77eb68f44c54604051908152f35b34610f46576020366003190112610f465760043561526d61572a565b8015613d6057601455005b34610f46576020366003190112610f46576001600160a01b036152996153ad565b165f526001602052602060ff60405f2054166040519015158152f35b34610f46575f366003190112610f46576020600f54604051908152f35b34610f46576040366003190112610f46576152eb6153ad565b602435906001600160a01b0381166e22d473030f116ddee9f6b43ac78ba318821915171561536157602052637f5e9f20600c52335f52806034600c20555f52602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3602060405160018152f35b633f68539a5f526004601cfd5b34610f46575f366003190112610f4657612e28614022615483565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b0382168203610f4657565b602435906001600160a01b0382168203610f4657565b6040906003190112610f46576004359060243590565b6040810190811067ffffffffffffffff82111761418557604052565b610140810190811067ffffffffffffffff82111761418557604052565b60a0810190811067ffffffffffffffff82111761418557604052565b6101c0810190811067ffffffffffffffff82111761418557604052565b90601f8019910116810190811067ffffffffffffffff82111761418557604052565b60405190615492604083615461565b600c82526b4d656d65537472617465677960a01b6020830152565b6001600160a01b0381166e22d473030f116ddee9f6b43ac78ba3186001171561536157602052637f5e9f20600c52335f525f196034600c20555f195f52602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3600190565b5f198114610f4a5760010190565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b600f0b6f7fffffffffffffffffffffffffffffff198114610f4a575f0390565b90816020910312610f46575190565b91908201809211610f4a57565b8051156155b55760200190565b634e487b7160e01b5f52603260045260245ffd5b8051600110156155b55760400190565b90602080835192838152019201905f5b8181106155f65750505090565b82516001600160a01b03168452602093840193909201916001016155e9565b919260809361563a92979695978452602084015260a0604084015260a08301906155d9565b6001600160a01b0390951660608201520152565b91908203918211610f4a57565b602081830312610f465780519067ffffffffffffffff8211610f4657019080601f83011215610f465781519167ffffffffffffffff8311614185578260051b9060208201936156ad6040519586615461565b8452602080850192820101928311610f4657602001905b8282106156d15750505090565b81518152602091820191016156c4565b8015610f4a575f190190565b906001600160a01b0381166e22d473030f116ddee9f6b43ac78ba31461572357602052637f5e9f20600c525f526034600c205490565b50505f1990565b638b78c6d81954330361573957565b6382b429005f526004601cfd5b5f80809338935af11561575557565b63b12d13eb5f526004601cfd5b60018060a01b031680638b78c6d819547f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3638b78c6d81955565b919060145260345263a9059cbb60601b5f5260205f6044601082855af1908160015f511416156157d2575b50505f603452565b3b153d1710156157e3575f806157ca565b6390b8ec185f526004601cfd5b6001600160a01b03168061586b5750604051630476982d60e21b815290602090829060049082907f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b03165af18015610f3b576158505750565b6158689060203d6020116140c7576140b88183615461565b50565b7f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031691823b15610f4657604051632961046560e21b8152600481018390525f9290838160248183895af18015610f3b57615908575b50926158d860209282859661579f565b600460405180958193630476982d60e21b83525af19081156158fc57506158505750565b604051903d90823e3d90fd5b8491935060209261591c5f6158d893615461565b5f94925092506158c8565b7f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b031691823b15610f4657604051630b0d9c0960e01b81526001600160a01b0390921660048301523060248301526044820152905f908290606490829084905af18015610f3b5761599c5750565b5f6159a691615461565b565b6040906159bf9392815281602082015201906155d9565b90565b81810292918115918404141715610f4a57565b8115612575570490565b90816020910312610f46575160ff81168103610f465790565b90615a78925f9260405192615a0e606085615461565b600284526040366020860137615a23846155a8565b6001600160a01b0391821690527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216615a5b846155c9565b5260405180958194829363d06ca61f60e01b8452600484016159a8565b03916001600160a01b03165afa5f9181615ae0575b50615aa1576365be670760e11b5f5260045ffd5b615aaa906155c9565b519061271003906127108211610f4a57612710615acb8193615ad6936159c2565b0492600554906159c2565b048110613d605790565b615af59192503d805f833e610f828183615461565b905f615a8d565b60195480615b075750565b615b10906156e1565b601955565b918115613d605760405163313ce56760e01b815290602090829060049082906001600160a01b03165afa8015610f3b5760ff915f91615b7f575b5016604d8111610f4a57600a0a91821561257557825f19048111612566576159bf92615b7a916159c2565b6159d5565b615b98915060203d6020116122fd576122ee8183615461565b5f615b4f565b8015615c1f576387a211a2600c52305f526020600c20549047908115615c17578215612575575f19839004811115615c0457615be39291615bde916159d5565b6159c2565b905b61271003906127108211610f4a5761271091615c00916159c2565b0490565b615c1192615b7a916159c2565b90615be5565b505050505f90565b50505f90565b9190918015615e65576387a211a2600c908152305f5260209020546001600160ff1b038211610f4657600160ff1b8214610f4a57600160ff19601a541617601a55615cad5f60405160016020820152848203604082015260408152615c8b606082615461565b604051809381926348c8949160e01b8352602060048401526024830190615389565b0381837f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b03165af19081615dde575b50615cf9575050601a805460ff191690555f9150565b615d1d9060ff19601a5416601a556387a211a2600c52305f526020600c205461564e565b928015159081615dd4575b50613d60576387a211a2600c52305f526020600c2090815490818511614f44577fe25c13ab9b2aded7bb7d39d4829c2efb98edd820bd84d49234678cedc8b8fd5692858093039055816805345cdf77eb68f44c54036805345cdf77eb68f44c55815f525f305f80516020615e6c833981519152602083a3615dcf615dae8360105461559b565b80601055604051938493846040919493926060820195825260208201520152565b0390a1565b905083105f615d28565b3d805f833e615ded8183615461565b810190602081830312610f465780519067ffffffffffffffff8211610f46570181601f82011215610f465780519067ffffffffffffffff82116141855760405192615e42601f8401601f191660200185615461565b82845260208383010111610f4657815f9260208093018386015e83010152615ce3565b505f915056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220ee7a358ad3f350b718c1081454c98ff4839353675864329d256cd3bae2e09b0864736f6c634300081a0033

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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.