Skip to content
Verified contractExactUNLICENSED

RecordedPoolReader

Address0x5d77b7733bf85b476326d1f584a21ac68ee548e2
Balance

0 ETH

 

Transactions

1,579

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,330,332
Creation transaction
0xdaeb3f4b49…ef99069357

30 files

src/v3/gap/readers/RecordedPoolReader.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {GapReaderBase} from "./GapReaderBase.sol";
import {GapPriceLib} from "../GapPriceLib.sol";

/// @title RecordedPoolReader -- a gap reader for pools with NO on-chain oracle (Uniswap v4, PancakeSwap Infinity
///        CL / bin), priced from KEEPER records in distinct time buckets (owner 2026-11-02: on-chain pools only).
/// @notice One instance per pool manager and kind (KIND_UNI_V4 / KIND_INFINITY_CL / KIND_INFINITY_BIN).
///         `poolRef` is the PoolId. A Uniswap v4 pool is `registerV4`'d first (v4 keeps no id -> key map; the id is
///         derived here from the key, so a registration cannot lie).
///
/// RECORDS. Only a KEEPER (an address the owner lists, `setKeeper`) records, through
/// `pokeObserved(poolRef, expectedSqrtPriceX96, tolBps)`: the keeper passes the price it read (`spot`) just before
/// sending, and if the pool's price at execution is more than tolBps (<= maxTolBps) away from it, NOTHING is recorded.
/// A sandwich around the keeper's transaction can therefore shift a record by at most tolBps. At most one record per
/// time bucket (`bucketSeconds`). The IGapReader `poke(bytes32)` reverts (a v3 token's route-hop poke fails,
/// harmlessly: the token ignores poke failures).
///
/// THE ANSWER. A keeper poke in bucket b first fixes bucket b's answer, from the keeper records of buckets BEFORE b
/// within `windowBuckets`: the MEDIAN of the newest `minRecords` of them (fewer: no new answer). It is then clamped to
/// at most ONE `capBps` step from the previous answer, however long ago that answer was (no saved-up room). There is
/// no unclamped answer: a pool prices only after the owner ANCHORS it (`reseed(poolId, sqrtPriceX96)`), and every
/// answer descends from that anchor one cap step at a time. `priceE18` returns the latest answer if it is at most
/// `staleBuckets` old and the pool is not CONVERGING, else 0 (the token reverts retriably and retries later).
/// ANCHOR BAND (audit round 6 M-2: a thin pool held off its price drifts the answer one cap step per bucket):
/// every pool also has an INDEPENDENT anchor -- the keeper's median of the same stock's sibling pools on other
/// chains, multiplier-adjusted (no oracle) -- and a band. An answer outside anchor / (1 + band) .. anchor * (1 + band),
/// an anchor older than anchorStaleSeconds, or a pool with no anchor or no band serves nothing (priceE18 0). The
/// owner seeds the anchor (seedAnchor) and sets the band (setBand); the keeper moves it (setAnchor) at most once a
/// bucket and at most anchorStepBps per move, and never more than maxDriftBps from its reference (round 7 M-1: the
/// owner's seedAnchor, or automatically, every REF_PERIOD, the anchor of that moment), so ramped sibling pools or a
/// stolen keeper key move it at most maxDriftBps a day.
/// CONVERGING: after an anchor, and after any stale gap (no answer and, while converging, no record for more than
/// staleBuckets), the clamped
/// answer may lag the market; priceE18 returns 0 until an answer equals its unclamped median (it halts, never jumps).
/// While converging, the median counts ONLY records made after the anchor / gap (`freshFrom`): pre-anchor and pre-gap
/// records never clear it. Ordinary clamped answers (no gap) are served.
/// FRESHNESS: an answer is fixed only by a poke that RECORDS (a poke skipped for tolerance fixes nothing), and only if
/// the newest record it uses is at most staleBuckets old; priceE18 serves an answer at most staleBuckets old.
///
/// WHAT IT RESISTS, AND WHAT IT DOES NOT (no "flash-proof" claim: a pool with no oracle cannot tell a pumped price
/// from an honest one).
///   - Nothing in the current bucket moves the current answer (it is fixed from earlier buckets).
///   - An attacker cannot write records. A sandwich of the keeper's transaction shifts a record by at most tolBps
///     (beyond it nothing is recorded), so owning a majority of the newest records moves the answer by at most
///     tolBps, not a cap step per bucket. The keeper MUST submit privately on every public-mempool chain (Ethereum:
///     Flashbots Protect; BSC: a private builder RPC such as 48club or bloXroute) -- runbook, enforced by the keeper.
///   - Route pools need a minimum depth (runbook): holding a pool's price across a keeper transaction costs more
///     the deeper the pool.
///   - Honest volatility never halts pricing (no band): the answer follows a real move with a lag of about
///     minRecords/2 buckets plus the cap (a move larger than capBps per bucket takes several buckets to follow).
///   - Time, not block numbers: Robinhood (Arbitrum Orbit) shares block.number across L2 blocks.
///
/// HOOKS AND FEES. Without the owner's `allowPool`, a pool must have no hook and a static fee >= MIN_FEE (0.05%).
/// Before allowing a hooked / dynamic-fee / low-fee pool the owner checks: the hook returns no swap deltas
/// (beforeSwapReturnDelta / afterSwapReturnDelta off), takes no fee exemption that changes execution vs slot0, and
/// is not upgradeable by a third party; the pool's liquidity is real (not one-sided) and its price tracks the asset.
///
/// GAS. A cold keeper poke costs up to ~125k (eight ring slots, the median, two writes); keepers are uncapped. A cold
/// priceE18 reads one answer slot (+ the pool key): a route hop on this reader needs a gasCap of at least 60,000.
///
/// @dev Record = sqrtPriceX96 (160) | bucket (64), ring of RING written by a never-resetting counter.
///      Answer = sqrtPriceX96 (160) | bucket (64) | converging (bit 224), one slot per pool.
contract RecordedPoolReader is GapReaderBase {
    using StateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;

    uint8 public constant KIND_UNI_V4 = 0;
    uint8 public constant KIND_INFINITY_CL = 1;
    uint8 public constant KIND_INFINITY_BIN = 2;
    uint256 public constant RING = 8;
    uint24 public constant MIN_FEE = 500; // 0.05% (hundredths of a bip)
    uint24 internal constant DYNAMIC_FEE = 0x800000;
    uint256 internal constant BIN_ID_ZERO = 1 << 23;
    uint256 internal constant E18 = 1e18;

    address public immutable manager;
    uint8 public immutable kind;
    address public immutable wrappedNative;
    address public immutable owner;
    uint256 public immutable bucketSeconds;
    uint256 public immutable minRecords;
    uint256 public immutable windowBuckets;
    uint256 public immutable staleBuckets;
    uint256 public immutable capBps;
    /// @notice The largest tolerance a keeper may pass to pokeObserved.
    uint256 public immutable maxTolBps;
    /// @dev sqrt((1e4 + capBps) / 1e4) * 1e18: one price cap step as a sqrtPrice factor.
    uint256 internal immutable capUpE18;
    uint256 internal constant CONVERGING = 1 << 224;
    /// @notice The widest band an owner may set (x / (1 + 500%) .. x * (1 + 500%)).
    uint256 public constant MAX_BAND_BPS = 50_000;
    /// @notice The largest move a keeper's anchor update may make (price, both ways).
    uint256 public immutable anchorStepBps;
    /// @notice An anchor older than this serves nothing (priceE18 0) until the keeper updates it.
    uint256 public immutable anchorStaleSeconds;
    /// @notice The furthest the keeper may take the anchor from its reference (price, both ways).
    uint256 public immutable maxDriftBps;
    /// @notice The reference moves to the then-current anchor at the first keeper update this long after it was set.
    uint256 public constant REF_PERIOD = 1 days;

    struct V4Key {
        address currency0;
        address currency1;
        address hooks;
        uint24 fee;
    }

    mapping(bytes32 => V4Key) public v4Keys;
    mapping(bytes32 => bool) public allowedPool;
    mapping(address => bool) public isKeeper;
    mapping(bytes32 => uint256[RING]) internal rings;
    /// @notice Records ever written per pool (the ring index is count % RING; never reset).
    mapping(bytes32 => uint256) public count;
    /// @notice The latest answer per pool: sqrtPriceX96 | bucket << 160 | converging bit 224 (0 = none).
    mapping(bytes32 => uint256) public answer;
    /// @notice While converging: the first bucket whose records count (records before it are pre-anchor / pre-gap).
    mapping(bytes32 => uint256) public freshFrom;
    /// @notice The INDEPENDENT anchor band per pool: anchor sqrtPriceX96 (160) | set at (timestamp, 64) << 160 |
    ///         bandBps (16) << 224. The answer is served only within anchor / (1 + band) .. anchor * (1 + band) in
    ///         price, and only while the anchor is at most anchorStaleSeconds old. 0 = no anchor: nothing is served.
    ///         The anchor is in the pool's own units (sqrtPriceX96 of currency1 per currency0), so the check needs no
    ///         decimals; the keeper converts its independent USD price (READY.txt).
    mapping(bytes32 => uint256) public anchorBand;
    /// @notice The drift reference per pool: sqrtPriceX96 (160) | set at (timestamp, 64) << 160.
    mapping(bytes32 => uint256) public anchorRef;

    event Registered(bytes32 indexed poolId, address currency0, address currency1, address hooks, uint24 fee);
    event PoolAllowed(bytes32 indexed poolId, bool allowed);
    event KeeperSet(address indexed keeper, bool allowed);
    event Reseeded(bytes32 indexed poolId, uint160 sqrtPriceX96);
    event Skipped(bytes32 indexed poolId, uint160 expected, uint160 actual);
    event Answered(bytes32 indexed poolId, uint256 bucket, uint160 sqrtPriceX96);
    event AnchorSet(bytes32 indexed poolId, uint160 sqrtPriceX96, bool byOwner);
    event BandSet(bytes32 indexed poolId, uint256 bandBps);
    event AnchorRefSet(bytes32 indexed poolId, uint160 sqrtPriceX96, bool byOwner);

    error BadParams();
    error NotUniV4();
    error NotInitialized();
    error NotOwner();
    error NotKeeper();
    error AnchorTooSoon();
    error AnchorStep();
    error NoAnchor();
    error AnchorDrift();

    constructor(
        address manager_,
        uint8 kind_,
        address wrappedNative_,
        address owner_,
        uint256 bucketSeconds_,
        uint256 minRecords_,
        uint256 windowBuckets_,
        uint256 staleBuckets_,
        uint256 capBps_,
        uint256 maxTolBps_,
        uint256 anchorStepBps_,
        uint256 anchorStaleSeconds_,
        uint256 maxDriftBps_
    ) {
        if (manager_ == address(0) || owner_ == address(0) || kind_ > KIND_INFINITY_BIN) revert BadParams();
        if (bucketSeconds_ < 12 || bucketSeconds_ > 3_600) revert BadParams();
        if (minRecords_ < 3 || minRecords_ > RING || minRecords_ % 2 == 0) revert BadParams();
        if (windowBuckets_ < minRecords_ || windowBuckets_ > 64) revert BadParams();
        if (staleBuckets_ == 0 || staleBuckets_ > windowBuckets_) revert BadParams();
        if (capBps_ == 0 || capBps_ > 2_000) revert BadParams();
        if (maxTolBps_ == 0 || maxTolBps_ > capBps_) revert BadParams();
        if (anchorStepBps_ == 0 || anchorStepBps_ > 2_000) revert BadParams();
        if (anchorStaleSeconds_ < bucketSeconds_ || anchorStaleSeconds_ > 7 days) revert BadParams();
        if (maxDriftBps_ < anchorStepBps_ || maxDriftBps_ > 5_000) revert BadParams();
        manager = manager_;
        kind = kind_;
        wrappedNative = wrappedNative_;
        owner = owner_;
        bucketSeconds = bucketSeconds_;
        minRecords = minRecords_;
        windowBuckets = windowBuckets_;
        staleBuckets = staleBuckets_;
        capBps = capBps_;
        maxTolBps = maxTolBps_;
        capUpE18 = Math.sqrt((10_000 + capBps_) * 1e36 / 10_000);
        anchorStepBps = anchorStepBps_;
        anchorStaleSeconds = anchorStaleSeconds_;
        maxDriftBps = maxDriftBps_;
    }

    // ------------------------------------------------------------------ owner / registration

    function _onlyOwner() internal view {
        if (msg.sender != owner) revert NotOwner();
    }

    /// @notice List or delist a keeper (the only addresses that may record). Owner only.
    function setKeeper(address keeper, bool allowed) external {
        _onlyOwner();
        isKeeper[keeper] = allowed;
        emit KeeperSet(keeper, allowed);
    }

    /// @notice Allow (or disallow) a pool with a hook or a dynamic / low fee (see HOOKS AND FEES). Owner only.
    function allowPool(bytes32 poolId, bool allowed) external {
        _onlyOwner();
        allowedPool[poolId] = allowed;
        emit PoolAllowed(poolId, allowed);
    }

    /// @notice Anchor a pool's answer at an owner-supplied price (a new pool, or after a real move larger than the cap
    ///         can follow). The pool then converges from it (priceE18 is 0 until an answer equals its median). Owner only.
    function reseed(bytes32 poolId, uint160 sqrtPriceX96) external {
        _onlyOwner();
        (bool ok,) = _inRange(sqrtPriceX96);
        if (!ok) revert BadParams();
        uint256 b = block.timestamp / bucketSeconds;
        answer[poolId] = uint256(sqrtPriceX96) | (b << 160) | CONVERGING;
        freshFrom[poolId] = b + 1; // this bucket's records may predate the anchor
        emit Reseeded(poolId, sqrtPriceX96);
    }

    /// @notice A pool's band around its anchor (bps of price, both ways; 1..MAX_BAND_BPS). Owner only.
    function setBand(bytes32 poolId, uint256 bandBps) external {
        _onlyOwner();
        if (bandBps == 0 || bandBps > MAX_BAND_BPS) revert BadParams();
        uint256 ab = anchorBand[poolId];
        anchorBand[poolId] = (ab & ((1 << 224) - 1)) | (bandBps << 224);
        emit BandSet(poolId, bandBps);
    }

    /// @notice Set a pool's anchor at any price (the first anchor, or after an outage the keeper cannot step across).
    ///         Owner only.
    function seedAnchor(bytes32 poolId, uint160 sqrtPriceX96) external {
        _onlyOwner();
        (bool ok,) = _inRange(sqrtPriceX96);
        if (!ok) revert BadParams();
        _writeAnchor(poolId, sqrtPriceX96);
        anchorRef[poolId] = uint256(sqrtPriceX96) | (block.timestamp << 160);
        emit AnchorSet(poolId, sqrtPriceX96, true);
        emit AnchorRefSet(poolId, sqrtPriceX96, true);
    }

    /// @notice Move a pool's anchor to the keeper's independent price (the median of the stock's sibling pools on
    ///         other chains, multiplier-adjusted). Keeper only; at most once per bucket; at most anchorStepBps from
    ///         the current anchor; the pool must have been anchored by the owner first.
    function setAnchor(bytes32 poolId, uint160 sqrtPriceX96) external {
        if (!isKeeper[msg.sender]) revert NotKeeper();
        uint256 ab = anchorBand[poolId];
        uint160 cur = uint160(ab);
        if (cur == 0) revert NoAnchor();
        uint256 at = (ab >> 160) & type(uint64).max;
        if (block.timestamp / bucketSeconds <= at / bucketSeconds) revert AnchorTooSoon();
        if (!_within(sqrtPriceX96, cur, anchorStepBps)) revert AnchorStep();
        (uint160 ref, bool rolled) = _driftRef(poolId, cur);
        if (rolled) {
            anchorRef[poolId] = uint256(ref) | (block.timestamp << 160);
            emit AnchorRefSet(poolId, ref, false);
        }
        if (!_within(sqrtPriceX96, ref, maxDriftBps)) revert AnchorDrift();
        _writeAnchor(poolId, sqrtPriceX96);
        emit AnchorSet(poolId, sqrtPriceX96, false);
    }

    /// @notice The reference a keeper update is measured against now (rolled = it moves to the current anchor at
    ///         this update), when it was set, and the drift allowed around it.
    function driftRef(bytes32 poolId) external view returns (uint160 sqrtPriceX96, uint256 at, bool rolled, uint256 driftBps) {
        uint256 rf = anchorRef[poolId];
        at = (rf >> 160) & type(uint64).max;
        (sqrtPriceX96, rolled) = _driftRef(poolId, uint160(anchorBand[poolId]));
        driftBps = maxDriftBps;
    }

    function _driftRef(bytes32 poolId, uint160 cur) internal view returns (uint160, bool) {
        uint256 rf = anchorRef[poolId];
        uint160 ref = uint160(rf);
        if (ref == 0 || block.timestamp - ((rf >> 160) & type(uint64).max) >= REF_PERIOD) return (cur, true);
        return (ref, false);
    }

    /// @notice A pool's anchor, when it was set, its band, and whether the anchor is fresh.
    function anchorOf(bytes32 poolId) external view returns (uint160 sqrtPriceX96, uint256 at, uint256 bandBps, bool fresh) {
        uint256 ab = anchorBand[poolId];
        sqrtPriceX96 = uint160(ab);
        at = (ab >> 160) & type(uint64).max;
        bandBps = ab >> 224;
        fresh = sqrtPriceX96 != 0 && block.timestamp - at <= anchorStaleSeconds;
    }

    function _writeAnchor(bytes32 poolId, uint160 sqrtPriceX96) internal {
        uint256 ab = anchorBand[poolId];
        anchorBand[poolId] = uint256(sqrtPriceX96) | (block.timestamp << 160) | ((ab >> 224) << 224);
    }

    /// @notice Uniswap v4: register `key` (its currencies, hook and fee); the id is computed here.
    function registerV4(PoolKey calldata key) external returns (bytes32 poolId) {
        if (kind != KIND_UNI_V4) revert NotUniV4();
        poolId = PoolId.unwrap(key.toId());
        (uint160 s,,,) = IPoolManager(manager).getSlot0(PoolId.wrap(poolId));
        if (s == 0) revert NotInitialized();
        v4Keys[poolId] = V4Key(Currency.unwrap(key.currency0), Currency.unwrap(key.currency1), address(key.hooks), key.fee);
        emit Registered(poolId, Currency.unwrap(key.currency0), Currency.unwrap(key.currency1), address(key.hooks), key.fee);
    }

    // ------------------------------------------------------------------ poke / price

    /// @notice IGapReader's poke: refused (records come only from pokeObserved by a keeper).
    function poke(bytes32) external pure override {
        revert NotKeeper();
    }

    /// @notice The pool's live price (what a keeper reads just before pokeObserved).
    function spot(bytes32 poolRef) external view returns (bool, uint160) {
        return _spot(poolRef);
    }

    /// @notice The bucket of the pool's newest record (0 = none), and the current bucket: a keeper pokes only when
    ///         the newest record is older than the current bucket.
    function lastBucket(bytes32 poolRef) external view returns (uint256 last, uint256 current) {
        uint256 n = count[poolRef];
        if (n != 0) last = rings[poolRef][(n - 1) % RING] >> 160;
        current = block.timestamp / bucketSeconds;
    }

    /// @notice Keepers only, at most once per bucket: fix this bucket's answer from earlier buckets, then record the
    ///         live price -- only if it is within tolBps of `expected`, the price the keeper observed before sending.
    function pokeObserved(bytes32 poolRef, uint160 expected, uint256 tolBps) external {
        if (!isKeeper[msg.sender]) revert NotKeeper();
        if (tolBps == 0 || tolBps > maxTolBps) revert BadParams();
        uint256 b = block.timestamp / bucketSeconds;
        uint256 n = count[poolRef];
        if (n != 0 && (rings[poolRef][(n - 1) % RING] >> 160) >= b) return; // this bucket is recorded
        (bool ok,,) = _currencies(poolRef);
        if (!ok) return;
        (bool okS, uint160 s) = _spot(poolRef);
        if (!okS) return;
        if (!_within(s, expected, tolBps)) {
            emit Skipped(poolRef, expected, s); // nothing recorded, no answer fixed
            return;
        }
        _answer(poolRef, b);
        rings[poolRef][n % RING] = uint256(s) | (b << 160);
        count[poolRef] = n + 1;
    }

    function priceE18(bytes32 poolRef, address base, address quote) external view returns (uint256) {
        if (base == quote) return 0;
        (bool ok, address c0, address c1) = _currencies(poolRef);
        if (!ok) return 0;
        bool baseIs0;
        if (_same(base, c0) && _same(quote, c1)) baseIs0 = true;
        else if (_same(base, c1) && _same(quote, c0)) baseIs0 = false;
        else return 0;
        (bool okA, uint160 a) = _current(poolRef);
        if (!okA) return 0;
        (bool okB, uint8 decB) = _decimals(base);
        (bool okQ, uint8 decQ) = _decimals(quote);
        if (!okB || !okQ) return 0;
        return _bounded(GapPriceLib.fromSqrtX96(a, baseIs0, decB, decQ, false));
    }

    /// @notice Monitoring: keeper records usable for the next answer, and the answer priceE18 would use now.
    function status(bytes32 poolRef) external view returns (uint256 usable, bool answered, uint160 sqrtPriceX96) {
        uint256 b = block.timestamp / bucketSeconds;
        usable = _collect(poolRef, b + 1, new uint160[](RING));
        (answered, sqrtPriceX96) = _current(poolRef);
    }

    // ------------------------------------------------------------------ internals

    /// @dev Fix bucket b's answer: the median of earlier records, one cap step at most from the previous answer
    ///      (an owner anchor is required); converging after an anchor or a stale gap, until the clamp is not needed.
    function _answer(bytes32 poolRef, uint256 b) internal {
        uint256 prev = answer[poolRef];
        if (prev == 0) return; // not anchored by the owner yet
        uint256 prevBucket = (prev >> 160) & type(uint64).max;
        if (prevBucket >= b) return; // already fixed for this bucket (an anchor made in this bucket)
        bool converging = (prev & CONVERGING) != 0;
        // The last bucket anything happened in: the answer's bucket; while converging (whose answer bucket may be
        // the anchor's, with no record behind it) also the newest record's. An outage longer than staleBuckets
        // since then -- converging or not -- restarts convergence from records made from this bucket on only
        // (round 5 M-1: an outage during convergence must not let pre-outage records serve as fresh).
        uint256 last = prevBucket;
        if (converging) {
            uint256 n = count[poolRef];
            if (n != 0) {
                uint256 nb = rings[poolRef][(n - 1) % RING] >> 160;
                if (nb > last) last = nb;
            }
        }
        if (b - last > staleBuckets) {
            if (!converging) {
                converging = true;
                prev |= CONVERGING;
                answer[poolRef] = prev;
            }
            freshFrom[poolRef] = b;
        }
        (bool okC, uint160 c) = _candidate(poolRef, b, converging ? freshFrom[poolRef] : 0);
        if (!okC) return;
        uint160 a = _clamp(uint160(prev), c);
        if (a == c) converging = false;
        answer[poolRef] = uint256(a) | (b << 160) | (converging ? CONVERGING : 0);
        emit Answered(poolRef, b, a);
    }

    /// @dev The answer priceE18 serves: fixed, not converging, at most staleBuckets old, and inside a fresh anchor's
    ///      band (an answer outside it, a stale anchor, no anchor or no band: nothing).
    function _current(bytes32 poolRef) internal view returns (bool, uint160) {
        uint256 a = answer[poolRef];
        if (a == 0 || (a & CONVERGING) != 0) return (false, 0);
        uint256 b = block.timestamp / bucketSeconds;
        if (b - ((a >> 160) & type(uint64).max) > staleBuckets) return (false, 0);
        uint256 ab = anchorBand[poolRef];
        uint160 anchor = uint160(ab);
        uint256 band = ab >> 224;
        if (anchor == 0 || band == 0) return (false, 0);
        if (block.timestamp - ((ab >> 160) & type(uint64).max) > anchorStaleSeconds) return (false, 0);
        if (!_within(uint160(a), anchor, band)) return (false, 0);
        return (true, uint160(a));
    }

    /// @dev |s / expected - 1| <= tolBps in price (sqrt factors: no overflow).
    function _within(uint160 s, uint160 expected, uint256 tolBps) internal pure returns (bool) {
        if (expected == 0) return false;
        uint256 f = Math.sqrt((10_000 + tolBps) * 1e36 / 10_000);
        return s <= Math.mulDiv(expected, f, E18) && s >= Math.mulDiv(expected, E18, f);
    }

    /// @dev The median of the newest minRecords keeper records of buckets in [max(b - windowBuckets, minBucket), b);
    ///      none if fewer, or if the newest of them is more than staleBuckets old.
    function _candidate(bytes32 poolRef, uint256 b, uint256 minBucket) internal view returns (bool, uint160) {
        uint160[] memory v = new uint160[](RING);
        uint256 newest;
        uint256 n;
        (n, newest) = _collectFrom(poolRef, b, minBucket, v);
        uint256 m = minRecords;
        if (n < m || b - newest > staleBuckets) return (false, 0);
        _sort(v, m); // v[0..m) are the newest m records
        return (true, v[m / 2]);
    }

    /// @dev Records of buckets in [b - windowBuckets, b), newest first (one per bucket).
    function _collect(bytes32 poolRef, uint256 b, uint160[] memory out) internal view returns (uint256 n) {
        (n,) = _collectFrom(poolRef, b, 0, out);
    }

    /// @dev Records of buckets in [max(b - windowBuckets, minBucket), b), newest first; also the newest one's bucket.
    function _collectFrom(bytes32 poolRef, uint256 b, uint256 minBucket, uint160[] memory out)
        internal
        view
        returns (uint256 n, uint256 newest)
    {
        uint256 total = count[poolRef];
        uint256 lim = total < RING ? total : RING;
        uint256 oldest = b > windowBuckets ? b - windowBuckets : 0;
        if (minBucket > oldest) oldest = minBucket;
        for (uint256 k = 1; k <= lim; k++) {
            uint256 r = rings[poolRef][(total - k) % RING];
            uint256 rb = r >> 160;
            if (rb >= b) continue;
            if (rb < oldest) break;
            if (n == 0) newest = rb;
            out[n++] = uint160(r);
        }
    }

    function _sort(uint160[] memory v, uint256 n) internal pure {
        for (uint256 i = 1; i < n; i++) {
            uint160 x = v[i];
            uint256 j = i;
            while (j > 0 && v[j - 1] > x) {
                v[j] = v[j - 1];
                j--;
            }
            v[j] = x;
        }
    }

    /// @dev `next` limited to one cap step from `prev` (sqrt factors: no overflow).
    function _clamp(uint160 prev, uint160 next) internal view returns (uint160) {
        uint256 hi = Math.mulDiv(prev, capUpE18, E18);
        uint256 lo = Math.mulDiv(prev, E18, capUpE18);
        if (hi > GapPriceLib.MAX_SQRT_PRICE) hi = GapPriceLib.MAX_SQRT_PRICE;
        if (lo < GapPriceLib.MIN_SQRT_PRICE) lo = GapPriceLib.MIN_SQRT_PRICE;
        if (next > hi) return uint160(hi);
        if (next < lo) return uint160(lo);
        return next;
    }

    function _same(address a, address c) internal view returns (bool) {
        if (a == c) return true;
        address w = wrappedNative;
        return w != address(0) && ((a == address(0) && c == w) || (a == w && c == address(0)));
    }

    function _acceptable(bytes32 poolRef, address hooks, uint24 fee) internal view returns (bool) {
        if (hooks == address(0) && fee != DYNAMIC_FEE && fee >= MIN_FEE) return true;
        return allowedPool[poolRef];
    }

    function _currencies(bytes32 poolRef) internal view returns (bool ok, address c0, address c1) {
        if (kind == KIND_UNI_V4) {
            V4Key memory k = v4Keys[poolRef];
            if (k.currency0 == address(0) && k.currency1 == address(0)) return (false, address(0), address(0));
            if (!_acceptable(poolRef, k.hooks, k.fee)) return (false, address(0), address(0));
            return (true, k.currency0, k.currency1);
        }
        (bool success, bytes memory ret) = manager.staticcall(abi.encodeWithSignature("poolIdToPoolKey(bytes32)", poolRef));
        if (!success || ret.length < 192) return (false, address(0), address(0));
        (uint256 w0, uint256 w1, uint256 hk, uint256 pm, uint256 fee) = abi.decode(ret, (uint256, uint256, uint256, uint256, uint256));
        if (w0 >> 160 != 0 || w1 >> 160 != 0 || hk >> 160 != 0 || fee > type(uint24).max) return (false, address(0), address(0));
        if (pm != uint256(uint160(manager))) return (false, address(0), address(0));
        if (!_acceptable(poolRef, address(uint160(hk)), uint24(fee))) return (false, address(0), address(0));
        c0 = address(uint160(w0));
        c1 = address(uint160(w1));
        if (c0 == c1) return (false, address(0), address(0));
        ok = true;
    }

    /// @dev The pool's live price as a sqrtPriceX96 (token1 per token0, raw units).
    function _spot(bytes32 poolRef) internal view returns (bool, uint160) {
        if (kind == KIND_UNI_V4) {
            (uint160 s,,,) = IPoolManager(manager).getSlot0(PoolId.wrap(poolRef));
            return _inRange(s);
        }
        (bool success, bytes memory ret) = manager.staticcall(abi.encodeWithSignature("getSlot0(bytes32)", poolRef));
        if (kind == KIND_INFINITY_CL) {
            if (!success || ret.length < 128) return (false, 0);
            uint256 sv = abi.decode(ret, (uint256));
            if (sv > type(uint160).max) return (false, 0);
            return _inRange(uint160(sv));
        }
        if (!success || ret.length < 96) return (false, 0);
        uint256 activeId = abi.decode(ret, (uint256));
        if (activeId > type(uint24).max) return (false, 0);
        (bool okK, bytes memory k) = manager.staticcall(abi.encodeWithSignature("poolIdToPoolKey(bytes32)", poolRef));
        if (!okK || k.length < 192) return (false, 0);
        (,,,,, bytes32 params) = abi.decode(k, (uint256, uint256, uint256, uint256, uint256, bytes32));
        uint256 binStep = (uint256(params) >> 16) & 0xffff;
        if (binStep == 0 || binStep > 1_000) return (false, 0);
        (bool okP, uint256 priceX128) = binPriceX128(activeId, binStep);
        if (!okP) return (false, 0);
        uint256 sq = Math.sqrt(priceX128) << 32; // sqrt(priceX128 * 2^64)
        if (sq > type(uint160).max) return (false, 0);
        return _inRange(uint160(sq));
    }

    /// @notice (1 + binStep/1e4)^(id - 2^23) as a 128.128 fixed-point number; false if out of range.
    function binPriceX128(uint256 id, uint256 binStep) public pure returns (bool, uint256) {
        uint256 base = (1 << 128) + Math.mulDiv(binStep, 1 << 128, 10_000);
        bool neg = id < BIN_ID_ZERO;
        uint256 e = neg ? BIN_ID_ZERO - id : id - BIN_ID_ZERO;
        if (e >= 1 << 20) return (false, 0);
        uint256 r = 1 << 128;
        uint256 bb = base;
        while (e > 0) {
            if (e & 1 == 1) {
                r = Math.mulDiv(r, bb, 1 << 128);
                if (r > type(uint192).max) return (false, 0);
            }
            e >>= 1;
            if (e > 0) {
                bb = Math.mulDiv(bb, bb, 1 << 128);
                if (bb > type(uint192).max) return (false, 0);
            }
        }
        if (neg) r = Math.mulDiv(1 << 128, 1 << 128, r); // r >= 2^128 here: no overflow
        return (r != 0, r);
    }

    function _inRange(uint160 s) internal pure returns (bool, uint160) {
        if (s < GapPriceLib.MIN_SQRT_PRICE || s > GapPriceLib.MAX_SQRT_PRICE) return (false, 0);
        return (true, s);
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

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

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

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

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

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

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

lib/openzeppelin-contracts/contracts/utils/math/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))
        }
    }
}

