ETH Price: $2,953.74 (-0.37%)

Contract

0x075017059f293B6EE8B8730917E78E61327440E5

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Set Authorized F...384861312026-01-24 6:01:3010 hrs ago1769234490IN
0x07501705...1327440E5
0 ETH0.000000060.0015

View more zero value Internal Transactions in Advanced View mode

Advanced mode:

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
VolatilityOracle

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

// - - - external deps - - -

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ReentrancyGuard} from "solmate/src/utils/ReentrancyGuard.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";

// - - - local deps - - -

import {Errors} from "../errors/Errors.sol";
import {TruncatedOracle} from "./TruncatedOracle.sol";

contract VolatilityOracle is ReentrancyGuard {
    /* ========== paged ring – each "leaf" holds 512 observations ========== */
    uint16 internal constant PAGE_SIZE = 512;

    using TruncatedOracle for TruncatedOracle.Observation[PAGE_SIZE];
    using PoolIdLibrary for PoolKey;
    using SafeCast for int256;

    /* -------------------------------------------------------------------------- */
    /*                               Library constants                            */
    /* -------------------------------------------------------------------------- */
    /* seconds in one day (for readability) */
    uint32 internal constant ONE_DAY_SEC = 86_400;
    /* parts-per-million constant */
    uint32 internal constant PPM = 1_000_000;
    /* pre-computed ONE_DAY × PPM to avoid a mul on every cap event            *
     * 86_400 * 1_000_000  ==  86 400 000 000  <  2¹²⁷ – safe for uint128      */
    uint64 internal constant ONE_DAY_PPM = 86_400 * 1_000_000;
    /* one add (ONE_DAY_PPM) short of uint64::max */
    uint64 internal constant CAP_FREQ_MAX = type(uint64).max - ONE_DAY_PPM + 1;
    /* minimum change required to emit MaxTicksPerBlockUpdated event */
    uint24 internal constant EVENT_DIFF = 5;

    // Custom errors
    error NotAuthorizedHook();
    error OnlyOwner();
    error OnlyOwnerOrFactory();
    error ObservationOverflow(uint16 cardinality);
    error ObservationTooOld(uint32 time, uint32 target);
    error TooManyObservationsRequested();

    event TickCapParamChanged(PoolId indexed poolId, uint24 newMaxTicksPerBlock);
    event MaxTicksPerBlockUpdated(
        PoolId indexed poolId, uint24 oldMaxTicksPerBlock, uint24 newMaxTicksPerBlock, uint32 blockTimestamp
    );
    event PolicyCacheRefreshed(PoolId indexed poolId);
    /// emitted once per pool when the oracle is first enabled
    event OracleConfigured(PoolId indexed poolId, address indexed hook, address indexed owner, uint24 initialCap);
    event HookAuthorized(address indexed hook);
    event HookRevoked(address indexed hook);
    event AuthorizedFactorySet(address indexed factory);

    /* ─────────────────── IMMUTABLE STATE ────────────────────── */
    IPoolManager public immutable poolManager;
    address public immutable owner; // Governance address that can refresh policy cache

    /* ─────────────────── MULTI-HOOK AUTHORIZATION ────────────────────── */
    /// @notice Mapping of authorized hook addresses that can push observations
    mapping(address => bool) public authorizedHooks;
    /// @notice Factory address that can register new hooks
    address public authorizedFactory;

    /* ───────────────────── MUTABLE STATE ────────────────────── */
    mapping(PoolId => uint24) public maxTicksPerBlock; // adaptive cap
    /* ppm-seconds never exceeds 8.64 e10 per event or 7.45 e15 per year  →
       well inside uint64.  Using uint64 halves slot gas / SLOAD cost.   */
    mapping(PoolId => uint64) private capFreq; // ***saturating*** counter
    mapping(PoolId => uint48) private lastFreqTs; // last decay update

    struct ObservationState {
        uint16 index;
        /**
         * @notice total number of populated observations.
         * Includes the bootstrap slot written by `enableOracleForPool`,
         * so after N user pushes the value is **N + 1**.
         */
        uint16 cardinality;
        uint16 cardinalityNext;
    }

    struct ObserveContext {
        uint32 time;
        int24 currentTick;
        uint128 liquidity;
        uint16 newestLocalIdx;
        uint16 newestCard;
    }

    /* ─────────────── cached policy parameters (baseFee logic removed) ─────────────── */
    struct CachedPolicy {
        uint24 minCap;
        uint24 maxCap;
        uint32 stepPpm;
        uint32 budgetPpm;
        uint32 decayWindow;
        uint32 updateInterval;
    }

    mapping(PoolId => CachedPolicy) internal _policy;

    /* ──────────────────  CHUNKED OBSERVATION RING  ──────────────────
       Each pool owns *pages* (index ⇒ Observation[PAGE_SIZE]).
       A page is allocated lazily the first time it is touched, so the
       storage footprint grows with `grow()` instead of pre-allocating
       65 k slots (≈ 4 MiB) per pool.                                        */
    /// pool ⇒ page# ⇒ 512-slot chunk (lazily created)
    mapping(PoolId => mapping(uint16 => TruncatedOracle.Observation[PAGE_SIZE])) internal _pages;

    function _leaf(PoolId poolId, uint16 globalIdx)
        internal
        view
        returns (TruncatedOracle.Observation[PAGE_SIZE] storage)
    {
        return _pages[poolId][globalIdx / PAGE_SIZE];
    }

    mapping(PoolId => ObservationState) public states;

    // Store last max tick update time for rate limiting governance changes
    mapping(PoolId => uint32) private _lastMaxTickUpdate;

    /* ────────────────────── CONSTRUCTOR ─────────────────────── */
    /// -----------------------------------------------------------------------
    /// @notice Deploy the oracle and wire the immutable dependencies.
    /// @param _poolManager Canonical v4 `PoolManager` contract
    /// @param _owner Governor address that can refresh the cached policy
    /// -----------------------------------------------------------------------
    constructor(IPoolManager _poolManager, address _owner) {
        if (address(_poolManager) == address(0)) revert Errors.ZeroAddress();
        if (_owner == address(0)) revert Errors.ZeroAddress();

        poolManager = _poolManager;
        owner = _owner;
    }

    /* ────────────────────── AUTHORIZATION MANAGEMENT ─────────────────────── */

    /// @notice Sets the authorized factory that can register hooks
    /// @param _factory The factory address to authorize
    function setAuthorizedFactory(address _factory) external {
        if (msg.sender != owner) revert OnlyOwner();
        authorizedFactory = _factory;
        emit AuthorizedFactorySet(_factory);
    }

    /// @notice Adds an authorized hook that can push observations
    /// @dev Can be called by owner or the authorized factory
    /// @param _hook The hook address to authorize
    function addAuthorizedHook(address _hook) external {
        if (msg.sender != owner && msg.sender != authorizedFactory) revert OnlyOwnerOrFactory();
        if (_hook == address(0)) revert Errors.ZeroAddress();
        authorizedHooks[_hook] = true;
        emit HookAuthorized(_hook);
    }

    /// @notice Removes an authorized hook
    /// @dev Can only be called by owner
    /// @param _hook The hook address to revoke
    function removeAuthorizedHook(address _hook) external {
        if (msg.sender != owner) revert OnlyOwner();
        authorizedHooks[_hook] = false;
        emit HookRevoked(_hook);
    }

    /**
     * @notice Refreshes the cached policy parameters for a pool.
     * @dev Can only be called by the owner (governance).
     * @param poolId The PoolId of the pool.
     * @param minCap Minimum maxTicksPerBlock value
     * @param maxCap Maximum maxTicksPerBlock value
     * @param stepPpm Auto-tune step size in PPM
     * @param budgetPpm Target CAP frequency in PPM
     * @param decayWindow Frequency decay window in seconds
     * @param updateInterval Minimum time between auto-tune adjustments
     */
    function refreshPolicyCache(
        PoolId poolId,
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external {
        if (msg.sender != owner) revert OnlyOwner();

        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("refreshPolicyCache", "Pool not enabled");
        }

        CachedPolicy storage pc = _policy[poolId];

        // Update all policy parameters
        pc.minCap = minCap;
        pc.maxCap = maxCap;
        pc.stepPpm = stepPpm;
        pc.budgetPpm = budgetPpm;
        pc.decayWindow = decayWindow;
        pc.updateInterval = updateInterval;

        _validatePolicy(pc);

        // Ensure current maxTicksPerBlock is within new min/max bounds
        uint24 currentCap = maxTicksPerBlock[poolId];
        if (currentCap < pc.minCap) {
            maxTicksPerBlock[poolId] = pc.minCap;
            emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.minCap, uint32(block.timestamp));
        } else if (currentCap > pc.maxCap) {
            maxTicksPerBlock[poolId] = pc.maxCap;
            emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.maxCap, uint32(block.timestamp));
        }

        emit PolicyCacheRefreshed(poolId);
    }

    /**
     * @notice Enables the oracle for a given pool, initializing its state.
     * @dev Can only be called by the configured hook address.
     * @param key The PoolKey of the pool to enable.
     * @param initialMaxTicksPerBlock User-set initial CAP threshold
     * @param minCap Minimum maxTicksPerBlock value
     * @param maxCap Maximum maxTicksPerBlock value
     * @param stepPpm Auto-tune step size in PPM
     * @param budgetPpm Target CAP frequency in PPM
     * @param decayWindow Frequency decay window in seconds
     * @param updateInterval Minimum time between auto-tune adjustments
     */
    function enableOracleForPool(
        PoolKey calldata key,
        uint24 initialMaxTicksPerBlock,
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external {
        if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
        PoolId poolId = key.toId();
        if (states[poolId].cardinality > 0) {
            revert Errors.OracleOperationFailed("enableOracleForPool", "Already enabled");
        }

        /* ------------------------------------------------------------------ *
         * Set policy parameters and validate                                 *
         * ------------------------------------------------------------------ */
        CachedPolicy storage pc = _policy[poolId];
        pc.minCap = minCap;
        pc.maxCap = maxCap;
        pc.stepPpm = stepPpm;
        pc.budgetPpm = budgetPpm;
        pc.decayWindow = decayWindow;
        pc.updateInterval = updateInterval;

        _validatePolicy(pc);

        // ---------- external read last (reduces griefing surface) ----------
        (, int24 initialTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        TruncatedOracle.Observation[PAGE_SIZE] storage first = _pages[poolId][0];
        first.initialize(uint32(block.timestamp), initialTick);
        states[poolId] = ObservationState({index: 0, cardinality: 1, cardinalityNext: 1});

        // Clamp initialMaxTicksPerBlock inside the validated range
        uint24 cappedInitial = initialMaxTicksPerBlock;
        if (cappedInitial < pc.minCap) cappedInitial = pc.minCap;
        if (cappedInitial > pc.maxCap) cappedInitial = pc.maxCap;
        maxTicksPerBlock[poolId] = cappedInitial;

        // --- audit-aid event ----------------------------------------------------
        emit OracleConfigured(poolId, msg.sender, owner, cappedInitial);
    }

    // Internal workhorse
    function _recordObservation(PoolId poolId, int24 preSwapTick) internal returns (bool tickWasCapped) {
        ObservationState storage state = states[poolId];
        uint16 index = state.index;

        int24 currentTick;
        // Scope to drop temporary variables
        {
            (, int24 tick,,) = StateLibrary.getSlot0(poolManager, poolId);
            currentTick = tick;

            uint24 cap = maxTicksPerBlock[poolId];
            int256 tickDelta256 = int256(currentTick) - int256(preSwapTick);
            uint256 absDelta = tickDelta256 >= 0 ? uint256(tickDelta256) : uint256(-tickDelta256);

            if (absDelta >= cap) {
                int256 capped = tickDelta256 > 0
                    ? int256(preSwapTick) + int256(uint256(cap))
                    : int256(preSwapTick) - int256(uint256(cap));
                currentTick = _toInt24(capped);
                tickWasCapped = true;
            }
        }

        uint32 ts = uint32(block.timestamp);
        TruncatedOracle.Observation storage last = _leaf(poolId, index)[index % PAGE_SIZE];
        if (last.blockTimestamp != ts) {
            uint16 cardinalityUpdated = state.cardinality;
            uint16 cardinalityNext = state.cardinalityNext;
            if (cardinalityNext == cardinalityUpdated && cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
                cardinalityNext = cardinalityUpdated + 1;
            }

            if (cardinalityNext > cardinalityUpdated && index == (cardinalityUpdated - 1)) {
                cardinalityUpdated = cardinalityNext;
                if (cardinalityUpdated > TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
                    cardinalityUpdated = TruncatedOracle.MAX_CARDINALITY_ALLOWED;
                }
            }

            unchecked {
                index += 1;
            }
            if (index >= cardinalityUpdated) {
                index = 0;
            }

            uint128 liquidity = StateLibrary.getLiquidity(poolManager, poolId);
            uint32 delta;
            unchecked {
                delta = ts - last.blockTimestamp;
            }
            TruncatedOracle.Observation storage o = _leaf(poolId, index)[index % PAGE_SIZE];
            o.blockTimestamp = ts;
            o.tickCumulative = last.tickCumulative + int56(currentTick) * int56(uint56(delta));
            o.secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128
                + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1));
            o.initialized = true;

            state.index = index;
            state.cardinality = cardinalityUpdated;

            if (
                state.cardinalityNext < cardinalityUpdated + 1
                    && state.cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED
            ) {
                state.cardinalityNext = cardinalityUpdated + 1;
            }
        }

        _updateCapFrequency(poolId, tickWasCapped);
    }

    /// -----------------------------------------------------------------------
    /// @notice Record a new observation using the actual pre-swap tick.
    /// -----------------------------------------------------------------------
    function pushObservationAndCheckCap(PoolId poolId, int24 preSwapTick)
        external
        nonReentrant
        returns (bool tickWasCapped)
    {
        if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("pushObservationAndCheckCap", "Pool not enabled");
        }
        return _recordObservation(poolId, preSwapTick);
    }

    /* ─────────────────── VIEW FUNCTIONS ──────────────────────── */

    /**
     * @notice Checks if the oracle is enabled for a given pool.
     * @param poolId The PoolId to check.
     * @return True if the oracle is enabled, false otherwise.
     */
    function isOracleEnabled(PoolId poolId) external view returns (bool) {
        return states[poolId].cardinality > 0;
    }

    /**
     * @notice Gets the latest observation for a pool.
     * @param poolId The PoolId of the pool.
     * @return tick The tick from the latest observation.
     * @return blockTimestamp The timestamp of the latest observation.
     */
    function getLatestObservation(PoolId poolId) external view returns (int24 tick, uint32 blockTimestamp) {
        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("getLatestObservation", "Pool not enabled");
        }

        ObservationState storage state = states[poolId];
        TruncatedOracle.Observation storage o = _leaf(poolId, state.index)[state.index % PAGE_SIZE];
        (, int24 liveTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        return (liveTick, o.blockTimestamp);
    }

    /// @notice View helper mirroring the public mapping but typed for tests.
    function getMaxTicksPerBlock(PoolId poolId) external view returns (uint24) {
        return maxTicksPerBlock[poolId];
    }

    /**
     * @notice Returns the saturation threshold for the capFreq counter.
     * @return The maximum value for the capFreq counter before it saturates.
     */
    function getCapFreqMax() external pure returns (uint64) {
        return CAP_FREQ_MAX;
    }

    /// @notice Calculates time-weighted means of tick and liquidity
    /// @param key the key of the pool to consult
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(PoolKey calldata key, uint32 secondsAgo)
        external
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, "BP");

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

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
            observe(key, secondsAgos);

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

        int56 secondsAgoI56 = int56(uint56(secondsAgo));

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

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

    /**
     * @notice Observe oracle values at specific secondsAgos from the current block timestamp
     * @dev Reverts if observation at or before the desired observation timestamp does not exist
     * @param key The pool key to observe
     * @param secondsAgos The array of seconds ago to observe
     * @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each secondsAgo
     * @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since pool initialized
     */
    function observe(PoolKey calldata key, uint32[] memory secondsAgos)
        public
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
    {
        PoolId poolId = key.toId();

        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("observe", "Pool not enabled");
        }

        ObservationState storage state = states[poolId];
        uint16 gIdx = state.index; // global index of newest obs

        uint256 len = secondsAgos.length;
        tickCumulatives = new int56[](len);
        secondsPerLiquidityCumulativeX128s = new uint160[](len);
        if (len == 0) return (tickCumulatives, secondsPerLiquidityCumulativeX128s);

        ObserveContext memory ctx;
        ctx.time = uint32(block.timestamp);
        (, ctx.currentTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        ctx.liquidity = StateLibrary.getLiquidity(poolManager, poolId);
        ctx.newestLocalIdx = uint16(gIdx % PAGE_SIZE);
        {
            uint16 newestBase = gIdx - ctx.newestLocalIdx;
            uint16 newestCard = state.cardinality > newestBase ? state.cardinality - newestBase : 1;
            if (newestCard > PAGE_SIZE) {
                newestCard = PAGE_SIZE;
            }
            ctx.newestCard = newestCard;
        }

        for (uint256 i = 0; i < len; i++) {
            uint32 secondsAgo = secondsAgos[i];
            if (secondsAgo == 0) {
                TruncatedOracle.Observation[PAGE_SIZE] storage newestPage = _leaf(poolId, gIdx);
                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                    TruncatedOracle.observeSingle(
                        newestPage,
                        ctx.time,
                        0,
                        ctx.currentTick,
                        ctx.newestLocalIdx,
                        ctx.liquidity,
                        ctx.newestCard
                    );
                continue;
            }

            (uint16 leafCursor, uint16 idx, uint16 card) =
                _resolveLeafForSecondsAgo(poolId, state, gIdx, ctx.newestLocalIdx, ctx.time, secondsAgo);
            TruncatedOracle.Observation[PAGE_SIZE] storage obs = _leaf(poolId, leafCursor);
            (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                TruncatedOracle.observeSingle(obs, ctx.time, secondsAgo, ctx.currentTick, idx, ctx.liquidity, card);
        }

        return (tickCumulatives, secondsPerLiquidityCumulativeX128s);
    }

    function _resolveLeafForSecondsAgo(
        PoolId poolId,
        ObservationState storage state,
        uint16 gIdx,
        uint16 newestLocalIdx,
        uint32 time,
        uint32 secondsAgo
    ) internal view returns (uint16 leafCursor, uint16 idx, uint16 card) {
        uint32 target;
        unchecked {
            target = time >= secondsAgo ? time - secondsAgo : time + (type(uint32).max - secondsAgo) + 1;
        }

        uint16 newestBase = gIdx - newestLocalIdx;
        uint16 pageCursor = newestBase;
        if (state.cardinality == TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
            uint16 pageCount = TruncatedOracle.MAX_CARDINALITY_ALLOWED / PAGE_SIZE;
            for (uint16 i = 0; i < pageCount; i++) {
                TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
                uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : PAGE_SIZE - 1;
                uint16 firstSlot = (pageNewestIdx + 1) % PAGE_SIZE;
                uint32 firstTs = page[firstSlot].blockTimestamp;

                if (target >= firstTs || i + 1 == pageCount) {
                    idx = pageNewestIdx;
                    card = PAGE_SIZE;
                    return (pageCursor, idx, card);
                }

                if (pageCursor >= PAGE_SIZE) {
                    pageCursor -= PAGE_SIZE;
                } else {
                    pageCursor = TruncatedOracle.MAX_CARDINALITY_ALLOWED - PAGE_SIZE;
                }
            }
        }

        while (true) {
            TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
            uint16 pageCardinality = state.cardinality > pageCursor ? state.cardinality - pageCursor : 1;
            if (pageCardinality > PAGE_SIZE) {
                pageCardinality = PAGE_SIZE;
            }

            uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : pageCardinality - 1;
            uint16 firstSlot = pageCardinality == PAGE_SIZE ? (pageNewestIdx + 1) % PAGE_SIZE : 0;
            uint32 firstTs = page[firstSlot].blockTimestamp;

            if (target >= firstTs || pageCursor == 0) {
                idx = pageNewestIdx;
                card = pageCardinality;
                return (pageCursor, idx, card);
            }
            pageCursor -= PAGE_SIZE;
        }
    }


    /* ────────────────────── INTERNALS ──────────────────────── */

    /**
     * @notice Updates the CAP frequency counter and potentially triggers auto-tuning.
     * @dev Decays the frequency counter based on time elapsed since the last update.
     *      Increments the counter if a CAP occurred.
     *      Triggers auto-tuning if the frequency exceeds the budget or is too low.
     * @param poolId The PoolId of the pool.
     * @param capOccurred True if a CAP event occurred in the current block.
     */
    function _updateCapFrequency(PoolId poolId, bool capOccurred) internal {
        uint32 lastTs = uint32(lastFreqTs[poolId]);
        uint32 nowTs = uint32(block.timestamp);
        uint32 timeElapsed = nowTs - lastTs;

        /* FAST-PATH ────────────────────────────────────────────────────────
           No tick was capped *and* we're still in the same second ⇒ every
           state var is already correct, so we avoid **all** SSTOREs.      */
        if (!capOccurred && timeElapsed == 0) return;

        lastFreqTs[poolId] = uint48(nowTs); // single SSTORE only when needed

        uint64 currentFreq = capFreq[poolId];

        // --------------------------------------------------------------------- //
        //  1️⃣  Add this block's CAP contribution *first* and saturate.         //
        // --------------------------------------------------------------------- //
        if (capOccurred) {
            unchecked {
                currentFreq += uint64(ONE_DAY_PPM);
            }
            if (currentFreq >= CAP_FREQ_MAX || currentFreq < ONE_DAY_PPM) {
                currentFreq = CAP_FREQ_MAX; // clamp one-step-early
            }
        }

        /* -------- cache policy once -------- */
        CachedPolicy storage pc = _policy[poolId];
        uint32 budgetPpm = pc.budgetPpm;
        uint32 decayWindow = pc.decayWindow;
        uint32 updateInterval = pc.updateInterval;

        // 2️⃣  Apply linear decay *only when no CAP in this block*.
        if (!capOccurred && timeElapsed > 0 && currentFreq > 0) {
            // decay factor = (window - elapsed) / window = 1 - elapsed / window
            if (timeElapsed >= decayWindow) {
                currentFreq = 0; // Fully decayed
            } else {
                uint64 decayFactorPpm = PPM - uint64(timeElapsed) * PPM / decayWindow;
                uint128 decayed = uint128(currentFreq) * decayFactorPpm / PPM;
                // ----- overflow-safe down-cast -------------------------
                if (decayed > type(uint64).max) {
                    currentFreq = CAP_FREQ_MAX;
                } else {
                    uint64 d64 = uint64(decayed);
                    currentFreq = d64 > CAP_FREQ_MAX ? CAP_FREQ_MAX : d64;
                }
            }
        }

        capFreq[poolId] = currentFreq; // single SSTORE

        // Only auto-tune if enough time has passed since last update
        if (!_autoTunePaused[poolId] && block.timestamp >= _lastMaxTickUpdate[poolId] + updateInterval) {
            uint64 targetFreq = uint64(budgetPpm) * ONE_DAY_SEC;
            if (currentFreq > targetFreq) {
                // Too frequent caps -> Increase maxTicksPerBlock (loosen cap)
                _autoTuneMaxTicks(poolId, pc, true);
            } else {
                // Caps too rare -> Decrease maxTicksPerBlock (tighten cap)
                _autoTuneMaxTicks(poolId, pc, false);
            }
        }
    }

    /**
     * @notice Adjusts the maxTicksPerBlock based on CAP frequency.
     * @dev Increases the cap if caps are too frequent, decreases otherwise.
     *      Clamps the adjustment based on policy step size and min/max bounds.
     * @param poolId The PoolId of the pool.
     * @param pc Cached policy struct
     * @param increase True to increase the cap, false to decrease.
     */
    function _autoTuneMaxTicks(PoolId poolId, CachedPolicy storage pc, bool increase) internal {
        uint24 currentCap = maxTicksPerBlock[poolId];

        uint32 stepPpm = pc.stepPpm;
        uint24 minCap = pc.minCap;
        uint24 maxCap = pc.maxCap;

        uint24 change = uint24(uint256(currentCap) * stepPpm / PPM);
        if (change == 0) change = 1; // Ensure minimum change of 1 tick

        uint24 newCap;
        if (increase) {
            newCap = currentCap + change > maxCap ? maxCap : currentCap + change;
        } else {
            newCap = currentCap > change + minCap ? currentCap - change : minCap;
        }

        uint24 diff = currentCap > newCap ? currentCap - newCap : newCap - currentCap;

        if (newCap != currentCap) {
            maxTicksPerBlock[poolId] = newCap;
            _lastMaxTickUpdate[poolId] = uint32(block.timestamp);
            if (diff >= EVENT_DIFF) {
                emit MaxTicksPerBlockUpdated(poolId, currentCap, newCap, uint32(block.timestamp));
            }
        }
    }

    /* ────────────────────── INTERNAL HELPERS ───────────────────────── */

    /// @dev bounded cast; reverts on overflow instead of truncating.
    function _toInt24(int256 v) internal pure returns (int24) {
        require(v >= type(int24).min && v <= type(int24).max, "Tick overflow");
        return int24(v);
    }

    /// @dev Validate policy parameters
    function _validatePolicy(CachedPolicy storage pc) internal view {
        require(pc.stepPpm != 0, "stepPpm cannot be 0");
        require(pc.minCap != 0, "minCap cannot be 0");
        require(pc.maxCap >= pc.minCap, "maxCap must be >= minCap");
        require(pc.decayWindow != 0, "decayWindow cannot be 0");
        require(pc.updateInterval != 0, "updateInterval cannot be 0");
    }

    /* ───────────────────── Emergency pause ────────────────────── */
    /// @notice Emitted when the governor toggles the auto-tune circuit-breaker.
    event AutoTunePaused(PoolId indexed poolId, bool paused, uint32 timestamp);

    /// @dev circuit-breaker flag per pool (default: false = auto-tune active)
    mapping(PoolId => bool) private _autoTunePaused;

    /**
     * @notice Pause or un-pause the adaptive cap algorithm for a pool.
     * @param poolId       Target PoolId.
     * @param paused    True to disable auto-tune, false to resume.
     */
    function setAutoTunePaused(PoolId poolId, bool paused) external {
        if (msg.sender != owner) revert OnlyOwner();
        _autoTunePaused[poolId] = paused;
        emit AutoTunePaused(poolId, paused, uint32(block.timestamp));
    }

    /* ─────────────────────── public cardinality grow ─────────────────────── */
    /**
     * @notice Requests the ring buffer to grow to `cardinalityNext` slots.
     * @dev Mirrors Uniswap-V3 behaviour. Callable by anyone; growth is capped
     *      by the TruncatedOracle library's internal MAX_CARDINALITY_ALLOWED.
     * @param key Encoded PoolKey.
     * @param cardinalityNext Desired new cardinality.
     * @return oldNext Previous next-size.
     * @return newNext Updated next-size after grow.
     */
    function increaseCardinalityNext(PoolKey calldata key, uint16 cardinalityNext)
        external
        returns (uint16 oldNext, uint16 newNext)
    {
        // Public function - anyone can grow the observation buffer (like Uniswap V3)
        PoolId poolId = key.toId();

        ObservationState storage state = states[poolId];
        if (state.cardinality == 0) {
            revert Errors.OracleOperationFailed("increaseCardinalityNext", "Pool not enabled");
        }

        oldNext = state.cardinalityNext;
        if (cardinalityNext <= oldNext) {
            return (oldNext, oldNext);
        }

        state.cardinalityNext = TruncatedOracle.grow(
            _leaf(poolId, state.cardinalityNext), // leaf storage slot
            oldNext,
            cardinalityNext
        );

        newNext = state.cardinalityNext;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

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

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

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

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

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

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

File 3 of 27 : ReentrancyGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

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

File 6 of 27 : 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 {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.0;

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     * @dev Note that feeGrowthGlobal can be artificially inflated
     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

File 9 of 27 : Errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

library Errors {
    error ZeroAddress();
    error UnauthorizedCaller(address caller);
    error NotInitialized();
    error OracleOperationFailed(string operation, string reason);
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @title TruncatedOracle
/// @notice Provides observation storage and TWAP queries for paged oracle architecture
/// @dev Designed to work with 512-slot pages, supporting lazy allocation
library TruncatedOracle {
    /// @notice Maximum number of observations across all pages
    /// @dev With PAGE_SIZE=512, this allows 16 full pages (8192 / 512 = 16)
    uint16 public constant MAX_CARDINALITY_ALLOWED = 8192;

    /// @notice Thrown when trying to observe a price that is older than the oldest recorded price
    error TargetPredatesOldestObservation(uint32 oldestTimestamp, uint32 targetTimestamp);

    struct Observation {
        // the block timestamp of the observation
        uint32 blockTimestamp;
        // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
        int56 tickCumulative;
        // the seconds per liquidity accumulator, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
        uint160 secondsPerLiquidityCumulativeX128;
        // whether or not the observation is initialized
        bool initialized;
    }

    /// @notice Initialize the first observation in a page
    /// @param self The storage array (512 slots)
    /// @param time The time of the observation
    function initialize(Observation[512] storage self, uint32 time, int24) internal {
        self[0] = Observation({
            blockTimestamp: time,
            tickCumulative: 0,
            secondsPerLiquidityCumulativeX128: 0,
            initialized: true
        });
    }

    /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
    /// @param last The specified observation to be transformed
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @return Observation The newly populated observation
    function transform(
        Observation memory last,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity
    ) private pure returns (Observation memory) {
        unchecked {
            uint32 delta = blockTimestamp - last.blockTimestamp;

            return Observation({
                blockTimestamp: blockTimestamp,
                tickCumulative: last.tickCumulative + int56(tick) * int56(uint56(delta)),
                secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128
                    + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
                initialized: true
            });
        }
    }

    /// @notice Writes an oracle observation to the page
    /// @dev Writable at most once per block within a page
    /// @param self The stored oracle page (512 slots)
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @param cardinality The number of populated observations in this page
    /// @param cardinalityNext The new length of the observations array after this write, capped at page size (512)
    /// @return indexUpdated The new index of the most recently written element in the oracle array
    /// @return cardinalityUpdated The new cardinality of the observations array
    function write(
        Observation[512] storage self,
        uint16 index,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity,
        uint16 cardinality,
        uint16 cardinalityNext
    ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
        unchecked {
            Observation memory last = self[index];

            // early return if we've already written an observation this block
            if (last.blockTimestamp == blockTimestamp) {
                return (index, cardinality);
            }

            // if the conditions are right, we can bump the cardinality
            if (cardinalityNext > cardinality && index == (cardinality - 1)) {
                cardinalityUpdated = cardinalityNext;
            } else {
                cardinalityUpdated = cardinality;
            }

            // increment index wrapping at page size (512)
            indexUpdated = (index + 1) % 512;
            self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);
        }
    }

    /// @notice Prepares the page to store observations by setting next-cardinality
    /// @dev Does not allocate storage; cardinality is incremented on first write
    /// @param current The current cardinality
    /// @param next The proposed next cardinality (what we want to grow to)
    /// @return The new cardinality-next value, capped at 512 and MAX_CARDINALITY_ALLOWED
    function grow(
        Observation[512] storage,
        uint16 current,
        uint16 next
    ) internal pure returns (uint16) {
        unchecked {
            if (next <= current) return current;
            // Cap at page size
            if (next > 512) next = 512;
            // Cap at global maximum
            if (next > MAX_CARDINALITY_ALLOWED) next = MAX_CARDINALITY_ALLOWED;
            return next;
        }
    }

    /// @notice comparator for 32-bit timestamps
    /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
    /// @param time A timestamp truncated to 32 bits
    /// @param a A comparison timestamp from which to determine the relative position of `time`
    /// @param b A comparison timestamp from which to determine the relative position of `time`
    /// @return Whether `a` is chronologically <= `b`
    function lte(
        uint32 time,
        uint32 a,
        uint32 b
    ) private pure returns (bool) {
        unchecked {
            // if there hasn't been overflow, no need to adjust
            if (a <= time && b <= time) return a <= b;

            uint256 aAdjusted = a > time ? a : a + 2 ** 32;
            uint256 bAdjusted = b > time ? b : b + 2 ** 32;

            return aAdjusted <= bAdjusted;
        }
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied
    /// @dev Assumes there is at least 1 initialized observation
    /// @dev Used by observeSingle() to compute time-weighted averages
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param tick The active tick at the time of the returned or simulated observation
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The total pool liquidity at the time of the call
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation recorded before, or at, the target
    /// @return atOrAfter The observation recorded at, or after, the target
    function getSurroundingObservations(
        Observation[512] storage self,
        uint32 time,
        uint32 target,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            // optimistically set before to the newest observation
            beforeOrAt = self[index];

            // if the target is chronologically at or after the newest observation, we can early return
            if (lte(time, beforeOrAt.blockTimestamp, target)) {
                if (beforeOrAt.blockTimestamp == target) {
                    return (beforeOrAt, atOrAfter);
                } else {
                    return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
                }
            }

            // now, set before to the oldest observation
            beforeOrAt = self[(index + 1) % cardinality];
            if (!beforeOrAt.initialized) beforeOrAt = self[0];

            // ensure that the target is chronologically at or after the oldest observation
            if (!lte(time, beforeOrAt.blockTimestamp, target)) {
                revert TargetPredatesOldestObservation(beforeOrAt.blockTimestamp, target);
            }

            // perform binary search
            return binarySearch(self, time, target, index, cardinality);
        }
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a given target using binary search
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation which occurred at, or before, the given timestamp
    /// @return atOrAfter The observation which occurred at, or after, the given timestamp
    function binarySearch(
        Observation[512] storage self,
        uint32 time,
        uint32 target,
        uint16 index,
        uint16 cardinality
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            uint256 l = (uint256(index) + 1) % cardinality; // oldest observation
            uint256 r = l + cardinality - 1; // newest observation (virtual index)
            uint256 i;

            while (true) {
                i = (l + r) / 2;

                beforeOrAt = self[i % cardinality];

                // we've landed on an uninitialized tick, keep searching higher (more recently)
                if (!beforeOrAt.initialized) {
                    l = i + 1;
                    continue;
                }

                atOrAfter = self[(i + 1) % cardinality];

                bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);

                // check if we've found the answer!
                if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) {
                    break;
                }

                if (!targetAtOrAfter) r = i - 1;
                else l = i + 1;
            }
        }
    }

    /// @notice Observes a single point in time
    /// @param self The stored oracle array
    /// @param time The current block timestamp
    /// @param secondsAgo The amount of time to look back, in seconds, from the current block timestamp
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
    function observeSingle(
        Observation[512] storage self,
        uint32 time,
        uint32 secondsAgo,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
        unchecked {
            if (secondsAgo == 0) {
                Observation memory last = self[index];
                if (last.blockTimestamp != time) {
                    last = transform(last, time, tick, liquidity);
                }
                return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
            }

            uint32 target = time - secondsAgo;

            (Observation memory beforeOrAt, Observation memory atOrAfter) =
                getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);

            if (target == beforeOrAt.blockTimestamp) {
                return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
            } else if (target == atOrAfter.blockTimestamp) {
                return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
            } else {
                // we're in the middle, interpolate
                uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
                uint32 targetDelta = target - beforeOrAt.blockTimestamp;

                tickCumulative = beforeOrAt.tickCumulative
                    + ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / int56(uint56(observationTimeDelta)))
                        * int56(uint56(targetDelta));

                secondsPerLiquidityCumulativeX128 = beforeOrAt.secondsPerLiquidityCumulativeX128
                    + uint160(
                        (uint256(
                            atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
                        ) * targetDelta) / observationTimeDelta
                    );
            }
        }
    }

    /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
    /// @dev Reverts if `secondsAgos` > oldest observation
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
    function observe(
        Observation[512] storage self,
        uint32 time,
        uint32[] memory secondsAgos,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
        require(cardinality > 0, "I");

        tickCumulatives = new int56[](secondsAgos.length);
        secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);

        unchecked {
            for (uint256 i = 0; i < secondsAgos.length; i++) {
                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                    observeSingle(self, time, secondsAgos[i], tick, index, liquidity, cardinality);
            }
        }
    }
}

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

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

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

