Skip to content
Verified contractExactMIT

ZappyHook

Address0x0ccad7b1035c7edd95201ed8737dbc29eea868ec
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,371,178
Creation transaction
0xbbaa213d30…cea54be274

55 files

src/ZappyHook.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";
import {IZappyRevenue} from "./interfaces/IZappyRevenue.sol";
import {IZappyToken} from "./interfaces/IZappyToken.sol";
import {Claims} from "./libraries/Claims.sol";
import {Curve, N_TRANCHES} from "./libraries/Curve.sol";
import {FloorMath} from "./libraries/FloorMath.sol";
import {Ticks} from "./libraries/Ticks.sol";
import {HookStorage} from "./hook/HookStorage.sol";
import {HookClaims} from "./hook/HookClaims.sol";
import {Owned} from "./base/Owned.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";

/// @title ZappyHook
/// @notice Owns every ZAPPY pool's liquidity. Charges a tax on the quote leg of every swap (no LP fee), and keeps a
///         single-tick wall of quote under the price that can buy back every circulating token. The wall moves up
///         whenever it can and never moves down. Floor money the wall can't use under the price buys back and burns
///         tokens instead, lifting the price to what the tokens are backed by, so it never sits idle for a pumper to
///         harvest. Both run once per block, before that block's first swap, on the state the block started with.
///         The snipe window's tax is 60% floor money (vesting) and 40% for a buy-and-burn of $ZAPPY (ZappyBurner).
///         Spec: packages/contracts/README.md.
/// @dev Orientation: currency0 = quote (native ETH for $ZAPPY, $ZAPPY for everything else), currency1 = token.
///      Pool price = token per quote, so a buy is zeroForOne and moves the tick DOWN; token-only positions sit below
///      the current tick and the quote-only floor band sits above it.
///      The logic lives in src/hook/: HookStorage (state, constants, shared helpers) <- HookFloor (the floor) <- HookTax
///      (the swap callbacks) <- HookClaims (payouts). This contract adds the launch, the unlock callback and the views.
/// @dev Zappy fork: the hook has an owner (two-step, no renounce) whose one power is collectFloor. Everything else is the
///      upstream logic unchanged.
contract ZappyHook is HookClaims, IUnlockCallback, Owned {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using CurrencyLibrary for Currency;
    using Claims for IPoolManager;

    /// @param _isArbitrum count blocks with ArbSys.arbBlockNumber() (an Arbitrum chain: Robinhood Chain), not
    ///        block.number (HookStorage.isArbitrum; script/Deploy.s.sol sets it from the chain id)
    constructor(
        IPoolManager _poolManager,
        address _factory,
        IZappyRevenue _revenue,
        address _limitOrders,
        address _burner,
        bool _isArbitrum,
        address _owner
    ) HookStorage(_poolManager, _factory, _revenue, _limitOrders, _burner, _isArbitrum) Owned(_owner) {}

    /// @dev Swaps (the tax and the raise) plus three callbacks enabled only to refuse them: pools the hook didn't create,
    ///      third-party liquidity (it would sit outside the floor invariant) and donations (fees the rebuild would then
    ///      have to settle). The hook's own calls skip its callbacks.
    function _permissions() internal pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true,
            afterInitialize: false,
            beforeAddLiquidity: true,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: false,
            afterRemoveLiquidity: false,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: true,
            afterDonate: false,
            beforeSwapReturnDelta: true,
            afterSwapReturnDelta: true,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    // =====================================================================================================
    // launch
    // =====================================================================================================

    /// @notice Creates the pool and places the launch curve's tranches (libraries/Curve.sol). The factory must have
    ///         transferred the full supply of `token` to this contract first.
    function createPool(address quote, address token, address creator, int24 tickStart)
        external
        returns (PoolKey memory key)
    {
        if (msg.sender != factory) revert NotFactory();
        if (quote >= token) revert BadOrder();
        if (tickStart % SPACING != 0 || tickStart < Ticks.MIN_START_TICK || tickStart >= TickMath.MAX_TICK - SPACING) {
            revert BadTick();
        }
        key = keyFor(quote, token);
        PoolId id = key.toId();
        // the factory's swaps in this launch (the creator's buy) pay the base rate on this pool only, until endLaunch
        // (_rate)
        bytes32 slot = LAUNCHING_SLOT;
        assembly ("memory-safe") {
            tstore(slot, id)
        }
        Pool storage p = pools[id];
        p.token = token;
        p.creator = creator;
        if (creator == address(0)) zappy = token; // the factory's first launch, $ZAPPY (ZappyFactory.launch)
        // forge-lint: disable-next-line(unsafe-typecast)
        p.launchedAt = uint40(block.timestamp); // seconds: < 2^40 for ~34,000 years
        p.tickStart = tickStart;
        p.tickF = tickStart;
        p.tickB = tickStart;
        // the hook initialises its own pools; beforeInitialize rejects everyone else (self-calls skip it)
        poolManager.initialize(key, TickMath.getSqrtPriceAtTick(tickStart));
        poolManager.unlock(abi.encode(ACTION_PLACE, abi.encode(key)));
    }

    /// @notice Ends the launch createPool started: the factory's swaps pay the normal rate everywhere again.
    function endLaunch() external {
        if (msg.sender != factory) revert NotFactory();
        bytes32 slot = LAUNCHING_SLOT;
        assembly ("memory-safe") {
            tstore(slot, 0)
        }
    }

    // =====================================================================================================
    // unlock callback: place, poke, claim
    // =====================================================================================================

    function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
        (uint8 action, bytes memory args) = abi.decode(data, (uint8, bytes));
        if (action == ACTION_PLACE) {
            _place(abi.decode(args, (PoolKey)));
        } else if (action == ACTION_POKE) {
            PoolKey memory key = abi.decode(args, (PoolKey));
            _refreshRef(pools[key.toId()], key.toId());
            _raise(key);
        } else if (action == ACTION_CLAIM) {
            (Currency currency, address to, uint256 amount) = abi.decode(args, (Currency, address, uint256));
            poolManager.redeem(currency, to, amount);
        } else if (action == ACTION_COLLECT) {
            (PoolKey memory key, uint16 bps, address to) = abi.decode(args, (PoolKey, uint16, address));
            _collectFloor(key, bps, to);
        }
        return "";
    }

    // =====================================================================================================
    // owner (Zappy)
    // =====================================================================================================

    /// @notice Zappy: the owner takes `bps` (1..10,000) of a pool's floor, its single-tick band and the pot waiting for
    ///         it, and sends the pair currency to `to`. Tokens the band held (a band the price is inside) join the dust
    ///         reserve. The curve's tranches are not touched. A floor collected this way is lower than the one the
    ///         swaps built: the next raises rebuild it from the tax that comes in after.
    function collectFloor(PoolKey calldata key, uint16 bps, address to) external onlyOwner {
        if (bps == 0 || bps > 10_000) revert BadBps();
        if (to == address(0)) revert ZeroAddress();
        if (pools[key.toId()].token == address(0)) revert UnknownPool();
        poolManager.unlock(abi.encode(ACTION_COLLECT, abi.encode(key, bps, to)));
    }

    /// @dev Takes `bps` of the pot and of the band's quote. The whole band comes out (its tokens, if the price was inside
    ///      it, join the dust reserve) and what is kept goes back in at the lowest tick at or above the old band where it
    ///      still buys back every circulating token (_lowerBand): the floor drops to what the money left can hold, the
    ///      invariant every raise checks (HookFloor.FloorBroken) holds again right away, and the raises go on from there.
    ///      A full collect leaves no band: the next raise rebuilds one once the pot can carry every holder.
    function _collectFloor(PoolKey memory key, uint16 bps, address to) internal {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        uint256 quoteOut = p.pot * bps / 10_000;
        p.pot -= quoteOut;
        uint256 tokens;
        uint256 keep;
        if (p.liqBand != 0) {
            (uint256 q, uint256 t) = _pullBand(key, p, p.liqBand);
            tokens = t;
            uint256 out = q * bps / 10_000;
            quoteOut += out;
            keep = q - out;
        }
        uint256 bandQuote;
        if (keep != 0) bandQuote = _lowerBand(key, p, id, keep);
        if (quoteOut != 0) poolManager.redeem(key.currency0, to, quoteOut);
        emit FloorCollected(id, bps, quoteOut, tokens, to, p.tickB, bandQuote);
    }

    /// @dev Puts `keep` of quote (held as claims) back as the band at the lowest tick (highest floor) at or above both the
    ///      current tick and tranche 0's top where tranche 0's quote over the price, the unreached tranches and this band
    ///      together absorb every circulating token (HookFloor._absorbNow's terms). A binary search over the ticks: a
    ///      cheaper band buys more tokens with the same quote, so the check is monotonic. Rounding dust the band can't
    ///      take stays in the pot. Returns the quote the band took.
    function _lowerBand(PoolKey memory key, Pool storage p, PoolId id, uint256 keep) internal returns (uint256) {
        (uint160 sCur, int24 cur,,) = poolManager.getSlot0(id);
        uint256 circulating = _circulating(p, sCur);
        uint256 fixedAbsorb = _absorbNow(p, sCur); // liqBand is 0 here: tranche 0 and the unreached tranches
        uint128 lbMax = _lbMax(id);
        int24 low = Ticks.alignDown(cur) + SPACING; // the band stays over the price
        if (low < p.tickF) low = p.tickF;
        int256 lo = int256(low / SPACING);
        int256 hi = int256(TickMath.MAX_TICK / SPACING) - 2; // the band's far edge within the usable ticks
        while (lo < hi) {
            int256 mid = (lo + hi) >> 1;
            // forge-lint: disable-next-line(unsafe-typecast)
            if (fixedAbsorb + _bandTokens(int24(mid * SPACING), keep, lbMax) >= circulating) hi = mid;
            else lo = mid + 1;
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        int24 tB = int24(hi * SPACING); // lo <= hi: between two int24 ticks
        uint128 lb = _bandLiquidity(
            TickMath.getSqrtPriceAtTick(tB), TickMath.getSqrtPriceAtTick(tB + SPACING), keep, lbMax
        );
        BalanceDelta d = _modify(key, tB, tB + SPACING, int256(uint256(lb)), SALT_BAND);
        // a band over the price only ever takes quote; rounding leaves it at most `keep`
        uint256 used = uint256(int256(-d.amount0()));
        poolManager.burn(address(this), key.currency0.toId(), used);
        p.pot += keep - used;
        p.tickB = tB;
        p.liqBand = lb;
        return used;
    }

    /// @dev Tokens a band at [t, t+60] funded with `keep` of quote (capped at lbMax) buys back.
    function _bandTokens(int24 t, uint256 keep, uint128 lbMax) internal pure returns (uint256) {
        uint160 sT = TickMath.getSqrtPriceAtTick(t);
        uint160 sT1 = TickMath.getSqrtPriceAtTick(t + SPACING);
        return FloorMath.token(sT, sT1, _bandLiquidity(sT, sT1, keep, lbMax), false);
    }

    function _place(PoolKey memory key) internal {
        Pool storage p = pools[key.toId()];
        uint256 supply = IZappyToken(p.token).totalSupply();
        uint160 sMin = TickMath.getSqrtPriceAtTick(MIN_TICK);
        uint256 left = supply - RESERVE;
        int256 used;
        for (uint256 i; i < N_TRANCHES; i++) {
            (uint256 bps,) = Curve.tranche(i);
            uint256 amt = i + 1 == N_TRANCHES ? left : supply * bps / 10_000; // the last tranche takes the remainder
            left -= amt;
            int24 top = _start(p, i);
            uint128 l = FloorMath.liquidityForToken(sMin, TickMath.getSqrtPriceAtTick(top), amt);
            used += _modify(key, MIN_TICK, top, int256(uint256(l)), _salt(i)).amount1();
            p.liqs[i] = l;
        }
        // pay the full supply in, keep what the positions didn't use as the dust reserve (claims)
        poolManager.sync(key.currency1);
        // forge-lint: disable-next-line(erc20-unchecked-transfer)
        IZappyToken(p.token).transfer(address(poolManager), supply); // ZappyToken (OpenZeppelin ERC20) reverts on failure
        poolManager.settle();
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 leftover = supply - uint256(-used); // used sums adds' amount1, each <= 0
        poolManager.mint(address(this), key.currency1.toId(), leftover);
        p.reserve = leftover;
    }

    // =====================================================================================================
    // views
    // =====================================================================================================

    /// @notice Tranche i of the launch curve as placed now: [MIN_TICK, top] with `liquidity`. Tranche 0's top is the
    ///         floor; a tranche merged into it (the floor passed its start) reads (tickF, 0). i >= N_TRANCHES: BadTranche.
    function trancheOf(PoolKey calldata key, uint256 i) external view returns (int24 top, uint128 liquidity) {
        if (i >= N_TRANCHES) revert BadTranche();
        Pool storage p = pools[key.toId()];
        if (i == 0) return (p.tickF, p.liqs[0]);
        if (i <= p.merged) return (p.tickF, 0);
        return (_start(p, i), p.liqs[i]);
    }

    /// @notice Worst-case token price in quote (Q96 sqrt of token-per-quote, far edge of the band) and circulating supply.
    function floorOf(PoolKey calldata key)
        external
        view
        returns (int24 tickF, uint160 sqrtPriceX96, uint256 circulating)
    {
        Pool storage p = pools[key.toId()];
        (uint160 sCur,,,) = poolManager.getSlot0(key.toId());
        // Zappy: the band's tick (tranche 0's top until a collect moves the band off it)
        return (p.tickB, TickMath.getSqrtPriceAtTick(p.tickB + SPACING), _circulating(p, sCur));
    }

    /// @notice A pool's tick at the start of this block: the one stored by the block's first swap (or poke); with none
    ///         yet, the pool hasn't moved this block, so its current tick.
    function startOfBlockTick(PoolId id) external view returns (int24 tick) {
        Pool storage p = pools[id];
        if (p.refBlock == _blockNumber()) return p.refTick;
        (, tick,,) = poolManager.getSlot0(id);
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/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/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/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 {IPoolManager} from "./IPoolManager.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,
        IPoolManager.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,
        IPoolManager.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,
        IPoolManager.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,
        IPoolManager.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,
        IPoolManager.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,
        IPoolManager.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/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";

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

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

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

    /// @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/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/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/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/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/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/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/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/v4-core/src/libraries/FixedPoint96.sol

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

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

lib/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/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 {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,
        IPoolManager.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,
        IPoolManager.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, IPoolManager.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,
        IPoolManager.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/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/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/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/v4-core/src/libraries/Pool.sol

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

import {SafeCast} from "./SafeCast.sol";
import {TickBitmap} from "./TickBitmap.sol";
import {Position} from "./Position.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {TickMath} from "./TickMath.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
import {SwapMath} from "./SwapMath.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {Slot0} from "../types/Slot0.sol";
import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @notice a library with all actions that can be performed on a pool
library Pool {
    using SafeCast for *;
    using TickBitmap for mapping(int16 => uint256);
    using Position for mapping(bytes32 => Position.State);
    using Position for Position.State;
    using Pool for State;
    using ProtocolFeeLibrary for *;
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when tickLower is not below tickUpper
    /// @param tickLower The invalid tickLower
    /// @param tickUpper The invalid tickUpper
    error TicksMisordered(int24 tickLower, int24 tickUpper);

    /// @notice Thrown when tickLower is less than min tick
    /// @param tickLower The invalid tickLower
    error TickLowerOutOfBounds(int24 tickLower);

    /// @notice Thrown when tickUpper exceeds max tick
    /// @param tickUpper The invalid tickUpper
    error TickUpperOutOfBounds(int24 tickUpper);

    /// @notice For the tick spacing, the tick has too much liquidity
    error TickLiquidityOverflow(int24 tick);

    /// @notice Thrown when trying to initialize an already initialized pool
    error PoolAlreadyInitialized();

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

    /// @notice Thrown when sqrtPriceLimitX96 on a swap has already exceeded its limit
    /// @param sqrtPriceCurrentX96 The invalid, already surpassed sqrtPriceLimitX96
    /// @param sqrtPriceLimitX96 The surpassed price limit
    error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96);

    /// @notice Thrown when sqrtPriceLimitX96 lies outside of valid tick/price range
    /// @param sqrtPriceLimitX96 The invalid, out-of-bounds sqrtPriceLimitX96
    error PriceLimitOutOfBounds(uint160 sqrtPriceLimitX96);

    /// @notice Thrown by donate if there is currently 0 liquidity, since the fees will not go to any liquidity providers
    error NoLiquidityToReceiveFees();

    /// @notice Thrown when trying to swap with max lp fee and specifying an output amount
    error InvalidFeeForExactOut();

    // info stored for each initialized individual tick
    struct TickInfo {
        // the total position liquidity that references this tick
        uint128 liquidityGross;
        // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
        int128 liquidityNet;
        // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
        // only has relative meaning, not absolute — the value depends on when the tick is initialized
        uint256 feeGrowthOutside0X128;
        uint256 feeGrowthOutside1X128;
    }

    /// @notice The state of a pool
    /// @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
    struct State {
        Slot0 slot0;
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
        uint128 liquidity;
        mapping(int24 tick => TickInfo) ticks;
        mapping(int16 wordPos => uint256) tickBitmap;
        mapping(bytes32 positionKey => Position.State) positions;
    }

    /// @dev Common checks for valid tick inputs.
    function checkTicks(int24 tickLower, int24 tickUpper) private pure {
        if (tickLower >= tickUpper) TicksMisordered.selector.revertWith(tickLower, tickUpper);
        if (tickLower < TickMath.MIN_TICK) TickLowerOutOfBounds.selector.revertWith(tickLower);
        if (tickUpper > TickMath.MAX_TICK) TickUpperOutOfBounds.selector.revertWith(tickUpper);
    }

    function initialize(State storage self, uint160 sqrtPriceX96, uint24 lpFee) internal returns (int24 tick) {
        if (self.slot0.sqrtPriceX96() != 0) PoolAlreadyInitialized.selector.revertWith();

        tick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);

        // the initial protocolFee is 0 so doesn't need to be set
        self.slot0 = Slot0.wrap(bytes32(0)).setSqrtPriceX96(sqrtPriceX96).setTick(tick).setLpFee(lpFee);
    }

    function setProtocolFee(State storage self, uint24 protocolFee) internal {
        self.checkPoolInitialized();
        self.slot0 = self.slot0.setProtocolFee(protocolFee);
    }

    /// @notice Only dynamic fee pools may update the lp fee.
    function setLPFee(State storage self, uint24 lpFee) internal {
        self.checkPoolInitialized();
        self.slot0 = self.slot0.setLpFee(lpFee);
    }

    struct ModifyLiquidityParams {
        // the address that owns the position
        address owner;
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // any change in liquidity
        int128 liquidityDelta;
        // the spacing between ticks
        int24 tickSpacing;
        // used to distinguish positions of the same owner, at the same tick range
        bytes32 salt;
    }

    struct ModifyLiquidityState {
        bool flippedLower;
        uint128 liquidityGrossAfterLower;
        bool flippedUpper;
        uint128 liquidityGrossAfterUpper;
    }

    /// @notice Effect changes to a position in a pool
    /// @dev PoolManager checks that the pool is initialized before calling
    /// @param params the position details and the change to the position's liquidity to effect
    /// @return delta the deltas of the token balances of the pool, from the liquidity change
    /// @return feeDelta the fees generated by the liquidity range
    function modifyLiquidity(State storage self, ModifyLiquidityParams memory params)
        internal
        returns (BalanceDelta delta, BalanceDelta feeDelta)
    {
        int128 liquidityDelta = params.liquidityDelta;
        int24 tickLower = params.tickLower;
        int24 tickUpper = params.tickUpper;
        checkTicks(tickLower, tickUpper);

        {
            ModifyLiquidityState memory state;

            // if we need to update the ticks, do it
            if (liquidityDelta != 0) {
                (state.flippedLower, state.liquidityGrossAfterLower) =
                    updateTick(self, tickLower, liquidityDelta, false);
                (state.flippedUpper, state.liquidityGrossAfterUpper) = updateTick(self, tickUpper, liquidityDelta, true);

                // `>` and `>=` are logically equivalent here but `>=` is cheaper
                if (liquidityDelta >= 0) {
                    uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing);
                    if (state.liquidityGrossAfterLower > maxLiquidityPerTick) {
                        TickLiquidityOverflow.selector.revertWith(tickLower);
                    }
                    if (state.liquidityGrossAfterUpper > maxLiquidityPerTick) {
                        TickLiquidityOverflow.selector.revertWith(tickUpper);
                    }
                }

                if (state.flippedLower) {
                    self.tickBitmap.flipTick(tickLower, params.tickSpacing);
                }
                if (state.flippedUpper) {
                    self.tickBitmap.flipTick(tickUpper, params.tickSpacing);
                }
            }

            {
                (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
                    getFeeGrowthInside(self, tickLower, tickUpper);

                Position.State storage position = self.positions.get(params.owner, tickLower, tickUpper, params.salt);
                (uint256 feesOwed0, uint256 feesOwed1) =
                    position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);

                // Fees earned from LPing are calculated, and returned
                feeDelta = toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128());
            }

            // clear any tick data that is no longer needed
            if (liquidityDelta < 0) {
                if (state.flippedLower) {
                    clearTick(self, tickLower);
                }
                if (state.flippedUpper) {
                    clearTick(self, tickUpper);
                }
            }
        }

        if (liquidityDelta != 0) {
            Slot0 _slot0 = self.slot0;
            (int24 tick, uint160 sqrtPriceX96) = (_slot0.tick(), _slot0.sqrtPriceX96());
            if (tick < tickLower) {
                // current tick is below the passed range; liquidity can only become in range by crossing from left to
                // right, when we'll need _more_ currency0 (it's becoming more valuable) so user must provide it
                delta = toBalanceDelta(
                    SqrtPriceMath.getAmount0Delta(
                        TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta
                    ).toInt128(),
                    0
                );
            } else if (tick < tickUpper) {
                delta = toBalanceDelta(
                    SqrtPriceMath.getAmount0Delta(sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta)
                        .toInt128(),
                    SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(tickLower), sqrtPriceX96, liquidityDelta)
                        .toInt128()
                );

                self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta);
            } else {
                // current tick is above the passed range; liquidity can only become in range by crossing from right to
                // left, when we'll need _more_ currency1 (it's becoming more valuable) so user must provide it
                delta = toBalanceDelta(
                    0,
                    SqrtPriceMath.getAmount1Delta(
                        TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta
                    ).toInt128()
                );
            }
        }
    }

    // Tracks the state of a pool throughout a swap, and returns these values at the end of the swap
    struct SwapResult {
        // the current sqrt(price)
        uint160 sqrtPriceX96;
        // the tick associated with the current price
        int24 tick;
        // the current liquidity in range
        uint128 liquidity;
    }

    struct StepComputations {
        // the price at the beginning of the step
        uint160 sqrtPriceStartX96;
        // the next tick to swap to from the current tick in the swap direction
        int24 tickNext;
        // whether tickNext is initialized or not
        bool initialized;
        // sqrt(price) for the next tick (1/0)
        uint160 sqrtPriceNextX96;
        // how much is being swapped in in this step
        uint256 amountIn;
        // how much is being swapped out
        uint256 amountOut;
        // how much fee is being paid in
        uint256 feeAmount;
        // the global fee growth of the input token. updated in storage at the end of swap
        uint256 feeGrowthGlobalX128;
    }

    struct SwapParams {
        int256 amountSpecified;
        int24 tickSpacing;
        bool zeroForOne;
        uint160 sqrtPriceLimitX96;
        uint24 lpFeeOverride;
    }

    /// @notice Executes a swap against the state, and returns the amount deltas of the pool
    /// @dev PoolManager checks that the pool is initialized before calling
    function swap(State storage self, SwapParams memory params)
        internal
        returns (BalanceDelta swapDelta, uint256 amountToProtocol, uint24 swapFee, SwapResult memory result)
    {
        Slot0 slot0Start = self.slot0;
        bool zeroForOne = params.zeroForOne;

        uint256 protocolFee =
            zeroForOne ? slot0Start.protocolFee().getZeroForOneFee() : slot0Start.protocolFee().getOneForZeroFee();

        // the amount remaining to be swapped in/out of the input/output asset. initially set to the amountSpecified
        int256 amountSpecifiedRemaining = params.amountSpecified;
        // the amount swapped out/in of the output/input asset. initially set to 0
        int256 amountCalculated = 0;
        // initialize to the current sqrt(price)
        result.sqrtPriceX96 = slot0Start.sqrtPriceX96();
        // initialize to the current tick
        result.tick = slot0Start.tick();
        // initialize to the current liquidity
        result.liquidity = self.liquidity;

        // if the beforeSwap hook returned a valid fee override, use that as the LP fee, otherwise load from storage
        // lpFee, swapFee, and protocolFee are all in pips
        {
            uint24 lpFee = params.lpFeeOverride.isOverride()
                ? params.lpFeeOverride.removeOverrideFlagAndValidate()
                : slot0Start.lpFee();

            swapFee = protocolFee == 0 ? lpFee : uint16(protocolFee).calculateSwapFee(lpFee);
        }

        // a swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
        if (swapFee >= SwapMath.MAX_SWAP_FEE) {
            // if exactOutput
            if (params.amountSpecified > 0) {
                InvalidFeeForExactOut.selector.revertWith();
            }
        }

        // swapFee is the pool's fee in pips (LP fee + protocol fee)
        // when the amount swapped is 0, there is no protocolFee applied and the fee amount paid to the protocol is set to 0
        if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, result);

        if (zeroForOne) {
            if (params.sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96()) {
                PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96);
            }
            // Swaps can never occur at MIN_TICK, only at MIN_TICK + 1, except at initialization of a pool
            // Under certain circumstances outlined below, the tick will preemptively reach MIN_TICK without swapping there
            if (params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_PRICE) {
                PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96);
            }
        } else {
            if (params.sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96()) {
                PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96);
            }
            if (params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_PRICE) {
                PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96);
            }
        }

        StepComputations memory step;
        step.feeGrowthGlobalX128 = zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128;

        // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
        while (!(amountSpecifiedRemaining == 0 || result.sqrtPriceX96 == params.sqrtPriceLimitX96)) {
            step.sqrtPriceStartX96 = result.sqrtPriceX96;

            (step.tickNext, step.initialized) =
                self.tickBitmap.nextInitializedTickWithinOneWord(result.tick, params.tickSpacing, zeroForOne);

            // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
            if (step.tickNext <= TickMath.MIN_TICK) {
                step.tickNext = TickMath.MIN_TICK;
            }
            if (step.tickNext >= TickMath.MAX_TICK) {
                step.tickNext = TickMath.MAX_TICK;
            }

            // get the price for the next tick
            step.sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(step.tickNext);

            // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
            (result.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(
                result.sqrtPriceX96,
                SwapMath.getSqrtPriceTarget(zeroForOne, step.sqrtPriceNextX96, params.sqrtPriceLimitX96),
                result.liquidity,
                amountSpecifiedRemaining,
                swapFee
            );

            // if exactOutput
            if (params.amountSpecified > 0) {
                unchecked {
                    amountSpecifiedRemaining -= step.amountOut.toInt256();
                }
                amountCalculated -= (step.amountIn + step.feeAmount).toInt256();
            } else {
                // safe because we test that amountSpecified > amountIn + feeAmount in SwapMath
                unchecked {
                    amountSpecifiedRemaining += (step.amountIn + step.feeAmount).toInt256();
                }
                amountCalculated += step.amountOut.toInt256();
            }

            // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
            if (protocolFee > 0) {
                unchecked {
                    // step.amountIn does not include the swap fee, as it's already been taken from it,
                    // so add it back to get the total amountIn and use that to calculate the amount of fees owed to the protocol
                    // cannot overflow due to limits on the size of protocolFee and params.amountSpecified
                    // this rounds down to favor LPs over the protocol
                    uint256 delta = (swapFee == protocolFee)
                        ? step.feeAmount // lp fee is 0, so the entire fee is owed to the protocol instead
                        : (step.amountIn + step.feeAmount) * protocolFee / ProtocolFeeLibrary.PIPS_DENOMINATOR;
                    // subtract it from the total fee and add it to the protocol fee
                    step.feeAmount -= delta;
                    amountToProtocol += delta;
                }
            }

            // update global fee tracker
            if (result.liquidity > 0) {
                unchecked {
                    // FullMath.mulDiv isn't needed as the numerator can't overflow uint256 since tokens have a max supply of type(uint128).max
                    step.feeGrowthGlobalX128 +=
                        UnsafeMath.simpleMulDiv(step.feeAmount, FixedPoint128.Q128, result.liquidity);
                }
            }

            // Shift tick if we reached the next price, and preemptively decrement for zeroForOne swaps to tickNext - 1.
            // If the swap doesn't continue (if amountRemaining == 0 or sqrtPriceLimit is met), slot0.tick will be 1 less
            // than getTickAtSqrtPrice(slot0.sqrtPrice). This doesn't affect swaps, but donation calls should verify both
            // price and tick to reward the correct LPs.
            if (result.sqrtPriceX96 == step.sqrtPriceNextX96) {
                // if the tick is initialized, run the tick transition
                if (step.initialized) {
                    (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = zeroForOne
                        ? (step.feeGrowthGlobalX128, self.feeGrowthGlobal1X128)
                        : (self.feeGrowthGlobal0X128, step.feeGrowthGlobalX128);
                    int128 liquidityNet =
                        Pool.crossTick(self, step.tickNext, feeGrowthGlobal0X128, feeGrowthGlobal1X128);
                    // if we're moving leftward, we interpret liquidityNet as the opposite sign
                    // safe because liquidityNet cannot be type(int128).min
                    unchecked {
                        if (zeroForOne) liquidityNet = -liquidityNet;
                    }

                    result.liquidity = LiquidityMath.addDelta(result.liquidity, liquidityNet);
                }

                unchecked {
                    result.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
                }
            } else if (result.sqrtPriceX96 != step.sqrtPriceStartX96) {
                // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
                result.tick = TickMath.getTickAtSqrtPrice(result.sqrtPriceX96);
            }
        }

        self.slot0 = slot0Start.setTick(result.tick).setSqrtPriceX96(result.sqrtPriceX96);

        // update liquidity if it changed
        if (self.liquidity != result.liquidity) self.liquidity = result.liquidity;

        // update fee growth global
        if (!zeroForOne) {
            self.feeGrowthGlobal1X128 = step.feeGrowthGlobalX128;
        } else {
            self.feeGrowthGlobal0X128 = step.feeGrowthGlobalX128;
        }

        unchecked {
            // "if currency1 is specified"
            if (zeroForOne != (params.amountSpecified < 0)) {
                swapDelta = toBalanceDelta(
                    amountCalculated.toInt128(), (params.amountSpecified - amountSpecifiedRemaining).toInt128()
                );
            } else {
                swapDelta = toBalanceDelta(
                    (params.amountSpecified - amountSpecifiedRemaining).toInt128(), amountCalculated.toInt128()
                );
            }
        }
    }

    /// @notice Donates the given amount of currency0 and currency1 to the pool
    function donate(State storage state, uint256 amount0, uint256 amount1) internal returns (BalanceDelta delta) {
        uint128 liquidity = state.liquidity;
        if (liquidity == 0) NoLiquidityToReceiveFees.selector.revertWith();
        unchecked {
            // negation safe as amount0 and amount1 are always positive
            delta = toBalanceDelta(-(amount0.toInt128()), -(amount1.toInt128()));
            // FullMath.mulDiv is unnecessary because the numerator is bounded by type(int128).max * Q128, which is less than type(uint256).max
            if (amount0 > 0) {
                state.feeGrowthGlobal0X128 += UnsafeMath.simpleMulDiv(amount0, FixedPoint128.Q128, liquidity);
            }
            if (amount1 > 0) {
                state.feeGrowthGlobal1X128 += UnsafeMath.simpleMulDiv(amount1, FixedPoint128.Q128, liquidity);
            }
        }
    }

    /// @notice Retrieves fee growth data
    /// @param self The Pool state struct
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
    /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
    function getFeeGrowthInside(State storage self, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        TickInfo storage lower = self.ticks[tickLower];
        TickInfo storage upper = self.ticks[tickUpper];
        int24 tickCurrent = self.slot0.tick();

        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128;
                feeGrowthInside1X128 = lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upper.feeGrowthOutside0X128 - lower.feeGrowthOutside0X128;
                feeGrowthInside1X128 = upper.feeGrowthOutside1X128 - lower.feeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 =
                    self.feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128;
                feeGrowthInside1X128 =
                    self.feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128;
            }
        }
    }

    /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tick The tick that will be updated
    /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
    /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
    /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
    /// @return liquidityGrossAfter The total amount of liquidity for all positions that references the tick after the update
    function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper)
        internal
        returns (bool flipped, uint128 liquidityGrossAfter)
    {
        TickInfo storage info = self.ticks[tick];

        uint128 liquidityGrossBefore = info.liquidityGross;
        int128 liquidityNetBefore = info.liquidityNet;

        liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);

        flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);

        if (liquidityGrossBefore == 0) {
            // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
            if (tick <= self.slot0.tick()) {
                info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128;
                info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128;
            }
        }

        // when the lower (upper) tick is crossed left to right, liquidity must be added (removed)
        // when the lower (upper) tick is crossed right to left, liquidity must be removed (added)
        int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta;
        assembly ("memory-safe") {
            // liquidityGrossAfter and liquidityNet are packed in the first slot of `info`
            // So we can store them with a single sstore by packing them ourselves first
            sstore(
                info.slot,
                // bitwise OR to pack liquidityGrossAfter and liquidityNet
                or(
                    // Put liquidityGrossAfter in the lower bits, clearing out the upper bits
                    and(liquidityGrossAfter, 0xffffffffffffffffffffffffffffffff),
                    // Shift liquidityNet to put it in the upper bits (no need for signextend since we're shifting left)
                    shl(128, liquidityNet)
                )
            )
        }
    }

    /// @notice Derives max liquidity per tick from given tick spacing
    /// @dev Executed when adding liquidity
    /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
    ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
    /// @return result The max liquidity per tick
    function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) {
        // Equivalent to:
        // int24 minTick = (TickMath.MIN_TICK / tickSpacing);
        // if (TickMath.MIN_TICK  % tickSpacing != 0) minTick--;
        // int24 maxTick = (TickMath.MAX_TICK / tickSpacing);
        // uint24 numTicks = maxTick - minTick + 1;
        // return type(uint128).max / numTicks;
        int24 MAX_TICK = TickMath.MAX_TICK;
        int24 MIN_TICK = TickMath.MIN_TICK;
        // tick spacing will never be 0 since TickMath.MIN_TICK_SPACING is 1
        assembly ("memory-safe") {
            tickSpacing := signextend(2, tickSpacing)
            let minTick := sub(sdiv(MIN_TICK, tickSpacing), slt(smod(MIN_TICK, tickSpacing), 0))
            let maxTick := sdiv(MAX_TICK, tickSpacing)
            let numTicks := add(sub(maxTick, minTick), 1)
            result := div(sub(shl(128, 1), 1), numTicks)
        }
    }

    /// @notice Reverts if the given pool has not been initialized
    function checkPoolInitialized(State storage self) internal view {
        if (self.slot0.sqrtPriceX96() == 0) PoolNotInitialized.selector.revertWith();
    }

    /// @notice Clears tick data
    /// @param self The mapping containing all initialized tick information for initialized ticks
    /// @param tick The tick that will be cleared
    function clearTick(State storage self, int24 tick) internal {
        delete self.ticks[tick];
    }

    /// @notice Transitions to next tick as needed by price movement
    /// @param self The Pool state struct
    /// @param tick The destination tick of the transition
    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
    /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
    function crossTick(State storage self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128)
        internal
        returns (int128 liquidityNet)
    {
        unchecked {
            TickInfo storage info = self.ticks[tick];
            info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
            info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
            liquidityNet = info.liquidityNet;
        }
    }
}

