Skip to content
Verified contractExactUNLICENSED

PangeaFeeHookV2M

Address0x1aef1467b4e4723996c01d31043d146c0cf6e8cc
Balance

0 ETH

 

Transactions

2

 

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,401,681
Creation transaction
0x58ca523fa3…069fb4dd7b

31 files

src/v3/PangeaFeeHookV2M.sol

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

import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, toBeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {SwapParams, ModifyLiquidityParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {FactoryList} from "../FactoryList.sol";
import {TermsV3, IFeeSplitterV3, IPangeaLaunchHookV2} from "./V3Shared.sol";

/// @title PangeaFeeHookV2M -- Hook V2 (hookv2-ready-20261107 @ 807b71cc6) merged with the v4 hook (PangeaFeeHookV4)
/// @notice MERGE (owner 2026-11-12): this file is src/v3/PangeaFeeHookV2.sol at 807b71cc6 with exactly these changes:
///   1. a THIRD fee-free swapper, `coreBuyer` = LaunchCoreV4's own BridgeBuyerV4 (`buyerOf(core)`: the first contract
///      the core proxy CREATEs, nonce 1), exactly as PangeaFeeHookV4 derives it -- so the v4 core's launch buys and
///      creator first buys pay no fee on this hook as they did on 0x2243..8cC. `core` and `coreBuyer` are immutable,
///      constructor-derived; no config value or admin can name another. `_free` = devBuyer || launchBuyer || coreBuyer.
///   2. the constructor takes `core_` (nonzero) after `locker_`.
///   `launchBuyer` keeps Hook V2's meaning (the chain's v3 LaunchBuys), which factory v3's allowLaunchHook checks.
///   Nothing else changed: fee model, setFee/delay machinery, gap record, range edge, flags, storage order.
///
/// (Hook V2's notes follow.)
/// @title PangeaFeeHookV2
/// @notice PangeaFeeHook with a fee that can move. Everything the live hook does, it does the same
///         way, with the same six permission bits, the same `register`, and `configs`/`factoryOf`
///         in the same shape (TokenomicsVault reads them). Three things are new:
///
///   1. `setFee(key, feeBps)`: the pool's payee (its splitter's `creator`) or the platform admin
///      (`factoryAdmin`) moves the pool's fee anywhere in [MIN_FEE_BPS, MAX_FEE_BPS].
///   2. A second fee-free swapper, `launchBuyer` (this chain's LaunchBuys), beside `devBuyer`.
///   3. `feeDelayBlocks`, fixed at construction: 0 (the default) and a change takes effect in the
///      transaction that makes it; N and it takes effect N blocks later. The second is the
///      fallback kept ready in case Uniswap's hook review objects to an instant change.
///
/// The live hook's notes, all still true here, are in src/venues/PangeaFeeHook.sol and
/// FEE-HOOK-REVIEW.md. What follows is only what changed.
///
/// A FEE CHANGE NEVER RE-PRICES WHAT WAS ALREADY EARNED. The splitter divides what it holds by its
/// own rate: the platform takes a fifth of the fee or 0.2% of volume, whichever is more, and it
/// works volume out from the amount and the rate. So fees earned at 0.3% and divided at 5% would
/// give the platform a fifth of them instead of two thirds -- 0.06% of that volume rather than
/// 0.2%. A change therefore runs in this order, and never another:
///
///   1. every claim this pool has earned at the old rate is redeemed to its splitter;
///   2. `splitter.setFeeBps(quote, new)`: the splitter pays out everything it holds at the old
///      rate, then switches;
///   3. the hook stores the new rate, and every swap from then on is charged it.
///
/// No fee earned at one rate reaches the splitter while it is dividing at the other.
///
/// WITH A DELAY, THE SAME ORDER, LATER. `setFee` only schedules the new rate (`pendingFeeOf`), for
/// `block.number + feeDelayBlocks`. From that block every swap is charged it -- but a swap runs
/// inside the PoolManager's lock, where nothing can be redeemed, so the claims earned at the new
/// rate before the switch has been settled are kept apart (`owedAtPending`). The switch itself --
/// steps 1 to 3 above, then the kept-apart claims joining `owed` -- runs on the next `applyFee`,
/// `redeem` or `setFee` for the pool, whichever comes first; `applyFee` is anyone's. Until it runs
/// `configs(id).feeBps` still shows the old rate; `feeOf(id)` is the rate a swap pays now.
///
/// A SPLITTER THAT REFUSES THE SWITCH LOCKS NOTHING. `redeem` runs the settlement as its own call
/// (`settleDue`) and, if the splitter refuses, rolls back only that: it still redeems every
/// old-rate claim to the splitter (which still divides at the old rate) and keeps the new-rate
/// claims held in `owedAtPending` until a settlement goes through. `applyFee` and a payee's next
/// `setFee` revert while the splitter refuses. The platform admin may `cancelPendingFee`: the
/// scheduled rate is dropped and its held claims join `owed`, to be divided at the rate the
/// splitter is still on -- the one remedy left when a splitter will not switch, and the admin's.
///
/// NO SWAP RUNS WHILE A FEE IS MOVING. `setFee`, `applyFee`, `redeem` and `cancelPendingFee`
/// call out (the PoolManager, the splitter, and through it the payee). A swap from inside one of
/// them would be charged at one rate between the redeem and the store and divided at the other, so
/// `beforeSwap` refuses every swap while any of them is running. And the other way round: none of
/// them runs while a swap is between its `beforeSwap` and its `afterSwap` (`FeeChangeDuringSwap`):
/// the swap's one external call (the token's price record) could otherwise settle or move the rate
/// after the swap was charged one and before its other half is booked (hookv2-ready I-1).
///
/// THE DELAY COUNTS `block.number`, WHICH IS NOT THE SAME CLOCK EVERYWHERE. On Ethereum, Base and
/// BSC it is the chain's own block (about 12 s, 2 s and under a second). On Robinhood Chain, an
/// Arbitrum chain, `block.number` is the PARENT chain's block number as last seen by the
/// sequencer, so many of its own blocks share one value and "one block" is one parent block, about
/// 12 s. Blocks rather than seconds on purpose: what the fallback promises is that a change never
/// applies in the block (by `block.number`) that made it -- so a trade sent before or alongside
/// a change, and every quote taken in that block, pays the rate it saw -- and `block.number`
/// gives exactly that on all four chains. A timestamp would need a number of seconds chosen per
/// chain, and on Arbitrum many blocks share a timestamp too. The default is no delay at all.
///
/// ONE CHANGE PER POOL PER BLOCK, WITH NO DELAY. Without it a payee contract could, in one
/// transaction, drop its pool to 0.3%, trade, and put it back to 5%: its own trades charged at the
/// floor -- where the platform's cut is 0.2% of volume, against a fifth of 5% at the ceiling -- on a
/// pool everybody else sees at 5%. So a no-delay `setFee` is refused in a block where the pool's
/// fee already changed (`lastChangeBlock`), whoever makes it: payee and admin share the count. With
/// a delay the rule is not needed (nothing takes effect inside the block that schedules it) and
/// scheduling, replacing and cancelling within a block stay possible.
///
/// THE PAYEE AND THE ADMIN ARE PEERS: LAST WRITER WINS. Either may change the fee, and the later
/// change replaces the earlier -- nothing gives one precedence. A change scheduled (delay mode) by
/// a payee the platform has since rotated out of the splitter still applies when it falls due; the
/// admin can `cancelPendingFee` it, and the new payee can replace it.
///
/// WHO MAY CHANGE IT, AND WHAT THAT MEANS FOR A TRADER. The payee -- the address the pool's fees
/// are for -- and the platform admin. Neither can take more than MAX_FEE_BPS, change where the
/// fees go, touch the range, the liquidity or a registered pool's splitter. What an instant change
/// does allow is a payee raising the fee in front of a pending trade; the trader's own slippage
/// bound (every router sets one) caps what that can cost them, and the delay mode takes it away.
///
/// TWO SWAPPERS PAY NOTHING. `devBuyer` (this chain's LaunchFeeCollector, the dev buy) as before,
/// and `launchBuyer` (this chain's LaunchBuys, the launch buys a creator pays for with the launch).
/// Both are constructor arguments, immutable, and part of the init code. Why that is safe is the
/// same for both: `sender` is the address that called `poolManager.swap`, which nobody can
/// pretend to be, and each of the two swaps only from its own unlock callback, inside a launch,
/// for that launch's pool -- neither swaps for a caller or takes a pool key from one.
///
/// Why a constructor argument and not "settable once". Under CREATE3 the address does not depend
/// on the init code, so a constructor argument costs the mined address nothing; it keeps the
/// exemption a storage-free compare on every swap; and it leaves no window in which an admin key
/// could exempt an address of its choosing. The cost: LaunchBuys must exist first, and a new
/// LaunchBuys means a new hook.
/// @dev Implements IPangeaLaunchHookV2 (and so IPangeaLaunchHook) without naming it as a base: the
///      interface declares `isFactory(address)` and FactoryList answers it with a public mapping,
///      which Solidity will not let a contract inherit alongside the interface's function, and
///      FactoryList is shared with the live hook, locker and collector, whose code hashes a change
///      there would move. The conformance is pinned by test instead (selector for selector, the
///      interface ids, and every call through the interface); `FeeChanged` is the interface's own
///      event, emitted by its qualified name, so it cannot drift.
contract PangeaFeeHookV2M is IHooks, IUnlockCallback, ReentrancyGuardTransient, FactoryList {
    using CurrencyLibrary for Currency;
    using StateLibrary for IPoolManager;

    /// @notice The six permissions this hook needs, which its address must encode: exactly the
    ///         live hook's, which is what `setLaunchHook` on factory v3 requires.
    uint160 public constant MINED_FLAGS = TermsV3.HOOK_FLAGS;

    uint256 internal constant BPS = 10_000;

    /// @notice The bounds a pool's fee must sit within, at registration and at every change. The
    ///         same two numbers the splitter enforces.
    uint16 public constant MIN_FEE_BPS = 30;
    uint16 public constant MAX_FEE_BPS = 500;

    /// @notice The most of a splitter's revert reason `SettleFailed` carries.
    uint256 internal constant MAX_REASON_BYTES = 256;

    /// @notice The longest delay a hook may be built with: a day of 12-second blocks.
    uint256 public constant MAX_FEE_DELAY_BLOCKS = 7_200;

    IPoolManager public immutable poolManager;

    /// @notice The key that deployed this hook, and its first `factoryAdmin`. Under CREATE3 the
    ///         deploying contract is CreateX's proxy, so this is an argument, not `msg.sender`.
    address public immutable deployer;

    // Storage in the live hook's order (FactoryList's three slots, then these), so a reader of
    // its slots -- and the tests that read them -- reads this one the same way.

    /// @notice The factory that registered each pool. Written once, with the pool's config.
    mapping(PoolId => address) public factoryOf;

    struct Config {
        /// @notice Where this pool's fees go: a FeeSplitterV3 whose `hook` is this contract.
        address splitter;
        /// @notice Which side of the pair is the money.
        bool quoteIsCurrency0;
        /// @notice The fee the pool's splitter divides by, in bps. With no delay, the fee every
        ///         swap is charged. The pool itself charges nothing.
        uint16 feeBps;
        bool registered;
        /// @notice The edge of the launch's range on its empty side (see PangeaFeeHook).
        int24 edgeTick;
    }

    mapping(PoolId => Config) public configs;

    /// @notice Addresses besides the locker that may ADD liquidity, set by `factoryAdmin`.
    mapping(address => bool) public isLiquidityAdder;

    /// @notice Claims accrued per pool, per currency, at the pool's `configs` rate, waiting to be
    ///         redeemed into real tokens.
    mapping(PoolId => mapping(Currency => uint256)) public owed;

    /// @notice Delay mode only: claims accrued at a pending rate that has taken effect, before the
    ///         switch has been settled with the splitter. They join `owed` when it is.
    mapping(PoolId => mapping(Currency => uint256)) public owedAtPending;

    struct PendingFee {
        /// @notice The rate scheduled. Meaningless when `fromBlock` is zero.
        uint16 feeBps;
        /// @notice The first block that is charged it. Zero: nothing scheduled.
        uint64 fromBlock;
        /// @notice Who scheduled it, for the `FeeChanged` event when the switch is settled.
        address by;
    }

    /// @notice Delay mode only: each pool's scheduled rate.
    mapping(PoolId => PendingFee) public pendingFee;

    /// @notice No delay only: the block of each pool's last fee change. See "ONE CHANGE PER POOL
    ///         PER BLOCK".
    mapping(PoolId => uint256) public lastChangeBlock;

    /// @notice Whether a pool's fee has ever been changed since it was registered: a `setFee` that
    ///         moved the rate (no delay) or scheduled a change (delay mode). A setFee to the rate in
    ///         force, or one that only cancels a pending change, leaves it as it was (xa-dvn-hooks I-4). The v3 token prices the gap fee's allowance at the
    ///         fee in force at its price records; before its first record it has none, and this
    ///         says whether the registered (launch) fee still stands (round-4 audit M-1).
    mapping(PoolId => bool) public feeChanged;

    /// @notice The only address that may add liquidity besides `isLiquidityAdder`: this chain's
    ///         LiquidityLocker.
    address public immutable locker;

    /// @notice This chain's LaunchFeeCollector, which makes each launch's dev buy: charged nothing.
    address public immutable devBuyer;

    /// @notice This chain's LaunchBuys, which makes each launch's launch buys: charged nothing.
    address public immutable launchBuyer;

    /// @notice Blocks between `setFee` and the first swap charged the new rate. 0: none.
    uint256 public immutable feeDelayBlocks;

    /// @notice MERGE: the LaunchCoreV4 (proxy) whose own buyer is free, and that buyer (CREATE by `core`, nonce 1).
    address public immutable core;
    address public immutable coreBuyer;

    event Registered(PoolId indexed id, address splitter, uint16 feeBps, bool quoteIsCurrency0, int24 edgeTick);
    event Redeemed(PoolId indexed id, Currency currency, uint256 amount, address to);
    event FeeTaken(PoolId indexed id, Currency currency, uint256 amount);
    event LiquidityAdderSet(address indexed adder, bool allowed);
    // FeeChanged(id, fromBps, toBps, by) is IPangeaLaunchHookV2's: the rate the splitter divides by
    // (and, with no delay, every swap is charged) moved. In delay mode it is emitted when the
    // switch is settled, with `by` the address that scheduled it.
    /// @notice Delay mode: `toBps` is charged from block `fromBlock`.
    event FeeScheduled(PoolId indexed id, uint16 fromBps, uint16 toBps, uint64 fromBlock, address by);
    /// @notice Delay mode: the scheduled rate `bps` was dropped -- by scheduling the rate in force,
    ///         or by the admin (`cancelPendingFee`).
    event FeeChangeCancelled(PoolId indexed id, uint16 bps, address by);
    /// @notice Delay mode: `redeem` could not settle a due change (the splitter refused the
    ///         switch). The old-rate claims were redeemed anyway; the new-rate ones stay held.
    event SettleFailed(PoolId indexed id, bytes reason);

    error NotPoolManager();
    error NotFactory();
    error NotDeployer();
    error AlreadyRegistered();
    error NotRegistered();
    error WrongFlags(uint160 have, uint160 want);
    error HookNotImplemented();
    error NothingOwed();
    error ZeroSplitter();
    error PartialFill(uint256 asked, uint256 traded);
    error ZeroAddress();
    error NothingSwapped();
    error WrongHook(address hooks);
    error PoolFeeNotZero(uint24 fee);
    error FeeOutOfRange(uint16 feeBps);
    error OnlyLocker(address sender);
    error OutOfRange(int24 tick, int24 edgeTick);
    error OpensOutOfRange(uint160 sqrtPriceX96, int24 edgeTick);
    /// @notice `setFee` from someone who is neither the pool's payee nor the platform admin.
    error NotPayeeOrAdmin(address caller);
    /// @notice The pool's splitter does not name this hook, so it would refuse `setFeeBps`.
    error SplitterNotOurs(address splitter);
    error DelayTooLong(uint256 blocks);
    /// @notice `applyFee` with nothing scheduled that has taken effect.
    error NothingToApply();
    /// @notice `cancelPendingFee` with nothing scheduled.
    error NothingPending();
    /// @notice A second no-delay fee change on one pool in one block.
    error OneChangePerBlock();
    /// @notice `settleDue` from anyone but this contract.
    error NotSelf();
    /// @notice A swap while this hook is changing, settling or redeeming a pool's fee: it would be
    ///         charged one rate and divided at another.
    error SwapDuringFeeChange();
    /// @notice `setFee`, `applyFee`, `redeem` or `cancelPendingFee` from inside a swap on this hook
    ///         (between its beforeSwap and its afterSwap): see "NO SWAP RUNS WHILE A FEE IS MOVING".
    error FeeChangeDuringSwap();

    /// @dev How many swaps on this hook are between their beforeSwap and their afterSwap (transient:
    ///      this transaction only, and a reverted swap rolls its count back). A count, not a flag, so a
    ///      swap nested inside another's price record does not clear the outer one's.
    uint256 private transient _swapsOpen;

    /// @dev The fee functions refuse to run inside a swap (hookv2-ready I-1).
    modifier notInSwap() {
        if (_swapsOpen != 0) revert FeeChangeDuringSwap();
        _;
    }

    constructor(
        address poolManager_,
        address deployer_,
        address devBuyer_,
        address launchBuyer_,
        address locker_,
        address core_,
        uint256 feeDelayBlocks_
    ) {
        uint160 flags = uint160(address(this)) & Hooks.ALL_HOOK_MASK;
        if (flags != MINED_FLAGS) revert WrongFlags(flags, MINED_FLAGS);

        if (
            poolManager_ == address(0) || deployer_ == address(0) || devBuyer_ == address(0)
                || launchBuyer_ == address(0) || locker_ == address(0) || core_ == address(0)
        ) revert ZeroAddress();
        if (feeDelayBlocks_ > MAX_FEE_DELAY_BLOCKS) revert DelayTooLong(feeDelayBlocks_);
        poolManager = IPoolManager(poolManager_);
        deployer = deployer_;
        devBuyer = devBuyer_;
        launchBuyer = launchBuyer_;
        locker = locker_;
        feeDelayBlocks = feeDelayBlocks_;
        core = core_;
        coreBuyer = buyerOf(core_);
        _initFactoryAdmin(deployer_);
    }

    /// @notice Allow or stop `adder` adding liquidity to the pools this hook serves. The factory
    ///         admin only. As on the live hook.
    function setLiquidityAdder(address adder, bool allowed) external onlyFactoryAdmin {
        if (adder == address(0)) revert ZeroAddress();
        isLiquidityAdder[adder] = allowed;
        emit LiquidityAdderSet(adder, allowed);
    }

    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /// @notice Record a pool, exactly as the live hook does. Once only; the splitter, the side and
    ///         the edge are fixed from then on. The fee is the starting fee; `setFee` moves it.
    function register(
        PoolKey calldata key,
        address splitter,
        bool quoteIsCurrency0,
        uint16 feeBps,
        int24 edgeTick
    ) external {
        if (!isFactory[msg.sender]) revert NotFactory();
        if (splitter == address(0)) revert ZeroSplitter();
        if (address(key.hooks) != address(this)) revert WrongHook(address(key.hooks));
        if (key.fee != 0) revert PoolFeeNotZero(key.fee);
        if (feeBps < MIN_FEE_BPS || feeBps > MAX_FEE_BPS) revert FeeOutOfRange(feeBps);

        PoolId id = key.toId();
        if (configs[id].registered) revert AlreadyRegistered();

        configs[id] = Config({
            splitter: splitter,
            quoteIsCurrency0: quoteIsCurrency0,
            feeBps: feeBps,
            registered: true,
            edgeTick: edgeTick
        });
        factoryOf[id] = msg.sender;
        emit Registered(id, splitter, feeBps, quoteIsCurrency0, edgeTick);
    }

    // ------------------------------------------------------------ the fee

    /// @notice Move a pool's fee to `feeBps`, inside [MIN_FEE_BPS, MAX_FEE_BPS]. The pool's payee
    ///         (its splitter's `creator`) or the platform admin (`factoryAdmin`) only.
    /// @dev With no delay: redeem, `splitter.setFeeBps`, store -- see "A FEE CHANGE NEVER
    ///      RE-PRICES". With a delay: settle any scheduled rate that has already taken effect, then
    ///      schedule this one, replacing one that has not. Scheduling the rate already in force
    ///      cancels a pending change (`FeeChangeCancelled`). While a due change cannot be settled
    ///      (its splitter refuses) this reverts; see "A SPLITTER THAT REFUSES".
    ///
    ///      Reverts inside a PoolManager unlock when the pool has claims to redeem (v4 refuses a
    ///      nested unlock); there is nothing to settle at the old rate in the case it lets through.
    function setFee(PoolKey calldata key, uint16 feeBps) external nonReentrant notInSwap {
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        if (feeBps < MIN_FEE_BPS || feeBps > MAX_FEE_BPS) revert FeeOutOfRange(feeBps);
        // Read live: a payee the platform has moved (the splitter's two-step) moves this right too.
        if (msg.sender != IFeeSplitterV3(c.splitter).creator() && msg.sender != factoryAdmin) {
            revert NotPayeeOrAdmin(msg.sender);
        }
        // The splitter takes `setFeeBps` from its own hook only. Checked here so a pool whose
        // splitter is not ours fails at the change rather than, in delay mode, at a later redeem.
        if (IFeeSplitterV3(c.splitter).hook() != address(this)) revert SplitterNotOurs(c.splitter);

        if (feeDelayBlocks == 0) {
            // The rate in force: nothing to do (hookv2-ready I-2). It neither uses the block's one
            // change nor redeems, and it leaves `feeChanged` as it was (xa-dvn-hooks I-4).
            if (feeBps == c.feeBps) return;
            if (lastChangeBlock[id] == block.number) revert OneChangePerBlock();
            lastChangeBlock[id] = block.number;
            if (!feeChanged[id]) feeChanged[id] = true;
            _switch(key, id, c, feeBps, msg.sender);
            return;
        }

        if (_due(pendingFee[id])) (c,) = _applyDue(key, id, c);
        if (feeBps == c.feeBps) {
            // The rate in force: nothing to schedule, and a pending change is cancelled.
            PendingFee memory p = pendingFee[id];
            if (p.fromBlock != 0) {
                delete pendingFee[id];
                emit FeeChangeCancelled(id, p.feeBps, msg.sender);
            }
            return;
        }
        // A change is scheduled: the pool is marked (a cancel-only call above never marks it).
        if (!feeChanged[id]) feeChanged[id] = true;
        uint64 fromBlock = uint64(block.number + feeDelayBlocks);
        pendingFee[id] = PendingFee({feeBps: feeBps, fromBlock: fromBlock, by: msg.sender});
        emit FeeScheduled(id, c.feeBps, feeBps, fromBlock, msg.sender);
    }

    /// @notice Delay mode: settle a scheduled rate that has taken effect -- redeem what was earned
    ///         at the old rate, switch the splitter, store the rate. Anyone may call it; `redeem`
    ///         and `setFee` do it too.
    function applyFee(PoolKey calldata key) external nonReentrant notInSwap {
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        if (!_due(pendingFee[id])) revert NothingToApply();
        _applyDue(key, id, c);
    }

    /// @notice Delay mode: drop a pool's scheduled rate, due or not. The platform admin only -- the
    ///         remedy for a splitter that refuses the switch. Claims already charged at the
    ///         scheduled rate join `owed`, divided at the rate the splitter is on.
    function cancelPendingFee(PoolKey calldata key) external nonReentrant notInSwap onlyFactoryAdmin {
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        PendingFee memory p = pendingFee[id];
        if (p.fromBlock == 0) revert NothingPending();
        delete pendingFee[id];
        _joinOwed(key, id, c);
        emit FeeChangeCancelled(id, p.feeBps, msg.sender);
    }

    /// @notice `redeem`'s settlement of a due change, as a call of its own so a splitter that
    ///         refuses rolls back the settlement only. This contract alone may call it.
    /// @dev Not `nonReentrant`: it runs inside `redeem`, which holds the guard.
    function settleDue(PoolKey calldata key) external returns (bool switched) {
        if (msg.sender != address(this)) revert NotSelf();
        PoolId id = key.toId();
        (, switched) = _applyDue(key, id, configs[id]);
    }

    /// @notice The rate a swap on this pool is charged now (before any exemption): THE read for
    ///         anyone pricing a trade or showing the fee. `configs(id).feeBps` is the rate the
    ///         splitter divides by, which lags it in delay mode until a change is settled.
    function feeOf(PoolId id) external view returns (uint16) {
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        (uint16 f,) = _feeNow(id, c.feeBps);
        return f;
    }

    /// @notice Every claim the pool has earned and not yet redeemed, in `currency`: `owed` plus,
    ///         in delay mode, what is held at a pending rate (`owedAtPending`).
    function owedNow(PoolId id, Currency currency) external view returns (uint256) {
        return owed[id][currency] + owedAtPending[id][currency];
    }

    /// @notice The rate scheduled for a pool and the first block charged it, or (0, 0).
    function pendingFeeOf(PoolId id) external view returns (uint16 feeBps, uint64 fromBlock) {
        PendingFee memory p = pendingFee[id];
        return p.fromBlock == 0 ? (uint16(0), uint64(0)) : (p.feeBps, p.fromBlock);
    }

    /// @dev Delay mode: the scheduled rate has taken effect but has not been settled.
    function _due(PendingFee memory p) internal view returns (bool) {
        return p.fromBlock != 0 && block.number >= p.fromBlock;
    }

    /// @dev The rate charged now, and whether it is a pending one that has taken effect (whose
    ///      claims go to `owedAtPending`). With no delay, `configs` and nothing else, for no
    ///      storage read beyond the one every swap already makes.
    function _feeNow(PoolId id, uint16 configured) internal view returns (uint16, bool) {
        if (feeDelayBlocks == 0) return (configured, false);
        PendingFee memory p = pendingFee[id];
        if (_due(p)) return (p.feeBps, true);
        return (configured, false);
    }

    /// @dev Settle the due pending rate: the old-rate claims out, the splitter switched, the rate
    ///      stored, and the claims earned at the new rate since it took effect moved into `owed`.
    ///      A pending rate equal to the one in force (`setFee` no longer schedules one, but the
    ///      rule holds whatever got there) has nothing to settle: its claims just join `owed`.
    ///      Returns whether the switch -- and with it the redeem of the old-rate claims -- ran.
    function _applyDue(PoolKey calldata key, PoolId id, Config memory c) internal returns (Config memory, bool switched) {
        PendingFee memory p = pendingFee[id];
        delete pendingFee[id];
        switched = p.feeBps != c.feeBps;
        if (switched) _switch(key, id, c, p.feeBps, p.by);
        _joinOwed(key, id, c);
        c.feeBps = p.feeBps;
        return (c, switched);
    }

    /// @dev The claims held at a pending rate join `owed`.
    function _joinOwed(PoolKey calldata key, PoolId id, Config memory c) internal {
        Currency quote = c.quoteIsCurrency0 ? key.currency0 : key.currency1;
        uint256 later = owedAtPending[id][quote];
        if (later != 0) {
            owedAtPending[id][quote] = 0;
            owed[id][quote] += later;
        }
    }

    /// @dev Steps 1 to 3: redeem at the old rate, the splitter settles and switches, store.
    function _switch(PoolKey calldata key, PoolId id, Config memory c, uint16 feeBps, address by) internal {
        _redeem(key, id, c.splitter);
        Currency quote = c.quoteIsCurrency0 ? key.currency0 : key.currency1;
        IFeeSplitterV3(c.splitter).setFeeBps(Currency.unwrap(quote), feeBps);
        configs[id].feeBps = feeBps;
        emit IPangeaLaunchHookV2.FeeChanged(id, c.feeBps, feeBps, by);
    }

    // ------------------------------------------------------------ redeeming

    /// @notice Turn a pool's accrued claims into real tokens, sent to its splitter. Permissionless,
    ///         as on the live hook. In delay mode a rate that has taken effect is settled first,
    ///         and the amounts returned include the old-rate claims that settlement redeemed.
    /// @dev `NothingOwed` only when nothing was redeemed AND nothing was settled. A settlement with
    ///      nothing else owed is a redeem that did its work: reverting it would roll the switch
    ///      back, and a caller that tries it and ignores failure -- TokenomicsVault's `_pull` -- would
    ///      leave the change unsettled and the old-rate claims in the hook. A settlement the
    ///      splitter refuses is rolled back alone (`settleDue` is its own call): the old-rate claims
    ///      are still redeemed, and `SettleFailed` says why the switch did not happen.
    function redeem(PoolKey calldata key) external nonReentrant notInSwap returns (uint256 amount0, uint256 amount1) {
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        bool settled;
        uint256 old0;
        uint256 old1;
        if (feeDelayBlocks != 0 && _due(pendingFee[id])) {
            // What the settlement's own redeem sends: everything owed at the old rate, now.
            old0 = owed[id][key.currency0];
            old1 = owed[id][key.currency1];
            try this.settleDue(key) returns (bool switched) {
                settled = true;
                // Only a switch redeemed them; a same-rate entry left them in `owed` for below.
                if (!switched) (old0, old1) = (0, 0);
            } catch (bytes memory reason) {
                // Rolled back: the old-rate claims are still in `owed` and go out below, at the
                // rate the splitter is still on; the new-rate ones stay held.
                (old0, old1) = (0, 0);
                // At most 256 bytes of whatever the splitter reverted with.
                if (reason.length > MAX_REASON_BYTES) {
                    assembly ("memory-safe") {
                        mstore(reason, MAX_REASON_BYTES)
                    }
                }
                emit SettleFailed(id, reason);
            }
        }
        (amount0, amount1) = _redeem(key, id, c.splitter);
        amount0 += old0;
        amount1 += old1;
        if (!settled && amount0 == 0 && amount1 == 0) revert NothingOwed();
    }

    /// @dev Everything `owed` for the pool, to its splitter. Nothing owed: nothing done.
    function _redeem(PoolKey calldata key, PoolId id, address splitter) internal returns (uint256 amount0, uint256 amount1) {
        amount0 = owed[id][key.currency0];
        amount1 = owed[id][key.currency1];
        if (amount0 == 0 && amount1 == 0) return (0, 0);

        // Cleared before the unlock, so a currency that re-enters cannot be redeemed twice.
        if (amount0 > 0) owed[id][key.currency0] = 0;
        if (amount1 > 0) owed[id][key.currency1] = 0;

        poolManager.unlock(abi.encode(key, splitter, amount0, amount1));

        if (amount0 > 0) emit Redeemed(id, key.currency0, amount0, splitter);
        if (amount1 > 0) emit Redeemed(id, key.currency1, amount1, splitter);
    }

    /// @inheritdoc IUnlockCallback
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (PoolKey memory key, address to, uint256 amount0, uint256 amount1) =
            abi.decode(data, (PoolKey, address, uint256, uint256));

        if (amount0 > 0) {
            poolManager.burn(address(this), key.currency0.toId(), amount0);
            poolManager.take(key.currency0, to, amount0);
        }
        if (amount1 > 0) {
            poolManager.burn(address(this), key.currency1.toId(), amount1);
            poolManager.take(key.currency1, to, amount1);
        }
        return "";
    }

    // ------------------------------------------------------------ the swap

    /// @dev The dev buy, the launch buys and (MERGE) the v4 core's launch / dev buys pay nothing.
    function _free(address sender) internal view returns (bool) {
        return sender == devBuyer || sender == launchBuyer || sender == coreBuyer;
    }

    /// @notice MERGE (as PangeaFeeHookV4.buyerOf): the core's own BridgeBuyerV4, the first contract `core_` CREATEs
    ///         (nonce 1).
    function buyerOf(address core_) public pure returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), core_, bytes1(0x01))))));
    }

    /// @dev Mint `fee` of `quote` as this contract's claim and book it: to `owed`, or, for a
    ///      pending rate in force but not yet settled, to `owedAtPending`.
    function _take(PoolId id, Currency quote, uint256 fee, bool atPending) internal {
        poolManager.mint(address(this), quote.toId(), fee);
        if (atPending) owedAtPending[id][quote] += fee;
        else owed[id][quote] += fee;
        emit FeeTaken(id, quote, fee);
    }

    /// @inheritdoc IHooks
    /// @dev Takes the fee when the quote is the specified currency -- a buy, for an exact-in swap.
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
        external
        onlyPoolManager
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        // See "NO SWAP RUNS WHILE A FEE IS MOVING": the guard is held by setFee, applyFee, redeem
        // and cancelPendingFee, and by nothing on the swap path.
        if (_reentrancyGuardEntered()) revert SwapDuringFeeChange();
        // Open until this swap's afterSwap (every swap on this hook reaches it: both flags are mined).
        _swapsOpen += 1;
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();
        // The price before this swap, for the token's record in afterSwap (transient: this swap only).
        {
            (uint160 pre,,,) = poolManager.getSlot0(id);
            bytes32 slot = _preSlot(id);
            assembly ("memory-safe") {
                tstore(slot, pre)
            }
        }

        bool exactIn = params.amountSpecified < 0;
        Currency specified = exactIn
            ? (params.zeroForOne ? key.currency0 : key.currency1)
            : (params.zeroForOne ? key.currency1 : key.currency0);
        Currency quote = c.quoteIsCurrency0 ? key.currency0 : key.currency1;

        if (Currency.unwrap(specified) != Currency.unwrap(quote)) {
            return (IHooks.beforeSwap.selector, toBeforeSwapDelta(0, 0), 0);
        }
        if (_free(sender)) return (IHooks.beforeSwap.selector, toBeforeSwapDelta(0, 0), 0);

        (uint16 feeBps, bool atPending) = _feeNow(id, c.feeBps);
        uint256 amount = uint256(exactIn ? -params.amountSpecified : params.amountSpecified);
        uint256 fee = _fee(amount, feeBps, !exactIn);
        if (fee == 0) return (IHooks.beforeSwap.selector, toBeforeSwapDelta(0, 0), 0);

        _take(id, quote, fee, atPending);
        return (IHooks.beforeSwap.selector, toBeforeSwapDelta(int128(uint128(fee)), 0), 0);
    }

    /// @inheritdoc IHooks
    /// @dev Takes the fee when the quote is the unspecified currency -- a sell, for an exact-in
    ///      swap -- and holds every swap to the launch's range.
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata
    ) external onlyPoolManager returns (bytes4, int128) {
        PoolId id = key.toId();
        Config memory c = configs[id];
        if (!c.registered) revert NotRegistered();

        if (delta.amount0() == 0 && delta.amount1() == 0) revert NothingSwapped();

        // The same block as beforeSwap, so the same rate; read ONCE, before the record's external
        // call, and nothing can move it during that call (notInSwap; hookv2-ready I-1).
        (uint16 feeBps, bool atPending) = _feeNow(id, c.feeBps);
        {
            (uint160 post, int24 tick,,) = poolManager.getSlot0(id);
            if (c.quoteIsCurrency0 ? tick >= c.edgeTick : tick < c.edgeTick) revert OutOfRange(tick, c.edgeTick);
            _record(key, id, c.quoteIsCurrency0, post, feeBps);
        }
        // The record was the swap's last call out: the swap is closed for the fee functions again.
        _swapsOpen -= 1;

        bool exactIn = params.amountSpecified < 0;
        Currency specified = exactIn
            ? (params.zeroForOne ? key.currency0 : key.currency1)
            : (params.zeroForOne ? key.currency1 : key.currency0);
        Currency quote = c.quoteIsCurrency0 ? key.currency0 : key.currency1;
        bool free = _free(sender);

        if (Currency.unwrap(specified) == Currency.unwrap(quote)) {
            _requireFullFill(params.amountSpecified, c.quoteIsCurrency0 ? delta.amount0() : delta.amount1(), free ? 0 : feeBps);
            return (IHooks.afterSwap.selector, 0);
        }

        int128 quoteDelta = c.quoteIsCurrency0 ? delta.amount0() : delta.amount1();
        uint256 moved = uint256(uint128(quoteDelta < 0 ? -quoteDelta : quoteDelta));
        if (moved == 0 || free) return (IHooks.afterSwap.selector, 0);

        uint256 fee = _fee(moved, feeBps, !exactIn);
        if (fee == 0) return (IHooks.afterSwap.selector, 0);

        _take(id, quote, fee, atPending);
        return (IHooks.afterSwap.selector, int128(uint128(fee)));
    }

    // ------------------------------------------------------------- the v3 gap fee's price record

    /// @notice The gas `recordPrice` is given on every swap: a v3 token's first record copies its
    ///         official pool from the registry (and reads its quote's decimals) and writes five slots.
    uint256 public constant RECORD_GAS = 250_000;

    /// @notice A swap left with less gas than its record needs reverts (`RecordGasTooLow`): a record
    ///         can never be skipped by the gas the swapper chose (owner 2026-10-28, v3 audit H-1/H-2).
    error RecordGasTooLow(uint256 needed, uint256 left);

    /// @dev `token.recordPrice(poolId, sqrtBefore, sqrtAfter, feeBps)` (PangeaOFTV3, through its gap
    ///      module), `feeBps` the rate this swap is charged (round-4 audit M-1: the token prices
    ///      the gap fee's allowance at the lowest of the fee now and the fees at its two closes):
    ///      the v3 gap fee's price record, made HERE, at swap time, so a record is a real swap's
    ///      outcome in the order the swaps ran -- never a transfer the swapper orders. Called on every
    ///      swap of every pool on this hook, with RECORD_GAS and its result ignored: a token that is
    ///      not a v3 token, or a pool that is not its official one, answers with a revert, which
    ///      changes nothing. The gas is required up front, so the call cannot be starved.
    function _record(PoolKey calldata key, PoolId id, bool quoteIsCurrency0, uint160 post, uint16 feeBps) internal {
        uint256 need = (RECORD_GAS * 64) / 63 + 5_000;
        uint256 left = gasleft();
        if (left < need) revert RecordGasTooLow(need, left);
        address token = Currency.unwrap(quoteIsCurrency0 ? key.currency1 : key.currency0);
        bytes32 slot = _preSlot(id);
        uint160 pre;
        assembly ("memory-safe") {
            pre := tload(slot)
        }
        bytes memory data = abi.encodeWithSelector(RECORD_PRICE, PoolId.unwrap(id), pre, post, feeBps);
        assembly ("memory-safe") {
            pop(call(RECORD_GAS, token, 0, add(data, 32), mload(data), 0, 0))
        }
    }

    /// @dev recordPrice(bytes32,uint160,uint160,uint16).
    bytes4 internal constant RECORD_PRICE = bytes4(keccak256("recordPrice(bytes32,uint160,uint160,uint16)"));

    /// @dev Where beforeSwap leaves the pool's pre-swap price for afterSwap (transient storage).
    function _preSlot(PoolId id) internal pure returns (bytes32) {
        return keccak256(abi.encode(PoolId.unwrap(id), "pangea.hook.v2.pre"));
    }

    /// @dev A quote-specified swap must trade exactly the request less (exact-in) or plus
    ///      (exact-out) the fee charged on it up front. See PangeaFeeHook.
    function _requireFullFill(int256 amountSpecified, int128 quoteDelta, uint16 feeBps) internal pure {
        bool exactIn = amountSpecified < 0;
        uint256 asked = uint256(exactIn ? -amountSpecified : amountSpecified);
        uint256 fee = _fee(asked, feeBps, !exactIn);
        uint256 traded = uint256(uint128(quoteDelta < 0 ? -quoteDelta : quoteDelta));
        if (traded != (exactIn ? asked - fee : asked + fee)) revert PartialFill(asked, traded);
    }

    /// @dev `feeBps` of the gross amount, given either the gross amount itself or the net one.
    ///      Rounds down both ways, so the trader is never charged more than the rate.
    function _fee(uint256 amount, uint16 feeBps, bool amountIsNet) internal pure returns (uint256) {
        return amountIsNet ? (amount * feeBps) / (BPS - feeBps) : (amount * feeBps) / BPS;
    }

    // ------------------------------------------------------- initialization

    /// @inheritdoc IHooks
    /// @dev Refuses a pool the factory has not registered, and a pool opening on the empty side of
    ///      its edge. As on the live hook.
    function beforeInitialize(address, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        view
        onlyPoolManager
        returns (bytes4)
    {
        Config memory c = configs[key.toId()];
        if (!c.registered) revert NotRegistered();
        uint160 edge = TickMath.getSqrtPriceAtTick(c.edgeTick);
        if (c.quoteIsCurrency0 ? sqrtPriceX96 >= edge : sqrtPriceX96 < edge) {
            revert OpensOutOfRange(sqrtPriceX96, c.edgeTick);
        }
        return IHooks.beforeInitialize.selector;
    }

    // ------------------------------------------- everything v4 may still call

    /// @dev v4 calls only what a hook's address advertises, so these can never be reached; they
    ///      revert so that a mis-mined address fails loudly.

    function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @notice Only the locker adds liquidity, and whoever the admin has named. As on the live hook.
    function beforeAddLiquidity(address sender, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        external
        view
        returns (bytes4)
    {
        if (sender != locker && !isLiquidityAdder[sender]) revert OnlyLocker(sender);
        return IHooks.beforeAddLiquidity.selector;
    }

    function afterAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external pure returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    function beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        external
        pure
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    function afterRemoveLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external pure returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        revert HookNotImplemented();
    }
}

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

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

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}

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

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

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

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/callback/IUnlockCallback.sol

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

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

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/BitMath.sol

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

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

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

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

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

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/Hooks.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}

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

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

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}

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/ParseBytes.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}

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/libraries/TickMath.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 price = uint256(sqrtPriceX96) << 32;

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

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

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

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

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

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

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

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

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/FactoryList.sol

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