lib/uniswap-v4-core/src/interfaces/IExtsload.sol

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

lib/uniswap-v4-core/src/interfaces/IExttload.sol

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

lib/uniswap-v4-core/src/interfaces/IHooks.sol

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

lib/uniswap-v4-core/src/interfaces/IPoolManager.sol

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

lib/uniswap-v4-core/src/interfaces/IProtocolFees.sol

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

lib/uniswap-v4-core/src/interfaces/external/IERC20Minimal.sol

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

lib/uniswap-v4-core/src/interfaces/external/IERC6909Claims.sol

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

lib/uniswap-v4-core/src/libraries/CustomRevert.sol

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

lib/uniswap-v4-core/src/libraries/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;
}

lib/uniswap-v4-core/src/libraries/FullMath.sol

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

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

lib/uniswap-v4-core/src/libraries/LiquidityMath.sol

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

lib/uniswap-v4-core/src/libraries/Position.sol

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

lib/uniswap-v4-core/src/libraries/SafeCast.sol

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

lib/uniswap-v4-core/src/libraries/StateLibrary.sol

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

lib/uniswap-v4-core/src/types/BalanceDelta.sol

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

lib/uniswap-v4-core/src/types/BeforeSwapDelta.sol

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

lib/uniswap-v4-core/src/types/Currency.sol

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