lib/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/v4-core/src/libraries/ProtocolFeeLibrary.sol

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

/// @notice library of functions related to protocol fees
library ProtocolFeeLibrary {
    /// @notice Max protocol fee is 0.1% (1000 pips)
    /// @dev Increasing these values could lead to overflow in Pool.swap
    uint16 public constant MAX_PROTOCOL_FEE = 1000;

    /// @notice Thresholds used for optimized bounds checks on protocol fees
    uint24 internal constant FEE_0_THRESHOLD = 1001;
    uint24 internal constant FEE_1_THRESHOLD = 1001 << 12;

    /// @notice the protocol fee is represented in hundredths of a bip
    uint256 internal constant PIPS_DENOMINATOR = 1_000_000;

    function getZeroForOneFee(uint24 self) internal pure returns (uint16) {
        return uint16(self & 0xfff);
    }

    function getOneForZeroFee(uint24 self) internal pure returns (uint16) {
        return uint16(self >> 12);
    }

    function isValidProtocolFee(uint24 self) internal pure returns (bool valid) {
        // Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE
        assembly ("memory-safe") {
            let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD)
            let isOneForZeroFeeOk := lt(and(self, 0xfff000), FEE_1_THRESHOLD)
            valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk)
        }
    }

    // The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining
    // The swap fee is capped at 100%
    // Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 (rounded up)
    /// @dev here `self` is just a single direction's protocol fee, not a packed type of 2 protocol fees
    function calculateSwapFee(uint16 self, uint24 lpFee) internal pure returns (uint24 swapFee) {
        // protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)
        assembly ("memory-safe") {
            self := and(self, 0xfff)
            lpFee := and(lpFee, 0xffffff)
            let numerator := mul(self, lpFee)
            swapFee := sub(add(self, lpFee), div(numerator, PIPS_DENOMINATOR))
        }
    }
}