/// @title FactoryList
/// @notice An append-only list of the launch factories a contract serves.
///
/// WHY A LIST AND NOT ONE FACTORY. The hook, the locker, the fee collector and the attestor each
/// used to take ONE factory, once. A new factory -- a new token, a new opening rule -- then meant a
/// new hook at a new mined address, and a hook's address is what routers and hook lists know it by.
/// With a list, a later factory is added to the same contracts and the hook keeps its address.
///
/// WHAT AN ADDED FACTORY CAN AND CANNOT DO. It can open NEW pools and launches, exactly as the first
/// one can. It cannot touch anything that already exists: every pool and launch is recorded once,
/// by the factory that created it, with its fee and rules fixed then, and nothing in these
/// contracts lets a factory -- any factory -- write to a record after it is made. Factories are
/// never removed or replaced, so no launch ever loses the factory it was made by.
///
/// WHO ADDS ONE. `factoryAdmin`, the platform's admin key; no timelock. It starts as the address
/// that deploys the contract, so the deploy can add the first factory in the same run, and the
/// deploy then hands it to the admin (`setFactoryAdmin`). That key can add a factory of its own
/// that opens new pools on its own terms. It is a power over new launches only.
abstract contract FactoryList {
    /// @notice Whether `factory` may act here.
    mapping(address => bool) public isFactory;

    /// @notice Every factory ever added, in order. Never shrinks.
    address[] private _factories;

    /// @notice May add a factory (and, on the hook, name who else may add liquidity).
    address public factoryAdmin;

    event FactoryAdded(address indexed factory, uint256 index);
    event FactoryAdminSet(address indexed previous, address indexed next);

    error ZeroFactory();
    error FactoryAlreadyAdded(address factory);
    error NotFactoryAdmin();
    error ZeroFactoryAdmin();

    modifier onlyFactoryAdmin() {
        if (msg.sender != factoryAdmin) revert NotFactoryAdmin();
        _;
    }

    function _initFactoryAdmin(address admin_) internal {
        if (admin_ == address(0)) revert ZeroFactoryAdmin();
        factoryAdmin = admin_;
        emit FactoryAdminSet(address(0), admin_);
    }

    /// @notice Hand the role to another key. The current admin only.
    function setFactoryAdmin(address next) external onlyFactoryAdmin {
        if (next == address(0)) revert ZeroFactoryAdmin();
        emit FactoryAdminSet(factoryAdmin, next);
        factoryAdmin = next;
    }

    /// @notice Add a factory that may open NEW pools or launches here. Append-only: no factory is
    ///         ever removed or replaced, and none can change a record already made.
    function addFactory(address factory_) external onlyFactoryAdmin {
        _addFactory(factory_);
    }

    function _addFactory(address factory_) internal {
        if (factory_ == address(0)) revert ZeroFactory();
        if (isFactory[factory_]) revert FactoryAlreadyAdded(factory_);
        isFactory[factory_] = true;
        _factories.push(factory_);
        emit FactoryAdded(factory_, _factories.length - 1);
    }

    /// @notice Every factory added, oldest first.
    function factories() external view returns (address[] memory) {
        return _factories;
    }

    function factoryCount() external view returns (uint256) {
        return _factories.length;
    }

    function factoryAt(uint256 index) external view returns (address) {
        return _factories[index];
    }
}