lib/uniswap-v4-core/src/types/PoolId.sol

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

lib/uniswap-v4-core/src/types/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;
}

lib/uniswap-v4-core/src/types/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;
}

src/v3/gap/GapMath.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @title GapMath -- the v3 bridge gap fee: the formula and the message codec (codec v3, docs/v3c-gap-spec.md)
/// @notice FROZEN (work item 1). The JS reference (script/gap/gap-math.mjs) and the Solana port
///         (solana/oft/programs/oft/src/gap/math.rs) implement the same functions and assert the
///         same vectors (test/fixtures/gap-vectors.json). A change here is a change to all three.
/// @dev Pure, and never reverts on the receive path except `decode` on a message shorter than 40
///      bytes (no `sendTo`/`amountSD` to credit). Every rounding is toward the fee (v3c).
library GapMath {
    // ---------------------------------------------------------------- message codec (v3c §1)

    /// @notice The only version this code accepts (codec v3, owner 2026-10-30). Any other byte at
    ///         offset 40, or a header shorter than 96 bytes (HEADER_LEN), is "not the gap codec": the v3 receive
    ///         REFUSES it (GapBadVersion), it never credits at fee 0.
    uint8 internal constant VER = 0x03;

    uint256 internal constant SEND_TO_OFFSET = 0; // bytes32
    uint256 internal constant AMOUNT_SD_OFFSET = 32; // uint64, big-endian
    uint256 internal constant VER_OFFSET = 40; // uint8
    uint256 internal constant PS_OFFSET = 41; // uint128, big-endian: psUsdE18
    uint256 internal constant FEE_SRC_OFFSET = 57; // uint32: the source pool fee + the bridge cost (costPpm)
    uint256 internal constant BRIDGE_FEE_OFFSET = 61; // uint32, big-endian
    /// @notice The sender's least credited amount, in shared decimals (0 = none): the receive
    ///         reverts, retriable, while credited < minCreditedSD x the destination's rate.
    uint256 internal constant MIN_CREDITED_OFFSET = 65; // uint64, big-endian
    /// @notice The source quote's price class (0 none, 1 USD stable, 2 ETH, 3..255 admin assets).
    uint256 internal constant PRICE_CLASS_OFFSET = 73; // uint8
    /// @notice The source price in class units per whole token (0 = unreadable or class 0).
    uint256 internal constant PS_CLASS_OFFSET = 74; // uint128, big-endian
    /// @notice AMENDMENT 6: the source's gas cover (its send + one swap at its block's basefee), micro-USD,
    ///         rounded down, at most srcCoverCapCents x 1e4 (GapCoverLib.sourceCover). 0 = no cover.
    uint256 internal constant SRC_GAS_MICRO_USD_OFFSET = 90; // uint32, big-endian
    /// @notice AMENDMENT 6: the source's per-message cover cap, US cents (<= COVER_CAP_MAX_CENTS). 0 = this
    ///         message carries no cover (cap unset, or the route's cover in this window is spent): the
    ///         destination then adds nothing either.
    uint256 internal constant SRC_COVER_CAP_OFFSET = 94; // uint16, big-endian
    /// @notice The fixed header. A longer message is composed; its tail
    ///         (`composeFrom(32) | composeMsg`) starts here.
    uint256 internal constant HEADER_LEN = 96;

    // ---------------------------------------------------------------- units and limits (spec §2)

    uint256 internal constant PPM = 1_000_000;
    uint256 internal constant E18 = 1e18;
    /// @notice Every price (Ps, Pd, a hop) lives in [1, PRICE_MAX]; above it is a read failure,
    ///         and Pd above it is clamped down to it.
    uint256 internal constant PRICE_MAX = type(uint128).max;
    /// @notice AMENDMENT 6 (owner 2026-10-30): the margin is a FIXED destination admin ppm (registry
    ///         `marginPpm`), default 0.1%; hard cap 10% (lead decision 4: the owner may raise it per chain
    ///         for tiny pools).
    uint32 internal constant MARGIN_DEFAULT_PPM = 1_000;
    uint32 internal constant MARGIN_MAX_PPM = 100_000;

    // ---------------------------------------------------------------- the gas cover (AMENDMENT 6 §2)

    /// @notice Hard caps of the registry's GasCover (identical in math.rs / gap-math.mjs).
    uint32 internal constant SWAP_GAS_UNITS_MAX = 2_000_000;
    uint32 internal constant SEND_GAS_UNITS_MAX = 4_000_000;
    /// @notice The counted basefee is clamp(block.basefee, floor, cap): floor <= 1 gwei, cap <= 1,000 gwei.
    uint64 internal constant BASEFEE_FLOOR_MAX_WEI = 1e9;
    uint64 internal constant BASEFEE_CAP_MAX_WEI = 1e12;
    /// @notice The per-chain per-message cover cap is at most $200 (coordinator 2026-10-30, was $50); a message
    ///         uses min(source cap, destination cap).
    uint16 internal constant COVER_CAP_MAX_CENTS = 20_000;
    /// @notice The cover window (lead decision 1): at most one cover per (token, dstEid) per window.
    uint32 internal constant COVER_WINDOW_SECONDS_DEFAULT = 30;
    uint32 internal constant COVER_WINDOW_SECONDS_MIN = 12;
    uint32 internal constant COVER_WINDOW_SECONDS_MAX = 86_400;
    /// @notice USD 1e18 per micro-dollar (the header's unit) and per cent.
    uint256 internal constant MICRO_USD_E18 = 1e12;
    uint256 internal constant CENT_E18 = 1e16;

    // ---------------------------------------------------------------- gas (spec §6.2, Q1, EVM only)

    /// @notice A route hop's gasCap is at most this (the registry refuses more: BadRoute).
    uint32 internal constant MAX_HOP_GAS = 100_000;
    /// @notice Before a reader call the registry requires gasleft() >= gasCap * 64 / 63 + this.
    uint256 internal constant HOP_GAS_RESERVE = 5_000;
    /// @notice Before the gap reads (send and receive) the token requires gasleft() >= this.
    ///         Covers the worst quote route (2 hops at MAX_HOP_GAS), the pool, fee and settings reads,
    ///         and AMENDMENT 6's destination native route at its worst (2 more hops at MAX_HOP_GAS,
    ///         when the Pd route does not give it): measured 561,938 gas given to the token's call
    ///         (~548k at this check) with every reader burning 95k of its 100k cap
    ///         (test_gapReadGasCoversTheWorstCoveredRoute), so 560k (+12k, 2.2%) -- once it passes, no
    ///         hop runs short. The 1-hop native route needs 448,674; no cover 411,700 (guard-bound).
    uint256 internal constant GAP_READ_GAS = 560_000;

    // ---------------------------------------------------------------- outcome reasons (spec §6)

    uint8 internal constant CHARGED = 0; // the formula ran and withheld something
    uint8 internal constant NOT_V1 = 1; // not the gap codec (unknown ver, or a short header): refused
    uint8 internal constant PS_ZERO = 2; // the source could not price
    uint8 internal constant DST_NO_POOL = 3; // no official pool on this chain yet
    uint8 internal constant DST_PRICE_FAILED = 4; // pool/route/reader failure, or Pd == 0
    uint8 internal constant DST_FEE_FAILED = 5; // the destination pool fee was unreadable (or >= 1e6)
    uint8 internal constant NO_GAP = 6; // Pd <= Ps
    uint8 internal constant WITHIN_ALLOWANCE = 7; // credited >= amountLD
    /// @notice Solana only (spec §5.1): the official pool's fee is not a flat base fee. Never
    ///         produced on EVM. Listed so every port shares the codes.
    uint8 internal constant UNSUPPORTED_FEE_MODE = 8;
    /// @notice v3c: the token's admin escape (registry `gapEscape`) is on: credited in full, fee 0.
    uint8 internal constant ESCAPED = 9;
    /// @notice v3c (4a): no official pool here yet and `to` is a listed seeder (a factory): fee 0.
    uint8 internal constant SEED_NO_POOL = 10;
    /// @notice v3c AMENDMENT 2: an expired-compose refund (Solana `return_expired_compose`): codec v3
    ///         with priceClass REFUND_CLASS and psUsd = psClass = 0 -> credited in full, fee 0.
    uint8 internal constant REFUND = 11;
    /// @notice v3c-evm-log: a V1-hook pool's price log cannot price this receive (too few entries
    ///         or too little unused capacity in the window): it holds (GapNeedRecords), retriable.
    uint8 internal constant NEED_RECORDS = 12;
    /// @notice The refund marker's price class. Never a quote's class (the registries refuse it) and
    ///         never sent by a send; with any non-zero price the receive refuses it (GapBadVersion).
    uint8 internal constant REFUND_CLASS = 255;

    error GapMsgTooShort(uint256 length);

    /// @notice What `decode` reads. `v1 == false` means "not the gap codec" (refused by the receive).
    struct Header {
        bytes32 sendTo;
        uint64 amountSD;
        bool v1;
        uint128 psE18;
        uint32 feeSrcPpm;
        uint32 bridgeFeePpm;
        uint64 minCreditedSD;
        uint8 priceClass;
        uint128 psClassE18;
        uint32 srcGasMicroUsd;
        uint16 srcCoverCapCents;
        bool composed;
    }

    /// @notice The fields a send carries (codec v3), as one struct (stack depth).
    struct Quote {
        uint128 psE18;
        uint32 feeSrcPpm;
        uint32 bridgeFeePpm;
        uint8 priceClass;
        uint128 psClassE18;
        uint32 srcGasMicroUsd;
        uint16 srcCoverCapCents;
    }

    /// @notice The gap message (codec version 3). `composeMsg` empty means not composed (as
    ///         LayerZero's OFT).
    function encode(
        bytes32 sendTo,
        uint64 amountSD,
        Quote memory q,
        uint64 minCreditedSD,
        bytes32 composeFrom,
        bytes memory composeMsg
    ) internal pure returns (bytes memory m) {
        m = abi.encodePacked(
            sendTo, amountSD, VER, q.psE18, q.feeSrcPpm, q.bridgeFeePpm, minCreditedSD, q.priceClass, q.psClassE18, q.srcGasMicroUsd, q.srcCoverCapCents
        );
        if (composeMsg.length != 0) m = abi.encodePacked(m, composeFrom, composeMsg);
    }

    /// @notice Reverts only below 40 bytes. A message of 40..95 bytes, or with ver != 3, decodes
    ///         as `v1 == false` (refused by the v3 receive).
    function decode(bytes calldata m) internal pure returns (Header memory h) {
        if (m.length < VER_OFFSET) revert GapMsgTooShort(m.length);
        h.sendTo = bytes32(m[SEND_TO_OFFSET:AMOUNT_SD_OFFSET]);
        h.amountSD = uint64(bytes8(m[AMOUNT_SD_OFFSET:VER_OFFSET]));
        if (m.length < HEADER_LEN || uint8(m[VER_OFFSET]) != VER) return h;
        h.v1 = true;
        h.psE18 = uint128(bytes16(m[PS_OFFSET:FEE_SRC_OFFSET]));
        h.feeSrcPpm = uint32(bytes4(m[FEE_SRC_OFFSET:BRIDGE_FEE_OFFSET]));
        h.bridgeFeePpm = uint32(bytes4(m[BRIDGE_FEE_OFFSET:MIN_CREDITED_OFFSET]));
        h.minCreditedSD = uint64(bytes8(m[MIN_CREDITED_OFFSET:PRICE_CLASS_OFFSET]));
        h.priceClass = uint8(m[PRICE_CLASS_OFFSET]);
        h.psClassE18 = uint128(bytes16(m[PS_CLASS_OFFSET:SRC_GAS_MICRO_USD_OFFSET]));
        h.srcGasMicroUsd = uint32(bytes4(m[SRC_GAS_MICRO_USD_OFFSET:SRC_COVER_CAP_OFFSET]));
        h.srcCoverCapCents = uint16(bytes2(m[SRC_COVER_CAP_OFFSET:HEADER_LEN]));
        h.composed = m.length > HEADER_LEN;
    }

    /// @notice `composeFrom | composeMsg` -- what LayerZero's `OFTComposeMsgCodec.encode` takes as
    ///         its last argument, with `amountLD = credited`. Only for a decoded `composed` message.
    function composeTail(bytes calldata m) internal pure returns (bytes calldata) {
        return m[HEADER_LEN:];
    }

    // ---------------------------------------------------------------- the formula (v3c §2)

    /// @notice The destination's withholding. Never reverts. Owner 2026-10-30: the arb keeps at most
    ///         about the margin at ANY gap, so the allowance is valued at the SOURCE price. With
    ///         G = amountLD * 1e6 / (1e6 - b) the gross amount sent (the bridge fee b is always
    ///         collected, inside G), the credit is what returns G x Ps x (1 + feeSrc + margin) when
    ///         sold at Pd after the destination pool fee; feeSrc already holds the bridge cost;
    ///         AMENDMENT 6: plus the gas cover (gasCoverPpm, GapCoverLib.coverPpm; 0 = none):
    ///             t = floor(amountLD * Ps / Pd)
    ///             K = (1e6 + feeSrcPpm + marginPpm + gasCoverPpm) * 1e6,  D = (1e6 - b) * (1e6 - feeDstPpm)
    ///             credited = floor(t * K / D),  withheld = credited >= amountLD ? 0 : amountLD - credited
    ///         b >= 1e6 counts as 0; feeDstPpm >= 1e6 is DST_FEE_FAILED. Every rounding is toward the
    ///         fee. Worked example: 998 tokens arrive of 1,000 sent at $1, Pd $2, 0.3% pools, 0.1%
    ///         margin, $0.50 cost (feeSrc 3,500): credited 503.761283851, withheld 494.238716149.
    /// @param amountLD what the destination would credit without the gap fee (amountSD * rate)
    /// @param psE18 the source price (of the pair `pickPair` chose); 0 means unknown
    /// @param pdE18 the destination price; 0 means unknown; above PRICE_MAX it is clamped down
    /// @return withheld the amount not credited (burned), in local decimals
    /// @return gapPpm floor((Pd - Ps) * 1e6 / Pd), 0 unless Pd > Ps > 0 (reported only)
    /// @param gasCoverPpm AMENDMENT 6: the gas cover as ppm of the gross amount (no 1e6 cap: a cover
    ///        above the value only lifts the credit to amountLD); 0 = no cover
    /// @return allowPpm feeSrcPpm + feeDstPpm + marginPpm + gasCoverPpm (reported only)
    /// @return reason CHARGED, PS_ZERO, DST_PRICE_FAILED, DST_FEE_FAILED, NO_GAP or WITHIN_ALLOWANCE
    function gapFee(
        uint256 amountLD,
        uint128 psE18,
        uint256 pdE18,
        uint32 feeSrcPpm,
        uint32 feeDstPpm,
        uint32 bridgeFeePpm,
        uint32 mPpm,
        uint32 gasCoverPpm
    ) internal pure returns (uint256 withheld, uint32 gapPpm, uint64 allowPpm, uint8 reason) {
        allowPpm = uint64(feeSrcPpm) + feeDstPpm + mPpm + gasCoverPpm;
        if (psE18 == 0) return (0, 0, allowPpm, PS_ZERO);
        if (pdE18 == 0) return (0, 0, allowPpm, DST_PRICE_FAILED);
        if (feeDstPpm >= PPM) return (0, 0, allowPpm, DST_FEE_FAILED);
        if (pdE18 > PRICE_MAX) pdE18 = PRICE_MAX;
        if (pdE18 <= psE18) return (0, 0, allowPpm, NO_GAP);
        // floor((Pd - Ps) * 1e6 / Pd) == 1e6 - ceil(Ps * 1e6 / Pd): exact, and Ps * 1e6 < 2^148.
        gapPpm = uint32(PPM - Math.ceilDiv(uint256(psE18) * PPM, pdE18));
        uint256 t = Math.mulDiv(amountLD, psE18, pdE18); // < amountLD (Ps < Pd)
        uint256 b = bridgeFeePpm < PPM ? bridgeFeePpm : 0;
        uint256 k = (PPM + feeSrcPpm + mPpm + gasCoverPpm) * PPM; // < 4 * 2^32 * 1e6 < 2^55
        uint256 d = (PPM - b) * (PPM - feeDstPpm); // in [1, 1e12]
        // credited >= amountLD  <=>  t * k >= amountLD * d  <=>  t >= ceil(amountLD * d / k): checked
        // first, so the credit's mulDiv below is < amountLD and never overflows.
        if (t >= Math.mulDiv(amountLD, d, k, Math.Rounding.Ceil)) return (0, gapPpm, allowPpm, WITHIN_ALLOWANCE);
        withheld = amountLD - Math.mulDiv(t, k, d);
        reason = CHARGED;
    }

    /// @notice Which price pair the destination compares (v3c §2): the class pair when both quotes
    ///         have the same non-zero class and both class prices are known, else the USD pair.
    ///         `ok == false`: nothing comparable (the receive reverts, GapUnreadable).
    function pickPair(uint8 msgClass, uint256 psClass, uint256 psUsd, uint8 dstClass, uint256 pdClass, uint256 pdUsd)
        internal
        pure
        returns (bool ok, uint256 ps, uint256 pd, bool isClass)
    {
        if (msgClass != 0 && msgClass == dstClass && psClass != 0 && pdClass != 0) return (true, psClass, pdClass, true);
        if (psUsd != 0 && pdUsd != 0) return (true, psUsd, pdUsd, false);
        return (false, 0, 0, false);
    }

    // ---------------------------------------------------------------- the bridge cost (v3c §2)

    /// @notice The LayerZero bridge cost counted (USD 1e18) is at most this: $20. It bounds what a
    ///         pumped native/USD hop could add to the allowance. (AMENDMENT 6: the static gas allowance
    ///         is removed; the send's own gas is in the gas cover, GapCoverLib.)
    uint256 internal constant COST_MAX_USD_E18 = 20e18;
    /// @notice v3c-evm-final: the registry's admin cost cap (setCostMax): default COST_MAX_USD_E18 ($20),
    ///         at most $50. A registry that does not answer counts the default.
    uint256 internal constant COST_MAX_LIMIT_USD_E18 = 50e18;
    /// @notice v3c-evm-final: the admin bridge fee (registry setBridgeFeeBps): default 20 bps (0.2%), at most
    ///         50 bps. A token that cannot read it charges the default, never 0.
    uint16 internal constant BRIDGE_FEE_DEFAULT_BPS = 20;
    uint16 internal constant BRIDGE_FEE_MAX_BPS = 50;
    /// @notice v3c-evm-final: the admin gas cap of the send's LayerZero quote (registry setQuoteGas):
    ///         default 400,000, within [150,000, 1,000,000]. Unreadable: the default.
    uint32 internal constant QUOTE_GAS_DEFAULT = 400_000;
    uint32 internal constant QUOTE_GAS_MIN = 150_000;
    uint32 internal constant QUOTE_GAS_MAX = 1_000_000;
    /// @notice v3c (5): a V2 hop record's greatest age, seconds: default and bounds. Audit M-1
    ///         (EVM-B): a touch of the pair (sync) chooses between the live reserves and the record,
    ///         so the age bounds that choice; default 30 s, at least 12 s.
    /// @dev Audit M-1 (evma): the receive's executor may choose the V2 record (touch the pair) or
    ///      the live price, so the record's age bounds what drift it can pick: 30 s default, 12 s min.
    uint32 internal constant V2_RECORD_MAX_AGE_DEFAULT = 30;
    uint32 internal constant V2_RECORD_MAX_AGE_MIN = 12;
    uint32 internal constant V2_RECORD_MAX_AGE_MAX = 86_400;

    /// @notice The bridge cost as ppm of the gross amount, the part of `feeSrcPpm` above the source
    ///         pool's fee (owner 2026-10-30). Every step rounds DOWN (toward the gap fee):
    ///             lzUsd   = floor(nativeFee * usdPerNative / 10^nativeDecimals)
    ///             costUsd = min(lzUsd, COST_MAX_USD_E18)          (AMENDMENT 6: no gas allowance)
    ///             costLD  = floor(costUsd * 10^tokenDecimals / Ps)
    ///             costPpm = min(1e6, floor(costLD * (1e6 - bridgeFeePpm) / amountLD))
    ///         where amountLD = amountSD * rate is what the message carries (net of the bridge fee),
    ///         so amountLD / (1e6 - bridgeFeePpm) is the gross base the destination charges on.
    ///         0 when Ps or amountLD is 0. usdPerNative 0 (unreadable) counts the LayerZero fee as 0.
    ///         Never reverts.
    /// @param nativeFee the LayerZero fee for the token's ENFORCED options only, in the native's units
    function costPpm(
        uint256 nativeFee,
        uint8 nativeDecimals,
        uint256 usdPerNativeE18,
        uint256 psE18,
        uint8 tokenDecimals,
        uint256 amountLD,
        uint32 bridgeFeePpm
    ) internal pure returns (uint32) {
        return costPpmCapped(nativeFee, nativeDecimals, usdPerNativeE18, psE18, tokenDecimals, amountLD, bridgeFeePpm, COST_MAX_USD_E18);
    }

    /// @notice `costPpm` with the registry's admin cap `costMaxUsdE18` (<= COST_MAX_LIMIT_USD_E18; above it
    ///         the limit counts) in place of the $20 default. costPpm(...) == costPpmCapped(..., 20e18).
    function costPpmCapped(
        uint256 nativeFee,
        uint8 nativeDecimals,
        uint256 usdPerNativeE18,
        uint256 psE18,
        uint8 tokenDecimals,
        uint256 amountLD,
        uint32 bridgeFeePpm,
        uint256 costMaxUsdE18
    ) internal pure returns (uint32) {
        if (psE18 == 0 || amountLD == 0) return 0;
        if (costMaxUsdE18 > COST_MAX_LIMIT_USD_E18) costMaxUsdE18 = COST_MAX_LIMIT_USD_E18;
        uint256 costUsd;
        if (usdPerNativeE18 != 0 && usdPerNativeE18 <= PRICE_MAX && nativeFee != 0 && nativeDecimals <= 36) {
            // Both factors below 2^128, so the exact product fits 2^256 and mulDiv cannot revert.
            costUsd = nativeFee > PRICE_MAX ? costMaxUsdE18 : Math.mulDiv(nativeFee, usdPerNativeE18, 10 ** nativeDecimals);
        }
        if (costUsd > costMaxUsdE18) costUsd = costMaxUsdE18;
        if (costUsd == 0 || tokenDecimals > 36) return 0;
        // costUsd <= 50e18 and 10^tokenDecimals <= 1e36: the product fits; Ps >= 1.
        uint256 costLD = Math.mulDiv(costUsd, 10 ** tokenDecimals, psE18);
        uint256 den = bridgeFeePpm < PPM ? PPM - bridgeFeePpm : PPM;
        // costLD < 2^256 / 1e6 (costLD <= 2e55): costLD * den fits, mulDiv cannot revert.
        uint256 v = Math.mulDiv(costLD, den, amountLD);
        return v >= PPM ? uint32(PPM) : uint32(v);
    }

    /// @notice The bridge cost of a CLASS-ONLY send (psUsd unreadable, psClass known), as ppm of the
    ///         gross amount (coordinator 2026-10-30). AMENDMENT 6 (decision 8): sends REQUIRE psUsd (the
    ///         gas cover is USD), so no send reaches this; it is kept, with its vectors, for the ports
    ///         that still carry it. The cost is a token amount, priced in class units through psClass:
    ///         - class 1 (USD stables): class units ARE USD -- exactly costPpm with Ps = psClass;
    ///         - class c != 1 equal to the NATIVE coin's class (e.g. ETH-class on an ETH chain): the
    ///           native is the class asset 1:1, so lzClass = floor(nativeFee * 1e18 / 10^nativeDecimals),
    ///           capped at $20 of it, floor(20e18 * 1e18 / usdPerNative); usdPerNative unreadable (0)
    ///           -> 0 (no cap can be read);
    ///         - any other class (incl. 0 and the refund marker 255): 0.
    ///         costLD = floor(costClass * 10^tokenDecimals / psClass); costPpm as `costPpm`. Every step
    ///         rounds down; never reverts.
    function costClassPpm(
        uint8 priceClass,
        uint8 nativeClass,
        uint256 nativeFee,
        uint8 nativeDecimals,
        uint256 usdPerNativeE18,
        uint256 psClassE18,
        uint8 tokenDecimals,
        uint256 amountLD,
        uint32 bridgeFeePpm
    ) internal pure returns (uint32) {
        if (priceClass == 1) {
            return costPpm(nativeFee, nativeDecimals, usdPerNativeE18, psClassE18, tokenDecimals, amountLD, bridgeFeePpm);
        }
        if (priceClass == 0 || priceClass == 255 || priceClass != nativeClass) return 0;
        if (psClassE18 == 0 || amountLD == 0 || nativeFee == 0) return 0;
        if (usdPerNativeE18 == 0 || usdPerNativeE18 > PRICE_MAX || nativeDecimals > 36 || tokenDecimals > 36) return 0;
        // $20 in class units (the native 1:1): <= 20e36 < 2^128.
        uint256 cap = Math.mulDiv(COST_MAX_USD_E18, E18, usdPerNativeE18);
        uint256 cost = nativeFee > PRICE_MAX ? cap : Math.mulDiv(nativeFee, E18, 10 ** nativeDecimals);
        if (cost > cap) cost = cap;
        if (cost == 0) return 0;
        // cost <= 2e37 and 10^tokenDecimals <= 1e36: the product fits.
        uint256 costLD = Math.mulDiv(cost, 10 ** tokenDecimals, psClassE18);
        if (costLD / amountLD >= PPM) return uint32(PPM);
        uint256 den = bridgeFeePpm < PPM ? PPM - bridgeFeePpm : PPM;
        uint256 v = Math.mulDiv(costLD, den, amountLD);
        return v >= PPM ? uint32(PPM) : uint32(v);
    }

    // ---------------------------------------------------------------- pool fees (spec §5.1)

    /// @notice EVM official pool fee: hook bps * 100 + the v4 static LP fee (already ppm).
    ///         `ok == false` (fee read failed) when lpFee > 1e6 -- that includes v4's dynamic flag.
    function evmPoolFeePpm(uint16 hookFeeBps, uint24 lpFee) internal pure returns (bool ok, uint32 ppm) {
        if (lpFee > PPM) return (false, 0);
        return (true, uint32(hookFeeBps) * 100 + lpFee);
    }

    /// @notice Solana (Meteora DAMM v2) pool fee: ceil(cliff_fee_numerator / 1000), the numerator
    ///         being over 1e9. `ok == false` when the numerator is above 1e9.
    function solanaPoolFeePpm(uint64 cliffFeeNumerator) internal pure returns (bool ok, uint32 ppm) {
        if (cliffFeeNumerator > 1e9) return (false, 0);
        return (true, uint32(Math.ceilDiv(cliffFeeNumerator, 1000)));
    }

    // ---------------------------------------------------------------- price chaining (spec §5.2)

    /// @notice ceil(a * b / 1e18); 0 (failure) if either factor is 0 or above PRICE_MAX, or the
    ///         product is above PRICE_MAX. The source chains with this, every reader factor + 1.
    function mulUp(uint256 a, uint256 b) internal pure returns (uint256 p) {
        if (a == 0 || b == 0 || a > PRICE_MAX || b > PRICE_MAX) return 0;
        p = Math.mulDiv(a, b, E18, Math.Rounding.Ceil);
        if (p > PRICE_MAX) return 0;
    }

    /// @notice floor(a * b / 1e18); 0 (failure) if either factor is 0 or above PRICE_MAX, or the
    ///         product is 0. Above PRICE_MAX it is clamped down. The destination chains with this.
    function mulDown(uint256 a, uint256 b) internal pure returns (uint256 p) {
        if (a == 0 || b == 0 || a > PRICE_MAX || b > PRICE_MAX) return 0;
        p = Math.mulDiv(a, b, E18);
        if (p > PRICE_MAX) p = PRICE_MAX;
    }

    /// @notice A reader's floor as a source factor: p + 1, or 0 when p is 0 or above PRICE_MAX - 1.
    function srcFactor(uint256 p) internal pure returns (uint256) {
        if (p == 0 || p >= PRICE_MAX) return 0;
        return p + 1;
    }
}