lib/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/v4-core/src/libraries/SqrtPriceMath.sol

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

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

import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

    error InvalidPriceOrLiquidity();
    error InvalidPrice();
    error NotEnoughLiquidity();
    error PriceOverflow();

    /// @notice Gets the next sqrt price given a delta of currency0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of currency0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            unchecked {
                uint256 product = amount * sqrtPX96;
                if (product / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1) {
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                    }
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product = amount * sqrtPX96;
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
                assembly ("memory-safe") {
                    if iszero(
                        and(
                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                            gt(numerator1, product)
                        )
                    ) {
                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()
                        revert(0x1c, 0x04)
                    }
                }
                uint256 denominator = numerator1 - product;
                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
            }
        }
    }

    /// @notice Gets the next sqrt price given a delta of currency1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of currency1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
            assembly ("memory-safe") {
                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
                    revert(0x1c, 0x04)
                }
            }
            // always fits 160 bits
            unchecked {
                return uint160(sqrtPX96 - quotient);
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of currency0, or currency1, is being swapped in
    /// @param zeroForOne Whether the amount in is currency0 or currency1
    /// @return uint160 The price after adding the input amount to currency0 or currency1
    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we don't pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of currency0, or currency1, is being swapped out
    /// @param zeroForOne Whether the amount out is currency1 or currency0
    /// @return uint160 The price after removing the output amount of currency0 or currency1
    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
            assembly ("memory-safe") {
                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
                    mstore(0, 0x00bfc921) // selector for InvalidPrice()
                    revert(0x1c, 0x04)
                }
            }

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;

            return roundUp
                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
        }
    }

    /// @notice Equivalent to: `a >= b ? a - b : b - a`
    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly ("memory-safe") {
            let diff :=
                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
            // mask = 0 if a >= b else -1 (all 1s)
            let mask := sar(255, diff)
            // if a >= b, res = a - b = 0 ^ (a - b)
            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
            // either way, res = mask ^ (a - b + mask)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256 amount1)
    {
        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity = uint256(liquidity);

        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
        assembly ("memory-safe") {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @notice Helper that gets signed currency0 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }

    /// @notice Helper that gets signed currency1 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }
}

lib/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/v4-core/src/libraries/SwapMath.sol

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

import {FullMath} from "./FullMath.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";

/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    /// @notice the swap fee is represented in hundredths of a bip, so the max is 100%
    /// @dev the swap fee is the total fee on a swap, including both LP and Protocol fee
    uint256 internal constant MAX_SWAP_FEE = 1e6;

    /// @notice Computes the sqrt price target for the next swap step
    /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0
    /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
    /// after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @return sqrtPriceTargetX96 The price target for the next swap step
    function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
        internal
        pure
        returns (uint160 sqrtPriceTargetX96)
    {
        assembly ("memory-safe") {
            // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
            // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
            // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
            // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
            // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceNextX96 := and(sqrtPriceNextX96, 0xffffffffffffffffffffffffffffffffffffffff)
            sqrtPriceLimitX96 := and(sqrtPriceLimitX96, 0xffffffffffffffffffffffffffffffffffffffff)
            let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), and(zeroForOne, 0x1))
            let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
        }
    }

    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
    /// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount.
    /// @param sqrtPriceCurrentX96 The current sqrt price of the pool
    /// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap
    /// @return feeAmount The amount of input that will be taken as a fee
    /// @dev feePips must be no larger than MAX_SWAP_FEE for this function. We ensure that before setting a fee using LPFeeLibrary.isValid.
    function computeSwapStep(
        uint160 sqrtPriceCurrentX96,
        uint160 sqrtPriceTargetX96,
        uint128 liquidity,
        int256 amountRemaining,
        uint24 feePips
    ) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) {
        unchecked {
            uint256 _feePips = feePips; // upcast once and cache
            bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96;
            bool exactIn = amountRemaining < 0;

            if (exactIn) {
                uint256 amountRemainingLessFee =
                    FullMath.mulDiv(uint256(-amountRemaining), MAX_SWAP_FEE - _feePips, MAX_SWAP_FEE);
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true);
                if (amountRemainingLessFee >= amountIn) {
                    // `amountIn` is capped by the target price
                    sqrtPriceNextX96 = sqrtPriceTargetX96;
                    feeAmount = _feePips == MAX_SWAP_FEE
                        ? amountIn // amountIn is always 0 here, as amountRemainingLessFee == 0 and amountRemainingLessFee >= amountIn
                        : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips);
                } else {
                    // exhaust the remaining amount
                    amountIn = amountRemainingLessFee;
                    sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                        sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne
                    );
                    // we didn't reach the target, so take the remainder of the maximum input as fee
                    feeAmount = uint256(-amountRemaining) - amountIn;
                }
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false);
            } else {
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false);
                if (uint256(amountRemaining) >= amountOut) {
                    // `amountOut` is capped by the target price
                    sqrtPriceNextX96 = sqrtPriceTargetX96;
                } else {
                    // cap the output amount to not exceed the remaining output amount
                    amountOut = uint256(amountRemaining);
                    sqrtPriceNextX96 =
                        SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne);
                }
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true);
                // `feePips` cannot be `MAX_SWAP_FEE` for exact out
                feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_SWAP_FEE - _feePips);
            }
        }
    }
}

lib/v4-core/src/libraries/TickBitmap.sol

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

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

/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
    /// @notice Thrown when the tick is not enumerated by the tick spacing
    /// @param tick the invalid tick
    /// @param tickSpacing The tick spacing of the pool
    error TickMisaligned(int24 tick, int24 tickSpacing);

    /// @dev round towards negative infinity
    function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {
        // compressed = tick / tickSpacing;
        // if (tick < 0 && tick % tickSpacing != 0) compressed--;
        assembly ("memory-safe") {
            tick := signextend(2, tick)
            tickSpacing := signextend(2, tickSpacing)
            compressed :=
                sub(
                    sdiv(tick, tickSpacing),
                    // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa
                    slt(smod(tick, tickSpacing), 0)
                )
        }
    }

    /// @notice Computes the position in the mapping where the initialized bit for a tick lives
    /// @param tick The tick for which to compute the position
    /// @return wordPos The key in the mapping containing the word in which the bit is stored
    /// @return bitPos The bit position in the word where the flag is stored
    function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {
        assembly ("memory-safe") {
            // signed arithmetic shift right
            wordPos := sar(8, signextend(2, tick))
            bitPos := and(tick, 0xff)
        }
    }

    /// @notice Flips the initialized state for a given tick from false to true, or vice versa
    /// @param self The mapping in which to flip the tick
    /// @param tick The tick to flip
    /// @param tickSpacing The spacing between usable ticks
    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
        // Equivalent to the following Solidity:
        //     if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing);
        //     (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
        //     uint256 mask = 1 << bitPos;
        //     self[wordPos] ^= mask;
        assembly ("memory-safe") {
            tick := signextend(2, tick)
            tickSpacing := signextend(2, tickSpacing)
            // ensure that the tick is spaced
            if smod(tick, tickSpacing) {
                let fmp := mload(0x40)
                mstore(fmp, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24)
                mstore(add(fmp, 0x20), tick)
                mstore(add(fmp, 0x40), tickSpacing)
                revert(add(fmp, 0x1c), 0x44)
            }
            tick := sdiv(tick, tickSpacing)
            // calculate the storage slot corresponding to the tick
            // wordPos = tick >> 8
            mstore(0, sar(8, tick))
            mstore(0x20, self.slot)
            // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))
            let slot := keccak256(0, 0x40)
            // mask = 1 << bitPos = 1 << (tick % 256)
            // self[wordPos] ^= mask
            sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))
        }
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param self The mapping in which to compute the next initialized tick
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    function nextInitializedTickWithinOneWord(
        mapping(int16 => uint256) storage self,
        int24 tick,
        int24 tickSpacing,
        bool lte
    ) internal view returns (int24 next, bool initialized) {
        unchecked {
            int24 compressed = compress(tick, tickSpacing);

            if (lte) {
                (int16 wordPos, uint8 bitPos) = position(compressed);
                // all the 1s at or to the right of the current bitPos
                uint256 mask = type(uint256).max >> (uint256(type(uint8).max) - bitPos);
                uint256 masked = self[wordPos] & mask;

                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                next = initialized
                    ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing
                    : (compressed - int24(uint24(bitPos))) * tickSpacing;
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (int16 wordPos, uint8 bitPos) = position(++compressed);
                // all the 1s at or to the left of the bitPos
                uint256 mask = ~((1 << bitPos) - 1);
                uint256 masked = self[wordPos] & mask;

                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                next = initialized
                    ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing
                    : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;
            }
        }
    }
}

lib/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/v4-core/src/libraries/UnsafeMath.sol

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

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @notice Returns ceil(x / y)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly ("memory-safe") {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }

    /// @notice Calculates floor(a×b÷denominator)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result, floor(a×b÷denominator)
    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            result := div(mul(a, b), denominator)
        }
    }
}

lib/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/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/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/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/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/v4-core/src/types/Slot0.sol

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

/**
 * @dev Slot0 is a packed version of solidity structure.
 * Using the packaged version saves gas by not storing the structure fields in memory slots.
 *
 * Layout:
 * 24 bits empty | 24 bits lpFee | 12 bits protocolFee 1->0 | 12 bits protocolFee 0->1 | 24 bits tick | 160 bits sqrtPriceX96
 *
 * Fields in the direction from the least significant bit:
 *
 * The current price
 * uint160 sqrtPriceX96;
 *
 * The current tick
 * int24 tick;
 *
 * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1
 * the maximum is 1000 - meaning the maximum protocol fee is 0.1%
 * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
 * uint24 protocolFee;
 *
 * The current LP fee of the pool. If the pool is dynamic, this does not include the dynamic fee flag.
 * uint24 lpFee;
 */
type Slot0 is bytes32;

using Slot0Library for Slot0 global;

/// @notice Library for getting and setting values in the Slot0 type
library Slot0Library {
    uint160 internal constant MASK_160_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
    uint24 internal constant MASK_24_BITS = 0xFFFFFF;

    uint8 internal constant TICK_OFFSET = 160;
    uint8 internal constant PROTOCOL_FEE_OFFSET = 184;
    uint8 internal constant LP_FEE_OFFSET = 208;

    // #### GETTERS ####
    function sqrtPriceX96(Slot0 _packed) internal pure returns (uint160 _sqrtPriceX96) {
        assembly ("memory-safe") {
            _sqrtPriceX96 := and(MASK_160_BITS, _packed)
        }
    }

    function tick(Slot0 _packed) internal pure returns (int24 _tick) {
        assembly ("memory-safe") {
            _tick := signextend(2, shr(TICK_OFFSET, _packed))
        }
    }

    function protocolFee(Slot0 _packed) internal pure returns (uint24 _protocolFee) {
        assembly ("memory-safe") {
            _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed))
        }
    }

    function lpFee(Slot0 _packed) internal pure returns (uint24 _lpFee) {
        assembly ("memory-safe") {
            _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed))
        }
    }

    // #### SETTERS ####
    function setSqrtPriceX96(Slot0 _packed, uint160 _sqrtPriceX96) internal pure returns (Slot0 _result) {
        assembly ("memory-safe") {
            _result := or(and(not(MASK_160_BITS), _packed), and(MASK_160_BITS, _sqrtPriceX96))
        }
    }

    function setTick(Slot0 _packed, int24 _tick) internal pure returns (Slot0 _result) {
        assembly ("memory-safe") {
            _result := or(and(not(shl(TICK_OFFSET, MASK_24_BITS)), _packed), shl(TICK_OFFSET, and(MASK_24_BITS, _tick)))
        }
    }

    function setProtocolFee(Slot0 _packed, uint24 _protocolFee) internal pure returns (Slot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(
                    and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed),
                    shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee))
                )
        }
    }

    function setLpFee(Slot0 _packed, uint24 _lpFee) internal pure returns (Slot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee)))
        }
    }
}