src/v3/V3Shared.sol

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

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

/// @title V3Shared -- the interfaces every factory-v3 piece builds against (docs/factory-v3.md)
/// @notice FIXED ON DAY 0. A change here is a change to every piece (EVM factory, hook, splitter,
///         LaunchBuys, Solana splitter, scripts, web) and goes through the lead.

/// @notice One wallet's launch buy: `amount` of `eid`'s pool quote (wei for a native pool, the
///         asset's own units otherwise) spent for `recipient` in the launch transaction on `eid`.
///         The whole list, every chain's entries, is hashed into the token's CREATE2 salt
///         (`TermsV3.buysHash` -> `TermsV3.launchSaltV3`), so the signed token address signs it.
struct LaunchBuy {
    uint32 eid;
    address recipient;
    uint256 amount;
}

/// @notice One leg's own launch fee in a creator self-launch (owner decision 2026-10-28: a split fee
///         per chain): at least `feeMin` held for the launch id by `payer` in `eid`'s collector
///         (on EVM a left-padded address, on Solana a 32-byte key).
struct LegFee {
    uint32 eid;
    uint256 feeMin;
    bytes32 payer;
}

/// @notice The launch terms v3: v2's eight fields and the creator self-launch (owner 2026-10-28):
///         `selfUntil` and `legFees`. (Moon mode's `poolBps` was removed, owner scope cut
///         2026-10-29: every chain's whole slice is its pool.)
struct LaunchTermsV3 {
    bytes32 payeeSolana;
    uint32 feeEid;
    uint256 feeMin;
    bytes32 payer;
    bytes32 metadata;
    bytes32 creatorSolana;
    bytes32 quoteSolana;
    /// @notice 0: today's flow (one pay chain, the platform sends every other leg). Otherwise a
    ///         creator SELF-LAUNCH on its self legs (those with a `legFees` entry): each is paid on
    ///         its own chain, the creator may send it, and the platform's launcher only from this
    ///         unix time on. Option C (2026-10-29): with a strict subset of the legs listed, the
    ///         others are ordinary legs (the pay chain, never a self leg, and platform-only legs).
    uint32 selfUntil;
    /// @notice With `selfUntil` 0: zero. Otherwise TermsV3.legFeesHash of the self legs' LegFee
    ///         rows (every leg's, or a non-empty subset's: the signed per-leg self mask).
    bytes32 legFees;
}