src/v3/gap/GapPriceLib.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @title GapPriceLib -- pool prices as "whole quote per whole base, 1e18" (docs/v3-gap-fee-spec.md §2)
/// @notice Shared by PangeaOFTV3 (its official pool, rounded up at the source and down at the
///         destination) and the gap readers (always down). Never reverts for the inputs it accepts;
///         anything outside them returns 0, which every caller treats as "unknown".
library GapPriceLib {
    uint256 internal constant Q64 = 1 << 64;
    uint256 internal constant Q128 = 1 << 128;
    uint256 internal constant Q192 = 1 << 192;
    /// @dev Uniswap's TickMath bounds (v3 and v4 share them). Outside them the price is not one a
    ///      Uniswap pool can hold, and the arithmetic below is only overflow-free inside them.
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev |18 + baseDecimals - quoteDecimals| at most this; beyond it the price is 0 (unknown).
    int256 internal constant MAX_EXP = 36;

    /// @notice The decimal scaling of a raw (base-unit) price into "whole quote per whole base, 1e18":
    ///         multiply by `num`, divide by `den`. (0, 0) when the decimals are out of range.
    function scale(uint8 baseDecimals, uint8 quoteDecimals) internal pure returns (uint256 num, uint256 den) {
        int256 e = 18 + int256(uint256(baseDecimals)) - int256(uint256(quoteDecimals));
        if (e > MAX_EXP || e < -MAX_EXP) return (0, 0);
        if (e >= 0) return (10 ** uint256(e), 1);
        return (1, 10 ** uint256(-e));
    }

    /// @notice The price of one whole `base` in whole `quote`, 1e18, from a Uniswap v3/v4
    ///         sqrtPriceX96 (sqrt of currency1 per currency0, raw units, Q96).
    /// @param baseIs0 whether `base` is the pool's currency0
    /// @param up round up (the source) or down (the destination, and every reader)
    /// @return p the price, possibly above type(uint128).max (callers bound it); 0 when unknown
    function fromSqrtX96(uint160 sqrtP, bool baseIs0, uint8 baseDecimals, uint8 quoteDecimals, bool up)
        internal
        pure
        returns (uint256 p)
    {
        if (sqrtP < MIN_SQRT_PRICE || sqrtP > MAX_SQRT_PRICE) return 0;
        (uint256 num, uint256 den) = scale(baseDecimals, quoteDecimals);
        if (num == 0) return 0;
        Math.Rounding r = up ? Math.Rounding.Ceil : Math.Rounding.Floor;
        uint256 s = sqrtP;
        // num <= 1e36 < 2^120, and sqrtP is inside TickMath's bounds, so no step below overflows:
        // currency0 side  s^2 < 2^256 (or s^2/2^64 < 2^256), times < 2^120, over >= 2^128;
        // currency1 side  2^192 (or 2^128) times < 2^120, over s^2 >= 2^64 (or s^2/2^64 >= 2^192).
        if (baseIs0) {
            // raw price of base (currency0) in quote = s^2 / 2^192
            if (s <= type(uint128).max) p = Math.mulDiv(s * s, num, Q192, r);
            else p = Math.mulDiv(Math.mulDiv(s, s, Q64, r), num, Q128, r);
        } else {
            // raw price of base (currency1) in quote = 2^192 / s^2: round the divisor the other way
            if (s <= type(uint128).max) p = Math.mulDiv(Q192, num, s * s, r);
            else p = Math.mulDiv(Q128, num, Math.mulDiv(s, s, Q64, up ? Math.Rounding.Floor : Math.Rounding.Ceil), r);
        }
        if (den > 1) p = up ? Math.ceilDiv(p, den) : p / den;
    }

    /// @notice The price of one whole `base` in whole `quote`, 1e18, from constant-product reserves,
    ///         rounded down. 0 when either reserve is 0 or the decimals are out of range.
    function fromReserves(uint256 reserveBase, uint256 reserveQuote, uint8 baseDecimals, uint8 quoteDecimals)
        internal
        pure
        returns (uint256 p)
    {
        if (reserveBase == 0 || reserveQuote == 0) return 0;
        if (reserveBase > type(uint128).max || reserveQuote > type(uint128).max) return 0;
        (uint256 num, uint256 den) = scale(baseDecimals, quoteDecimals);
        if (num == 0) return 0;
        // reserveQuote * num < 2^248: no overflow.
        p = Math.mulDiv(reserveQuote, num, reserveBase) / den;
    }
}