src/base/BaseHook.sol

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

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";

/// @notice A Uniswap v4 hook base with only the callbacks ZappyHook's address enables (the PoolManager calls no other:
///         Hooks.callHook only calls a callback whose flag is set), each reverting Disabled unless the hook overrides it.
///         A hook overrides the callbacks it acts in; one its address enables only to refuse it (ZappyHook's
///         beforeInitialize, beforeAddLiquidity and beforeDonate) keeps the revert, so the refusal has a clear error.
///         Checks the address's permission bits on deploy.
abstract contract BaseHook {
    error NotPoolManager();
    error Disabled();

    IPoolManager public immutable poolManager;

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

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
        Hooks.validateHookPermissions(IHooks(address(this)), _permissions());
    }

    /// @dev The callbacks this hook's address enables (the PoolManager calls only these). An enabled callback that isn't
    ///      overridden reverts Disabled: that refuses the action.
    function _permissions() internal pure virtual returns (Hooks.Permissions memory);

    function beforeInitialize(address, PoolKey calldata, uint160) external virtual returns (bytes4) {
        revert Disabled();
    }

    function beforeAddLiquidity(address, PoolKey calldata, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)
        external
        virtual
        returns (bytes4)
    {
        revert Disabled();
    }

    function beforeSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, bytes calldata)
        external
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert Disabled();
    }

    function afterSwap(address, PoolKey calldata, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)
        external
        virtual
        returns (bytes4, int128)
    {
        revert Disabled();
    }

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

src/base/Owned.sol

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

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";

/// @notice OpenZeppelin's two-step ownership (the owner is a Safe), without renouncing: an ownerless contract could never
///         rotate its keys or recover from a bad registrar again.
abstract contract Owned is Ownable2Step {
    error RenounceDisabled();

    constructor(address owner_) Ownable(owner_) {}

    function renounceOwnership() public pure override {
        revert RenounceDisabled();
    }
}

src/hook/HookClaims.sol

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

import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {IZappyFactory} from "../interfaces/IZappyFactory.sol";
import {HookTax} from "./HookTax.sol";

/// @title HookClaims
/// @notice Paying out: creator and team balances, and handing a pool's creator fees on.
abstract contract HookClaims is HookTax {
    using PoolIdLibrary for PoolKey;

    /// @notice Pays a pool's creator balance to `to`: every creator fee is owed, never paid in a swap. Anyone can send it
    ///         to the creator (the keeper's payouts); only the creator can name another `to`.
    function claimCreator(PoolKey calldata key, address to) external {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        uint256 amount = p.creatorOwed;
        if (amount == 0) return;
        address creator = p.creator;
        if (creator != address(0)) {
            if (to == address(0)) revert ZeroAddress();
            if (to != creator && msg.sender != creator) revert NotCreator();
        }
        p.creatorOwed = 0;
        if (creator == address(0)) {
            // $ZAPPY's creator fee is ZAPPY's revenue, credited in every swap: this is only what a swap couldn't credit
            // (CreditFailed). ZappyRevenue shares it out with the partners at this claim (no trader, so no referral)
            revenue.credit(Currency.unwrap(key.currency0), address(0), 0, amount);
            return;
        }
        _pay(key.currency0, to, amount);
    }

    /// @notice Pays the team what the hook keeps for it ($ZAPPY's own pool's swept floor money, a protocol fee whose
    ///         credit failed): the protocol fee normally goes through ZappyRevenue in the swap.
    function claimTeam(Currency currency) external {
        uint256 amount = teamOwed[currency];
        if (amount == 0) return;
        teamOwed[currency] = 0;
        _pay(currency, IZappyFactory(factory).team(), amount);
    }

    function setCreator(PoolKey calldata key, address creator) external {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        if (p.creator == address(0) || msg.sender != p.creator || creator == address(0)) revert NotCreator();
        p.creator = creator;
        emit CreatorChanged(id, creator);
    }

    function _pay(Currency currency, address to, uint256 amount) internal {
        poolManager.unlock(abi.encode(ACTION_CLAIM, abi.encode(currency, to, amount)));
        emit Claimed(to, Currency.unwrap(currency), amount);
    }
}

src/hook/HookFloor.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {FullMath} from "v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/src/libraries/FixedPoint96.sol";
import {SafeCast} from "v4-core/src/libraries/SafeCast.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {Pool as V4Pool} from "v4-core/src/libraries/Pool.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {N_TRANCHES} from "../libraries/Curve.sol";
import {FloorMath} from "../libraries/FloorMath.sol";
import {Ticks} from "../libraries/Ticks.sol";
import {IZappyToken} from "../interfaces/IZappyToken.sol";
import {HookStorage} from "./HookStorage.sol";