File 18 of 27 : 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.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: BUSL-1.1
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

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

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

File 26 of 27 : FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

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

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

Settings
{
  "remappings": [
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/liquidity-launcher/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin-latest/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "@optimism/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/",
    "@solady/=lib/liquidity-launcher/lib/solady/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@uniswap/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
    "blocknumberish/=lib/liquidity-launcher/lib/blocknumberish/",
    "ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/liquidity-launcher/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solady/=lib/liquidity-launcher/lib/solady/src/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/",
    "scripts/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/scripts/",
    "liquidity-launcher/src/token-factories/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
    "liquidity-launcher/src/=lib/liquidity-launcher/src/",
    "liquidity-launcher/=lib/liquidity-launcher/",
    "periphery/=lib/liquidity-launcher/src/periphery/",
    "continuous-clearing-auction/=lib/liquidity-launcher/lib/continuous-clearing-auction/",
    "ll/=lib/liquidity-launcher/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"NotAuthorizedHook","type":"error"},{"inputs":[{"internalType":"uint16","name":"cardinality","type":"uint16"}],"name":"ObservationOverflow","type":"error"},{"inputs":[{"internalType":"uint32","name":"time","type":"uint32"},{"internalType":"uint32","name":"target","type":"uint32"}],"name":"ObservationTooOld","type":"error"},{"inputs":[],"name":"OnlyOwner","type":"error"},{"inputs":[],"name":"OnlyOwnerOrFactory","type":"error"},{"inputs":[{"internalType":"string","name":"operation","type":"string"},{"internalType":"string","name":"reason","type":"string"}],"name":"OracleOperationFailed","type":"error"},{"inputs":[{"internalType":"uint32","name":"oldestTimestamp","type":"uint32"},{"internalType":"uint32","name":"targetTimestamp","type":"uint32"}],"name":"TargetPredatesOldestObservation","type":"error"},{"inputs":[],"name":"TooManyObservationsRequested","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"factory","type":"address"}],"name":"AuthorizedFactorySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"paused","type":"bool"},{"indexed":false,"internalType":"uint32","name":"timestamp","type":"uint32"}],"name":"AutoTunePaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"hook","type":"address"}],"name":"HookAuthorized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"hook","type":"address"}],"name":"HookRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"oldMaxTicksPerBlock","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"newMaxTicksPerBlock","type":"uint24"},{"indexed":false,"internalType":"uint32","name":"blockTimestamp","type":"uint32"}],"name":"MaxTicksPerBlockUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"hook","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint24","name":"initialCap","type":"uint24"}],"name":"OracleConfigured","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"PolicyCacheRefreshed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"newMaxTicksPerBlock","type":"uint24"}],"name":"TickCapParamChanged","type":"event"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"}],"name":"addAuthorizedHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"authorizedFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"authorizedHooks","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint32","name":"secondsAgo","type":"uint32"}],"name":"consult","outputs":[{"internalType":"int24","name":"arithmeticMeanTick","type":"int24"},{"internalType":"uint128","name":"harmonicMeanLiquidity","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"initialMaxTicksPerBlock","type":"uint24"},{"internalType":"uint24","name":"minCap","type":"uint24"},{"internalType":"uint24","name":"maxCap","type":"uint24"},{"internalType":"uint32","name":"stepPpm","type":"uint32"},{"internalType":"uint32","name":"budgetPpm","type":"uint32"},{"internalType":"uint32","name":"decayWindow","type":"uint32"},{"internalType":"uint32","name":"updateInterval","type":"uint32"}],"name":"enableOracleForPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCapFreqMax","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"getLatestObservation","outputs":[{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint32","name":"blockTimestamp","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"getMaxTicksPerBlock","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint16","name":"cardinalityNext","type":"uint16"}],"name":"increaseCardinalityNext","outputs":[{"internalType":"uint16","name":"oldNext","type":"uint16"},{"internalType":"uint16","name":"newNext","type":"uint16"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"isOracleEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"}],"name":"maxTicksPerBlock","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint32[]","name":"secondsAgos","type":"uint32[]"}],"name":"observe","outputs":[{"internalType":"int56[]","name":"tickCumulatives","type":"int56[]"},{"internalType":"uint160[]","name":"secondsPerLiquidityCumulativeX128s","type":"uint160[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"int24","name":"preSwapTick","type":"int24"}],"name":"pushObservationAndCheckCap","outputs":[{"internalType":"bool","name":"tickWasCapped","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint24","name":"minCap","type":"uint24"},{"internalType":"uint24","name":"maxCap","type":"uint24"},{"internalType":"uint32","name":"stepPpm","type":"uint32"},{"internalType":"uint32","name":"budgetPpm","type":"uint32"},{"internalType":"uint32","name":"decayWindow","type":"uint32"},{"internalType":"uint32","name":"updateInterval","type":"uint32"}],"name":"refreshPolicyCache","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"}],"name":"removeAuthorizedHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_factory","type":"address"}],"name":"setAuthorizedFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"paused","type":"bool"}],"name":"setAutoTunePaused","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"}],"name":"states","outputs":[{"internalType":"uint16","name":"index","type":"uint16"},{"internalType":"uint16","name":"cardinality","type":"uint16"},{"internalType":"uint16","name":"cardinalityNext","type":"uint16"}],"stateMutability":"view","type":"function"}]