src/v3/gap/IGapReader.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

/// @title IGapReader -- one read-only DEX price adapter (docs/v3c-gap-spec.md §5)
/// @notice The registry calls it as
///         `staticcall{gas: hop.gasCap}(abi.encodeCall(IGapReader.priceE18, (poolRef, base, quote)))`
///         and accepts the answer only if the call succeeded, returned EXACTLY 32 bytes, and the
///         value is in [1, type(uint128).max]. Anything else is a read failure: the registry
///         answers 0 and a v3c token turns that into a retriable revert (never fee 0).
///         v3c (§5): every reader is FLASH-PROOF: nothing done earlier in the same transaction
///         (a swap in, before the read, swapped back after it) moves its answer.
interface IGapReader {
    /// @notice The price of one whole `base` in whole `quote`, 1e18 fixed point, both tokens'
    ///         decimals already applied, ROUNDED DOWN. `address(0)` is the chain's native coin.
    ///         0 when it cannot price flash-proof.
    /// @param poolRef the pool, as the reader names it: a v4 PoolId, or a v2/v3 pool address
    ///        left-padded to 32 bytes, or whatever the reader documents
    function priceE18(bytes32 poolRef, address base, address quote) external view returns (uint256);

    /// @notice v3c (5), OPTIONAL (V2-style readers only): store `poolRef`'s price from reserves NOT touched in this
    ///         block (blockTimestampLast < block.timestamp); a no-op otherwise. It can only write a pre-block
    ///         price. Only tokens with an official pool may call it (V2PairReader checks the registry's
    ///         hasOfficialPool for msg.sender): a v3 token's recordPrice, run by its official pool's hook,
    ///         pokes the hops of its quote's and the native's routes on a block's first record (not on the
    ///         very first record ever), gas-capped, failures ignored. `priceE18` uses the stored price only when the pair was touched this block and the
    ///         record is at most the registry's v2RecordMaxAge old. Readers without it revert (ignored).
    function poke(bytes32 poolRef) external;
}