library TermsV3 {
    /// @notice The most launch-buy entries one launch may carry, over all its chains.
    uint256 internal constant MAX_LAUNCH_BUYS = 32;

    /// @notice A self-launch's leg fees are not one per leg in strictly ascending eid (at `index`).
    error LegFeesNotAscending(uint256 index);

    /// @notice The version word every v3 (gap fee) launch's terms end with (audit r1 L-3, v3c).
    uint256 internal constant GAP_TERMS_VERSION = 3;

    /// @notice The terms hash: v2's words and then `uint256 GAP_TERMS_VERSION` (3). With
    ///         `selfUntil == 0` (today's flow; `legFees` is then zero, and not hashed) nine words:
    ///         keccak256(abi.encode(address payee, bytes32 payeeSolana, uint32 feeEid, uint256 feeMin,
    ///         bytes32 payer, bytes32 metadata, bytes32 creatorSolana, bytes32 quoteSolana, uint256 3)).
    ///         A SELF-LAUNCH (`selfUntil != 0`) eleven: those eight, `uint32 selfUntil`, `bytes32
    ///         legFees`, then the version (Moon mode's `poolBps` word removed, 2026-10-29, decision (a)).
    ///         The version word binds a signed snapshot to the v3 gap-fee token: a snapshot signed
    ///         for the v2 factory (eight words) never verifies here, and on Solana a v3-signed launch
    ///         is the only one that opens a v3 store (price.rs `terms_hash_v3`, which reproduces
    ///         both forms), so a store and its EVM peers always speak the same codec.
    function termsHash(address payee, LaunchTermsV3 memory t) internal pure returns (bytes32) {
        if (t.selfUntil != 0) {
            return keccak256(
                abi.encode(
                    payee,
                    t.payeeSolana,
                    t.feeEid,
                    t.feeMin,
                    t.payer,
                    t.metadata,
                    t.creatorSolana,
                    t.quoteSolana,
                    t.selfUntil,
                    t.legFees,
                    GAP_TERMS_VERSION
                )
            );
        }
        return keccak256(
            abi.encode(
                payee,
                t.payeeSolana,
                t.feeEid,
                t.feeMin,
                t.payer,
                t.metadata,
                t.creatorSolana,
                t.quoteSolana,
                GAP_TERMS_VERSION
            )
        );
    }

    /// @notice A self-launch's `legFees`: keccak256(abi.encode(LegFee[] fees)), the fees listed by
    ///         strictly ascending `eid` (one per leg), so one set of fees has one hash. Reverts
    ///         `LegFeesNotAscending` otherwise, and on an empty list.
    function legFeesHash(LegFee[] memory fees) internal pure returns (bytes32) {
        if (fees.length == 0) revert LegFeesNotAscending(0);
        for (uint256 i = 1; i < fees.length; i++) {
            if (fees[i].eid <= fees[i - 1].eid) revert LegFeesNotAscending(i);
        }
        return keccak256(abi.encode(fees));
    }

    /// @notice Zero for no launch buys, else keccak256(abi.encode(LaunchBuy[] buys)).
    function buysHash(LaunchBuy[] memory buys) internal pure returns (bytes32) {
        if (buys.length == 0) return bytes32(0);
        return keccak256(abi.encode(buys));
    }

    /// @notice The CREATE2 salt a v3 token is deployed with: v2's `launchSalt` (salt, eids,
    ///         foreign, quotes), then keccak256(abi.encode(bytes32 v2Salt, address hook, bytes32
    ///         buysHash)). Binds the launch's hook and its launch buys under the signature (the
    ///         signer signs every EVM token address) without touching the Solana-reproduced terms.
    function launchSaltV3(bytes32 v2Salt, address hook, bytes32 buysHash_) internal pure returns (bytes32) {
        return keccak256(abi.encode(v2Salt, hook, buysHash_));
    }

    /// @notice The permission bits every launch hook's address carries -- PangeaFeeHook's mined
    ///         flags. A hook with any other set is refused by `setLaunchHook`.
    uint160 internal constant HOOK_FLAGS = Hooks.BEFORE_INITIALIZE_FLAG | Hooks.BEFORE_ADD_LIQUIDITY_FLAG
        | Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG | Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG
        | Hooks.AFTER_SWAP_RETURNS_DELTA_FLAG;
}