60c060405260015f55348015610013575f80fd5b506040516138a33803806138a3833981016040819052610032916100ae565b6001600160a01b0382166100595760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381166100805760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b039182166080521660a0526100e6565b6001600160a01b03811681146100ab575f80fd5b50565b5f80604083850312156100bf575f80fd5b82516100ca81610097565b60208401519092506100db81610097565b809150509250929050565b60805160a05161374861015b5f395f818161030c01528181610465015281816104f6015281816107c001528181610e2a01528181610e9c01526110e401525f8181610398015281816108ea01528181610cda01528181611310015281816113450152818161183a01526119e801526137485ff3fe608060405234801561000f575f80fd5b5060043610610163575f3560e01c806386c2acb7116100c7578063a1a532961161007d578063ead73b2311610063578063ead73b23146103ba578063f96f97f2146103db578063fbdc1ef1146103fc575f80fd5b8063a1a5329614610380578063dc4c90d314610393575f80fd5b80638da5cb5b116100ad5780638da5cb5b146103075780638f1c92171461032e578063a0669eff1461035c575f80fd5b806386c2acb7146102d25780638a9cd86a146102f4575f80fd5b8063435426361161011c5780636613720e116101025780636613720e14610271578063680d4cdb146102845780637321ca9514610297575f80fd5b8063435426361461020a57806362aaf2661461023c575f80fd5b80631a2093e91161014c5780631a2093e9146101ac5780632625dbae146101bf5780633e791463146101d2575f80fd5b80630852f9f3146101675780630d69500514610197575b5f80fd5b60025461017a906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101aa6101a5366004612c2b565b61045a565b005b6101aa6101ba366004612c70565b6104eb565b6101aa6101cd366004612c2b565b6107b5565b6101f66101e0366004612cea565b60036020525f908152604090205462ffffff1681565b60405162ffffff909116815260200161018e565b61021d610218366004612cea565b61085f565b6040805160029390930b835263ffffffff90911660208301520161018e565b61024f61024a366004612d17565b610928565b6040805160029390930b83526001600160801b0390911660208301520161018e565b6101aa61027f366004612d49565b610b08565b6101aa610292366004612de0565b610e91565b6102c26102a5366004612cea565b5f9081526008602052604090205462010000900461ffff16151590565b604051901515815260200161018e565b6102c26102e0366004612c2b565b60016020525f908152604090205460ff1681565b6102c2610302366004612e23565b610f3e565b61017a7f000000000000000000000000000000000000000000000000000000000000000081565b61034161033c366004612e44565b61100f565b6040805161ffff93841681529290911660208301520161018e565b6101f661036a366004612cea565b5f9081526003602052604090205462ffffff1690565b6101aa61038e366004612c2b565b6110d9565b61017a7f000000000000000000000000000000000000000000000000000000000000000081565b6103c26111b0565b60405167ffffffffffffffff909116815260200161018e565b6103ee6103e9366004612eba565b6111d8565b60405161018e929190612f7d565b61043561040a366004612cea565b60086020525f908152604090205461ffff808216916201000081048216916401000000009091041683565b6040805161ffff9485168152928416602084015292169181019190915260600161018e565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146104a357604051635fc483c560e01b815260040160405180910390fd5b6001600160a01b0381165f81815260016020526040808220805460ff19169055517ffa5ebd8c1fd1de9d275a47326e8fe93e1375aafa566297090355ed2f2366a0269190a250565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461053457604051635fc483c560e01b815260040160405180910390fd5b5f8781526008602052604081205462010000900461ffff169003610574576040516340a6eef160e11b815260040161056b90613009565b60405180910390fd5b5f878152600660205260409020805462ffffff88811665ffffffffffff1990921691909117630100000091881691909102176dffffffffffffffff0000000000001916660100000000000063ffffffff878116919091026dffffffff000000000000000000001916919091176a010000000000000000000086831602177fffffffffffffffffffff0000000000000000ffffffffffffffffffffffffffff16600160701b858316027fffffffffffffffffffff00000000ffffffffffffffffffffffffffffffffffff1617600160901b9184169190910217815561065781611564565b5f88815260036020526040902054815462ffffff91821691168110156106ea5781545f8a815260036020908152604091829020805462ffffff191662ffffff9485161790558454825185851681529316908301524263ffffffff169082015289907f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b9060600160405180910390a2610780565b815462ffffff6301000000909104811690821611156107805781545f8a815260036020908152604091829020805462ffffff191662ffffff63010000009586900481169190911790915585548351868316815294900416908301524263ffffffff169082015289907f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b9060600160405180910390a25b60405189907f968495b9cc7fd42b0f66a11b246d95132765f9d2aa8fd7b8026716a137e155f2905f90a2505050505050505050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146107fe57604051635fc483c560e01b815260040160405180910390fd5b600280547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0383169081179091556040517f7efff426e5519e84f0be2c23407005f33987158a500ff7afd6c5da7f7eaaf569905f90a250565b5f81815260086020526040812054819062010000900461ffff168103610898576040516340a6eef160e11b815260040161056b9061306c565b5f83815260086020526040812080549091906108b990869061ffff16611736565b82546108cc906102009061ffff166130e3565b61ffff1661020081106108e1576108e1613106565b0190505f61090f7f00000000000000000000000000000000000000000000000000000000000000008761176e565b50509254929763ffffffff909316965091945050505050565b5f808263ffffffff165f036109645760405162461bcd60e51b8152602060048201526002602482015261042560f41b604482015260640161056b565b6040805160028082526060820183525f9260208301908036833701905050905083815f8151811061099757610997613106565b602002602001019063ffffffff16908163ffffffff16815250505f816001815181106109c5576109c5613106565b602002602001019063ffffffff16908163ffffffff16815250505f806109eb87846111d8565b915091505f825f81518110610a0257610a02613106565b602002602001015183600181518110610a1d57610a1d613106565b6020026020010151610a2f919061312e565b90505f825f81518110610a4457610a44613106565b602002602001015183600181518110610a5f57610a5f613106565b6020026020010151610a71919061315b565b905063ffffffff8816610a84818461317a565b97505f8360060b128015610aa35750610a9d81846131b6565b60060b15155b15610ab65787610ab2816131d7565b9850505b5f610ace6001600160a01b0363ffffffff8c166131f8565b9050610af877ffffffffffffffffffffffffffffffffffffffff00000000602085901b1682613237565b9750505050505050509250929050565b335f9081526001602052604090205460ff16610b3757604051632f9b722960e01b815260040160405180910390fd5b5f610b51610b4a368b90038b018b613264565b60a0902090565b5f8181526008602052604090205490915062010000900461ffff1615610bf057604080516340a6eef160e11b81526004810191909152601360448201527f656e61626c654f7261636c65466f72506f6f6c00000000000000000000000000606482015260806024820152600f60848201527f416c726561647920656e61626c6564000000000000000000000000000000000060a482015260c40161056b565b5f60065f8381526020019081526020015f20905087815f015f6101000a81548162ffffff021916908362ffffff16021790555086815f0160036101000a81548162ffffff021916908362ffffff16021790555085815f0160066101000a81548163ffffffff021916908363ffffffff16021790555084815f01600a6101000a81548163ffffffff021916908363ffffffff16021790555083815f01600e6101000a81548163ffffffff021916908363ffffffff16021790555082815f0160126101000a81548163ffffffff021916908363ffffffff160217905550610cd481611564565b5f610cff7f00000000000000000000000000000000000000000000000000000000000000008461176e565b50505f8581526007602090815260408083208380528252808320815160808101835263ffffffff4216808252938101859052918201939093526001606090910152600160f81b1781559092509050604080516060810182525f80825260016020808401828152848601928352898452600890915293909120915182549351915161ffff9081166401000000000265ffff0000000019938216620100000263ffffffff199096169290911691909117939093171691909117905582548b9062ffffff9081169082161015610dd55750825462ffffff165b835462ffffff630100000090910481169082161115610dfe575082546301000000900462ffffff165b5f85815260036020908152604091829020805462ffffff191662ffffff851690811790915591519182527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691339188917fcee8ab927ae052458b05f94ddf3230c4ac0643e7878c93f11dacd30df130b511910160405180910390a450505050505050505050505050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610eda57604051635fc483c560e01b815260040160405180910390fd5b5f828152600a6020908152604091829020805460ff1916841515908117909155825190815263ffffffff42169181019190915283917fbb69f394074935087cc548b39e6b512d198fc9d5cfa828409e7cfb5303c1618e910160405180910390a25050565b5f8054600114610f905760405162461bcd60e51b815260206004820152600a60248201527f5245454e5452414e435900000000000000000000000000000000000000000000604482015260640161056b565b60025f9081553381526001602052604090205460ff16610fc357604051632f9b722960e01b815260040160405180910390fd5b5f8381526008602052604081205462010000900461ffff169003610ffa576040516340a6eef160e11b815260040161056b906132f8565b6110048383611820565b60015f559392505050565b5f8080611024610b4a36879003870187613264565b5f81815260086020526040812080549293509162010000900461ffff169003611060576040516340a6eef160e11b815260040161056b9061335b565b805461ffff640100000000909104811694508516841061108557508291506110d29050565b80546110a9906110a2908490640100000000900461ffff16611736565b8587611bf5565b815465ffff00000000191664010000000061ffff92831681029190911792839055909104169150505b9250929050565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480159061111d57506002546001600160a01b03163314155b1561113b57604051631747acaf60e31b815260040160405180910390fd5b6001600160a01b0381166111625760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381165f818152600160208190526040808320805460ff1916909217909155517f573951c8503ba3a904540e91b6d8630137863b3484254520500995c865281cf29190a250565b5f6111c864141dd7600067ffffffffffffffff6133be565b6111d39060016133de565b905090565b6060805f6111ee610b4a36879003870187613264565b5f818152600860205260408120549192506201000090910461ffff169003611229576040516340a6eef160e11b815260040161056b906133fe565b5f8181526008602052604090208054855161ffff909116908067ffffffffffffffff81111561125a5761125a612e75565b604051908082528060200260200182016040528015611283578160200160208202803683370190505b5095508067ffffffffffffffff81111561129f5761129f612e75565b6040519080825280602002602001820160405280156112c8578160200160208202803683370190505b509450805f036112db57505050506110d2565b6040805160a0810182525f602082018190529181018290526060810182905260808101919091524263ffffffff1681526113357f00000000000000000000000000000000000000000000000000000000000000008661176e565b505060020b60208301525061136a7f000000000000000000000000000000000000000000000000000000000000000086611c3e565b6001600160801b03166040820152611384610200846130e3565b61ffff16606082018190525f9061139b9085613461565b85549091505f9061ffff8084166201000090920416116113bc5760016113d3565b85546113d390839062010000900461ffff16613461565b905061020061ffff821611156113e857506102005b61ffff166080830152505f5b82811015611557575f89828151811061140f5761140f613106565b602002602001015190508063ffffffff165f036114b0575f6114318887611736565b905061145581855f01515f8760200151886060015189604001518a60800151611cca565b8b858151811061146757611467613106565b602002602001018b868151811061148057611480613106565b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b8152505050505061154f565b5f805f6114c88a8a8a89606001518a5f015189611e77565b9250925092505f6114d98b85611736565b90506114f581885f0151878a60200151878c6040015188611cca565b8e888151811061150757611507613106565b602002602001018e898151811061152057611520613106565b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b815250505050505050505b6001016113f4565b5050505050509250929050565b80546601000000000000900463ffffffff165f036115c45760405162461bcd60e51b815260206004820152601360248201527f7374657050706d2063616e6e6f74206265203000000000000000000000000000604482015260640161056b565b805462ffffff165f036116195760405162461bcd60e51b815260206004820152601260248201527f6d696e4361702063616e6e6f7420626520300000000000000000000000000000604482015260640161056b565b805462ffffff80821663010000009092041610156116795760405162461bcd60e51b815260206004820152601860248201527f6d6178436170206d757374206265203e3d206d696e4361700000000000000000604482015260640161056b565b8054600160701b900463ffffffff165f036116d65760405162461bcd60e51b815260206004820152601760248201527f646563617957696e646f772063616e6e6f742062652030000000000000000000604482015260640161056b565b8054600160901b900463ffffffff165f036117335760405162461bcd60e51b815260206004820152601a60248201527f757064617465496e74657276616c2063616e6e6f742062652030000000000000604482015260640161056b565b50565b5f828152600760205260408120816117506102008561347b565b61ffff1661ffff1681526020019081526020015f2090505b92915050565b5f805f805f61177c866120fd565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156117c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e8919061349e565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b5f828152600860205260408120805461ffff16828061185f7f00000000000000000000000000000000000000000000000000000000000000008861176e565b50505f8981526003602052604081205491945084935062ffffff909116915061188f600289810b9085900b6134b5565b90505f808212156118a8576118a3826134db565b6118aa565b815b90508262ffffff1681106118fe575f8083136118d8576118d362ffffff851660028c900b6134b5565b6118eb565b6118eb62ffffff851660028c900b6134f5565b90506118f681612139565b955060019850505b505050505f4290505f6119118885611736565b61191d610200866130e3565b61ffff16610200811061193257611932613106565b01805490915063ffffffff838116911614611be057845461ffff6201000082048116916401000000009004168082148015611972575061200061ffff8216105b1561198557611982826001613514565b90505b8161ffff168161ffff161180156119ad57506119a2600183613461565b61ffff168661ffff16145b156119c95790508061200061ffff821611156119c95761200091505b6001860195508161ffff168661ffff16106119e2575f95505b5f611a0d7f00000000000000000000000000000000000000000000000000000000000000008c611c3e565b845490915063ffffffff1685035f611a258d8a611736565b611a316102008b6130e3565b61ffff166102008110611a4657611a46613106565b01805463ffffffff191663ffffffff898116919091178255909150611a7190831660028a900b61352e565b8654611a889190640100000000900460060b61354d565b815466ffffffffffffff91909116640100000000026affffffffffffff00000000199091161781556001600160801b038316611ac5576001611ac7565b825b611ae7906001600160801b031663ffffffff60801b608085901b1661357a565b8654611b039190600160581b90046001600160a01b03166135a7565b81547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b0392909216600160581b02919091166affffffffffffffffffffff90911617600160f81b178155895461ffff868116620100000263ffffffff19909216908b1617178a55611b7b856001613514565b8a5461ffff918216640100000000909104909116108015611bab5750895461200064010000000090910461ffff16105b15611bda57611bbb856001613514565b8a5461ffff919091166401000000000265ffff0000000019909116178a555b50505050505b611bea88876121a1565b505050505092915050565b5f8261ffff168261ffff1611611c0c575081611c37565b6102008261ffff161115611c205761020091505b61200061ffff83161115611c345761200091505b50805b9392505050565b5f80611c49836120fd565b90505f611c576003836135c6565b604051631e2eaeaf60e01b8152600481018290529091506001600160a01b03861690631e2eaeaf90602401602060405180830381865afa158015611c9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cc1919061349e565b95945050505050565b5f808663ffffffff165f03611d71575f898661ffff166102008110611cf157611cf1613106565b60408051608081018252919092015463ffffffff808216808452640100000000830460060b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a1614611d5d57611d5a818a89886124f3565b90505b806020015181604001519250925050611e6b565b8688035f80611d858c8c858c8c8c8c6125b4565b91509150815f015163ffffffff168363ffffffff1603611db5578160200151826040015194509450505050611e6b565b805f015163ffffffff168363ffffffff1603611de1578060200151816040015194509450505050611e6b565b5f825f0151825f01510390505f835f0151850390508063ffffffff168263ffffffff1660060b856020015185602001510360060b81611e2257611e226130cf565b050284602001510196508163ffffffff168163ffffffff1685604001518560400151036001600160a01b03160281611e5c57611e5c6130cf565b04846040015101955050505050505b97509795505050505050565b5f805f808463ffffffff168663ffffffff161015611ea0578463ffffffff038601600101611ea4565b8486035b90505f611eb1888a613461565b8a549091508190611fff196201000090910461ffff1601611fe2575f611edb61020061200061347b565b90505f5b8161ffff168161ffff161015611fdf575f611efa8f85611736565b90505f8561ffff168561ffff1614611f1e57611f196001610200613461565b611f20565b8c5b90505f610200611f31836001613514565b611f3b91906130e3565b90505f838261ffff166102008110611f5557611f55613106565b015463ffffffff9081169150891681111580611f82575061ffff8616611f7c866001613514565b61ffff16145b15611f9e5750949950975061020096506120f195505050505050565b61020061ffff881610611fbe57611fb761020088613461565b9650611fcf565b611fcc610200612000613461565b96505b505060019092019150611edf9050565b50505b5f611fed8d83611736565b8c549091505f9061ffff80851662010000909204161161200e576001612025565b8c5461202590849062010000900461ffff16613461565b905061020061ffff8216111561203a57506102005b5f8461ffff168461ffff161461205a57612055600183613461565b61205c565b8b5b90505f61ffff831661020014612072575f61208a565b610200612080836001613514565b61208a91906130e3565b90505f848261ffff1661020081106120a4576120a4613106565b015463ffffffff90811691508816811115806120c2575061ffff8616155b156120d95750939850965094506120f19350505050565b6120e561020087613461565b95505050505050611fe2565b96509650969350505050565b6040515f9061211c908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b5f627fffff1982128015906121515750627fffff8213155b61219d5760405162461bcd60e51b815260206004820152600d60248201527f5469636b206f766572666c6f7700000000000000000000000000000000000000604482015260640161056b565b5090565b5f8281526005602052604081205465ffffffffffff169042906121c483836135d9565b9050831580156121d8575063ffffffff8116155b156121e4575050505050565b5f858152600560209081526040808320805465ffffffffffff191663ffffffff8716179055600490915290205467ffffffffffffffff1684156122a25764141dd760009081019061223d9067ffffffffffffffff6133be565b6122489060016133de565b67ffffffffffffffff168167ffffffffffffffff16101580612278575064141dd7600067ffffffffffffffff8216105b156122a25761229464141dd7600067ffffffffffffffff6133be565b61229f9060016133de565b90505b5f868152600660205260409020805463ffffffff6a01000000000000000000008204811691600160701b8104821691600160901b90910416881580156122ed57505f8663ffffffff16115b801561230257505f8567ffffffffffffffff16115b1561242b578163ffffffff168663ffffffff1610612322575f945061242b565b5f63ffffffff8084169061233c90620f4240908a166135f5565b6123469190613618565b61235390620f42406133be565b90505f620f424061237167ffffffffffffffff808516908a16613647565b61237b9190613669565b905067ffffffffffffffff6001600160801b03821611156123bf576123ad64141dd7600067ffffffffffffffff6133be565b6123b89060016133de565b9650612428565b806123d764141dd7600067ffffffffffffffff6133be565b6123e29060016133de565b67ffffffffffffffff168167ffffffffffffffff16116124025780612424565b61241964141dd7600067ffffffffffffffff6133be565b6124249060016133de565b9750505b50505b5f8a8152600460209081526040808320805467ffffffffffffffff191667ffffffffffffffff8a16179055600a90915290205460ff1615801561249257505f8a81526009602052604090205461248890829063ffffffff16613696565b63ffffffff164210155b156124e7575f6124ab6201518063ffffffff86166135f5565b90508067ffffffffffffffff168667ffffffffffffffff1611156124da576124d58b8660016127d2565b6124e5565b6124e58b865f6127d2565b505b50505050505050505050565b604080516080810182525f8082526020820181905291810182905260608101919091525f855f01518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020015f856001600160801b031611612567576001612569565b845b6001600160801b031663ffffffff60801b608085901b168161258d5761258d6130cf565b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b604080516080810182525f808252602082018190529181018290526060810191909152604080516080810182525f808252602082018190529181018290526060810191909152888561ffff16610200811061261157612611613106565b60408051608081018252919092015463ffffffff8116808352640100000000820460060b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff161515606082015292506126709089908961297b565b1561269c57815163ffffffff888116911614611e6b5781612693838989886124f3565b91509150611e6b565b888361ffff168660010161ffff16816126b7576126b76130cf565b0661ffff1661020081106126cd576126cd613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290925061277857604080516080810182528a5463ffffffff81168252640100000000810460060b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b61278688835f01518961297b565b6127b557815160405162a3913760e61b815263ffffffff9182166004820152908816602482015260440161056b565b6127c28989898887612a3b565b9150915097509795505050505050565b5f83815260036020526040812054835462ffffff9182169263ffffffff66010000000000008304169282811692630100000090041690620f424061281685876136b2565b61282091906136c9565b90508062ffffff165f03612832575060015b5f861561286b5762ffffff831661284983886136dc565b62ffffff16116128625761285d82876136dc565b612864565b825b9050612898565b61287584836136dc565b62ffffff168662ffffff161161288b5783612895565b61289582876136f7565b90505b5f8162ffffff168762ffffff16116128b9576128b487836136f7565b6128c3565b6128c382886136f7565b90508662ffffff168262ffffff16146124e7575f8a8152600360209081526040808320805462ffffff191662ffffff878116919091179091556009909252909120805463ffffffff19164263ffffffff161790556005908216106124e7576040805162ffffff8981168252841660208201524263ffffffff168183015290518b917f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b919081900360600190a250505050505050505050565b5f8363ffffffff168363ffffffff16111580156129a457508363ffffffff168263ffffffff1611155b156129c0578163ffffffff168363ffffffff1611159050611c37565b5f8463ffffffff168463ffffffff16116129e7578363ffffffff16640100000000016129ef565b8363ffffffff165b64ffffffffff1690505f8563ffffffff168463ffffffff1611612a1f578363ffffffff1664010000000001612a27565b8363ffffffff165b64ffffffffff169091111595945050505050565b604080516080810182525f808252602082018190529181018290526060810191909152604080516080810182525f8082526020820181905291810182905260608101919091525f8361ffff168561ffff1660010181612a9c57612a9c6130cf565b0690505f1961ffff85168201015f5b506002818301048961ffff87168281612ac657612ac66130cf565b066102008110612ad857612ad8613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909550612b3d57806001019250612aab565b898661ffff168260010181612b5457612b546130cf565b066102008110612b6657612b66613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094505f90612bca908b908b61297b565b9050808015612be25750612be28a8a875f015161297b565b15612bed5750612c0a565b80612bfd57600182039250612c04565b8160010193505b50612aab565b5050509550959350505050565b6001600160a01b0381168114611733575f80fd5b5f60208284031215612c3b575f80fd5b8135611c3781612c17565b803562ffffff81168114612c58575f80fd5b919050565b803563ffffffff81168114612c58575f80fd5b5f805f805f805f60e0888a031215612c86575f80fd5b87359650612c9660208901612c46565b9550612ca460408901612c46565b9450612cb260608901612c5d565b9350612cc060808901612c5d565b9250612cce60a08901612c5d565b9150612cdc60c08901612c5d565b905092959891949750929550565b5f60208284031215612cfa575f80fd5b5035919050565b5f60a08284031215612d11575f80fd5b50919050565b5f8060c08385031215612d28575f80fd5b612d328484612d01565b9150612d4060a08401612c5d565b90509250929050565b5f805f805f805f80610180898b031215612d61575f80fd5b612d6b8a8a612d01565b9750612d7960a08a01612c46565b9650612d8760c08a01612c46565b9550612d9560e08a01612c46565b9450612da46101008a01612c5d565b9350612db36101208a01612c5d565b9250612dc26101408a01612c5d565b9150612dd16101608a01612c5d565b90509295985092959890939650565b5f8060408385031215612df1575f80fd5b8235915060208301358015158114612e07575f80fd5b809150509250929050565b8035600281900b8114612c58575f80fd5b5f8060408385031215612e34575f80fd5b82359150612d4060208401612e12565b5f8060c08385031215612e55575f80fd5b612e5f8484612d01565b915060a083013561ffff81168114612e07575f80fd5b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715612eb257612eb2612e75565b604052919050565b5f8060c08385031215612ecb575f80fd5b612ed58484612d01565b915060a083013567ffffffffffffffff811115612ef0575f80fd5b8301601f81018513612f00575f80fd5b803567ffffffffffffffff811115612f1a57612f1a612e75565b8060051b612f2a60208201612e89565b91825260208184018101929081019088841115612f45575f80fd5b6020850194505b83851015612f6e57612f5d85612c5d565b825260209485019490910190612f4c565b80955050505050509250929050565b604080825283519082018190525f9060208501906060840190835b81811015612fb957835160060b835260209384019390920191600101612f98565b5050838103602080860191909152855180835291810192508501905f5b81811015612ffd5782516001600160a01b0316845260209384019390920191600101612fd6565b50919695505050505050565b60408152601260408201527f72656672657368506f6c696379436163686500000000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b60408152601460408201527f6765744c61746573744f62736572766174696f6e0000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b634e487b7160e01b5f52601260045260245ffd5b5f61ffff8316806130f6576130f66130cf565b8061ffff84160691505092915050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156117685761176861311a565b6001600160a01b0382811682821603908111156117685761176861311a565b5f8160060b8360060b80613190576131906130cf565b667fffffffffffff1982145f19821416156131ad576131ad61311a565b90059392505050565b5f8260060b806131c8576131c86130cf565b808360060b0791505092915050565b5f8160020b627fffff1981036131ef576131ef61311a565b5f190192915050565b5f6001600160c01b0382166001600160c01b0384166001600160c01b03818302169250818304811482151761322f5761322f61311a565b505092915050565b5f6001600160c01b0383168061324f5761324f6130cf565b806001600160c01b0384160491505092915050565b5f60a0828403128015613275575f80fd5b5060405160a0810167ffffffffffffffff8111828210171561329957613299612e75565b60405282356132a781612c17565b815260208301356132b781612c17565b60208201526132c860408401612c46565b60408201526132d960608401612e12565b606082015260808301356132ec81612c17565b60808201529392505050565b60408152601a60408201527f707573684f62736572766174696f6e416e64436865636b4361700000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b60408152601760408201527f696e63726561736543617264696e616c6974794e6578740000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b67ffffffffffffffff82811682821603908111156117685761176861311a565b67ffffffffffffffff81811683821601908111156117685761176861311a565b60408152600760408201527f6f627365727665000000000000000000000000000000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b61ffff82811682821603908111156117685761176861311a565b5f61ffff83168061348e5761348e6130cf565b8061ffff84160491505092915050565b5f602082840312156134ae575f80fd5b5051919050565b8181035f8312801583831316838312821617156134d4576134d461311a565b5092915050565b5f600160ff1b82016134ef576134ef61311a565b505f0390565b8082018281125f83128015821682158216171561322f5761322f61311a565b61ffff81811683821601908111156117685761176861311a565b5f8260060b8260060b028060060b91508082146134d4576134d461311a565b600681810b9083900b01667fffffffffffff8113667fffffffffffff19821217156117685761176861311a565b5f6001600160a01b03831680613592576135926130cf565b806001600160a01b0384160491505092915050565b6001600160a01b0381811683821601908111156117685761176861311a565b808201808211156117685761176861311a565b63ffffffff82811682821603908111156117685761176861311a565b67ffffffffffffffff81811683821602908116908181146134d4576134d461311a565b5f67ffffffffffffffff831680613631576136316130cf565b8067ffffffffffffffff84160491505092915050565b6001600160801b0381811683821602908116908181146134d4576134d461311a565b5f6001600160801b03831680613681576136816130cf565b806001600160801b0384160491505092915050565b63ffffffff81811683821601908111156117685761176861311a565b80820281158282048414176117685761176861311a565b5f826136d7576136d76130cf565b500490565b62ffffff81811683821601908111156117685761176861311a565b62ffffff82811682821603908111156117685761176861311a56fea2646970667358221220d5a04881f261b9aab35dc59c0ada6a959594f9f9c6eddc4d9ad81cb065eb45b664736f6c634300081a00330000000000000000000000001f98400000000000000000000000000000000004000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610163575f3560e01c806386c2acb7116100c7578063a1a532961161007d578063ead73b2311610063578063ead73b23146103ba578063f96f97f2146103db578063fbdc1ef1146103fc575f80fd5b8063a1a5329614610380578063dc4c90d314610393575f80fd5b80638da5cb5b116100ad5780638da5cb5b146103075780638f1c92171461032e578063a0669eff1461035c575f80fd5b806386c2acb7146102d25780638a9cd86a146102f4575f80fd5b8063435426361161011c5780636613720e116101025780636613720e14610271578063680d4cdb146102845780637321ca9514610297575f80fd5b8063435426361461020a57806362aaf2661461023c575f80fd5b80631a2093e91161014c5780631a2093e9146101ac5780632625dbae146101bf5780633e791463146101d2575f80fd5b80630852f9f3146101675780630d69500514610197575b5f80fd5b60025461017a906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101aa6101a5366004612c2b565b61045a565b005b6101aa6101ba366004612c70565b6104eb565b6101aa6101cd366004612c2b565b6107b5565b6101f66101e0366004612cea565b60036020525f908152604090205462ffffff1681565b60405162ffffff909116815260200161018e565b61021d610218366004612cea565b61085f565b6040805160029390930b835263ffffffff90911660208301520161018e565b61024f61024a366004612d17565b610928565b6040805160029390930b83526001600160801b0390911660208301520161018e565b6101aa61027f366004612d49565b610b08565b6101aa610292366004612de0565b610e91565b6102c26102a5366004612cea565b5f9081526008602052604090205462010000900461ffff16151590565b604051901515815260200161018e565b6102c26102e0366004612c2b565b60016020525f908152604090205460ff1681565b6102c2610302366004612e23565b610f3e565b61017a7f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec181565b61034161033c366004612e44565b61100f565b6040805161ffff93841681529290911660208301520161018e565b6101f661036a366004612cea565b5f9081526003602052604090205462ffffff1690565b6101aa61038e366004612c2b565b6110d9565b61017a7f0000000000000000000000001f9840000000000000000000000000000000000481565b6103c26111b0565b60405167ffffffffffffffff909116815260200161018e565b6103ee6103e9366004612eba565b6111d8565b60405161018e929190612f7d565b61043561040a366004612cea565b60086020525f908152604090205461ffff808216916201000081048216916401000000009091041683565b6040805161ffff9485168152928416602084015292169181019190915260600161018e565b336001600160a01b037f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec116146104a357604051635fc483c560e01b815260040160405180910390fd5b6001600160a01b0381165f81815260016020526040808220805460ff19169055517ffa5ebd8c1fd1de9d275a47326e8fe93e1375aafa566297090355ed2f2366a0269190a250565b336001600160a01b037f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1161461053457604051635fc483c560e01b815260040160405180910390fd5b5f8781526008602052604081205462010000900461ffff169003610574576040516340a6eef160e11b815260040161056b90613009565b60405180910390fd5b5f878152600660205260409020805462ffffff88811665ffffffffffff1990921691909117630100000091881691909102176dffffffffffffffff0000000000001916660100000000000063ffffffff878116919091026dffffffff000000000000000000001916919091176a010000000000000000000086831602177fffffffffffffffffffff0000000000000000ffffffffffffffffffffffffffff16600160701b858316027fffffffffffffffffffff00000000ffffffffffffffffffffffffffffffffffff1617600160901b9184169190910217815561065781611564565b5f88815260036020526040902054815462ffffff91821691168110156106ea5781545f8a815260036020908152604091829020805462ffffff191662ffffff9485161790558454825185851681529316908301524263ffffffff169082015289907f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b9060600160405180910390a2610780565b815462ffffff6301000000909104811690821611156107805781545f8a815260036020908152604091829020805462ffffff191662ffffff63010000009586900481169190911790915585548351868316815294900416908301524263ffffffff169082015289907f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b9060600160405180910390a25b60405189907f968495b9cc7fd42b0f66a11b246d95132765f9d2aa8fd7b8026716a137e155f2905f90a2505050505050505050565b336001600160a01b037f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec116146107fe57604051635fc483c560e01b815260040160405180910390fd5b600280547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0383169081179091556040517f7efff426e5519e84f0be2c23407005f33987158a500ff7afd6c5da7f7eaaf569905f90a250565b5f81815260086020526040812054819062010000900461ffff168103610898576040516340a6eef160e11b815260040161056b9061306c565b5f83815260086020526040812080549091906108b990869061ffff16611736565b82546108cc906102009061ffff166130e3565b61ffff1661020081106108e1576108e1613106565b0190505f61090f7f0000000000000000000000001f984000000000000000000000000000000000048761176e565b50509254929763ffffffff909316965091945050505050565b5f808263ffffffff165f036109645760405162461bcd60e51b8152602060048201526002602482015261042560f41b604482015260640161056b565b6040805160028082526060820183525f9260208301908036833701905050905083815f8151811061099757610997613106565b602002602001019063ffffffff16908163ffffffff16815250505f816001815181106109c5576109c5613106565b602002602001019063ffffffff16908163ffffffff16815250505f806109eb87846111d8565b915091505f825f81518110610a0257610a02613106565b602002602001015183600181518110610a1d57610a1d613106565b6020026020010151610a2f919061312e565b90505f825f81518110610a4457610a44613106565b602002602001015183600181518110610a5f57610a5f613106565b6020026020010151610a71919061315b565b905063ffffffff8816610a84818461317a565b97505f8360060b128015610aa35750610a9d81846131b6565b60060b15155b15610ab65787610ab2816131d7565b9850505b5f610ace6001600160a01b0363ffffffff8c166131f8565b9050610af877ffffffffffffffffffffffffffffffffffffffff00000000602085901b1682613237565b9750505050505050509250929050565b335f9081526001602052604090205460ff16610b3757604051632f9b722960e01b815260040160405180910390fd5b5f610b51610b4a368b90038b018b613264565b60a0902090565b5f8181526008602052604090205490915062010000900461ffff1615610bf057604080516340a6eef160e11b81526004810191909152601360448201527f656e61626c654f7261636c65466f72506f6f6c00000000000000000000000000606482015260806024820152600f60848201527f416c726561647920656e61626c6564000000000000000000000000000000000060a482015260c40161056b565b5f60065f8381526020019081526020015f20905087815f015f6101000a81548162ffffff021916908362ffffff16021790555086815f0160036101000a81548162ffffff021916908362ffffff16021790555085815f0160066101000a81548163ffffffff021916908363ffffffff16021790555084815f01600a6101000a81548163ffffffff021916908363ffffffff16021790555083815f01600e6101000a81548163ffffffff021916908363ffffffff16021790555082815f0160126101000a81548163ffffffff021916908363ffffffff160217905550610cd481611564565b5f610cff7f0000000000000000000000001f984000000000000000000000000000000000048461176e565b50505f8581526007602090815260408083208380528252808320815160808101835263ffffffff4216808252938101859052918201939093526001606090910152600160f81b1781559092509050604080516060810182525f80825260016020808401828152848601928352898452600890915293909120915182549351915161ffff9081166401000000000265ffff0000000019938216620100000263ffffffff199096169290911691909117939093171691909117905582548b9062ffffff9081169082161015610dd55750825462ffffff165b835462ffffff630100000090910481169082161115610dfe575082546301000000900462ffffff165b5f85815260036020908152604091829020805462ffffff191662ffffff851690811790915591519182527f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec16001600160a01b031691339188917fcee8ab927ae052458b05f94ddf3230c4ac0643e7878c93f11dacd30df130b511910160405180910390a450505050505050505050505050565b336001600160a01b037f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec11614610eda57604051635fc483c560e01b815260040160405180910390fd5b5f828152600a6020908152604091829020805460ff1916841515908117909155825190815263ffffffff42169181019190915283917fbb69f394074935087cc548b39e6b512d198fc9d5cfa828409e7cfb5303c1618e910160405180910390a25050565b5f8054600114610f905760405162461bcd60e51b815260206004820152600a60248201527f5245454e5452414e435900000000000000000000000000000000000000000000604482015260640161056b565b60025f9081553381526001602052604090205460ff16610fc357604051632f9b722960e01b815260040160405180910390fd5b5f8381526008602052604081205462010000900461ffff169003610ffa576040516340a6eef160e11b815260040161056b906132f8565b6110048383611820565b60015f559392505050565b5f8080611024610b4a36879003870187613264565b5f81815260086020526040812080549293509162010000900461ffff169003611060576040516340a6eef160e11b815260040161056b9061335b565b805461ffff640100000000909104811694508516841061108557508291506110d29050565b80546110a9906110a2908490640100000000900461ffff16611736565b8587611bf5565b815465ffff00000000191664010000000061ffff92831681029190911792839055909104169150505b9250929050565b336001600160a01b037f000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1161480159061111d57506002546001600160a01b03163314155b1561113b57604051631747acaf60e31b815260040160405180910390fd5b6001600160a01b0381166111625760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381165f818152600160208190526040808320805460ff1916909217909155517f573951c8503ba3a904540e91b6d8630137863b3484254520500995c865281cf29190a250565b5f6111c864141dd7600067ffffffffffffffff6133be565b6111d39060016133de565b905090565b6060805f6111ee610b4a36879003870187613264565b5f818152600860205260408120549192506201000090910461ffff169003611229576040516340a6eef160e11b815260040161056b906133fe565b5f8181526008602052604090208054855161ffff909116908067ffffffffffffffff81111561125a5761125a612e75565b604051908082528060200260200182016040528015611283578160200160208202803683370190505b5095508067ffffffffffffffff81111561129f5761129f612e75565b6040519080825280602002602001820160405280156112c8578160200160208202803683370190505b509450805f036112db57505050506110d2565b6040805160a0810182525f602082018190529181018290526060810182905260808101919091524263ffffffff1681526113357f0000000000000000000000001f984000000000000000000000000000000000048661176e565b505060020b60208301525061136a7f0000000000000000000000001f9840000000000000000000000000000000000486611c3e565b6001600160801b03166040820152611384610200846130e3565b61ffff16606082018190525f9061139b9085613461565b85549091505f9061ffff8084166201000090920416116113bc5760016113d3565b85546113d390839062010000900461ffff16613461565b905061020061ffff821611156113e857506102005b61ffff166080830152505f5b82811015611557575f89828151811061140f5761140f613106565b602002602001015190508063ffffffff165f036114b0575f6114318887611736565b905061145581855f01515f8760200151886060015189604001518a60800151611cca565b8b858151811061146757611467613106565b602002602001018b868151811061148057611480613106565b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b8152505050505061154f565b5f805f6114c88a8a8a89606001518a5f015189611e77565b9250925092505f6114d98b85611736565b90506114f581885f0151878a60200151878c6040015188611cca565b8e888151811061150757611507613106565b602002602001018e898151811061152057611520613106565b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b815250505050505050505b6001016113f4565b5050505050509250929050565b80546601000000000000900463ffffffff165f036115c45760405162461bcd60e51b815260206004820152601360248201527f7374657050706d2063616e6e6f74206265203000000000000000000000000000604482015260640161056b565b805462ffffff165f036116195760405162461bcd60e51b815260206004820152601260248201527f6d696e4361702063616e6e6f7420626520300000000000000000000000000000604482015260640161056b565b805462ffffff80821663010000009092041610156116795760405162461bcd60e51b815260206004820152601860248201527f6d6178436170206d757374206265203e3d206d696e4361700000000000000000604482015260640161056b565b8054600160701b900463ffffffff165f036116d65760405162461bcd60e51b815260206004820152601760248201527f646563617957696e646f772063616e6e6f742062652030000000000000000000604482015260640161056b565b8054600160901b900463ffffffff165f036117335760405162461bcd60e51b815260206004820152601a60248201527f757064617465496e74657276616c2063616e6e6f742062652030000000000000604482015260640161056b565b50565b5f828152600760205260408120816117506102008561347b565b61ffff1661ffff1681526020019081526020015f2090505b92915050565b5f805f805f61177c866120fd565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156117c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e8919061349e565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b5f828152600860205260408120805461ffff16828061185f7f0000000000000000000000001f984000000000000000000000000000000000048861176e565b50505f8981526003602052604081205491945084935062ffffff909116915061188f600289810b9085900b6134b5565b90505f808212156118a8576118a3826134db565b6118aa565b815b90508262ffffff1681106118fe575f8083136118d8576118d362ffffff851660028c900b6134b5565b6118eb565b6118eb62ffffff851660028c900b6134f5565b90506118f681612139565b955060019850505b505050505f4290505f6119118885611736565b61191d610200866130e3565b61ffff16610200811061193257611932613106565b01805490915063ffffffff838116911614611be057845461ffff6201000082048116916401000000009004168082148015611972575061200061ffff8216105b1561198557611982826001613514565b90505b8161ffff168161ffff161180156119ad57506119a2600183613461565b61ffff168661ffff16145b156119c95790508061200061ffff821611156119c95761200091505b6001860195508161ffff168661ffff16106119e2575f95505b5f611a0d7f0000000000000000000000001f984000000000000000000000000000000000048c611c3e565b845490915063ffffffff1685035f611a258d8a611736565b611a316102008b6130e3565b61ffff166102008110611a4657611a46613106565b01805463ffffffff191663ffffffff898116919091178255909150611a7190831660028a900b61352e565b8654611a889190640100000000900460060b61354d565b815466ffffffffffffff91909116640100000000026affffffffffffff00000000199091161781556001600160801b038316611ac5576001611ac7565b825b611ae7906001600160801b031663ffffffff60801b608085901b1661357a565b8654611b039190600160581b90046001600160a01b03166135a7565b81547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b0392909216600160581b02919091166affffffffffffffffffffff90911617600160f81b178155895461ffff868116620100000263ffffffff19909216908b1617178a55611b7b856001613514565b8a5461ffff918216640100000000909104909116108015611bab5750895461200064010000000090910461ffff16105b15611bda57611bbb856001613514565b8a5461ffff919091166401000000000265ffff0000000019909116178a555b50505050505b611bea88876121a1565b505050505092915050565b5f8261ffff168261ffff1611611c0c575081611c37565b6102008261ffff161115611c205761020091505b61200061ffff83161115611c345761200091505b50805b9392505050565b5f80611c49836120fd565b90505f611c576003836135c6565b604051631e2eaeaf60e01b8152600481018290529091506001600160a01b03861690631e2eaeaf90602401602060405180830381865afa158015611c9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cc1919061349e565b95945050505050565b5f808663ffffffff165f03611d71575f898661ffff166102008110611cf157611cf1613106565b60408051608081018252919092015463ffffffff808216808452640100000000830460060b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a1614611d5d57611d5a818a89886124f3565b90505b806020015181604001519250925050611e6b565b8688035f80611d858c8c858c8c8c8c6125b4565b91509150815f015163ffffffff168363ffffffff1603611db5578160200151826040015194509450505050611e6b565b805f015163ffffffff168363ffffffff1603611de1578060200151816040015194509450505050611e6b565b5f825f0151825f01510390505f835f0151850390508063ffffffff168263ffffffff1660060b856020015185602001510360060b81611e2257611e226130cf565b050284602001510196508163ffffffff168163ffffffff1685604001518560400151036001600160a01b03160281611e5c57611e5c6130cf565b04846040015101955050505050505b97509795505050505050565b5f805f808463ffffffff168663ffffffff161015611ea0578463ffffffff038601600101611ea4565b8486035b90505f611eb1888a613461565b8a549091508190611fff196201000090910461ffff1601611fe2575f611edb61020061200061347b565b90505f5b8161ffff168161ffff161015611fdf575f611efa8f85611736565b90505f8561ffff168561ffff1614611f1e57611f196001610200613461565b611f20565b8c5b90505f610200611f31836001613514565b611f3b91906130e3565b90505f838261ffff166102008110611f5557611f55613106565b015463ffffffff9081169150891681111580611f82575061ffff8616611f7c866001613514565b61ffff16145b15611f9e5750949950975061020096506120f195505050505050565b61020061ffff881610611fbe57611fb761020088613461565b9650611fcf565b611fcc610200612000613461565b96505b505060019092019150611edf9050565b50505b5f611fed8d83611736565b8c549091505f9061ffff80851662010000909204161161200e576001612025565b8c5461202590849062010000900461ffff16613461565b905061020061ffff8216111561203a57506102005b5f8461ffff168461ffff161461205a57612055600183613461565b61205c565b8b5b90505f61ffff831661020014612072575f61208a565b610200612080836001613514565b61208a91906130e3565b90505f848261ffff1661020081106120a4576120a4613106565b015463ffffffff90811691508816811115806120c2575061ffff8616155b156120d95750939850965094506120f19350505050565b6120e561020087613461565b95505050505050611fe2565b96509650969350505050565b6040515f9061211c908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b5f627fffff1982128015906121515750627fffff8213155b61219d5760405162461bcd60e51b815260206004820152600d60248201527f5469636b206f766572666c6f7700000000000000000000000000000000000000604482015260640161056b565b5090565b5f8281526005602052604081205465ffffffffffff169042906121c483836135d9565b9050831580156121d8575063ffffffff8116155b156121e4575050505050565b5f858152600560209081526040808320805465ffffffffffff191663ffffffff8716179055600490915290205467ffffffffffffffff1684156122a25764141dd760009081019061223d9067ffffffffffffffff6133be565b6122489060016133de565b67ffffffffffffffff168167ffffffffffffffff16101580612278575064141dd7600067ffffffffffffffff8216105b156122a25761229464141dd7600067ffffffffffffffff6133be565b61229f9060016133de565b90505b5f868152600660205260409020805463ffffffff6a01000000000000000000008204811691600160701b8104821691600160901b90910416881580156122ed57505f8663ffffffff16115b801561230257505f8567ffffffffffffffff16115b1561242b578163ffffffff168663ffffffff1610612322575f945061242b565b5f63ffffffff8084169061233c90620f4240908a166135f5565b6123469190613618565b61235390620f42406133be565b90505f620f424061237167ffffffffffffffff808516908a16613647565b61237b9190613669565b905067ffffffffffffffff6001600160801b03821611156123bf576123ad64141dd7600067ffffffffffffffff6133be565b6123b89060016133de565b9650612428565b806123d764141dd7600067ffffffffffffffff6133be565b6123e29060016133de565b67ffffffffffffffff168167ffffffffffffffff16116124025780612424565b61241964141dd7600067ffffffffffffffff6133be565b6124249060016133de565b9750505b50505b5f8a8152600460209081526040808320805467ffffffffffffffff191667ffffffffffffffff8a16179055600a90915290205460ff1615801561249257505f8a81526009602052604090205461248890829063ffffffff16613696565b63ffffffff164210155b156124e7575f6124ab6201518063ffffffff86166135f5565b90508067ffffffffffffffff168667ffffffffffffffff1611156124da576124d58b8660016127d2565b6124e5565b6124e58b865f6127d2565b505b50505050505050505050565b604080516080810182525f8082526020820181905291810182905260608101919091525f855f01518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020015f856001600160801b031611612567576001612569565b845b6001600160801b031663ffffffff60801b608085901b168161258d5761258d6130cf565b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b604080516080810182525f808252602082018190529181018290526060810191909152604080516080810182525f808252602082018190529181018290526060810191909152888561ffff16610200811061261157612611613106565b60408051608081018252919092015463ffffffff8116808352640100000000820460060b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff161515606082015292506126709089908961297b565b1561269c57815163ffffffff888116911614611e6b5781612693838989886124f3565b91509150611e6b565b888361ffff168660010161ffff16816126b7576126b76130cf565b0661ffff1661020081106126cd576126cd613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290925061277857604080516080810182528a5463ffffffff81168252640100000000810460060b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b61278688835f01518961297b565b6127b557815160405162a3913760e61b815263ffffffff9182166004820152908816602482015260440161056b565b6127c28989898887612a3b565b9150915097509795505050505050565b5f83815260036020526040812054835462ffffff9182169263ffffffff66010000000000008304169282811692630100000090041690620f424061281685876136b2565b61282091906136c9565b90508062ffffff165f03612832575060015b5f861561286b5762ffffff831661284983886136dc565b62ffffff16116128625761285d82876136dc565b612864565b825b9050612898565b61287584836136dc565b62ffffff168662ffffff161161288b5783612895565b61289582876136f7565b90505b5f8162ffffff168762ffffff16116128b9576128b487836136f7565b6128c3565b6128c382886136f7565b90508662ffffff168262ffffff16146124e7575f8a8152600360209081526040808320805462ffffff191662ffffff878116919091179091556009909252909120805463ffffffff19164263ffffffff161790556005908216106124e7576040805162ffffff8981168252841660208201524263ffffffff168183015290518b917f7a37676da46997b7dd6c3c7e13ca12e5b70ea101f0521b8628dd033490a3492b919081900360600190a250505050505050505050565b5f8363ffffffff168363ffffffff16111580156129a457508363ffffffff168263ffffffff1611155b156129c0578163ffffffff168363ffffffff1611159050611c37565b5f8463ffffffff168463ffffffff16116129e7578363ffffffff16640100000000016129ef565b8363ffffffff165b64ffffffffff1690505f8563ffffffff168463ffffffff1611612a1f578363ffffffff1664010000000001612a27565b8363ffffffff165b64ffffffffff169091111595945050505050565b604080516080810182525f808252602082018190529181018290526060810191909152604080516080810182525f8082526020820181905291810182905260608101919091525f8361ffff168561ffff1660010181612a9c57612a9c6130cf565b0690505f1961ffff85168201015f5b506002818301048961ffff87168281612ac657612ac66130cf565b066102008110612ad857612ad8613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909550612b3d57806001019250612aab565b898661ffff168260010181612b5457612b546130cf565b066102008110612b6657612b66613106565b60408051608081018252929091015463ffffffff81168352640100000000810460060b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094505f90612bca908b908b61297b565b9050808015612be25750612be28a8a875f015161297b565b15612bed5750612c0a565b80612bfd57600182039250612c04565b8160010193505b50612aab565b5050509550959350505050565b6001600160a01b0381168114611733575f80fd5b5f60208284031215612c3b575f80fd5b8135611c3781612c17565b803562ffffff81168114612c58575f80fd5b919050565b803563ffffffff81168114612c58575f80fd5b5f805f805f805f60e0888a031215612c86575f80fd5b87359650612c9660208901612c46565b9550612ca460408901612c46565b9450612cb260608901612c5d565b9350612cc060808901612c5d565b9250612cce60a08901612c5d565b9150612cdc60c08901612c5d565b905092959891949750929550565b5f60208284031215612cfa575f80fd5b5035919050565b5f60a08284031215612d11575f80fd5b50919050565b5f8060c08385031215612d28575f80fd5b612d328484612d01565b9150612d4060a08401612c5d565b90509250929050565b5f805f805f805f80610180898b031215612d61575f80fd5b612d6b8a8a612d01565b9750612d7960a08a01612c46565b9650612d8760c08a01612c46565b9550612d9560e08a01612c46565b9450612da46101008a01612c5d565b9350612db36101208a01612c5d565b9250612dc26101408a01612c5d565b9150612dd16101608a01612c5d565b90509295985092959890939650565b5f8060408385031215612df1575f80fd5b8235915060208301358015158114612e07575f80fd5b809150509250929050565b8035600281900b8114612c58575f80fd5b5f8060408385031215612e34575f80fd5b82359150612d4060208401612e12565b5f8060c08385031215612e55575f80fd5b612e5f8484612d01565b915060a083013561ffff81168114612e07575f80fd5b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715612eb257612eb2612e75565b604052919050565b5f8060c08385031215612ecb575f80fd5b612ed58484612d01565b915060a083013567ffffffffffffffff811115612ef0575f80fd5b8301601f81018513612f00575f80fd5b803567ffffffffffffffff811115612f1a57612f1a612e75565b8060051b612f2a60208201612e89565b91825260208184018101929081019088841115612f45575f80fd5b6020850194505b83851015612f6e57612f5d85612c5d565b825260209485019490910190612f4c565b80955050505050509250929050565b604080825283519082018190525f9060208501906060840190835b81811015612fb957835160060b835260209384019390920191600101612f98565b5050838103602080860191909152855180835291810192508501905f5b81811015612ffd5782516001600160a01b0316845260209384019390920191600101612fd6565b50919695505050505050565b60408152601260408201527f72656672657368506f6c696379436163686500000000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b60408152601460408201527f6765744c61746573744f62736572766174696f6e0000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b634e487b7160e01b5f52601260045260245ffd5b5f61ffff8316806130f6576130f66130cf565b8061ffff84160691505092915050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156117685761176861311a565b6001600160a01b0382811682821603908111156117685761176861311a565b5f8160060b8360060b80613190576131906130cf565b667fffffffffffff1982145f19821416156131ad576131ad61311a565b90059392505050565b5f8260060b806131c8576131c86130cf565b808360060b0791505092915050565b5f8160020b627fffff1981036131ef576131ef61311a565b5f190192915050565b5f6001600160c01b0382166001600160c01b0384166001600160c01b03818302169250818304811482151761322f5761322f61311a565b505092915050565b5f6001600160c01b0383168061324f5761324f6130cf565b806001600160c01b0384160491505092915050565b5f60a0828403128015613275575f80fd5b5060405160a0810167ffffffffffffffff8111828210171561329957613299612e75565b60405282356132a781612c17565b815260208301356132b781612c17565b60208201526132c860408401612c46565b60408201526132d960608401612e12565b606082015260808301356132ec81612c17565b60808201529392505050565b60408152601a60408201527f707573684f62736572766174696f6e416e64436865636b4361700000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b60408152601760408201527f696e63726561736543617264696e616c6974794e6578740000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b67ffffffffffffffff82811682821603908111156117685761176861311a565b67ffffffffffffffff81811683821601908111156117685761176861311a565b60408152600760408201527f6f627365727665000000000000000000000000000000000000000000000000006060820152608060208201525f61176860808301601081526f141bdbdb081b9bdd08195b98589b195960821b602082015260400190565b61ffff82811682821603908111156117685761176861311a565b5f61ffff83168061348e5761348e6130cf565b8061ffff84160491505092915050565b5f602082840312156134ae575f80fd5b5051919050565b8181035f8312801583831316838312821617156134d4576134d461311a565b5092915050565b5f600160ff1b82016134ef576134ef61311a565b505f0390565b8082018281125f83128015821682158216171561322f5761322f61311a565b61ffff81811683821601908111156117685761176861311a565b5f8260060b8260060b028060060b91508082146134d4576134d461311a565b600681810b9083900b01667fffffffffffff8113667fffffffffffff19821217156117685761176861311a565b5f6001600160a01b03831680613592576135926130cf565b806001600160a01b0384160491505092915050565b6001600160a01b0381811683821601908111156117685761176861311a565b808201808211156117685761176861311a565b63ffffffff82811682821603908111156117685761176861311a565b67ffffffffffffffff81811683821602908116908181146134d4576134d461311a565b5f67ffffffffffffffff831680613631576136316130cf565b8067ffffffffffffffff84160491505092915050565b6001600160801b0381811683821602908116908181146134d4576134d461311a565b5f6001600160801b03831680613681576136816130cf565b806001600160801b0384160491505092915050565b63ffffffff81811683821601908111156117685761176861311a565b80820281158282048414176117685761176861311a565b5f826136d7576136d76130cf565b500490565b62ffffff81811683821601908111156117685761176861311a565b62ffffff82811682821603908111156117685761176861311a56fea2646970667358221220d5a04881f261b9aab35dc59c0ada6a959594f9f9c6eddc4d9ad81cb065eb45b664736f6c634300081a0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000001f98400000000000000000000000000000000004000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1

-----Decoded View---------------
Arg [0] : _poolManager (address): 0x1F98400000000000000000000000000000000004
Arg [1] : _owner (address): 0xe911f518449ba0011D84b047B4cde50dAA081eC1

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 0000000000000000000000001f98400000000000000000000000000000000004
Arg [1] : 000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ 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.