src/v3/gap/readers/GapReaderBase.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IGapReader} from "../IGapReader.sol";
import {GapMath} from "../GapMath.sol";

/// @title GapReaderBase -- what every gap reader shares (docs/v3c-gap-spec.md §5)
/// @notice A reader answers `priceE18(poolRef, base, quote)`: the price of one whole `base` in
///         whole `quote`, 1e18, decimals applied, ROUNDED DOWN, FLASH-PROOF (§5). It never answers
///         above type(uint128).max, and answers 0 when it cannot price (the registry treats 0, a
///         revert, or anything but exactly 32 bytes as a read failure; the v3c token then reverts
///         retriably, never fee 0).
/// @dev Readers are read-only except V2PairReader's `poke` record. They are allowed per chain by
///      the registry owner and called under a gas cap, so a slow or broken one is an unreadable
///      price (a retry later), never a wrong one. `address(0)` is the chain's native coin
///      (18 decimals).
abstract contract GapReaderBase is IGapReader {
    /// @notice `poke` on a reader that keeps no record (every reader but V2PairReader).
    error PokeUnsupported();

    /// @dev Only V2-style readers record (spec §5); the token's recordPrice ignores this revert.
    function poke(bytes32) external virtual {
        revert PokeUnsupported();
    }

    /// @dev The decimals of `token`; (false, 0) when it does not answer a uint8.
    function _decimals(address token) internal view returns (bool ok, uint8 d) {
        if (token == address(0)) return (true, 18);
        if (token.code.length == 0) return (false, 0);
        (bool success, bytes memory ret) = token.staticcall(abi.encodeWithSelector(IERC20Metadata.decimals.selector));
        if (!success || ret.length != 32) return (false, 0);
        uint256 v = abi.decode(ret, (uint256));
        if (v > type(uint8).max) return (false, 0);
        return (true, uint8(v));
    }

    /// @dev `p` if it is an answer the registry accepts, else 0.
    function _bounded(uint256 p) internal pure returns (uint256) {
        return p > GapMath.PRICE_MAX ? 0 : p;
    }

    /// @dev A v2/v3 pool address from a poolRef: the low 20 bytes, with the high 12 zero, and code.
    function _poolAddress(bytes32 poolRef) internal view returns (bool ok, address pool) {
        if (uint256(poolRef) >> 160 != 0) return (false, address(0));
        pool = address(uint160(uint256(poolRef)));
        ok = pool.code.length != 0;
    }

    /// @dev `token` as a v2/v3 pool names it: native (address(0)) is the wrapped native.
    function _wrapped(address token, address wrappedNative) internal pure returns (address) {
        return token == address(0) ? wrappedNative : token;
    }

    /// @dev One address-returning view of `target` (token0(), token1()); (false, 0) on any failure.
    function _addressCall(address target, bytes4 selector) internal view returns (bool ok, address a) {
        (bool success, bytes memory ret) = target.staticcall(abi.encodeWithSelector(selector));
        if (!success || ret.length < 32) return (false, address(0));
        uint256 w = abi.decode(ret, (uint256));
        if (w >> 160 != 0) return (false, address(0));
        return (true, address(uint160(w)));
    }

    /// @dev Which side `base` is on in a pool of (t0, t1): (true, baseIs0) when the pool is exactly
    ///      {base, quote}, (false, _) otherwise.
    function _sides(address base, address quote, address t0, address t1) internal pure returns (bool ok, bool baseIs0) {
        if (base == t0 && quote == t1) return (true, true);
        if (base == t1 && quote == t0) return (true, false);
        return (false, false);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
    "@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
    "@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v4-core/=lib/uniswap-v4-core/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "layerzero/=lib/layerzero/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/",
    "uniswap-v4-core/=lib/uniswap-v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.