/// @title HookFloor
/// @notice The floor: a single-tick band of quote under the price that can buy back every circulating token. Once per
///         block, before the block's first swap and on the state the block started with, it moves up as far as the floor
///         money allows (a raise), buys back and burns tokens with money the band can't use under the price (a
///         buyback), or sends an empty pool's floor money to the burn (a drain). It never moves down.
abstract contract HookFloor is HookStorage {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using SafeCast for uint256;

    /// @notice Raise entry used from beforeSwap (via try/catch). Only callable by the hook itself.
    function raiseFromHook(PoolKey calldata key) external {
        if (msg.sender != address(this)) revert NotSelf();
        _raise(key);
    }

    /// @notice Applies the pot to the floor now. Anyone can call it; trading normally does this already (a block's first
    ///         swap settles the block: a poke after it does nothing until the next block).
    function poke(PoolKey calldata key) external {
        if (pools[key.toId()].token == address(0)) revert UnknownPool();
        poolManager.unlock(abi.encode(ACTION_POKE, abi.encode(key)));
    }

    struct Ctx {
        uint160 sCur;
        int24 cur;
        uint256 circulating;
        int24 tLow;
        int24 tHigh;
        uint256 vested; // snipe tax vested since the last raise (moved into pot by this raise)
        // the most quote over the price (pot, vested snipe tax, band, tranche 0's curve) the circulating tokens can
        // carry: their worth at the highest price a buyback may lift to (_setCap). More would only wait under the price
        // for whoever buys past the next tranche's start (_rebuild and _planDrain send it to the burn)
        uint256 cap;
        bool go;
        // the floor money the circulating tokens can't carry leaves (_drain) without a raise: an empty pool's (all of it,
        // circulating < EMPTY_CIRCULATING), or one beyond `cap` that can't move this block. The band keeps `keep`, the
        // pot loses `potOut`, `swept` of the snipe pot leaves with them
        bool drain;
        uint128 keep;
        uint256 potOut;
        uint256 swept;
        // computed once per raise, read by every step of the search:
        uint160 sF; // sqrt price at tickF
        uint256 qBase; // the pot, the vested snipe tax and the old band's quote
        uint256 first; // first live tranche (merged + 1)
        uint256 last; // tranches first..last-1 may be passed by this raise (reached by the price, within MAX_PASS)
        int24[N_TRANCHES] start; // start tick of each passable tranche
        uint160[N_TRANCHES] sStart; // and its sqrt price
        uint256[N_TRANCHES] absorbKept; // tokens a passable tranche takes back above the price if it isn't passed
        uint256 absorbFixed; // the same, summed over the reached tranches this raise can't pass
        uint128 lbMax; // most liquidity the band may hold: v4's per-tick cap less everything placed at MIN_TICK
        // buyback: the backing can carry the floor above the price's cap. The floor goes to tBuyMin + 60..tBuy and the
        // price is lifted to two spacings over it
        bool buy;
        int24 tBuy;
        int24 tBuyMin;
    }

    /// @dev Can the floor move up at least one tick right now? View-only; _raise acts on it.
    function _plan(Pool storage p, PoolId id) internal view returns (Ctx memory c) {
        // no pot gate: the old band's quote, the vested snipe tax and the quote freed above can fund a climb too
        (c.sCur, c.cur,,) = poolManager.getSlot0(id);
        int24 tickF = p.tickF;
        c.circulating = _circulating(p, c.sCur);
        if (c.circulating < EMPTY_CIRCULATING) {
            // nothing an empty pool holds backs anyone (cap 0): the snipe pot leaves too, vested or not. Left vesting it
            // would only go to whoever buys next (E12)
            c.swept = p.snipePot - p.snipeReleased;
            _planDrain(p, c);
            return c;
        }
        // price past the band: nothing to do. Inside it (being eaten), only a buyback may move the floor: it burns the
        // tokens the band bought back and lifts the price over the new band
        if (c.cur >= p.tickB + SPACING) return c;
        // lowest candidate: one full spacing above both the start-of-block tick and the current tick
        int24 base = c.cur > p.refTick ? c.cur : p.refTick;
        c.tLow = Ticks.alignDown(base) + 2 * SPACING;
        // pass cap: the floor stops at the start of the (MAX_PASS + 1)-th live tranche; the next raise continues
        c.first = uint256(p.merged) + 1;
        c.last = c.first + MAX_PASS;
        if (c.last < N_TRANCHES) {
            int24 capLow = _start(p, c.last);
            if (c.tLow < capLow) c.tLow = capLow;
        } else {
            c.last = N_TRANCHES;
        }
        c.tHigh = tickF - SPACING;
        // buyback candidates: at least one spacing over the price, never lifting it past the next live tranche's start
        // (only while none is reached, so tranche 0 is all there is between the old and the new price), and never while
        // the price is above where the block started: a buyback only ever lifts a price no one has pumped this block
        c.tBuy = Ticks.alignDown(c.cur) + SPACING;
        if (c.tBuy > c.tHigh) c.tBuy = c.tHigh;
        int24 nextStart = c.first < N_TRANCHES ? _start(p, c.first) : MIN_TICK;
        c.tBuyMin = nextStart + 2 * SPACING; // every tranche merged: MIN_TICK + 120, the lowest a lifted price can go
        // every search below keeps a one-spacing margin: it lands one spacing under the tightest floor its rounding
        // allows, so the rebuilt positions never miss C by a wei (FloorBroken)
        bool canBuy = c.tBuyMin <= c.tBuy - SPACING && nextStart <= c.cur && c.cur >= p.refTick;
        c.sF = TickMath.getSqrtPriceAtTick(tickF);
        uint160 sB = TickMath.getSqrtPriceAtTick(p.tickB);
        uint256 band =
            FloorMath.quote(c.sCur > sB ? c.sCur : sB, TickMath.getSqrtPriceAtTick(p.tickB + SPACING), p.liqBand, false);
        c.vested = _vested(p);
        c.qBase = p.pot + c.vested + band;
        if (c.tLow > c.tHigh - SPACING && !canBuy) {
            _drainIfOver(p, c);
            return c;
        }
        // a floor that can't use all its money within the per-tick cap leaves the rest in pot
        c.lbMax = _lbMax(id);
        // Only tranches the price has reached (cur < start) can be passed: every candidate t is above the current tick.
        // Starts only rise with i, so the first one not reached ends the reached ones.
        uint256 i = c.first;
        for (; i < N_TRANCHES; i++) {
            int24 s = _start(p, i);
            if (c.cur >= s) break;
            uint160 sS = TickMath.getSqrtPriceAtTick(s);
            uint256 kept = FloorMath.token(c.sCur, sS, p.liqs[i], false);
            if (i < c.last) {
                c.start[i] = s;
                c.sStart[i] = sS;
                c.absorbKept[i] = kept;
            } else {
                c.absorbFixed += kept;
            }
        }
        if (i < c.last) c.last = i;
        if (canBuy && _okBuy(p, c, c.tBuy - SPACING)) {
            c.buy = true;
            c.go = true;
        } else if (c.tLow <= c.tHigh - SPACING) {
            c.go = _ok(p, c, c.tHigh - SPACING);
        }
        if (!c.go) _drainIfOver(p, c);
    }

    /// @dev Ctx.cap: the circulating tokens' worth at the highest price a buyback may lift to, the next live tranche's
    ///      start (tBuyMin - 120, _plan), unless the price is already past it. Only an almost empty pool (a few tokens
    ///      left after an exit) gets near it: a real holder base is worth far more there than the floor holds.
    function _setCap(Ctx memory c) internal pure {
        int24 s = c.tBuyMin - 2 * SPACING;
        uint160 sCap = s <= c.cur ? TickMath.getSqrtPriceAtTick(s) : c.sCur;
        c.cap = FullMath.mulDiv(FullMath.mulDiv(c.circulating, FixedPoint96.Q96, sCap), FixedPoint96.Q96, sCap);
    }

    /// @dev A floor that can't move this block but holds more than the holders can carry (tranche 0's quote over the
    ///      price counted: they sell into it first) drains the rest instead (_planDrain).
    function _drainIfOver(Pool storage p, Ctx memory c) internal view {
        _setCap(c);
        if (c.qBase + FloorMath.quote(c.sCur, c.sF, p.liqs[0], true) > c.cap) _planDrain(p, c);
    }

    /// @dev Floor money beyond what the circulating tokens can carry (_plan's c.cap; an empty pool: all of it) leaves for
    ///      the burn (_drain) without a raise: the band is cut to _bandMax (never below what absorbs every circulating
    ///      token tranche 0 doesn't, so the invariant still holds and the dust can still sell), then the pot and then the
    ///      vested snipe tax keep what that leaves of c.cap. The rest leaves (an empty pool's unvested snipe tax too,
    ///      c.swept), once it is more than 1/DRAIN_SLACK of c.cap (an empty pool's: anything).
    function _planDrain(Pool storage p, Ctx memory c) internal view {
        c.drain = true;
        c.keep = p.liqBand;
        uint160 sF = TickMath.getSqrtPriceAtTick(p.tickF);
        uint160 sB1 = TickMath.getSqrtPriceAtTick(p.tickB + SPACING);
        uint160 sTop = c.sCur > sF ? c.sCur : sF; // tranche 0's top
        uint160 sLow = TickMath.getSqrtPriceAtTick(p.tickB);
        if (c.sCur > sLow) sLow = c.sCur; // the band's near edge
        uint256 band = FloorMath.quote(sLow, sB1, c.keep, true);
        (uint256 lMax, uint256 room) = _bandMax(c, c.sCur, sTop, sLow, sB1, p.liqs[0], band);
        // forge-lint: disable-next-line(unsafe-typecast)
        if (lMax < c.keep) c.keep = uint128(lMax); // lMax < keep, a uint128
        // cut or not, the band takes `band` of the room or all of it (a cut band's quote was more than the room)
        room = room > band ? room - band : 0;
        uint256 pot = p.pot;
        if (pot > room) c.potOut = pot - room;
        room -= pot - c.potOut;
        if (c.vested > room) (c.swept, c.vested) = (c.swept + c.vested - room, room);
        // the snipe tax and pot that leave, and the band's quote above `keep` (both rounded up, so 0 if it isn't cut)
        c.go = c.swept + c.potOut + band - FloorMath.quote(sLow, sB1, c.keep, true) > c.cap / DRAIN_SLACK;
    }

    /// @dev Most liquidity a band over [sA, sB] may hold: what c.cap buys after the quote tranche 0 (liquidity `l0`) holds
    ///      between the price sP and its top sTop (sA, unless a collect moved the band off it), which the circulating
    ///      tokens sell into first, but never less than what absorbs every circulating token that curve doesn't (the
    ///      invariant; rounds against itself). No limit (the uint256 max) while the band's quote `q` fits: c.cap can be
    ///      astronomically large, so its liquidity is only computed when it is below a real amount. Also returns the quote
    ///      c.cap leaves after the curve, for the band and the pot.
    function _bandMax(Ctx memory c, uint160 sP, uint160 sTop, uint160 sA, uint160 sB, uint128 l0, uint256 q)
        internal
        pure
        returns (uint256 lMax, uint256 room)
    {
        uint256 qc = FloorMath.quote(sP, sTop, l0, true);
        room = c.cap > qc ? c.cap - qc : 0;
        if (q <= room) return (type(uint256).max, room);
        lMax = FloorMath.liquidityForQuote(sA, sB, room);
        uint256 tc = FloorMath.token(sP, sTop, l0, false);
        if (c.circulating > tc) {
            uint256 need = uint256(FloorMath.liquidityForToken(sA, sB, c.circulating - tc)) + 1;
            if (need > lMax) lMax = need;
        }
    }

    /// @dev Snipe tax vested since the last release: snipePot x min(elapsed, SNIPE_VEST) / SNIPE_VEST - snipeReleased,
    ///      or 0 while that is below what has left already: a drain releases the whole snipe pot at once (_plan), so tax
    ///      paid after it vests only once the schedule passes what left, still all of it by SNIPE_VEST. Never reverts:
    ///      _plan runs outside the raise's try/catch, so a revert here would block every swap.
    function _vested(Pool storage p) internal view returns (uint256) {
        uint256 e = block.timestamp - uint256(p.launchedAt);
        if (e > SNIPE_VEST) e = SNIPE_VEST;
        uint256 v = uint256(p.snipePot) * e / SNIPE_VEST;
        uint256 r = p.snipeReleased;
        return v > r ? v - r : 0;
    }

    function _raise(PoolKey memory key) internal {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        uint256 bn = _blockNumber();
        if (p.lastRaiseBlock == bn) return;
        Ctx memory c = _plan(p, id);
        if (!c.go) return;
        // this block's raise (or drain): a revert below rolls it back with everything else. A block number: < 2^64
        // forge-lint: disable-next-line(unsafe-typecast)
        p.lastRaiseBlock = uint64(bn);
        if (c.drain) return _drain(key, p, c);
        // the vested snipe tax joins the pot; what the holders can't carry leaves in the rebuild (c.cap)
        p.pot += c.vested;
        p.snipeReleased += c.vested.toUint128();
        // binary search for the lowest t (highest floor) that still absorbs everything; hi always satisfies the check.
        // The floor goes one spacing under it (the margin, see _plan)
        int256 lo = int256((c.buy ? c.tBuyMin : c.tLow) / SPACING);
        int256 hi = int256((c.buy ? c.tBuy : c.tHigh) / SPACING) - 1;
        while (lo < hi) {
            int256 mid = (lo + hi) >> 1; // arithmetic shift = floor division, also for negatives
            // forge-lint: disable-next-line(unsafe-typecast)
            int24 m = int24(mid * SPACING); // lo <= mid <= hi: between two int24 ticks
            if (c.buy ? _okBuy(p, c, m) : _ok(p, c, m)) hi = mid;
            else lo = mid + 1;
        }
        int24 t = int24((hi + 1) * SPACING);
        _setCap(c);
        (uint256 bandQuote, uint256 burned) = _rebuild(key, p, t, c);
        // re-check against what the positions actually hold now
        (uint160 sNow,,,) = poolManager.getSlot0(id);
        if (_absorbNow(p, sNow) < _circulating(p, sNow)) revert FloorBroken();
        if (c.buy) emit BoughtBack(id, burned, sNow);
        emit FloorRaised(id, t, TickMath.getSqrtPriceAtTick(t + SPACING), bandQuote, c.circulating);
    }

    /// @dev Floor money the circulating tokens can't carry (_planDrain) leaves for the burn: `swept` of the snipe pot (the
    ///      rest of what vested joins the pot), `potOut` of the pot and the band's liquidity above `keep`. Tokens that
    ///      liquidity held (a band the price is inside) join the dust reserve, so circulating doesn't change. No price
    ///      impact: only the band moves, and never below what absorbs every circulating token.
    function _drain(PoolKey memory key, Pool storage p, Ctx memory c) internal {
        PoolId id = key.toId();
        uint256 amount = c.swept + c.potOut;
        p.snipeReleased += (c.vested + c.swept).toUint128();
        p.pot = p.pot + c.vested - c.potOut;
        if (c.keep < p.liqBand) {
            (uint256 q,) = _pullBand(key, p, p.liqBand - c.keep);
            amount += q;
            // every token left can still sell into what remains of the band
            if (_absorbNow(p, c.sCur) < c.circulating) revert FloorBroken();
        }
        if (amount != 0) emit FloorSwept(id, amount, _burnShare(p, id, key.currency0, amount));
    }

    /// @dev Takes `liq` of the band out: its quote becomes the hook's claims (returned, for the caller to account for),
    ///      its tokens (a band the price is inside) join the dust reserve as claims. Removing liquidity only ever pays out.
    function _pullBand(PoolKey memory key, Pool storage p, uint128 liq) internal returns (uint256 q, uint256 t) {
        BalanceDelta d = _modify(key, p.tickB, p.tickB + SPACING, -int256(uint256(liq)), SALT_BAND);
        p.liqBand -= liq;
        q = uint256(int256(d.amount0()));
        t = uint256(int256(d.amount1()));
        if (q != 0) poolManager.mint(address(this), key.currency0.toId(), q);
        if (t != 0) {
            poolManager.mint(address(this), key.currency1.toId(), t);
            p.reserve += t;
        }
    }

    /// @dev Most liquidity the band may hold: v4's per-tick cap less everything placed at MIN_TICK (every tranche's lower
    ///      tick; the band's ticks hold at most those same positions' upper ends, so a band within this always fits).
    function _lbMax(PoolId id) internal view returns (uint128) {
        (uint128 placed,) = poolManager.getTickLiquidity(id, MIN_TICK);
        return V4Pool.tickSpacingToMaxLiquidityPerTick(SPACING) - placed;
    }

    /// @dev Would a band at [t, t+60] (funded by the pot, the old band and the quote freed above t) plus the curve
    ///      between the price and t absorb every circulating token? Rounds against itself. Tranche 0 is cut from tickF
    ///      to t, and every live tranche starting above t is merged into it: their liquidity ends up in [MIN_TICK, t]
    ///      and their quote in [t, start] moves into the band. t is always above the current tick. (_okBuy is the buyback
    ///      version.)
    function _ok(Pool storage p, Ctx memory c, int24 t) internal view returns (bool) {
        uint160 sT = TickMath.getSqrtPriceAtTick(t);
        uint160 sT1 = TickMath.getSqrtPriceAtTick(t + SPACING);
        uint128 lCut = p.liqs[0];
        uint256 q = c.qBase + FloorMath.quote(sT, c.sF, lCut, false);
        uint256 absorb = c.absorbFixed;
        for (uint256 i = c.first; i < c.last; i++) {
            if (c.start[i] > t) {
                uint128 l = p.liqs[i];
                q += FloorMath.quote(sT, c.sStart[i], l, false);
                lCut += l;
            } else {
                absorb += c.absorbKept[i];
            }
        }
        absorb += FloorMath.token(c.sCur, sT, lCut, false);
        absorb += FloorMath.token(sT, sT1, _bandLiquidity(sT, sT1, q, c.lbMax), false);
        return absorb >= c.circulating;
    }

    /// @dev Liquidity `q` of quote buys in the band at [sT, sT1], capped at lbMax (_plan).
    function _bandLiquidity(uint160 sT, uint160 sT1, uint256 q, uint128 lbMax) internal pure returns (uint128 lb) {
        lb = FloorMath.liquidityForQuote(sT, sT1, q);
        if (lb > lbMax) lb = lbMax;
    }

    /// @dev Buyback check: would a band at [t, t+60] absorb every circulating token if the price were lifted to t - 120
    ///      first? Tranche 0 then holds quote over [price, t] (taking back token(price, t)); everything else it held
    ///      above the old price, the pot, the vested snipe tax and the old band fund the band. The tokens tranche 0 no
    ///      longer holds below the new price are burned, so circulating doesn't change. Rounds against itself.
    function _okBuy(Pool storage p, Ctx memory c, int24 t) internal view returns (bool) {
        uint160 sP = TickMath.getSqrtPriceAtTick(t - 2 * SPACING);
        uint160 sT = TickMath.getSqrtPriceAtTick(t);
        uint160 sT1 = TickMath.getSqrtPriceAtTick(t + SPACING);
        uint128 l0 = p.liqs[0];
        uint256 q = c.qBase + FloorMath.quote(c.sCur, c.sF, l0, false);
        uint256 kept = FloorMath.quote(sP, sT, l0, true);
        if (kept >= q) return false;
        uint256 absorb = FloorMath.token(sP, sT, l0, false)
            + FloorMath.token(sT, sT1, _bandLiquidity(sT, sT1, q - kept, c.lbMax), false);
        return absorb >= c.circulating;
    }

    /// @dev Tokens the positions take back as the price falls from sCur to the far edge of the band.
    function _absorbNow(Pool storage p, uint160 sCur) internal view returns (uint256 absorb) {
        uint160 sF = TickMath.getSqrtPriceAtTick(p.tickF);
        absorb = FloorMath.token(sCur, sF, p.liqs[0], false)
            + FloorMath.token(
                TickMath.getSqrtPriceAtTick(p.tickB), TickMath.getSqrtPriceAtTick(p.tickB + SPACING), p.liqBand, false
            );
        for (uint256 i = uint256(p.merged) + 1; i < N_TRANCHES; i++) {
            uint160 sS = TickMath.getSqrtPriceAtTick(_start(p, i));
            if (sCur >= sS) break; // not reached yet, and starts only rise from here
            absorb += FloorMath.token(sCur, sS, p.liqs[i], false);
        }
    }

    /// @dev Tokens outside this pool's positions and dust reserve. Anything else the hook holds counts as circulating.
    function _circulating(Pool storage p, uint160 sCur) internal view returns (uint256) {
        uint160 sMin = TickMath.getSqrtPriceAtTick(MIN_TICK);
        uint160 sF = TickMath.getSqrtPriceAtTick(p.tickF);
        uint256 held = FloorMath.token(sMin, sCur < sF ? sCur : sF, p.liqs[0], false) + p.reserve;
        for (uint256 i = uint256(p.merged) + 1; i < N_TRANCHES; i++) {
            uint160 sS = TickMath.getSqrtPriceAtTick(_start(p, i));
            held += FloorMath.token(sMin, sCur < sS ? sCur : sS, p.liqs[i], false);
        }
        uint160 sB = TickMath.getSqrtPriceAtTick(p.tickB);
        if (sCur > sB) {
            uint160 sB1 = TickMath.getSqrtPriceAtTick(p.tickB + SPACING);
            held += FloorMath.token(sB, sCur < sB1 ? sCur : sB1, p.liqBand, false);
        }
        uint256 supply = IZappyToken(p.token).totalSupply();
        return supply > held ? supply - held : 0;
    }

    /// @dev Moves tranche 0's top down to t, merging in every live tranche that starts above t (removed, its liquidity
    ///      added to tranche 0's: the same amounts as cutting each to t, but later raises only rebuild tranche 0), and
    ///      puts the freed quote plus the pot into a band at [t, t+60]. Everything touched is above the current tick: no
    ///      price impact, except a buyback (c.buy), which moves the price to t - 120 while tranche 0 and the band are
    ///      out and burns the tokens they no longer need. The band never takes more than c.cap (what the circulating
    ///      tokens can carry); the rest leaves the pot for the burn. Settles exactly the deltas the PoolManager returned,
    ///      against the pot (quote) and the dust reserve or the burn (token).
    function _rebuild(PoolKey memory key, Pool storage p, int24 t, Ctx memory c)
        internal
        returns (uint256 bandQuote, uint256 burned)
    {
        int256 d0;
        int256 d1;
        BalanceDelta d;
        if (p.liqBand != 0) {
            d = _modify(key, p.tickB, p.tickB + SPACING, -int256(uint256(p.liqBand)), SALT_BAND);
            (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
        }
        uint128 l0 = p.liqs[0];
        uint128 added;
        uint256 i = uint256(p.merged) + 1;
        for (; i < N_TRANCHES; i++) {
            int24 s = _start(p, i);
            if (s <= t) break; // _plan's pass cap keeps this to at most MAX_PASS tranches
            uint128 l = p.liqs[i];
            d = _modify(key, MIN_TICK, s, -int256(uint256(l)), _salt(i));
            (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
            added += l;
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        p.merged = uint8(i - 1); // i <= N_TRANCHES
        d = _modify(key, MIN_TICK, p.tickF, -int256(uint256(l0)), _salt(0));
        (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
        if (c.buy) {
            // buyback: nothing is placed between the old and the new price now, so lifting the price costs nothing;
            // re-placing tranche 0 under the new price needs fewer tokens and the rest is burned below
            d = poolManager.swap(
                key,
                IPoolManager.SwapParams({
                    zeroForOne: true,
                    amountSpecified: -1,
                    sqrtPriceLimitX96: TickMath.getSqrtPriceAtTick(t - 2 * SPACING)
                }),
                ""
            );
            (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
        }
        // tranche 0 back, now [MIN_TICK, t] with every merged tranche in it. The tokens it holds under the price are paid
        // from what the removals above freed (d1: they and a lift only ever pay out) plus the dust reserve. Their rounding
        // (each removal rounds down, the add up) can cost a few wei more than was freed, so the liquidity is cut to what
        // those can pay: a raise never fails for want of reserve (it would revert every raise after, freezing the floor);
        // an empty reserve only places a few wei of tokens less, which the search's one-spacing margin covers (_raise
        // still re-checks FloorBroken)
        uint128 lNew = l0 + added;
        (uint160 sNow,,,) = poolManager.getSlot0(key.toId());
        {
            // forge-lint: disable-next-line(unsafe-typecast)
            uint256 have = uint256(d1) + p.reserve; // d1 >= 0, see above
            // rounds down, so it never needs more than `have`
            uint128 lMax = FloorMath.liquidityForToken(TickMath.getSqrtPriceAtTick(MIN_TICK), sNow, have);
            if (lNew > lMax) lNew = lMax;
        }
        d = _modify(key, MIN_TICK, t, int256(uint256(lNew)), _salt(0));
        (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
        p.liqs[0] = lNew;
        uint160 sT = TickMath.getSqrtPriceAtTick(t);
        uint160 sT1 = TickMath.getSqrtPriceAtTick(t + SPACING);
        // forge-lint: disable-start(unsafe-typecast)
        // d0 and d1 are sums of a few int128 deltas: every cast below is of a non-negative value, by its sign check
        uint256 available = p.pot + (d0 > 0 ? uint256(d0) : 0);
        if (d0 < 0) available -= uint256(-d0);
        uint128 lb = _bandLiquidity(sT, sT1, available, c.lbMax);
        // beyond _bandMax (c.cap less tranche 0's quote over the price) the band's quote would only wait for whoever buys
        // past the next tranche's start: it stays in the pot and leaves below
        (uint256 lCap, uint256 room) = _bandMax(c, sNow, sT, sT, sT1, lNew, available);
        // forge-lint: disable-next-line(unsafe-typecast)
        if (lb > lCap) lb = uint128(lCap); // lCap < lb, a uint128
        d = _modify(key, t, t + SPACING, int256(uint256(lb)), SALT_BAND);
        (d0, d1) = (d0 + d.amount0(), d1 + d.amount1());
        bandQuote = uint256(int256(-d.amount0()));

        // settle: quote against the pot, token rounding against the reserve
        if (d0 < 0) {
            poolManager.burn(address(this), key.currency0.toId(), uint256(-d0));
            p.pot -= uint256(-d0);
        } else if (d0 > 0) {
            poolManager.mint(address(this), key.currency0.toId(), uint256(d0));
            p.pot += uint256(d0);
        }
        if (d1 < 0) {
            poolManager.burn(address(this), key.currency1.toId(), uint256(-d1));
            p.reserve -= uint256(-d1);
        } else if (d1 > 0) {
            if (c.buy) {
                burned = uint256(d1);
                poolManager.take(key.currency1, address(this), burned);
                IZappyToken(p.token).burn(burned);
            } else {
                poolManager.mint(address(this), key.currency1.toId(), uint256(d1));
                p.reserve += uint256(d1);
            }
        }
        // forge-lint: disable-end(unsafe-typecast)
        p.tickF = t;
        p.tickB = t; // the band sits on tranche 0's top again (Zappy: a collect may have moved it off)
        p.liqBand = lb;
        // the pot keeps what c.cap leaves after the band; the rest leaves for the burn
        room = room > bandQuote ? room - bandQuote : 0;
        uint256 pot = p.pot;
        if (pot > room) {
            p.pot = room;
            pot -= room;
            PoolId id = key.toId();
            emit FloorSwept(id, pot, _burnShare(p, id, key.currency0, pot));
        }
    }
}

src/hook/HookStorage.sol

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

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BaseHook} from "../base/BaseHook.sol";
import {IZappyHook} from "../interfaces/IZappyHook.sol";
import {IZappyRevenue} from "../interfaces/IZappyRevenue.sol";
import {IZappyToken} from "../interfaces/IZappyToken.sol";
import {Blocks} from "../libraries/Blocks.sol";
import {Claims} from "../libraries/Claims.sol";
import {Curve, N_TRANCHES} from "../libraries/Curve.sol";
import {Tax} from "../libraries/Tax.sol";
import {Ticks} from "../libraries/Ticks.sol";

/// @title HookStorage
/// @notice ZappyHook's state, constants and the helpers every part shares (the pool key, positions, tranche starts, the
///         start-of-block tick, where burn shares go). ZappyHook = HookStorage <- HookFloor <- HookTax <- HookClaims.
abstract contract HookStorage is BaseHook, IZappyHook {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using CurrencyLibrary for Currency;
    using Claims for IPoolManager;

    // ---- constants ----
    // internal unless an integrator reads them (RAISE_GAS, CREDIT_GAS): no getters, ZappyHook is at the size limit
    int24 internal constant SPACING = Ticks.SPACING;
    int24 internal constant MIN_TICK = Ticks.MIN_TICK;
    /// @dev The snipe window's floor share (60% of its tax) joins the floor linearly over this, from launch: a sniper can't
    ///      sell straight back into a floor his own tax just built (a sim: an instant floor hands a 61 s dumper ~1 ETH more
    ///      of his own tax back). The base 1.5% floor share goes in at once. A price that falls below where the vested
    ///      money could put the floor doesn't strand it: the raise can't place the floor above the price, so each block's
    ///      raise spends what it can't use on a buyback (buys tokens and burns them, lifting the price).
    uint256 internal constant SNIPE_VEST = 10 minutes;
    /// @dev Snipe window split: 60% floor (vesting, snipePot) / 40% bought back and burned as $ZAPPY (_burnShare: burned
    ///      at once on a $ZAPPY pair, else to ZappyBurner), nothing to the creator. The burn share is what a sniper can never
    ///      get back through the floor his own tokens are backed by (red team E1). In $ZAPPY's own pool the 40% is its
    ///      creator fee instead, shared out by ZappyRevenue in the swap (partners and team).
    uint256 internal constant SNIPE_BURN_PCT = Tax.SNIPE_BURN_PCT;
    /// @dev A pool with less than this circulating (1,000 tokens, a millionth of supply) is empty: every holder sold. Its
    ///      floor money backs no one, so it goes to the burn (_drain) instead of lifting an empty pool or waiting under
    ///      the price for whoever buys next (red team E12).
    uint256 internal constant EMPTY_CIRCULATING = 1_000e18;
    /// @dev A floor that can't move drains what its holders can't carry (Ctx.cap) only once that is more than
    ///      1/DRAIN_SLACK of what they can (_planDrain), and then down to the cap: a pool sitting at it would otherwise
    ///      drain a few wei of every swap's tax each block (~95k gas and a FloorSwept, paid by the block's first swap).
    uint256 internal constant DRAIN_SLACK = 100;
    /// @dev Most tranche starts one raise may pass (each costs a position removal), so a raise's gas is bounded whatever
    ///      the price did. A floor that has more to climb continues in the next block's raise.
    uint256 internal constant MAX_PASS = 2;
    /// @dev Token dust kept out of every position at launch: pays rebuild rounding. A rebuild never takes more than it
    ///      holds (_rebuild cuts tranche 0 to fit), so a spent reserve never fails a raise.
    uint256 internal constant RESERVE = 1e6;
    uint256 internal constant BASE_TAX = Tax.BASE; // 2.5%: 1.5% floor / 0.6% creator / 0.4% protocol (team)
    uint256 internal constant SNIPE_START_TAX = Tax.SNIPE_START; // 90% at second 0, linear to 2.5% at 60 s
    uint256 internal constant SNIPE_SECONDS = Tax.SNIPE_SECONDS;
    /// @dev Gas budget for one raise (worst case measured ~556k: a cold poke passing MAX_PASS tranche starts with every
    ///      tranche reached, test_worstRaise --isolate; a buyback ~502k, test_gas_buyback --isolate; a buyback searching
    ///      the whole tick range ~476k, test_gas_worstBuyback --isolate; an empty pool's drain ~196k). A swap that
    ///      triggers a raise must leave room for it, so wallets' gas estimates include the raise instead of quietly
    ///      skipping it.
    uint256 public constant RAISE_GAS = 700_000;
    /// @dev Gas budget for ZappyRevenue.credit (worst case measured ~226k cold: a referred trader with MAX_PARTNERS (5)
    ///      partners and every balance written for the first time; ZappyRevenue pays no one in the swap;
    ///      test_gas_creditWorst --isolate, 50% headroom). Reserved like RAISE_GAS, so a wallet's gas estimate never finds the limit where the credit
    ///      quietly fails and the share goes to the team.
    uint256 public constant CREDIT_GAS = 400_000;

    bytes32 internal constant SALT_BAND = bytes32(uint256(3));
    /// @dev Transient: the pool the factory is launching in this transaction (the only one its swaps pay the base rate on)
    bytes32 internal constant LAUNCHING_SLOT = keccak256("zappy.hook.launching");
    uint256 internal constant SALT_TRANCHE0 = 16; // tranche i's position uses salt 16 + i

    uint8 internal constant ACTION_PLACE = 1;
    uint8 internal constant ACTION_POKE = 2;
    uint8 internal constant ACTION_CLAIM = 3;
    uint8 internal constant ACTION_COLLECT = 4; // Zappy: the owner's floor collect (ZappyHook.collectFloor)

    address public immutable factory;
    /// @notice Shares out the protocol fee (and $ZAPPY's own creator fee) in every swap: referrer, partners, team. The
    ///         hook's ERC-6909 operator: it takes each credit's claims itself (only in credit, which only the hook calls,
    ///         exactly the amount the hook passes, from the hook), so a credit that reverts moves nothing
    IZappyRevenue public immutable revenue;
    /// @notice ZappyLimitOrders: on its swaps (and only on its swaps) the trader credited is the order's owner, which it
    ///         passes as hookData (_trader), not tx.origin (the keeper that filled it)
    address public immutable limitOrders;
    /// @notice ZappyBurner: gets every burn share that isn't already $ZAPPY (the snipe tax's on other pairs, swept floor
    ///         money) as a transfer of the hook's ERC-6909 claims, and buys $ZAPPY with it and burns it later
    address public immutable burner;
    /// @notice The block numbers the once-per-block rules key on (lastRaiseBlock, refBlock, startOfBlockTick) are the
    ///         chain's own: ArbSys.arbBlockNumber() on an Arbitrum chain (true: Robinhood Chain, whose block.number is
    ///         Ethereum's), else block.number (libraries/Blocks.sol). Set at deploy from the chain id, never changed.
    bool public immutable isArbitrum;

    struct Pool {
        address token;
        address creator; // address(0) = the team (used for $ZAPPY itself)
        uint40 launchedAt;
        int24 tickStart;
        int24 tickF; // floor band is [tickF, tickF + 60]; tranche 0 (launch, plus every merged tranche) is [MIN_TICK, tickF]
        int24 refTick; // pool tick at the start of refBlock
        uint64 refBlock; // block numbers: _blockNumber()
        uint64 lastRaiseBlock;
        uint128 snipePot; // the snipe window's floor share, vesting into pot over SNIPE_VEST from launch
        uint128 snipeReleased; // the part of snipePot already moved into pot (or out of the floor: FloorSwept)
        // tranches 1..merged were merged into tranche 0 once the floor passed their start; the rest are still placed at
        // [MIN_TICK, tickStart - topOff] (libraries/Curve.sol)
        uint8 merged;
        uint128 liqBand;
        uint256 pot; // quote waiting for the floor (ERC-6909 claims)
        uint256 creatorOwed; // quote (claims)
        uint256 reserve; // token dust (claims)
        // liqs[0]: tranche 0's liquidity, which grows as tranches merge in; liqs[i > 0]: what tranche i was placed with
        // (live while i > merged, then part of liqs[0])
        uint128[N_TRANCHES] liqs;
        // Zappy: the band's tick, [tickB, tickB + 60]. Equal to tickF (the band sits on tranche 0's top) until the owner
        // collects part of the floor: the band then moves up to where what is left still buys back every circulating
        // token, leaving a gap over tranche 0, and the next raise puts both back together (HookFloor._rebuild)
        int24 tickB;
    }

    mapping(PoolId => Pool) public pools;
    mapping(Currency => uint256) public teamOwed;
    /// @notice $ZAPPY, recorded when the factory launches it (the only pool whose creator is the team, address(0))
    address public zappy;

    constructor(
        IPoolManager _poolManager,
        address _factory,
        IZappyRevenue _revenue,
        address _limitOrders,
        address _burner,
        bool _isArbitrum
    ) BaseHook(_poolManager) {
        if (
            address(_poolManager) == address(0) || _factory == address(0) || address(_revenue) == address(0)
                || _limitOrders == address(0) || _burner == address(0)
        ) {
            revert ZeroAddress();
        }
        factory = _factory;
        revenue = _revenue;
        limitOrders = _limitOrders;
        burner = _burner;
        isArbitrum = _isArbitrum;
        _poolManager.setOperator(address(_revenue), true);
    }

    /// @notice The pool key for a pair: `quote` is currency0 (address(0) = ETH), `token` currency1, no LP fee.
    function keyFor(address quote, address token) public view returns (PoolKey memory) {
        return PoolKey({
            currency0: Currency.wrap(quote),
            currency1: Currency.wrap(token),
            fee: 0,
            tickSpacing: SPACING,
            hooks: IHooks(address(this))
        });
    }

    /// @dev Sends `amount` of quote (already held as claims) to the $ZAPPY buy-and-burn and returns true; or to the team
    ///      and returns false. $ZAPPY pair: the quote is $ZAPPY, burned now. Any other pair (ETH, or an owner-allowed ERC-20
    ///      quote such as USDG): the claims go to ZappyBurner (an ERC-6909 transfer: nothing leaves the PoolManager and no
    ///      code runs there, so it is safe inside a swap), which buys $ZAPPY with them and burns it later. $ZAPPY's own pool
    ///      (its swept floor money; its snipe share never comes here, _collect): the team (buying itself back would only
    ///      move its own price).
    function _burnShare(Pool storage p, PoolId id, Currency quote, uint256 amount) internal returns (bool) {
        if (p.creator == address(0)) {
            teamOwed[quote] += amount;
            return false;
        }
        if (amount != 0) {
            address q = Currency.unwrap(quote);
            if (q == zappy) {
                poolManager.redeem(quote, address(this), amount);
                IZappyToken(q).burn(amount);
                emit ZappyBurned(id, amount);
            } else {
                poolManager.transfer(burner, quote.toId(), amount);
            }
        }
        return true;
    }

    /// @dev This block's number, as the once-per-block rules count blocks. Robinhood Chain is an Arbitrum Orbit chain,
    ///      where block.number is Ethereum's (~12 s), so the chain's own block number comes from ArbSys (Blocks).
    ///      isArbitrum is fixed at deploy.
    function _blockNumber() internal view returns (uint256) {
        return Blocks.current(isArbitrum);
    }

    /// @dev Records the pool's tick as this block's reference on its first swap (or poke) of the block.
    ///      Returns the block number (_blockNumber).
    function _refreshRef(Pool storage p, PoolId id) internal returns (uint256 bn) {
        bn = _blockNumber();
        if (p.refBlock != bn) {
            (, int24 tick,,) = poolManager.getSlot0(id);
            p.refTick = tick;
            // forge-lint: disable-next-line(unsafe-typecast)
            p.refBlock = uint64(bn); // a block number: < 2^64
        }
    }

    function _modify(PoolKey memory key, int24 lower, int24 upper, int256 liq, bytes32 salt)
        internal
        returns (BalanceDelta delta)
    {
        if (liq == 0) return delta;
        (delta,) = poolManager.modifyLiquidity(
            key,
            IPoolManager.ModifyLiquidityParams({tickLower: lower, tickUpper: upper, liquidityDelta: liq, salt: salt}),
            ""
        );
    }

    /// @dev Start tick of tranche i (its position's upper tick until it's merged into tranche 0).
    function _start(Pool storage p, uint256 i) internal view returns (int24) {
        (, int24 topOff) = Curve.tranche(i);
        return p.tickStart - topOff;
    }

    function _salt(uint256 i) internal pure returns (bytes32) {
        return bytes32(SALT_TRANCHE0 + i);
    }
}

src/hook/HookTax.sol

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

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";
import {SafeCast} from "v4-core/src/libraries/SafeCast.sol";
import {Tax} from "../libraries/Tax.sol";
import {HookFloor} from "./HookFloor.sol";

/// @title HookTax
/// @notice The swap callbacks: run the block's floor raise first, then tax the quote leg of every swap (no LP fee) and
///         split it: floor, creator, protocol (shared out by ZappyRevenue), and in the snipe window the $ZAPPY burn.
///         Nobody is paid in a swap: the creator's share is owed (claimCreator), the burn share goes to ZappyBurner as
///         claims (or, already $ZAPPY, is burned).
abstract contract HookTax is HookFloor {
    using PoolIdLibrary for PoolKey;
    using CurrencyLibrary for Currency;
    using SafeCast for uint256;

    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        if (p.token == address(0)) revert UnknownPool();
        uint256 bn = _refreshRef(p, id);
        // The block's raise (or buyback) runs before its first swap, on the state the block started with, so no swap
        // can buy into a raise it triggers itself. Reserve its gas up front (so estimates include it), then run it in
        // its own frame: if it fails for any other reason it rolls back on its own and the swap still goes through.
        // Only the block's first swap looks: one that finds nothing to move, or whose raise failed, still settles the
        // block, so its later swaps don't pay for the check again (the next block's first swap looks again)
        if (p.lastRaiseBlock != bn) {
            if (_plan(p, id).go) {
                if (gasleft() < RAISE_GAS * 64 / 63 + 40_000) revert NeedGas();
                try this.raiseFromHook{gas: RAISE_GAS}(key) {}
                catch (bytes memory reason) {
                    emit RaiseFailed(id, reason);
                }
            }
            // forge-lint: disable-next-line(unsafe-typecast)
            p.lastRaiseBlock = uint64(bn); // a block number: < 2^64
        }
        int128 specified;
        if (params.zeroForOne == (params.amountSpecified < 0)) {
            // quote is the specified currency: buy exact-in (quote in) or sell exact-out (quote out)
            (uint256 r, bool snipe) = _rate(p, id, sender);
            // |amountSpecified| (negating type(int256).min reverts)
            uint256 amt =
                params.amountSpecified < 0 ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
            // buy: r of the gross input; sell: gross up the output
            uint256 volume = params.zeroForOne ? amt : Tax.grossUp(amt, r);
            uint256 tax = params.zeroForOne ? Tax.ofGross(amt, r) : volume - amt;
            _collect(p, id, key.currency0, sender, params.zeroForOne, volume, tax, snipe, _trader(sender, hookData));
            specified = tax.toInt128();
        }
        return (IHooks.beforeSwap.selector, toBeforeSwapDelta(specified, 0), 0);
    }

    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external override onlyPoolManager returns (bytes4, int128) {
        PoolId id = key.toId();
        Pool storage p = pools[id];
        (uint256 r, bool snipe) = _rate(p, id, sender);
        // the unspecified leg's tax, when quote is the unspecified currency (none when beforeSwap took it)
        uint256 volume;
        uint256 tax;
        if (params.zeroForOne) {
            if (params.amountSpecified < 0) {
                // buy exact-in: the whole (input - tax) must have been swapped. Compared in int256: amt is a negated
                // int256 (< 2^255), so the cast can't wrap
                uint256 amt = uint256(-params.amountSpecified);
                // forge-lint: disable-next-line(unsafe-typecast)
                if (delta.amount0() != -int256(amt - Tax.ofGross(amt, r))) revert PartialFill();
            } else {
                // buy exact-out: charge r of the gross on top of the quote the pool took
                if (delta.amount1() != params.amountSpecified) revert PartialFill();
                uint256 quoteIn = uint256(int256(-delta.amount0())); // a buy's amount0 is <= 0
                volume = Tax.grossUp(quoteIn, r);
                tax = volume - quoteIn;
            }
        } else {
            if (params.amountSpecified < 0) {
                // sell exact-in: keep r of the quote the pool released
                if (delta.amount1() != params.amountSpecified) revert PartialFill();
                volume = uint256(int256(delta.amount0())); // a sell's amount0 is >= 0
                tax = Tax.ofGross(volume, r);
            } else {
                // sell exact-out: the pool must have released the grossed-up amount
                if (delta.amount0() != Tax.grossUp(uint256(params.amountSpecified), r).toInt256()) {
                    revert PartialFill();
                }
            }
        }
        _collect(p, id, key.currency0, sender, params.zeroForOne, volume, tax, snipe, _trader(sender, hookData));
        return (IHooks.afterSwap.selector, tax.toInt128());
    }

    /// @dev Tax rate in pips and whether it's the snipe window. The factory pays the base rate on the pool it is launching
    ///      in this transaction (the creator's buy, before anyone else can trade it), and the normal rate everywhere else,
    ///      so a launch is no way into another pool's snipe window.
    function _rate(Pool storage p, PoolId id, address sender) internal view returns (uint256, bool) {
        if (sender == factory) {
            bytes32 slot = LAUNCHING_SLOT;
            bytes32 launching;
            assembly ("memory-safe") {
                launching := tload(slot)
            }
            if (launching == PoolId.unwrap(id)) return (BASE_TAX, false);
        }
        return Tax.rate(block.timestamp - p.launchedAt);
    }

    /// @dev Takes `tax` of quote as ERC-6909 claims (offsetting the hook delta the PoolManager books after afterSwap)
    ///      and splits it. Snipe window: 60% floor, vesting over SNIPE_VEST (snipePot), 40% to the $ZAPPY burn
    ///      (_burnShare: ZappyBurner's claims, or burned at once on a $ZAPPY pair), nothing to the creator; in $ZAPPY's own
    ///      pool the 40% is its creator fee instead. After: 60% floor / 24% creator / 16% team (of a 2.5% tax: 1.5% /
    ///      0.6% / 0.4% of the trade), the floor share straight into pot. The protocol fee (the team's share after the
    ///      window) and $ZAPPY's creator fee are shared out by ZappyRevenue in this swap (_credit), on `trader`'s referral
    ///      (_trader; of the protocol fee only). Every other creator fee is owed (creatorOwed), never paid in the swap:
    ///      claimCreator pays it (the keeper's payouts).
    function _collect(
        Pool storage p,
        PoolId id,
        Currency quote,
        address swapper,
        bool buy,
        uint256 volume,
        uint256 tax,
        bool snipe,
        address trader
    ) internal {
        if (tax == 0) return;
        poolManager.mint(address(this), quote.toId(), tax);
        uint256 toCreator;
        uint256 toTeam;
        uint256 toBurn;
        uint256 fee; // the protocol fee (none in the snipe window)
        if (snipe) {
            uint256 share = Tax.snipeBurn(tax);
            // $ZAPPY's own pool can't buy itself back: the share is its creator fee
            if (p.creator == address(0)) {
                toCreator = share;
            } else {
                _burnShare(p, id, quote, share);
                toBurn = share;
            }
            p.snipePot += (tax - share).toUint128();
        } else {
            toCreator = Tax.creatorShare(tax);
            toTeam = fee = Tax.protocolShare(tax);
            p.pot += tax - toCreator - toTeam;
        }
        // $ZAPPY's creator fee is ZAPPY's revenue: ZappyRevenue shares it out with the protocol fee, in this swap
        p.creatorOwed += toCreator - _credit(id, quote, trader, fee, p.creator == address(0) ? toCreator : 0);
        emit TaxPaid(id, swapper, buy, volume, tax - toCreator - toTeam - toBurn, toCreator, toTeam, toBurn);
    }

    /// @dev Shares out the protocol fee and `creatorFee` (already held as claims) through ZappyRevenue: it takes exactly
    ///      those claims from the hook itself (its ERC-6909 operator, HookStorage's constructor), so a credit that
    ///      reverts never moved them, and books the partners', `trader`'s referrer's (_trader) and the team's shares
    ///      (it pays no one). Runs in its own frame with CREDIT_GAS, reserved up front like the raise's; if it
    ///      reverts anyway the swap still goes through and the protocol fee stays the team's here (teamOwed: no referral
    ///      or partner share of it, accepted, README §5.1). Returns the creator fee ZappyRevenue took (`creatorFee`, or 0
    ///      if it failed: the caller keeps it in the creator balance, which claimCreator credits to ZappyRevenue later).
    function _credit(PoolId id, Currency quote, address trader, uint256 protocolFee, uint256 creatorFee)
        internal
        returns (uint256)
    {
        uint256 amount = protocolFee + creatorFee;
        if (amount == 0) return 0;
        if (gasleft() < CREDIT_GAS * 64 / 63 + 20_000) revert NeedGas();
        try revenue.credit{gas: CREDIT_GAS}(Currency.unwrap(quote), trader, protocolFee, creatorFee) {
            return creatorFee;
        } catch {
            emit CreditFailed(id, amount);
            teamOwed[quote] += protocolFee;
            return 0;
        }
    }

    /// @dev The trader a swap's referral is credited to. A ZappyLimitOrders fill: the order's owner, which it passes as
    ///      hookData (`sender` is the PoolManager's caller, so no one else's hookData is ever read). Anything else: the
    ///      swap's tx.origin (the hook can't see the wallet behind a router): smart-wallet or bundled swaps credit the
    ///      bundler's EOA, which normally has no referrer. Only ever used to pick a referrer, never for authorization.
    function _trader(address sender, bytes calldata hookData) internal view returns (address) {
        if (sender == limitOrders) return abi.decode(hookData, (address));
        return tx.origin;
    }
}

src/interfaces/IZappyFactory.sol

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

import {PoolId} from "v4-core/src/types/PoolId.sol";
import {IZappyHook} from "./IZappyHook.sol";
import {IZappyVesting} from "./IZappyVesting.sol";

/// @notice ZappyFactory: launches tokens into ZappyHook pools. Spec: packages/contracts/README.md.
interface IZappyFactory {
    struct LaunchParams {
        string name;
        string ticker;
        string metadataURI;
        bytes32 salt; // the token is deployed at CREATE2(keccak(creator, salt)) (predictToken); it must sort after the quote
        // the pair: an allowed quote (quotes[quote].allowed; address(0) = ETH). $ZAPPY itself (the first launch) is ETH
        address quote;
        uint256 devBuyTokens; // creator's initial buy, <= 5% of supply; 0 = none
        // the most the initial buy may cost, in the pair's quote (ETH, $ZAPPY or another token): the site's quote plus a
        // little slippage
        uint256 devBuyMaxCost;
        // $ZAPPY (the owner's first launch): the start tick, unsigned. Every later launch: the start tick the start signer
        // signed for (creator, salt, quote, name, ticker), valid until `deadline` (unix seconds). In ticks of
        // tokens per quote
        int24 tickStart;
        uint256 deadline;
        // 65-byte EIP-712 signature of LaunchStart(creator, salt, quote, name, ticker, tickStart, deadline);
        // empty for $ZAPPY
        bytes signature;
        // lock the dev buy in ZappyVesting for the creator, vesting linearly over 1, 3, 6 or 12 months; 0 = no lock (the
        // tokens go to the creator). The creator's choice: not part of the signed start. Needs a dev buy (VestWithoutDevBuy)
        uint8 vestMonths;
    }

    struct QuoteConfig {
        bool allowed;
        // quotes other than ETH and $ZAPPY: the start band in ticks of raw token units per raw quote unit
        int24 bandLow;
        int24 bandHigh;
        // the quote's ERC-20 decimals (18 for ETH and $ZAPPY), read by setQuoteAllowed: what its pools are priced in
        uint8 decimals;
    }

    event TokenLaunched(
        address indexed token,
        PoolId indexed poolId,
        address indexed creator,
        address quote,
        int24 tickStart,
        uint256 devBuyTokens,
        string name,
        string ticker,
        string metadataURI
    );
    event ConfigChanged(bytes32 indexed what, uint256 value);
    event QuoteAllowed(address indexed quote, bool allowed);
    event QuoteBandSet(address indexed quote, int24 low, int24 high);

    error NotPoolManager();
    error Paused();
    error HookSet();
    error BadHook();
    error BadTick();
    error BadStartSignature();
    error StartExpired();
    error StartUsed();
    error StartOutOfBand();
    error FeeNotPaid();
    error DevBuyTooBig();
    error DevBuyTooExpensive();
    error DevBuyUnderpaid();
    error BadSalt();
    error BadQuote();
    error NoBand();
    error RefundFailed();
    error FeeTransferFailed();
    error ZeroAddress();
    error VestWithoutDevBuy();

    /// @notice Launch a token. Send the launch fee plus enough ETH for the dev buy; the rest is refunded. On a pair other
    ///         than ETH or $ZAPPY the dev buy is paid in the quote itself: approve this factory for it first.
    function launch(LaunchParams calldata lp) external payable returns (address token, PoolId poolId);

    /// @notice The EIP-712 digest the start signer signs for a launch.
    function launchStartDigest(
        address creator,
        bytes32 salt,
        address quote,
        string calldata name,
        string calldata ticker,
        int24 tickStart,
        uint256 deadline
    ) external view returns (bytes32);

    /// @notice The start ticks (tokens per quote) a signed launch on this pair may use right now.
    function startTickRange(address quote) external view returns (int24 low, int24 high);

    /// @notice CREATE2 address a launch with these params will deploy the token at (for the front end's salt search).
    /// @param creator the launch's creator: the launching wallet
    function predictToken(address creator, bytes32 salt, string calldata name, string calldata ticker)
        external
        view
        returns (address);

    function setHook(IZappyHook hook) external;
    function setStartSigner(address signer) external;
    function setStartBand(int24 low, int24 high) external;
    function setQuoteAllowed(address quote, bool allowed) external;
    function setQuoteBand(address quote, int24 low, int24 high) external;
    function setLaunchFee(uint256 fee) external;
    function setDevBuyMax(uint256 tokens) external;
    function setTeam(address team) external;
    function setLaunchesPaused(bool paused) external;

    /// @notice Where team balances (and $ZAPPY's creator fees) are paid.
    function team() external view returns (address);
    function hook() external view returns (IZappyHook);
    /// @notice ZappyBurner, which every launch fee is sent to (the hook's, set with it).
    function burner() external view returns (address);
    function zappy() external view returns (address);
    /// @notice ZappyVesting, where a launch locks its dev buy when LaunchParams.vestMonths is set (immutable).
    function vesting() external view returns (IZappyVesting);
}

src/interfaces/IZappyHook.sol

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

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

/// @notice ZappyHook: owns every ZAPPY pool's liquidity, taxes the quote leg of every swap and keeps the ratcheting floor.
///         Spec: packages/contracts/README.md.
interface IZappyHook {
    /// @param toBurn the snipe tax's $ZAPPY buy-and-burn share: burned at once on a $ZAPPY pair (ZappyBurned), sent to
    ///        ZappyBurner as claims on any other pair. toFloor + toCreator + toTeam + toBurn == the tax
    event TaxPaid(
        PoolId indexed poolId,
        address indexed swapper,
        bool buy,
        uint256 quoteVolume,
        uint256 toFloor,
        uint256 toCreator,
        uint256 toTeam,
        uint256 toBurn
    );
    /// @param sqrtPriceX96 worst-case price if everyone sells: the far edge of the band (tickF + 60)
    event FloorRaised(
        PoolId indexed poolId, int24 tickF, uint160 sqrtPriceX96, uint256 quoteInFloor, uint256 circulating
    );
    /// @notice The block's raise reverted (and rolled back); the swap went through. `reason` is the revert data: empty
    ///         when the raise ran out of its RAISE_GAS, else the error (FloorBroken, a PoolManager error, ...). It still
    ///         counts as the block's raise: the next block retries it
    event RaiseFailed(PoolId indexed poolId, bytes reason);
    /// @notice Floor money no one holds tokens for left the floor: an empty pool's pot, band and snipe pot (vested or
    ///         not), or floor money (pot, vested snipe tax, band) beyond what the circulating tokens can carry: their
    ///         worth at the highest price a buyback may lift to. Quote amount.
    /// @param burn it went to the $ZAPPY buy-and-burn, like TaxPaid.toBurn (burned at once on a $ZAPPY pair, else to
    ///        ZappyBurner as claims); false: to the team, only in $ZAPPY's own pool (unlike its snipe share, which is its
    ///        creator fee)
    event FloorSwept(PoolId indexed poolId, uint256 amount, bool burn);
    /// @notice $ZAPPY burned at once by a $ZAPPY pair's burn share (its snipe tax's, or its swept floor money): `poolId` is
    ///         the pool it was paid in. Every other pair's burn share goes to ZappyBurner, whose BoughtAndBurned logs its
    ///         burns.
    event ZappyBurned(PoolId indexed poolId, uint256 zappyBurned);
    /// @param burned tokens the spare floor money bought back and burned; sqrtPriceX96 the price it lifted the pool to
    event BoughtBack(PoolId indexed poolId, uint256 burned, uint160 sqrtPriceX96);
    event Claimed(address indexed account, address indexed currency, uint256 amount);
    event CreatorChanged(PoolId indexed poolId, address indexed creator);
    /// @notice ZappyRevenue.credit reverted: this swap's protocol fee stayed with the team here (teamOwed; $ZAPPY's creator
    ///         fee in its creatorOwed, which claimCreator credits to ZappyRevenue)
    event CreditFailed(PoolId indexed poolId, uint256 amount);
    /// @notice Zappy: the owner took `bps` of a pool's floor (its band and its pot): `quote` of the pair to `to`, and
    ///         `tokens` the band held (a band the price is inside) into the dust reserve. The band went back in with
    ///         `quoteInFloor` at `tickF` (0 of it after a full collect), the lowest tick where that still buys back every
    ///         circulating token: the floor dropped to what the money left can hold (floorOf reads the new worst case).
    event FloorCollected(
        PoolId indexed poolId,
        uint16 bps,
        uint256 quote,
        uint256 tokens,
        address indexed to,
        int24 tickF,
        uint256 quoteInFloor
    );

    error NotFactory();
    error ZeroAddress();
    error NotSelf();
    error NotCreator();
    error UnknownPool();
    error BadOrder();
    error BadTick();
    error PartialFill();
    error FloorBroken();
    error NeedGas();
    error BadTranche();
    error BadBps();

    /// @notice The pool key for a pair: `quote` is currency0 (address(0) = ETH), `token` currency1, no LP fee.
    function keyFor(address quote, address token) external view returns (PoolKey memory);

    /// @notice Creates the pool and places the launch curve. Factory only; it must have sent the full supply here first.
    /// @param creator address(0) for $ZAPPY (the team is its creator)
    function createPool(address quote, address token, address creator, int24 tickStart)
        external
        returns (PoolKey memory key);

    /// @notice Ends the launch createPool started: the factory's swaps pay the normal rate everywhere again.
    function endLaunch() external;

    /// @notice Raise entry used from beforeSwap (via try/catch). Only callable by the hook itself.
    function raiseFromHook(PoolKey calldata key) external;

    /// @notice Applies the pot to the floor now. Anyone can call it; trading normally does this already (a block's first
    ///         swap settles the block: a poke after it does nothing until the next block).
    function poke(PoolKey calldata key) external;

    /// @notice Pays a pool's creator balance to `to`. Every creator fee is owed (nobody is paid in a swap) until this
    ///         claims it. Anyone can send it to the creator (the keeper's payouts); only the creator can name another `to`. $ZAPPY's fees are ZAPPY's revenue, credited to ZappyRevenue in every swap: what a swap
    ///         couldn't credit (CreditFailed) is credited to it here instead (`to` unused), shared out to the partners and
    ///         the team with no referral (reverts if ZappyRevenue does: the fees stay owed).
    function claimCreator(PoolKey calldata key, address to) external;

    /// @notice Pays the team what it is owed in `currency`. Anyone can call it.
    function claimTeam(Currency currency) external;

    /// @notice Hands a pool's creator fees to a new address. The current creator only.
    function setCreator(PoolKey calldata key, address creator) external;

    /// @notice Tranche i of the launch curve as placed now: [MIN_TICK, top] with `liquidity`. Reverts BadTranche past the
    ///         last tranche.
    function trancheOf(PoolKey calldata key, uint256 i) external view returns (int24 top, uint128 liquidity);

    /// @notice The floor tick, the worst-case price (Q96 sqrt of token-per-quote at the band's far edge) and circulating supply.
    function floorOf(PoolKey calldata key)
        external
        view
        returns (int24 tickF, uint160 sqrtPriceX96, uint256 circulating);

    /// @notice A pool's tick at the start of this block (what the floor and the start bands measure against).
    function startOfBlockTick(PoolId id) external view returns (int24);

    /// @notice Blocks are counted with ArbSys.arbBlockNumber() (an Arbitrum chain: Robinhood Chain), not block.number.
    ///         Fixed at deploy.
    function isArbitrum() external view returns (bool);

    function factory() external view returns (address);
    /// @notice ZappyRevenue, which shares out the protocol fee (and $ZAPPY's own creator fee) of every swap.
    function revenue() external view returns (IZappyRevenue);
    /// @notice ZappyLimitOrders: the one swapper whose hookData names the trader ZappyRevenue credits (the order's owner).
    function limitOrders() external view returns (address);
    /// @notice ZappyBurner: gets every burn share that isn't already $ZAPPY, as ERC-6909 claims.
    function burner() external view returns (address);
    function zappy() external view returns (address);
    function teamOwed(Currency currency) external view returns (uint256);
}

src/interfaces/IZappyRevenue.sol

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

/// @notice ZappyRevenue: shares out the protocol fee (and $ZAPPY's own creator fee) between revenue-share partners
///         (partnerBps of the gross), referrers (referralBps of the protocol fee) and the team (the rest), and keeps the referral registry. Spec: packages/contracts/README.md §5.1.
interface IZappyRevenue {
    struct Partner {
        address account;
        uint16 bps;
    }

    /// @dev Why registerBy skipped an entry: a zero trader, or a referrer that is zero, the trader itself or one that could
    ///      never claim (ZappyRevenue, the hook, the PoolManager); the trader already had a referrer before this batch; it
    ///      was already set earlier in this batch
    enum SkipReason {
        BadReferrer,
        AlreadyReferred,
        Duplicate
    }

    /// @notice One per credit (one per taxed swap after the snipe window and per snipe-window swap of $ZAPPY's pool, and
    ///         one per ZappyHook.claimCreator of $ZAPPY's pool for a fee a swap's credit failed on, trader zero): who
    ///         traded, its referrer (zero: none), what was shared out and where it went. toReferrer + toPartners + toTeam
    ///         == protocolFee + creatorFee.
    /// @param creatorFee $ZAPPY's own creator fee (only in the $ZAPPY pool; no referral on it)
    event Split(
        address indexed currency,
        address indexed trader,
        address indexed referrer,
        uint256 protocolFee,
        uint256 creatorFee,
        uint256 toReferrer,
        uint256 toPartners,
        uint256 toTeam
    );
    /// @notice A partner's share of one credit (one per partner with a non-zero share, before its Split).
    event PartnerCredited(address indexed account, address indexed currency, uint256 amount);
    /// @notice Named apart from ZappyHook's Claimed so the two never share a topic. `account` is who was owed (the
    ///         recipient is the claim's `to`: the account unless it sent it elsewhere).
    event RevenueClaimed(address indexed account, address indexed currency, uint256 amount);
    /// @notice A registerBy entry that was not set, and why.
    event RegisterSkipped(address indexed trader, address indexed referrer, SkipReason reason);
    /// @notice The owner reset a trader to unreferred (clearReferrers: the recovery from a bad registrar). Only for a
    ///         trader that had a referrer.
    event ReferrerCleared(address indexed trader);
    event ReferrerSet(address indexed trader, address indexed referrer);
    /// @notice The partner list was replaced by this one (empty: no partners), shares in bps of the partner fee (adding
    ///         up to 10_000).
    event PartnersSet(address[] recipients, uint16[] bps);
    /// @notice Both fees, from now on: the partners' (bps of the gross) and the referrer's (bps of the protocol fee). Also
    ///         from the constructor, for the defaults (0, DEFAULT_REFERRAL_BPS).
    event FeePercentSet(uint16 partnerBps, uint16 referralBps);
    event TeamSet(address indexed team);
    event HookSet(address indexed hook);
    event RegistrarSet(address indexed registrar);

    error NotHook();
    error NotPoolManager();
    error HookAlreadySet();
    error BadHook();
    error ZeroAddress();
    error TooManyPartners();
    error BadShareTotal();
    error PartnerFeeActive();
    error NoPartners();
    error FeeTooHigh();
    error BadPartner();
    error LengthMismatch();
    error ZeroShare();
    error DuplicatePartner();
    error SelfAddress();
    error NotRegistrar();
    error BatchTooLarge();
    error NotAccount();

    /// @notice Shares out `protocolFee + creatorFee` of `currency`, taking exactly that much of the hook's ERC-6909 claims
    ///         (as the hook's ERC-6909 operator), and books every share (owed: nobody is paid in the swap). Only the hook:
    ///         inside the swap, or from claimCreator for a $ZAPPY creator fee a swap's credit failed on (no trader).
    /// @param currency the pool's quote (address(0) = ETH)
    /// @param trader the swap's tx.origin, or a ZappyLimitOrders fill's order owner (address(0) from claimCreator: never
    ///        referred, registerBy skips a zero trader)
    /// @param protocolFee the protocol fee (referral applies)
    /// @param creatorFee $ZAPPY's own creator fee (partners only), 0 in every other pool
    function credit(address currency, address trader, uint256 protocolFee, uint256 creatorFee) external;

    /// @notice Pays everything `account` is owed in `currency` to `to`. Anyone can trigger it with `to` = `account`;
    ///         only the account can pick another `to`.
    function claim(address account, address currency, address to) external returns (uint256 amount);

    /// @notice The registrar binds unreferred traders to referrers, in batches of at most MAX_REGISTER_BATCH.
    /// @return set how many entries were set
    function registerBy(address[] calldata traders, address[] calldata referrers) external returns (uint256 set);

    function setHook(address hook) external;
    function setTeam(address team) external;
    function setPartners(address[] calldata recipients, uint16[] calldata bps) external;
    function setFeePercent(uint16 partnerBps, uint16 referralBps) external;
    function setRegistrar(address registrar) external;
    function clearReferrers(address[] calldata traders) external;

    function hook() external view returns (address);
    function team() external view returns (address);
    function registrar() external view returns (address);
    function partnerBps() external view returns (uint16);
    function referralBps() external view returns (uint16);
    function partnerCount() external view returns (uint8);
    function referrerOf(address trader) external view returns (address);
    function owed(address account, address currency) external view returns (uint256);
    function partners() external view returns (address[] memory recipients, uint16[] memory bps);
}

src/interfaces/IZappyToken.sol

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

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

/// @notice The ERC-20 every launch deploys (ZappyToken): fixed supply, holders can burn their own.
interface IZappyToken is IERC20 {
    /// @notice Burns the caller's tokens; total supply goes down (the floor treats burned tokens as gone).
    function burn(uint256 amount) external;
}

src/interfaces/IZappyVesting.sol

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

/// @notice ZappyVesting: locks ERC-20 tokens for a beneficiary and releases them linearly. Spec: packages/contracts/README.md.
interface IZappyVesting {
    struct Lock {
        address token;
        uint64 start; // unix seconds
        uint32 duration; // seconds: months x MONTH
        address beneficiary;
        uint256 amount; // what the lock received
        uint256 claimed; // paid out so far
    }

    event Locked(
        uint256 indexed id,
        address indexed token,
        address indexed beneficiary,
        address from,
        uint256 amount,
        uint64 start,
        uint32 duration
    );
    event Claimed(uint256 indexed id, uint256 amount);

    error BadMonths();
    error ZeroAddress();
    error ZeroAmount();
    error UnknownLock();
    error NothingToClaim();

    /// @notice Locks `amount` of `token` (pulled from the caller: approve first) for `beneficiary`, vesting linearly per
    ///         second over `months` (1, 3, 6 or 12) from now. The lock holds what actually arrived.
    function lock(address token, uint256 amount, uint8 months, address beneficiary) external returns (uint256 id);

    /// @notice Pays the lock's vested, unclaimed tokens to its beneficiary (anyone may trigger it).
    function claim(uint256 id) external returns (uint256 amount);

    function claimable(uint256 id) external view returns (uint256);
    function getLock(uint256 id) external view returns (Lock memory);
    function lockCount() external view returns (uint256);
    function locksOf(address beneficiary) external view returns (uint256[] memory);
    function locksOfToken(address token) external view returns (uint256[] memory);
}

src/libraries/Blocks.sol

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

/// @notice The block number the hook's once-per-block rules key on (README §6). On an Arbitrum chain (Robinhood Chain is
///         an Arbitrum Orbit chain) the EVM's `block.number` is the parent chain's block number (Ethereum's, ~12 s); the
///         chain's own block number comes from the ArbSys precompile. Which one a hook reads is fixed when it is
///         deployed (ZappyHook.isArbitrum).
library Blocks {
    /// @dev This block's number: ArbSys.arbBlockNumber() when `isArbitrum`, else block.number. ArbSys is Arbitrum's
    ///      system precompile at 0x64 (code 0xfe on chain: it answers calls, never runs EVM code); 0xa3b1b31d is
    ///      arbBlockNumber()'s selector.
    ///      Reverts when ArbSys doesn't answer with a word (a hook made for an Arbitrum chain running anywhere else):
    ///      never falls back to block.number.
    function current(bool isArbitrum) internal view returns (uint256 n) {
        if (!isArbitrum) return block.number;
        assembly ("memory-safe") {
            mstore(0, 0xa3b1b31d)
            let ok := staticcall(gas(), 0x64, 28, 4, 0, 32)
            if or(iszero(ok), lt(returndatasize(), 32)) { revert(0, 0) }
            n := mload(0)
        }
    }
}

src/libraries/Claims.sol

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

import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {Currency} from "v4-core/src/types/Currency.sol";

/// @notice The contracts hold their balances as PoolManager ERC-6909 claims; this pays them out. Only ever outside a
///         swap (a claim's own unlock): nobody is paid in a swap, every share is owed and claimed later.
library Claims {
    /// @dev Burns `amount` of the caller's claims on `currency` and sends the currency to `to`. Inside an unlock only.
    function redeem(IPoolManager poolManager, Currency currency, address to, uint256 amount) internal {
        poolManager.burn(address(this), currency.toId(), amount);
        poolManager.take(currency, to, amount);
    }
}

src/libraries/Curve.sol

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

// GENERATED by packages/contracts/scripts/curve.mjs (do not edit by hand): launch 35% from the start + 8 open tranches from 100000x, one per 10x, depth x6 per 10x.
// The derivation is documented there; packages/core/src/curve.ts holds the same table for the site.

uint256 constant N_TRANCHES = 9;
int24 constant MAX_TRANCHE_OFFSET = 276300;

/// @dev The launch curve: N_TRANCHES single-sided token positions, each open-ended ([MIN_TICK, top], i.e. from its start
///      price to infinity), so they stack. Tranche i holds `bps` of supply (the last one takes the remainder) and starts
///      `topOff` ticks below tickStart (price multiple 1.0001^topOff above the start). Starts strictly rise with i, and
///      tranche 0 starts at the start price (topOff 0): the floor starts there.
library Curve {
    function tranche(uint256 i) internal pure returns (uint256 bps, int24 topOff) {
        if (i == 0) return (3500, 0);
        if (i == 1) return (31, 115140);
        if (i == 2) return (67, 138180);
        if (i == 3) return (126, 161160);
        if (i == 4) return (239, 184200);
        if (i == 5) return (454, 207240);
        if (i == 6) return (860, 230280);
        if (i == 7) return (1631, 253320);
        return (3092, 276300);
    }
}

src/libraries/FloorMath.sol

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

import {FullMath} from "v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/src/libraries/FixedPoint96.sol";
import {SqrtPriceMath} from "v4-core/src/libraries/SqrtPriceMath.sol";

/// @notice Amount <-> liquidity helpers for single-sided ranges. Pool orientation (see ZappyHook): currency0 = quote,
///         currency1 = launched token, so "quote" amounts are amount0 and "token" amounts are amount1.
library FloorMath {
    /// @dev Liquidity that `amount0` of quote buys over [sqrtA, sqrtB] (all of it above the price). Rounds down.
    function liquidityForQuote(uint160 sqrtA, uint160 sqrtB, uint256 amount0) internal pure returns (uint128) {
        uint256 inter = FullMath.mulDiv(sqrtA, sqrtB, FixedPoint96.Q96);
        uint256 l = FullMath.mulDiv(amount0, inter, sqrtB - sqrtA);
        // forge-lint: disable-next-line(unsafe-typecast)
        return l > type(uint128).max ? type(uint128).max : uint128(l); // clamped
    }

    /// @dev Liquidity that `amount1` of token buys over [sqrtA, sqrtB] (all of it below the price). Rounds down.
    function liquidityForToken(uint160 sqrtA, uint160 sqrtB, uint256 amount1) internal pure returns (uint128) {
        uint256 l = FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtB - sqrtA);
        // forge-lint: disable-next-line(unsafe-typecast)
        return l > type(uint128).max ? type(uint128).max : uint128(l); // clamped
    }

    /// @dev Quote held by liquidity `l` over [sqrtA, sqrtB].
    function quote(uint160 sqrtA, uint160 sqrtB, uint128 l, bool roundUp) internal pure returns (uint256) {
        if (sqrtA >= sqrtB || l == 0) return 0;
        return SqrtPriceMath.getAmount0Delta(sqrtA, sqrtB, l, roundUp);
    }

    /// @dev Token held by liquidity `l` over [sqrtA, sqrtB].
    function token(uint160 sqrtA, uint160 sqrtB, uint128 l, bool roundUp) internal pure returns (uint256) {
        if (sqrtA >= sqrtB || l == 0) return 0;
        return SqrtPriceMath.getAmount1Delta(sqrtA, sqrtB, l, roundUp);
    }
}

src/libraries/Tax.sol

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

import {FullMath} from "v4-core/src/libraries/FullMath.sol";

/// @notice The swap tax: its rate over a pool's life and how it is split. Rates are in pips (1e6 = 100%) and always taken
///         on the quote leg's gross amount, rounded up (against the trader).
library Tax {
    uint256 internal constant PIPS = 1_000_000;
    /// @dev 2.5%: 1.5% floor / 0.6% creator / 0.4% protocol (team)
    uint256 internal constant BASE = 25_000;
    /// @dev The snipe window: 90% at second 0, linear down to BASE at SNIPE_SECONDS
    uint256 internal constant SNIPE_START = 900_000;
    uint256 internal constant SNIPE_SECONDS = 60;
    /// @dev The snipe window's split: this much to the $ZAPPY buy-and-burn ($ZAPPY's own pool: its creator fee, ZAPPY's
    ///      revenue), the rest to the floor (vesting), none to the creator
    uint256 internal constant SNIPE_BURN_PCT = 40;

    /// @dev Rate `elapsed` seconds after launch, and whether that's still the snipe window.
    function rate(uint256 elapsed) internal pure returns (uint256 r, bool snipe) {
        if (elapsed >= SNIPE_SECONDS) return (BASE, false);
        return (SNIPE_START - (SNIPE_START - BASE) * elapsed / SNIPE_SECONDS, true);
    }

    /// @dev Tax on a gross amount: r of it.
    function ofGross(uint256 gross, uint256 r) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(gross, r, PIPS);
    }

    /// @dev The gross amount whose net (after r) is `net`; the tax is the difference.
    function grossUp(uint256 net, uint256 r) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(net, PIPS, PIPS - r);
    }

    /// @dev A normal (post-snipe) tax's creator share (24%: 0.6% of the trade); the floor gets 60%.
    function creatorShare(uint256 tax) internal pure returns (uint256) {
        return tax * 6 / 25;
    }

    /// @dev A normal (post-snipe) tax's protocol (team) share (16%: 0.4% of the trade).
    function protocolShare(uint256 tax) internal pure returns (uint256) {
        return tax * 4 / 25;
    }

    /// @dev A snipe-window tax's burn share; the floor gets the rest.
    function snipeBurn(uint256 tax) internal pure returns (uint256) {
        return tax * SNIPE_BURN_PCT / 100;
    }
}

src/libraries/Ticks.sol

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

/// @notice Tick bounds shared by the hook and the factory.
library Ticks {
    int24 internal constant SPACING = 60;
    int24 internal constant MIN_TICK = -887220; // TickMath.minUsableTick(SPACING)
    /// @dev Lowest start tick a pool may have (ZappyHook.createPool, and every start band in ZappyFactory): every tranche
    ///      shares the lower tick MIN_TICK, so their summed liquidity must fit v4's per-tick cap, with half of it left for
    ///      the floor band (test_minStartTickIsTheLiquidityBound pins the value to the curve). The liquidity falls as the
    ///      start tick rises, so a quote with fewer than 18 decimals (its ticks sit higher: ZappyFactory.quotes) is
    ///      always inside it; only a quote worth millions per unit, or one with many more decimals, is not.
    int24 internal constant MIN_START_TICK = -54780;

    /// @dev Rounds down to a multiple of SPACING (towards negative infinity).
    function alignDown(int24 tick) internal pure returns (int24) {
        int24 r = tick % SPACING;
        return r < 0 ? tick - r - SPACING : tick - r;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "@ensdomains/=/tmp/claude-0/-home-user-Launchpad/2c15f8d4-9629-5fde-b76e-4ea97bf2ebee/scratchpad/fobo-src/lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "hardhat/=/tmp/claude-0/-home-user-Launchpad/2c15f8d4-9629-5fde-b76e-4ea97bf2ebee/scratchpad/fobo-src/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.