/// @notice What the v3 factory asks of a launch hook. The live PangeaFeeHook answers all of it
///         (v1 hook); PangeaFeeHookV2 adds `IPangeaLaunchHookV2`. `configs` keeps its five-field
///         shape: TokenomicsVault reads it.
interface IPangeaLaunchHook {
    function poolManager() external view returns (IPoolManager);
    function locker() external view returns (address);
    function devBuyer() external view returns (address);
    function isFactory(address) external view returns (bool);
    function factoryOf(PoolId) external view returns (address);
    function configs(PoolId)
        external
        view
        returns (address splitter, bool quoteIsCurrency0, uint16 feeBps, bool registered, int24 edgeTick);
    function register(PoolKey calldata key, address splitter, bool quoteIsCurrency0, uint16 feeBps, int24 edgeTick)
        external;
    function redeem(PoolKey calldata key) external returns (uint256 amount0, uint256 amount1);
}

/// @notice PangeaFeeHookV2's additions: a per-pool fee the payee (the splitter's `creator`) or the
///         platform admin changes -- with no delay by default (constructor feeDelayBlocks = 0; a one-block-delay build schedules it instead, see PangeaFeeHookV2) -- inside [MIN_FEE_BPS, MAX_FEE_BPS]; fees already
///         earned are settled at the old rate first (redeem -> splitter.setFeeBps). `launchBuyer`
///         is fee-free like `devBuyer`.
interface IPangeaLaunchHookV2 is IPangeaLaunchHook {
    event FeeChanged(PoolId indexed id, uint16 fromBps, uint16 toBps, address by);

    function launchBuyer() external view returns (address);
    function setFee(PoolKey calldata key, uint16 feeBps) external;
}

/// @notice FeeSplitterV3 = FeeSplitterV2 + a fee its pool's hook may change. `setFeeBps` is the
///         hook's alone: it releases every native and `quote` balance at the old rate, then
///         switches. With the v1 hook nobody calls it and it is FeeSplitterV2 exactly.
interface IFeeSplitterV3 {
    function hook() external view returns (address);
    function feeBps() external view returns (uint16);
    function creator() external view returns (address);
    function factory() external view returns (address);
    function setFeeBps(address quote, uint16 feeBps) external;
}

/// @notice The launch-buys escrow (one per EVM chain). Payers deposit per-launch lines before the
///         launch; the factory calls `onLaunch` after `feeCollector.onLaunch`, inside try/catch,
///         so a failing buy never blocks a launch. It spends ONLY `payer`'s lines for `launchId`,
///         at most `cap` in total, executes only `buys` entries whose `eid` is this chain, and
///         leaves everything unspent reclaimable by its payer.
interface ILaunchBuys {
    function onLaunch(bytes32 launchId, address payer, address token, LaunchBuy[] calldata buys, uint256 cap)
        external;
}
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.