Skip to content
Verified contractPartialMIT

BasedBidHook

Address0x558c8768a17ddcabbdbdd75a99433609933fdacc
Balance

0 ETH

 

Transactions

11

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,703,646
Creation transaction
0xbab47bf4bb…578db7936a
Libraries
src/BasedBidHook.sol:BasedBidHookLib0x1bf2…36db7a

39 files

src/BasedBidHook.sol

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

// ─── External imports (Uniswap V4 core) ─────────────────────────────────────
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {SwapParams, ModifyLiquidityParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
// ─── Internal imports (OpenZeppelin Uniswap Hooks + access) ─────────────────
import {CurrencySettler} from "@openzeppelin/uniswap-hooks/src/utils/CurrencySettler.sol";
import {BaseHook} from "@openzeppelin/uniswap-hooks/src/base/BaseHook.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";

// ─── Hook interface ──────────────────────────────────────────────────────────
import {IBasedBidHook, IWETH} from "./IBasedBidHook.sol";
// Single-library consolidation (2026-08-06): the hook links ONLY BasedBidHookLib.
// The former BasedBidHookDistLib (distribution/conversion) and BasedBidHookViewLib
// (validation/quotes/encoders) were merged into it; the ViewLib's small pool-owner
// setters now live inline in this contract — one delegatecall less per admin action.
import {BasedBidHookLib} from "./BasedBidHookLib.sol";

/**
 * @title BasedBidHook
 * @author RedRum
 * @notice Uniswap V4 hook that layers additional trading-fee mechanics on top of every swap.
 *         See {IBasedBidHook} for the full feature description and function signatures.
 */
contract BasedBidHook is
    BaseHook,
    Ownable,
    IUnlockCallback,
    IBasedBidHook
{
    using CurrencySettler for Currency;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;

    // Errors, events, structs, and enums are inherited from IBasedBidHook.

    // ──────────────────────── Immutables ─────────────────────

    /// @notice Canonical WETH contract; used to wrap native ETH before sending to token contracts.
    IWETH internal immutable WETH;

    // ──────────────────────── Storage ───────────────────────

    AdminConfig internal adminConfig;

    mapping(PoolId id => PoolConfig) internal poolConfig;
    mapping(PoolId id => HookFeeDistributionConfig)
        internal hookFeeDistributionConfig;
    mapping(PoolId id => DynamicFeeConfig) internal dynamicFeeConfig;
    mapping(PoolId id => DynamicFeeState) internal dynamicFeeState;
    mapping(PoolId id => VolumeConfig) internal volumeConfig;
    mapping(PoolId id => VolumeState) internal volumeState;
    mapping(PoolId id => TieredFeeConfig) internal tieredFeeConfig;
    mapping(PoolId id => PendingFees) internal pendingFees;
    mapping(PoolId id => RWASwapConfig) internal _rewardSwapConfig;
    mapping(PoolId id => mapping(address wallet => Whitelist)) public  isWhitelisted;
    mapping(PoolId id => mapping(address origin => uint256 amount))
        internal boughtPerOrigin;
    mapping(PoolId id => mapping(address trader => uint256 timestamp))
        internal lastTradeTimestamp;


    // GAS: the `isSwapping`/`distributing` execution flags live in EIP-1153 transient
    // storage (see BasedBidHookLib) — no storage slot, no cold SLOAD on swap guards.

    // ──────────────────────── Constructor ───────────────────

    constructor(
        IPoolManager _poolManager,
        address _WETH,
        address _treasury,
        uint16 _minAdminFeeBps,
        AdminFeeMathConfig memory _standardMath,
        uint16 _dddExternal,
        AdminFeeMathConfig memory _whitelistMath,
        uint16 _referralShareBps,
        address _owner
    ) BaseHook(_poolManager) Ownable(_owner) {
        WETH = IWETH(_WETH);
        _setAdminConfig(_treasury, _minAdminFeeBps, _standardMath, _dddExternal, _whitelistMath, _referralShareBps);
    }

    /// @dev Shared constructor/`updateAdminFee` body: validates and stores the admin-fee
    ///      configuration. The floor must stay strictly below the 2 % hard cap, both
    ///      formula divisors must be non-zero, and the referral share (portion of the
    ///      admin fee routed to a pool's referral) may not exceed 100 %.
    ///      Inline in the hook (not the library) since the consolidation: it is small,
    ///      and admin updates skip a delegatecall this way.
    function _setAdminConfig(
        address _treasury,
        uint16 _minAdminFeeBps,
        AdminFeeMathConfig memory _standardMath,
        uint16 _dddExternal,
        AdminFeeMathConfig memory _whitelistMath,
        uint16 _referralShareBps
    ) internal {
        if (_minAdminFeeBps >= BasedBidHookLib.MAX_ADMIN_FEE_BPS) revert InvalidAdminFeeConfig();
        if (_standardMath.bbb == 0 || _whitelistMath.bbb == 0) revert InvalidAdminFeeConfig();
        if (_referralShareBps > BasedBidHookLib.BPS) revert InvalidAdminFeeConfig();
        adminConfig.treasury = _treasury;
        adminConfig.minAdminFeeBps = _minAdminFeeBps;
        adminConfig.dddExternal = _dddExternal;
        adminConfig.referralShareBps = _referralShareBps;
        adminConfig.standardMath = _standardMath;
        adminConfig.whitelistMath = _whitelistMath;
        emit AdminFeeUpdated(
            _treasury, _minAdminFeeBps, _standardMath, _dddExternal, _whitelistMath, _referralShareBps
        );
    }

    /// @dev Loads the pool config and reverts unless `msg.sender` is the pool owner.
    function _requirePoolOwner(
        PoolId id
    ) internal view returns (PoolConfig storage cfg) {
        cfg = poolConfig[id];
        if (cfg.poolOwner == address(0)) revert PoolNotInitialized();
        if (cfg.poolOwner != msg.sender) revert NotPoolOwner();
    }

    /// @dev F-01: forbids fee/distribution configuration mutations while a distribution
    ///      or internal conversion swap is executing. Distribution runs external reward
    ///      callbacks; without this a malicious recipient could reenter and rewrite the
    ///      very configuration the in-progress distribution reads.
    modifier notDuringDistribution() {
        if (BasedBidHookLib.isDistributing() || BasedBidHookLib.isSwapping()) {
            revert ConfigLockedDuringDistribution();
        }
        _;
    }

    /// @notice Contract-owner-only: replace the admin-fee configuration (treasury, floor,
    ///         referral share, formula parameter sets). See {IBasedBidHook.AdminConfig}.
    function updateAdminFee(
        address _treasury,
        uint16 _minAdminFeeBps,
        AdminFeeMathConfig calldata _standardMath,
        uint16 _dddExternal,
        AdminFeeMathConfig calldata _whitelistMath,
        uint16 _referralShareBps
    ) external onlyOwner notDuringDistribution {
        _setAdminConfig(_treasury, _minAdminFeeBps, _standardMath, _dddExternal, _whitelistMath, _referralShareBps);
    }



    /**
     * @dev Thin wrapper: delegates to `BasedBidHookLib.simulateSwapTickBody` via
     *      DELEGATECALL.  Always reverts with `RevertWithTick`; the caller catches
     *      the revert to obtain the simulated post-swap tick without persisting state.
     */
    function simulateSwapTick(
        PoolKey calldata key,
        SwapParams calldata params
    ) external {
        // Only ever reached via the hook's own `simulateSwapTickAfter` self-call.
        if (msg.sender != address(this)) revert UnexpectedSimulationRevert();
        BasedBidHookLib.simulateSwapTickBody(poolManager, key, params);
    }

    // ═══════════════════════ Admin Functions ══════════════════

    /**
     * @notice One-shot setter for launch / protection fields on an initialised pool.
     * @dev Only callable by the current pool owner.
     */
    function setInitialConfig(
        PoolKey calldata key,
        uint48 whitelistPeriod,
        bool projectTokenIsCurrency1,
        uint256 maxBuyPerOrigin
    ) external notDuringDistribution {
        PoolId id = key.toId();
        _requirePoolOwner(id);
        BasedBidHookLib.applyInitialConfig(
            poolConfig[id],
            pendingFees[id],
            id,
            whitelistPeriod,
            projectTokenIsCurrency1,
            maxBuyPerOrigin
        );
    }

    /// @notice Configure or update the whitelist settings for a pool.
    /// @dev Inline (no library delegatecall) since the consolidation — trivially small.
    function setWhitelistConfig(
        PoolKey calldata key,
        bool isWhitelistPool,
        uint256 maxBuyPerOriginForWhitelistedUser
    ) external notDuringDistribution {
        PoolId id = key.toId();
        PoolConfig storage cfg = _requirePoolOwner(id);
        cfg.isWhitelistPool = isWhitelistPool;
        cfg.maxBuyPerOriginForWhitelistedUser = maxBuyPerOriginForWhitelistedUser;
        emit WhitelistConfigUpdated(id, isWhitelistPool, maxBuyPerOriginForWhitelistedUser);
    }

    /// @dev Inline (no library delegatecall) since the consolidation — a plain copy loop.
    function updateWhitelistWallets(
        PoolKey calldata key,
        address[] calldata wallets,
        Whitelist[] calldata _isWhitelisted
    ) external notDuringDistribution {
        PoolId id = key.toId();
        _requirePoolOwner(id);
        mapping(address => Whitelist) storage whitelistForPool = isWhitelisted[id];
        for (uint256 i = 0; i < wallets.length; i++) {
            whitelistForPool[wallets[i]] = _isWhitelisted[i];
        }
        emit WhitelistWalletsUpdated(id, wallets, _isWhitelisted);
    }

    /// @notice Set the fee-distribution threshold for a pool.
    /// @dev Inline (no library delegatecall) since the consolidation — two storage writes.
    function setFeeThreshold(PoolKey calldata key, uint256 threshold, bool isExternalFeeTrigger) external notDuringDistribution {
        PoolId id = key.toId();
        PoolConfig storage cfg = _requirePoolOwner(id);
        pendingFees[id].feeThreshold = threshold;
        cfg.isExternalFeeTrigger = isExternalFeeTrigger;
        emit ExternalFeeTriggerRequired(id, isExternalFeeTrigger);
    }

    /// @inheritdoc IBasedBidHook
    function setRewardSwapConfig(
        PoolKey calldata key,
        bool isSwapAll,
        uint8 swapForRewardNo,
        uint16[] calldata RWAPercentsBps,
        PoolKey[][] calldata paths
    ) external notDuringDistribution {
        PoolId id = key.toId();
        _requirePoolOwner(id);
        BasedBidHookLib.validateAndSetRWASwapConfig(
            _rewardSwapConfig[id], isSwapAll, swapForRewardNo, RWAPercentsBps, paths, id
        );
        emit RewardSwapConfigUpdated(id, isSwapAll, swapForRewardNo, RWAPercentsBps, paths);
    }

    /// @inheritdoc IBasedBidHook
    /// @dev Body lives in `BasedBidHookLib.batchSetPoolFeeAndDistributionConfig`
    ///      (EIP-170 headroom); the library delegatecall runs in this contract's context,
    ///      so its `poolManager.unlock` still calls back into this hook.
    function batchSetPoolFeeAndDistributionConfig(
        PoolKey calldata key,
        HookFeeDistributionConfig calldata hookFeeDistributionCfg,
        uint256 feeThreshold,
        FeeKind feeKind,
        TieredFeeConfig calldata tieredConfig,
        DynamicFeeConfig calldata dynamicConfig,
        VolumeConfig calldata _volumeConfig,
        uint24 hookFeeBpsBuy,
        uint24 hookFeeBpsSell,
        bool isExternalFeeTrigger
    ) external notDuringDistribution {
        PoolId id = key.toId();
        _requirePoolOwner(id);
        BasedBidHookLib.batchSetPoolFeeAndDistributionConfig(
            poolManager,
            poolConfig[id],
            hookFeeDistributionConfig[id],
            pendingFees[id],
            tieredFeeConfig[id],
            dynamicFeeConfig[id],
            dynamicFeeState[id],
            volumeConfig[id],
            key,
            hookFeeDistributionCfg,
            feeThreshold,
            feeKind,
            tieredConfig,
            dynamicConfig,
            _volumeConfig,
            hookFeeBpsBuy,
            hookFeeBpsSell,
            isExternalFeeTrigger
        );
    }

    /// @notice Configure the cooldown penalty: extra fee when the same origin trades within `cooldownSeconds`.
    /// @dev The penalty is part of the total hook fee, so it is bounded by (and corrected
    ///      at swap time to) the 18 % `MAX_HOOK_FEE_BPS` cap.
    ///      Inline (no library delegatecall) since the consolidation.
    function setCooldownConfig(
        PoolKey calldata key,
        uint32 cooldownSeconds,
        uint24 penaltyFeeBps
    ) external notDuringDistribution {
        PoolConfig storage cfg = _requirePoolOwner(key.toId());
        if (penaltyFeeBps > BasedBidHookLib.MAX_HOOK_FEE_BPS) revert HookFeeTooLarge();
        cfg.cooldownSeconds = cooldownSeconds;
        cfg.penaltyFeeBps = penaltyFeeBps;
    }

    /// @notice Pool owner: set the max tolerated slippage (BPS) for internal conversion swaps (F-02).
    /// @dev `maxConversionSlippageBps >= BPS` disables the guard.
    ///      Inline (no library delegatecall) since the consolidation.
    function setConversionSlippage(PoolKey calldata key, uint16 maxConversionSlippageBps) external notDuringDistribution {
        PoolId id = key.toId();
        PoolConfig storage cfg = _requirePoolOwner(id);
        cfg.maxConversionSlippageBps = maxConversionSlippageBps;
        emit ConversionSlippageUpdated(id, maxConversionSlippageBps);
    }

    /// @notice Disabled: the contract owner cannot be renounced (L-5).
    /// @dev `distributeAdminFees` and `updateAdminFee` are both `onlyOwner`. Renouncing would
    ///      leave the admin-fee accrual running with no way to sweep it to the treasury and no
    ///      way to zero the treasury to stop it, permanently stranding every future admin fee
    ///      as hook-held ERC-6909. Use `transferOwnership` instead.
    function renounceOwnership() public pure override {
        revert OwnershipCannotBeRenounced();
    }

    /// @notice Transfer pool-admin rights to a new address.  Cannot be set to address(0).
    function transferOwnershipOfPool(PoolId id, address newOwner) public notDuringDistribution {
        if (newOwner == address(0)) revert InvalidZeroAddress();
        PoolConfig storage cfg = _requirePoolOwner(id);
        cfg.poolOwner = newOwner;
        emit PoolOwnerTransferred(id, newOwner);
    }

    /// @inheritdoc IBasedBidHook
    /// @dev Body in `BasedBidHookLib` (EIP-170 headroom); the delegatecalled library
    ///      runs in this contract's context, so its pre-distribution `unlock` still calls
    ///      back into this hook.
    function renounceOwnershipOfPool(PoolKey calldata key) external notDuringDistribution {
        PoolId id = key.toId();
        BasedBidHookLib.renounceOwnershipOfPool(
            poolManager, _requirePoolOwner(id), pendingFees[id], key
        );
    }

    /// @inheritdoc IBasedBidHook
    /// @dev Inline (no library delegatecall) since the consolidation.
    function setReferral(PoolKey calldata key, address referral) external notDuringDistribution {
        PoolId id = key.toId();
        PoolConfig storage cfg = _requirePoolOwner(id);
        cfg.referral = referral;
        emit ReferralUpdated(id, referral);
    }

    /// @dev L-4: a fee distribution calls out to reward trackers, custom wallets and fee
    ///      tokens, and the hook's own conversion swaps run inside that same unlock. Those
    ///      callbacks could previously add or remove liquidity in one of this hook's pools
    ///      mid-distribution — JIT-sandwiching the hook's buyback/reward conversion, whose
    ///      only other protection is the spot-relative F-02 slippage bound. Swaps are already
    ///      rejected under these flags (COR-001); liquidity moves now are too.
    ///      Third-party hop pools remain outside this hook's reach, so a conversion routed
    ///      through them is still bounded only by `maxConversionSlippageBps`.
    function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        override
        returns (bytes4)
    {
        _requireNoLiquidityDuringDistribution();
        return this.beforeAddLiquidity.selector;
    }

    /// @dev Mirror of {_beforeAddLiquidity}; see there.
    function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        override
        returns (bytes4)
    {
        _requireNoLiquidityDuringDistribution();
        return this.beforeRemoveLiquidity.selector;
    }

    function _requireNoLiquidityDuringDistribution() internal view {
        if (BasedBidHookLib.isSwapping() || BasedBidHookLib.isDistributing()) {
            revert LiquidityLockedDuringDistribution();
        }
    }

    /**
     * @dev First-time initialisation of a pool's config.  Sets the deployer as pool owner,
     */
    function _afterInitialize(
        address sender,
        PoolKey calldata key,
        uint160,
        int24 tick
    ) internal virtual override returns (bytes4) {
        PoolId id = key.toId();
        BasedBidHookLib.initializePool(
            poolConfig,
            dynamicFeeConfig,
            volumeConfig,
            tieredFeeConfig,
            dynamicFeeState,
            hookFeeDistributionConfig,
            id,
            sender,
            tick
        );
        return this.afterInitialize.selector;
    }

    /**
     * @dev Pre-swap hook.  For external (non-internal) swaps:
     *      1. Computes the hook fee (static / tiered / dynamic), corrected to the 18 % cap.
     *      2. Optionally updates the pool's LP swap fee.
     *      3. Applies cooldown penalty when `tx.origin` traded recently.
     *      4. When the unspecified leg is the project token (exact-in buy OR
     *         exact-out sell), takes ALL fees from the non-project token,
     *         distributes directly, and returns a BeforeSwapDelta so V4
     *         adjusts `amountToSwap` accordingly.
     */
    function _beforeSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        bytes calldata
    ) internal virtual override returns (bytes4, BeforeSwapDelta, uint24) {
        PoolId poolId = key.toId();
        // The hook's own conversion swaps are identified exactly: the hook itself calls
        // `poolManager.swap`, so V4 reports it as `sender`.
        if (sender == address(this)) {
            return (this.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
        }
        // COR-001: the `isSwapping` / `distributing` execution flags are hook-GLOBAL.
        // Skipping (instead of rejecting) foreign swaps while they are set would let a
        // recipient or route-hop hook, called during a Pool A distribution, swap fee-free
        // and protection-free in ANY pool served by this hook. Reject such nested swaps
        // outright; honest recipients have no reason to swap mid-payout, and the lock only
        // spans the current unlock/transaction.
        if (BasedBidHookLib.isSwapping() || BasedBidHookLib.isDistributing()) {
            revert SwapBlockedDuringDistribution();
        }
        PoolConfig storage cfg = poolConfig[poolId];
        // A-3: a fee exemption waives the HOOK fee only — the fee path still runs so the
        // static pool (LP) fee applies and the whitelist-set ADMIN fee is charged.
        bool feeExempt = isWhitelisted[poolId][tx.origin].isBuilderFeeExempt;
        BeforeSwapDelta beforeDelta = BasedBidHookLib.handleBeforeSwapFees(
            poolManager,
            WETH,
            adminConfig,
            feeExempt,
            key,
            params,
            sender,
            poolId,
            cfg,
            dynamicFeeConfig,
            dynamicFeeState,
            tieredFeeConfig,
            hookFeeDistributionConfig,
            pendingFees,
            _rewardSwapConfig,
            volumeState,
            lastTradeTimestamp
        );
        return (this.beforeSwap.selector, beforeDelta, 0);
    }

    /**
     * @dev Post-swap hook.  Handles percentage fees, protect-period buy limits,
     *      volume accounting, and trade timestamps.
     *
     *      **Percentage fee (!unspecifiedIsProject only):**
     *        Taken from the non-project output and distributed via
     *        `BasedBidHookLib.distributeHookFeeNP`.
     */
    function _afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata
    ) internal virtual override returns (bytes4, int128) {
        PoolId poolId = key.toId();
        if (sender == address(this)) {
            return (this.afterSwap.selector, 0);
        }
        // COR-001: mirror of the _beforeSwap guard — reject, don't waive (see there).
        // Defense-in-depth: a foreign swap already reverts in _beforeSwap, so this is
        // only reachable if the flags flip between the two callbacks.
        if (BasedBidHookLib.isSwapping() || BasedBidHookLib.isDistributing()) {
            revert SwapBlockedDuringDistribution();
        }
        // GAS: one read for both whitelist bits (they share a slot).
        Whitelist memory wl = isWhitelisted[poolId][tx.origin];

        PoolConfig storage cfg = poolConfig[poolId];

        uint256 totalFeeAmount = BasedBidHookLib.handleAfterSwapFees(
            poolManager,
            WETH,
            adminConfig,
            wl.isBuilderFeeExempt,
            address(this),
            key,
            params,
            delta,
            sender,
            poolId,
            cfg,
            hookFeeDistributionConfig,
            pendingFees,
            _rewardSwapConfig,
            boughtPerOrigin,
            volumeConfig,
            volumeState,
            lastTradeTimestamp,
            wl.isWhitelistedForTradeLimit
        );
        return (this.afterSwap.selector, int128(int256(totalFeeAmount)));
    }

    // ═══════════════════════ View Helpers ═════════════════════

    /// @inheritdoc IBasedBidHook
    /// @dev Return payload is ABI-encoded in `BasedBidHookLib` and forwarded with
    ///      `assembly` so this contract does not embed a second copy of the encoder
    ///      (keeps runtime size under EIP-170).
    function getPoolFullConfig(PoolId id)
        external
        view
        returns (
            PoolConfig memory,
            HookFeeDistributionConfig memory,
            DynamicFeeConfig memory,
            DynamicFeeState memory,
            VolumeConfig memory,
            VolumeState memory,
            TieredFeeConfig memory,
            PendingFees memory,
            RWASwapConfig memory
        )
    {
        bytes memory data = BasedBidHookLib.encodePoolFullConfig(
            poolConfig[id],
            hookFeeDistributionConfig[id],
            dynamicFeeConfig[id],
            dynamicFeeState[id],
            volumeConfig[id],
            volumeState[id],
            tieredFeeConfig[id],
            pendingFees[id],
            _rewardSwapConfig[id]
        );
        assembly ("memory-safe") {
            return(add(data, 0x20), mload(data))
        }
    }

    function getDynamicFeeState(
        PoolId poolId,
        bool surgeSignMatches,
        bool isBuy
    )
        external
        view
        returns (uint256 baseFee, uint256 surgeFee, uint256 totalFee)
    {
        return
            BasedBidHookLib.calcDynamicFees(
                dynamicFeeConfig[poolId],
                dynamicFeeState[poolId],
                surgeSignMatches,
                volumeState[poolId].activeVolumeMultiplierBps,
                isBuy
            );
    }

    /// @inheritdoc IBasedBidHook
    /// @dev Inline since the consolidation: the caps are `internal` library constants,
    ///      so referencing them compiles to literals — no delegatecall, no dispatcher.
    function getFeeHardLimits()
        external
        view
        returns (
            uint24 defaultHookFeeCapBps,
            uint24 maxHookFeeBps,
            uint24 maxAdminFeeBps,
            uint24 maxTotalFeeBps,
            uint16 minAdminFeeBps
        )
    {
        return (
            BasedBidHookLib.MAX_DEFAULT_HOOK_FEE_BPS,
            BasedBidHookLib.MAX_HOOK_FEE_BPS,
            BasedBidHookLib.MAX_ADMIN_FEE_BPS,
            BasedBidHookLib.MAX_TOTAL_FEE_BPS,
            adminConfig.minAdminFeeBps
        );
    }

    /// @inheritdoc IBasedBidHook
    /// @dev Encoded in the library and forwarded with assembly so this contract does not
    ///      embed the nested-struct encoder (EIP-170 headroom).
    function getAdminFeeConfig() external view returns (AdminConfig memory) {
        bytes memory data = BasedBidHookLib.encodeAdminConfig(adminConfig);
        assembly ("memory-safe") {
            return(add(data, 0x20), mload(data))
        }
    }

    /// @inheritdoc IBasedBidHook
    function quoteSwapFees(
        PoolId id,
        bool isBuy,
        uint256 projectTokenAmount,
        address trader
    )
        external
        view
        returns (uint24 builderFeeBps, uint24 protectionFeeBps, uint24 adminFeeBps, uint24 totalFeeBps)
    {
        return BasedBidHookLib.quoteSwapFees(
            poolConfig,
            dynamicFeeConfig,
            dynamicFeeState,
            tieredFeeConfig,
            volumeState,
            isWhitelisted,
            lastTradeTimestamp,
            adminConfig,
            id,
            isBuy,
            projectTokenAmount,
            trader
        );
    }

    // ═══════════════════ Fee Distribution ═════════════════════

    /// @inheritdoc IBasedBidHook
    /// @dev M-1: exists so the threshold-triggered distribution inside a user's swap runs in
    ///      its OWN call frame and can therefore be `try`ed by the library. A failure then
    ///      reverts only this frame — pending fees stay accounted in their source currency
    ///      and the user's swap still succeeds — instead of bricking every swap on the pool.
    ///      Self-only: the pool-owner-gated `distributeFee` and the threshold path are the
    ///      only legitimate ways to start a distribution.
    function selfDistributeFees(PoolKey calldata key) external {
        if (msg.sender != address(this)) revert UnexpectedSimulationRevert();
        PoolId poolId = key.toId();
        BasedBidHookLib.distributeFees(
            poolManager,
            WETH,
            key,
            poolConfig[poolId],
            hookFeeDistributionConfig[poolId],
            pendingFees[poolId],
            _rewardSwapConfig[poolId]
        );
    }

    /// @notice Distribute accumulated non-liquidity fees (buyback, reward, custom
    ///         wallets) and the accumulated referral share.
    /// @dev The referral accumulator can be non-zero while `totalFeeAmount` is zero
    ///      (e.g. a 100 % LP split), so both gates matter.
    function distributeFee(PoolKey calldata key) external {
        PoolId poolId = key.toId();
        _requirePoolOwner(poolId);
        IBasedBidHook.PendingFees storage pf = pendingFees[poolId];
        if (pf.totalFeeAmount == 0 && pf.referralFeeAmount == 0) return;
        poolManager.unlock(abi.encode(CallbackAction.DISTRIBUTE_FEE, key));
    }

    /// @notice Distribute accumulated admin fees to the treasury.  Callable only by admin.
    function distributeAdminFees(PoolKey calldata key) external onlyOwner {
        PoolId poolId = key.toId();
        if (pendingFees[poolId].adminFeeAmount == 0) return;
        poolManager.unlock(
            abi.encode(CallbackAction.DISTRIBUTE_ADMIN_FEES, key)
        );
    }

    // ═══════════════════ Unlock Callback ═══════════════════

    /**
     * @dev Single entry-point for all pool-manager unlock callbacks.
     *      Dispatches based on the encoded `CallbackAction`.
     */
    function unlockCallback(
        bytes calldata data
    ) external override returns (bytes memory) {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        (CallbackAction action, PoolKey memory key) = abi.decode(
            data,
            (CallbackAction, PoolKey)
        );
        PoolId poolId = key.toId();

        if (action == CallbackAction.DISTRIBUTE_FEE) {
            BasedBidHookLib.distributeFees(
                poolManager,
                WETH,
                key,
                poolConfig[poolId],
                hookFeeDistributionConfig[poolId],
                pendingFees[poolId],
                _rewardSwapConfig[poolId]
            );
        } else if (action == CallbackAction.DISTRIBUTE_ADMIN_FEES) {
            BasedBidHookLib.distributeAdminFees(
                poolManager,
                WETH,
                key,
                adminConfig.treasury,
                poolConfig[poolId],
                pendingFees[poolId]
            );
        }
        return "";
    }

    // ═══════════════════ Hook Permissions ═══════════════════

    /// @dev Declares which hook callbacks this contract uses.
    function getHookPermissions()
        public
        pure
        virtual
        override
        returns (Hooks.Permissions memory permissions)
    {
        return
            Hooks.Permissions({
                beforeInitialize: false,
                afterInitialize: true,
                // L-4: liquidity callbacks are enabled purely to reject JIT liquidity moves
                // while one of this hook's conversions or distributions is in flight.
                // NOTE: this changes the required hook-address flag bits, so the deployment
                // salt must be re-mined.
                beforeAddLiquidity: true,
                afterAddLiquidity: false,
                beforeRemoveLiquidity: true,
                afterRemoveLiquidity: false,
                beforeSwap: true,
                afterSwap: true,
                beforeDonate: false,
                afterDonate: false,
                beforeSwapReturnDelta: true,
                afterSwapReturnDelta: true,
                afterAddLiquidityReturnDelta: false,
                afterRemoveLiquidityReturnDelta: false
            });
    }

    /// @dev Required to receive native ETH from the pool manager for WETH wrapping.
    receive() external payable {}
}

lib/uniswap-hooks/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/uniswap-hooks/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/uniswap-hooks/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/uniswap-hooks/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

lib/uniswap-hooks/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

lib/uniswap-hooks/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/uniswap-hooks/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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 {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

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

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

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

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

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

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

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

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

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

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

lib/uniswap-hooks/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";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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 {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/uniswap-hooks/src/base/BaseHook.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Uniswap Hooks (last updated v1.2.0) (src/base/BaseHook.sol)

pragma solidity ^0.8.26;

// External imports
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {SwapParams, ModifyLiquidityParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";

/**
 * @dev Base hook implementation.
 *
 * This contract defines all hook entry points, as well as security and permission helpers.
 * Based on the https://github.com/Uniswap/v4-periphery/blob/main/src/base/hooks/BaseHook.sol[Uniswap v4 periphery implementation].
 *
 * NOTE: Hook entry points must be overridden and implemented by the inheriting hook to be used. Their respective
 * flags must be set to true in the `getHookPermissions` function as well.
 *
 * WARNING: This is experimental software and is provided on an "as is" and "as available" basis. We do
 * not give any warranties and will not be liable for any losses incurred through any use of this code
 * base.
 *
 * _Available since v0.1.0_
 */
abstract contract BaseHook is IHooks {
    /*
     * @dev The pool manager singleton contract.
     */
    IPoolManager public immutable poolManager;

    /**
     * @dev The hook function is not implemented.
     */
    error HookNotImplemented();

    /**
     * @notice Thrown when calling unlockCallback where the caller is not `PoolManager`.
     */
    error NotPoolManager();

    /**
     * @dev Check that the hook address matches the expected permissions and flags.
     */
    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
        _validateHookAddress(this);
    }

    /**
     * @notice Only allow calls from the `PoolManager` contract
     */
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /**
     * @dev Get the hook permissions to signal which hook functions are to be implemented.
     *
     * Used at deployment to validate the address correctly represents the expected permissions.
     *
     * @return permissions The hook permissions.
     */
    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory permissions);

    /**
     * @dev Validate the hook address against the expected permissions.
     */
    function _validateHookAddress(BaseHook hook) internal pure {
        Hooks.validateHookPermissions(hook, getHookPermissions());
    }

    /**
     * @inheritdoc IHooks
     */
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _beforeInitialize(sender, key, sqrtPriceX96);
    }

    /**
     * @dev Hook implementation for `beforeInitialize`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _afterInitialize(sender, key, sqrtPriceX96, tick);
    }

    /**
     * @dev Hook implementation for `afterInitialize`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeAddLiquidity(sender, key, params, hookData);
    }

    /**
     * @dev Hook implementation for `beforeAddLiquidity`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeRemoveLiquidity(sender, key, params, hookData);
    }

    /**
     * @dev Hook implementation for `beforeRemoveLiquidity`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta0,
        BalanceDelta delta1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterAddLiquidity(sender, key, params, delta0, delta1, hookData);
    }

    /**
     * @dev Hook implementation for `afterAddLiquidity`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _afterAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta0,
        BalanceDelta delta1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterRemoveLiquidity(sender, key, params, delta0, delta1, hookData);
    }

    /**
     * @dev Hook implementation for `afterRemoveLiquidity`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _afterRemoveLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        onlyPoolManager
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        return _beforeSwap(sender, key, params, hookData);
    }

    /**
     * @dev Hook implementation for `beforeSwap`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, int128) {
        return _afterSwap(sender, key, params, delta, hookData);
    }

    /**
     * @dev Hook implementation for `afterSwap`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
        internal
        virtual
        returns (bytes4, int128)
    {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeDonate(sender, key, amount0, amount1, hookData);
    }

    /**
     * @dev Hook implementation for `beforeDonate`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /**
     * @inheritdoc IHooks
     */
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _afterDonate(sender, key, amount0, amount1, hookData);
    }

    /**
     * @dev Hook implementation for `afterDonate`, to be overridden by the inheriting hook. The
     * flag must be set to true in the `getHookPermissions` function.
     */
    function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }
}

lib/uniswap-hooks/src/utils/CurrencySettler.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Uniswap Hooks (last updated v0.1.0) (src/utils/CurrencySettler.sol)

pragma solidity ^0.8.26;

// External imports
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/**
 * @dev Library used to interact with the `PoolManager` to settle any open deltas.
 * To settle a positive delta (a credit to the user), a user may take or mint.
 * To settle a negative delta (a debt on the user), a user may transfer or burn to pay off a debt.
 *
 * Based on the https://github.com/Uniswap/v4-core/blob/main/test/utils/CurrencySettler.sol[Uniswap v4 test utils implementation].
 *
 * NOTE: Deltas are synced before any ERC-20 transfers in {settle} function.
 */
library CurrencySettler {
    using SafeERC20 for IERC20;

    /**
     * @notice Settle (pay) a currency to the `PoolManager`
     * @param currency Currency to settle
     * @param poolManager `PoolManager` to settle to
     * @param payer Address of the payer, which can be the hook itself or an external address.
     * @param amount Amount to send
     * @param burn If true, burn the ERC-6909 token, otherwise transfer ERC-20 to the `PoolManager`
     */
    function settle(Currency currency, IPoolManager poolManager, address payer, uint256 amount, bool burn) internal {
        // Early return when amount is 0 given that some tokens may revert in this case
        if (amount == 0) return;

        // For native currencies or burns, calling sync is not required
        // Short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
        if (burn) {
            poolManager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            poolManager.sync(currency);
            poolManager.settle{value: amount}();
        } else {
            poolManager.sync(currency);
            if (payer != address(this)) {
                IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(poolManager), amount);
            } else {
                IERC20(Currency.unwrap(currency)).safeTransfer(address(poolManager), amount);
            }
            poolManager.settle();
        }
    }

    /**
     * @notice Take (receive) a currency from the `PoolManager`
     * @param currency Currency to take
     * @param poolManager `PoolManager` to take from
     * @param recipient Address of the recipient of the ERC-6909 or ERC-20 token.
     * @param amount Amount to receive
     * @param claims If true, mint the ERC-6909 token, otherwise transfer ERC-20 from the `PoolManager` to recipient
     */
    function take(Currency currency, IPoolManager poolManager, address recipient, uint256 amount, bool claims)
        internal
    {
        // Early return when amount is 0 given that some tokens may revert in this case
        if (amount == 0) return;

        claims ? poolManager.mint(recipient, currency.toId(), amount) : poolManager.take(currency, recipient, amount);
    }
}

src/BasedBidHookLib.sol

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

import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {CurrencySettler} from "@openzeppelin/uniswap-hooks/src/utils/CurrencySettler.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IBasedBidHook, IWETH, IRewardDistributor, ITreasury, IDividendTracker} from "./IBasedBidHook.sol";

library BasedBidHookLib {
    using CurrencySettler for Currency;
    using SafeERC20 for IERC20;
    using StateLibrary for IPoolManager;

    // ─── Execution flags (GAS: EIP-1153 transient storage) ───
    // `isSwapping` / `distributing` are transaction-scoped execution locks. They were a
    // storage struct toggled set→reset within every conversion swap / distribution, which
    // cost a cold SLOAD on every swap guard plus SSTORE toggling. Transient storage has
    // identical semantics here (revert-scoped, cleared at end of transaction — the flags
    // were always reset before the transaction ended anyway) at TLOAD/TSTORE cost.
    // Slots are unique keccak-derived literals (inline assembly only accepts direct
    // number constants). Helpers are `internal` so DistLib inlines them — no link
    // dependency is created.
    /// @dev = uint256(keccak256("basedbid.hook.isSwapping.v1"))
    uint256 private constant IS_SWAPPING_TSLOT =
        0xc01b1f0a3e5a1f822bb527abfa532b64b471e4a88994285790f27c99ff1fe287;
    /// @dev = uint256(keccak256("basedbid.hook.distributing.v1"))
    uint256 private constant DISTRIBUTING_TSLOT =
        0x17928c7b313b230beb808a51be2731f701383502ce45ab9f6412d39097ac0064;

    function isSwapping() internal view returns (bool v) {
        assembly ("memory-safe") { v := tload(IS_SWAPPING_TSLOT) }
    }

    function setSwapping(bool v) internal {
        assembly ("memory-safe") { tstore(IS_SWAPPING_TSLOT, v) }
    }

    function isDistributing() internal view returns (bool v) {
        assembly ("memory-safe") { v := tload(DISTRIBUTING_TSLOT) }
    }

    function setDistributing(bool v) internal {
        assembly ("memory-safe") { tstore(DISTRIBUTING_TSLOT, v) }
    }

    struct BeforeSwapFeeContext {
        PoolId poolId;
        uint16 volumeMultiplierBps;
        int24 currentTick;
        int24 estimatedTickAfter;
        uint256 lastTradeTs;
    }

    uint16 internal constant BPS = 10_000;
    // ─── Fee hard limits (constants; see IBasedBidHook.getFeeHardLimits) ───
    /// @dev Cap on each fee mode's DEFAULT hook fee: STATIC `hookFeeBpsBuy/Sell`,
    ///      DYNAMIC `defaultBaseFeeBpsBuy/Sell`, TIERED `buyFeesBps[0]`/`sellFeesBps[0]`.
    uint24 internal constant MAX_DEFAULT_HOOK_FEE_BPS = 1_000; // 10 %
    /// @dev Cap on the total hook fee excluding the admin fee — the fee-kind engine
    ///      output and the cooldown penalty are each corrected down at their
    ///      application step so their sum never exceeds it.
    uint24 internal constant MAX_HOOK_FEE_BPS = 1_800; // 18 %
    /// @dev Hard cap on the admin fee.
    uint24 internal constant MAX_ADMIN_FEE_BPS = 200; // 2 %
    /// @dev Overall cap on hook + admin fee (follows from the two caps above).
    uint24 internal constant MAX_TOTAL_FEE_BPS = MAX_HOOK_FEE_BPS + MAX_ADMIN_FEE_BPS; // 20 %
    uint32 internal constant PPM = 1_000_000;
    address internal constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
    uint64 private constant ONE_DAY_PPM = 86_400 * 1_000_000;

    uint64 private constant CAP_FREQ_MAX = type(uint64).max - ONE_DAY_PPM + 1;
    uint32 private constant DEFAULT_CAP_BUDGET_PPM = 1_000_000;
    uint32 private constant DEFAULT_DECAY_WINDOW = 15_552_000;

    // ═══════════════════ Admin Fee Formula ═════════════════════

    /// @dev Admin fee in BPS for one swap:
    ///          min(max(minAdminFeeBps, (hookFeeBps * aaa / bbb) * ccc + ddd), 2 %)
    ///      `hookFeeBps` is the total hook fee excluding the admin fee (base + penalty).
    ///      A zero treasury disables the admin fee entirely (F-05) — the floor included.
    ///      `internal` so it inlines into the hook/ViewLib without a link dependency.
    function calcAdminFeeBps(IBasedBidHook.ResolvedAdminFeeParams memory p, uint256 hookFeeBps)
        internal
        pure
        returns (uint24)
    {
        if (p.treasury == address(0)) return 0;
        // `bbb != 0` is validated at configuration time; guard anyway so a swap can
        // never revert on division by zero if storage were ever left unset.
        uint256 fee = p.bbb == 0 ? p.ddd : (hookFeeBps * p.aaa / p.bbb) * p.ccc + p.ddd;
        if (fee < p.minAdminFeeBps) fee = p.minAdminFeeBps;
        if (fee > MAX_ADMIN_FEE_BPS) fee = MAX_ADMIN_FEE_BPS;
        return uint24(fee);
    }

    /// @dev Resolves the admin-fee inputs for one swap from the stored config: picks the
    ///      whitelist or standard math set and substitutes `dddExternal` for
    ///      external-trigger pools (standard set only). F-05: a zero treasury disables
    ///      the admin fee — `calcAdminFeeBps` returns 0 for `treasury == address(0)`.
    function resolveAdminFeeParams(
        IBasedBidHook.AdminConfig storage ac,
        bool isExternalFeeTrigger,
        bool feeExempt
    ) internal view returns (IBasedBidHook.ResolvedAdminFeeParams memory p) {
        p.treasury = ac.treasury;
        p.minAdminFeeBps = ac.minAdminFeeBps;
        IBasedBidHook.AdminFeeMathConfig storage m = feeExempt ? ac.whitelistMath : ac.standardMath;
        p.aaa = m.aaa;
        p.bbb = m.bbb;
        p.ccc = m.ccc;
        p.ddd = (!feeExempt && isExternalFeeTrigger) ? ac.dddExternal : m.ddd;
        p.referralShareBps = ac.referralShareBps;
    }

    // ═══════════════════ Dynamic Fee Engine ═════════════════════

    /// @dev Computes the base fee from `maxTicks × factor`, optionally scaled by
    ///      the volume multiplier, then clamped between min and max.
    function calcBaseFee(IBasedBidHook.DynamicFeeConfig memory dc, uint24 maxTicks, uint16 volumeMultiplierBps, bool isBuy) internal pure returns (uint256) {
        uint24 minFee = isBuy ? dc.minBaseFeeBpsBuy : dc.minBaseFeeBpsSell;
        uint24 maxFee = isBuy ? dc.maxBaseFeeBpsBuy : dc.maxBaseFeeBpsSell;
        uint32 factor = isBuy ? dc.baseFeeFactorBuy : dc.baseFeeFactorSell;
        uint24 defaultFee = isBuy ? dc.defaultBaseFeeBpsBuy : dc.defaultBaseFeeBpsSell;

        uint256 base;
        if (maxTicks == 0) {
            base = defaultFee;
        } else {
            unchecked { base = uint256(maxTicks) * factor; }
        }
        if (volumeMultiplierBps != 0) {
            unchecked { base = base * uint256(volumeMultiplierBps) / BPS; }
        }
        if (base < minFee) base = minFee;
        if (base > maxFee) base = maxFee;
        return base;
    }

    /// @dev Linearly-decaying surge surcharge: `baseFee × multiplier × remaining / period`.
    function calcSurgeFee(
        IBasedBidHook.DynamicFeeConfig memory dc, IBasedBidHook.DynamicFeeState memory ds, uint256 baseFee
    ) internal view returns (uint256) {
        if (!ds.inCap || ds.capStartTime == 0) return 0;
        uint32 period = dc.surgeDecayPeriodSeconds;
        if (period == 0) return 0;
        uint256 elapsed = block.timestamp - uint256(ds.capStartTime);
        if (elapsed >= period) return 0;
        unchecked {
            uint256 maxSurge = baseFee * dc.surgeMultiplierPpm / PPM;
            return maxSurge * (period - elapsed) / period;
        }
    }

    /// @dev Returns true when the surge fee has not yet fully decayed.
    function isSurgeFeeActive(
        IBasedBidHook.DynamicFeeConfig memory dc, IBasedBidHook.DynamicFeeState memory ds
    ) internal view returns (bool) {
        if (!ds.inCap || ds.capStartTime == 0) return false;
        uint32 period = dc.surgeDecayPeriodSeconds;
        if (period == 0) return false;
        uint256 elapsed = block.timestamp - uint256(ds.capStartTime);
        if (elapsed >= period) return false;
        return true;
    }

    /// @dev Returns `(baseFee, surgeFee, totalFee)`; the total (= the DYNAMIC hook fee)
    ///      is capped at the 18 % total-hook-fee limit.
    function calcDynamicFees(
        IBasedBidHook.DynamicFeeConfig memory dc, IBasedBidHook.DynamicFeeState memory ds,
        bool surgeSignMatches, uint16 volumeMultiplierBps, bool isBuy
    ) public view returns (uint256 baseFee, uint256 surgeFee, uint256 totalFee) {
        baseFee = calcBaseFee(dc, ds.maxTicksPerBlock, volumeMultiplierBps, isBuy);
        surgeFee = surgeSignMatches ? calcSurgeFee(dc, ds, baseFee) : 0;
        unchecked { totalFee = baseFee + surgeFee; }
        if (totalFee > MAX_HOOK_FEE_BPS) totalFee = MAX_HOOK_FEE_BPS;
    }

    /// @dev Measures tick displacement, enters/exits the cap state, updates cap-frequency
    ///      tracking, and triggers the periodic auto-tune of `maxTicksPerBlock`.
    function updateDynamicFeeState(
        IBasedBidHook.DynamicFeeConfig memory dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.PoolConfig storage cfg,
        int24 preSwapTick, int24 estimatedTickAfter, PoolId poolId
    ) internal {
        uint64 bn = uint64(block.number);
        if (bn != ds.lastObservationBlock) {
            ds.blockInitialTick = preSwapTick;
            ds.lastObservationBlock = bn;
        }

        uint24 maxTicks = ds.maxTicksPerBlock;
        bool tickWasCapped;

        if (dc.perSwapMode) {
            int256 tickDiff = int256(estimatedTickAfter) - int256(preSwapTick);
            uint256 absDiff = uint256(tickDiff >= 0 ? tickDiff : -tickDiff);
            tickWasCapped = absDiff > maxTicks;
            if (tickWasCapped) {
                ds.inCap = true;
                ds.capTickDirectionPositive = tickDiff > 0;
                ds.capStartTime = uint40(block.timestamp);
                emit IBasedBidHook.CapToggled(poolId, true);
            } else if (ds.inCap) {
                if (!isSurgeFeeActive(dc, ds)) {
                    ds.inCap = false;
                    emit IBasedBidHook.CapToggled(poolId, false);
                }
            }
        } else {
            int24 initial = ds.blockInitialTick;
            int256 tickDiff = int256(estimatedTickAfter) - int256(initial);
            uint256 absDiff = uint256(tickDiff >= 0 ? tickDiff : -tickDiff);
            tickWasCapped = absDiff > maxTicks;
            if (tickWasCapped) {
                ds.capTickDirectionPositive = tickDiff > 0;
                if (ds.lastCapEventBlock == bn) { tickWasCapped = false; }
                else {
                    ds.lastCapEventBlock = bn;
                    ds.inCap = true;
                    ds.capStartTime = uint40(block.timestamp);
                    emit IBasedBidHook.CapToggled(poolId, true);
                }
            } else {
                if (ds.lastCapEventBlock == bn) {
                    ds.inCap = false;
                    ds.lastCapEventBlock = 0;
                    emit IBasedBidHook.CapToggled(poolId, false);
                } else if (ds.inCap) {
                    if (!isSurgeFeeActive(dc, ds)) {
                        ds.inCap = false;
                        emit IBasedBidHook.CapToggled(poolId, false);
                    }
                }
            }
        }

        _updateCapFreqAndAutoTune(dc, ds, cfg, tickWasCapped);
    }

    function _updateCapFreqAndAutoTune(
        IBasedBidHook.DynamicFeeConfig memory dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.PoolConfig storage cfg,
        bool capOccurred
    ) internal {
        uint48 nowTs = uint48(block.timestamp);
        uint48 timeElapsed;
        unchecked { timeElapsed = nowTs - ds.lastCapFreqTs; }
        if (!capOccurred && timeElapsed == 0) return;
        ds.lastCapFreqTs = nowTs;

        uint64 freq = ds.capFreq;
        if (capOccurred) {
            unchecked { freq += uint64(ONE_DAY_PPM); }
            if (freq >= CAP_FREQ_MAX || freq < ONE_DAY_PPM) freq = CAP_FREQ_MAX;
        }
        if (!capOccurred && timeElapsed != 0 && freq != 0) {
            uint32 decayWindow = DEFAULT_DECAY_WINDOW;
            if (timeElapsed >= decayWindow) { freq = 0; }
            else {
                unchecked {
                    uint64 decayFactor = uint64(PPM) - uint64(timeElapsed) * uint64(PPM) / decayWindow;
                    uint128 decayed = uint128(freq) * decayFactor / PPM;
                    freq = decayed > CAP_FREQ_MAX ? CAP_FREQ_MAX : uint64(decayed);
                }
            }
        }
        ds.capFreq = freq;

        uint32 tuneInterval = dc.capAutoTuneIntervalSeconds == 0 ? 86400 : dc.capAutoTuneIntervalSeconds;
        if (block.timestamp >= cfg.lastAutoTuneTs + tuneInterval) {
            uint64 targetFreq;
            unchecked { targetFreq = uint64(DEFAULT_CAP_BUDGET_PPM) * uint64(DEFAULT_DECAY_WINDOW); }
            _autoTuneMaxTicks(dc, ds, cfg, freq > targetFreq);
        }
    }

    function _autoTuneMaxTicks(
        IBasedBidHook.DynamicFeeConfig memory dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.PoolConfig storage cfg,
        bool increase
    ) internal {
        uint24 currentCap = ds.maxTicksPerBlock;
        uint32 stepPpm = dc.capAutoTuneStepPpm == 0 ? 20_000 : dc.capAutoTuneStepPpm;
        uint24 change;
        unchecked { change = uint24(uint256(currentCap) * stepPpm / PPM); }
        if (change == 0) change = 1;

        uint24 newCap;
        unchecked {
            if (increase) { newCap = currentCap + change > 400 ? 400 : currentCap + change; }
            else { newCap = currentCap > change + 1 ? currentCap - change : 1; }
        }

        if (newCap != currentCap) {
            ds.maxTicksPerBlock = newCap;
            cfg.lastAutoTuneTs = uint32(block.timestamp);
        }
    }


    // ═══════════════════ Volume-Based Fee Multiplier ═════════════════

    /// @dev Validates sort order and length invariants, then persists the new volume config.
    function validateAndSetVolumeConfig(
        IBasedBidHook.VolumeConfig storage vc,
        IBasedBidHook.VolumeConfig calldata config
    ) internal {
        uint256 len = config.volumeLevels.length;
        if (len + 1 != config.volumeMultiplierBps.length) revert IBasedBidHook.InvalidVolumeConfig();
        for (uint256 i = 1; i < len;) {
            if (config.volumeLevels[i] <= config.volumeLevels[i - 1]) revert IBasedBidHook.InvalidVolumeConfig();
            unchecked { ++i; }
        }
        for (uint256 i = 1; i < config.volumeMultiplierBps.length;) {
            if (config.volumeMultiplierBps[i] <= config.volumeMultiplierBps[i - 1]) revert IBasedBidHook.InvalidVolumeConfig();
            unchecked { ++i; }
        }
        vc.volumeIntervalSeconds = config.volumeIntervalSeconds;
        delete vc.volumeLevels;
        delete vc.volumeMultiplierBps;
        for (uint256 i; i < len;) {
            vc.volumeLevels.push(config.volumeLevels[i]);
            vc.volumeMultiplierBps.push(config.volumeMultiplierBps[i]);
            unchecked { ++i; }
        }
        vc.volumeMultiplierBps.push(config.volumeMultiplierBps[len]);
    }  

    /// @dev Accumulates `projectTokenVolume` into the current window.  When the window
    ///      closes, resolves the active multiplier and resets the accumulator.
    function updateVolumeState(
        IBasedBidHook.VolumeConfig storage vc,
        IBasedBidHook.VolumeState storage vs,
        uint256 projectTokenVolume
    ) internal {
        uint32 interval = vc.volumeIntervalSeconds;
        if (interval == 0) return;
        
        if (vs.lastVolumeTs == 0) {
            vs.lastVolumeTs = uint48(block.timestamp);
            vs.volumeRecorded = projectTokenVolume;
            return;
        }
        vs.volumeRecorded += projectTokenVolume;
        if (block.timestamp >= uint256(vs.lastVolumeTs) + interval) {
            vs.activeVolumeMultiplierBps = _resolveVolumeMultiplier(vc, vs.volumeRecorded);
            vs.volumeRecorded = 0;
            vs.lastVolumeTs = uint48(block.timestamp);
        }
    }

    function _resolveVolumeMultiplier(
        IBasedBidHook.VolumeConfig storage vc,
        uint256 volume
    ) internal view returns (uint16) {
        uint256 len = vc.volumeLevels.length;
        uint16 multiplier = uint16(vc.volumeMultiplierBps[0]);
        for (uint256 i; i < len;) {
            if (volume >= vc.volumeLevels[i]) {
                multiplier = vc.volumeMultiplierBps[i+1];
            } else {
                break;
            }
            unchecked { ++i; }
        }
        return multiplier;
    }

    function applyInitialConfig(
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.PendingFees storage pf,
        PoolId id,
        uint48 whitelistPeriod, bool projectTokenIsCurrency1, uint256 maxBuyPerOrigin
    ) public {
        // H-2: the F-03 lock below used to be reached only when `block.timestamp` had moved
        // PAST `launchTimestamp`. Since the first call sets `launchTimestamp` to the current
        // timestamp, a SECOND call in the SAME block fell through to the unguarded branch and
        // could re-point the project-token side while fees were already outstanding — the
        // exact reinterpretation F-03 exists to prevent, reachable permissionlessly in one
        // transaction. The gate is now the pool's lifecycle (`launchTimestamp == 0`, i.e. the
        // genuine first configuration) rather than elapsed time, and the side flip is
        // obligation-checked on EVERY call after that first one, same block or not.
        if (cfg.launchTimestamp == 0) {
            // First configuration. No fee can exist yet: `enforceWhitelistBuyLimit` reverts
            // `PoolNotInitialized` while `launchTimestamp == 0`, so no swap has ever settled
            // on this pool and there is nothing for a side change to reinterpret.
            cfg.whitelistPeriod = whitelistPeriod;
            cfg.projectTokenIsCurrency1 = projectTokenIsCurrency1;
            cfg.maxBuyPerOrigin = maxBuyPerOrigin;
            cfg.launchTimestamp = uint48(block.timestamp);
        } else {
            // Launch parameters stay tunable for the remainder of the launch block, exactly
            // as before — they carry no cross-currency meaning, so correcting them is safe.
            if (block.timestamp <= cfg.launchTimestamp) {
                cfg.whitelistPeriod = whitelistPeriod;
                cfg.maxBuyPerOrigin = maxBuyPerOrigin;
            }
            // F-03: the project-token side is stored implicitly and pending fee amounts are
            // scalar (they do not record their currency). Re-pointing the flag while any
            // obligation is outstanding would reinterpret one currency's amount as another,
            // stranding claims or cross-subsidising from the newly selected currency's
            // global ERC-6909 balance. Only permit a change once every obligation is zero.
            if (projectTokenIsCurrency1 != cfg.projectTokenIsCurrency1) {
                if (
                    pf.totalFeeAmount != 0 || pf.adminFeeAmount != 0 || pf.referralFeeAmount != 0
                ) revert IBasedBidHook.ProjectTokenSideLocked();
                cfg.projectTokenIsCurrency1 = projectTokenIsCurrency1;
            }
        }

        // Emit current persisted values rather than the call arguments, so post-launch
        // calls (which only update projectTokenIsCurrency1) don't broadcast stale data.
        emit IBasedBidHook.PoolConfigured(
            id,
            cfg.poolOwner,
            cfg.launchTimestamp,
            cfg.whitelistPeriod,
            cfg.projectTokenIsCurrency1,
            cfg.maxBuyPerOrigin
        );
    }

    /// @dev Sets `feeKind`, writes the corresponding fee config (tiered / dynamic),
    ///      and applies the static fee BPS.  Emits all relevant events.
    function handleSetFeeConfig(
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.TieredFeeConfig storage tc,
        IBasedBidHook.DynamicFeeConfig storage dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.VolumeConfig storage vc,
        PoolId id,
        IBasedBidHook.FeeKind feeKind,
        IBasedBidHook.TieredFeeConfig calldata _tieredConfig,
        IBasedBidHook.DynamicFeeConfig calldata _dynamicConfig,
        IBasedBidHook.VolumeConfig calldata _volumeConfig,
        uint24 hookFeeBpsBuy,
        uint24 hookFeeBpsSell,
        bool isExternalFeeTrigger
    ) internal {
        cfg.feeKind = feeKind;
        cfg.isExternalFeeTrigger = isExternalFeeTrigger;
        emit IBasedBidHook.FeeKindUpdated(id, feeKind);
        if (feeKind == IBasedBidHook.FeeKind.TIERED) {
            validateAndSetTieredFeeConfig(tc, _tieredConfig);
            emit IBasedBidHook.TieredFeeConfigUpdated(id);
        } else if (feeKind == IBasedBidHook.FeeKind.DYNAMIC) {
            dc.minBaseFeeBpsBuy = _dynamicConfig.minBaseFeeBpsBuy;
            dc.minBaseFeeBpsSell = _dynamicConfig.minBaseFeeBpsSell;
            dc.maxBaseFeeBpsBuy = _dynamicConfig.maxBaseFeeBpsBuy;
            dc.maxBaseFeeBpsSell = _dynamicConfig.maxBaseFeeBpsSell;
            dc.baseFeeFactorBuy = _dynamicConfig.baseFeeFactorBuy;
            dc.baseFeeFactorSell = _dynamicConfig.baseFeeFactorSell;
            dc.defaultBaseFeeBpsBuy = _dynamicConfig.defaultBaseFeeBpsBuy;
            dc.defaultBaseFeeBpsSell = _dynamicConfig.defaultBaseFeeBpsSell;
            dc.surgeDecayPeriodSeconds = _dynamicConfig.surgeDecayPeriodSeconds;
            dc.surgeMultiplierPpm = _dynamicConfig.surgeMultiplierPpm;
            dc.perSwapMode = _dynamicConfig.perSwapMode;
            dc.capAutoTuneStepPpm = _dynamicConfig.capAutoTuneStepPpm;
            dc.capAutoTuneIntervalSeconds = _dynamicConfig.capAutoTuneIntervalSeconds;
            emit IBasedBidHook.DynamicFeeConfigUpdated(id);
            validateAndSetVolumeConfig(vc, _volumeConfig);
            emit IBasedBidHook.VolumeConfigUpdated(id);
        }
        applyHookFeeBps(cfg, dc, ds, id, hookFeeBpsBuy, hookFeeBpsSell);
    }

    /// @dev Validates the per-direction DEFAULT hook fee against the 10 % cap, persists
    ///      it, recalculates the dynamic defaults/factors (the DYNAMIC default base fee
    ///      tracks the hook fee), and emits `HookFeeBpsUpdated`. The pool (LP) fee is not
    ///      managed by the hook at all.
    function applyHookFeeBps(
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.DynamicFeeConfig storage dc,
        IBasedBidHook.DynamicFeeState storage ds,
        PoolId id,
        uint24 hookFeeBpsBuy,
        uint24 hookFeeBpsSell
    ) internal {
        if (hookFeeBpsBuy > MAX_DEFAULT_HOOK_FEE_BPS) revert IBasedBidHook.HookFeeTooLarge();
        if (hookFeeBpsSell > MAX_DEFAULT_HOOK_FEE_BPS) revert IBasedBidHook.HookFeeTooLarge();
        cfg.hookFeeBpsBuy = hookFeeBpsBuy;
        cfg.hookFeeBpsSell = hookFeeBpsSell;

        dc.defaultBaseFeeBpsBuy = hookFeeBpsBuy;
        dc.defaultBaseFeeBpsSell = hookFeeBpsSell;

        uint24 maxTicks = ds.maxTicksPerBlock;
        if (maxTicks != 0) {
            dc.baseFeeFactorBuy = uint32(uint256(dc.defaultBaseFeeBpsBuy) / maxTicks);
            dc.baseFeeFactorSell = uint32(uint256(dc.defaultBaseFeeBpsSell) / maxTicks);
        }

        emit IBasedBidHook.HookFeeBpsUpdated(id, hookFeeBpsBuy, hookFeeBpsSell);
    }

    // ═══════════════════ Initialization ═════════════════════

    function initializePool(
        mapping(PoolId => IBasedBidHook.PoolConfig) storage poolConfigs,
        mapping(PoolId => IBasedBidHook.DynamicFeeConfig) storage dynamicFeeConfigs,
        mapping(PoolId => IBasedBidHook.VolumeConfig) storage volumeConfigs,
        mapping(PoolId => IBasedBidHook.TieredFeeConfig) storage tieredFeeConfigs,
        mapping(PoolId => IBasedBidHook.DynamicFeeState) storage dynamicFeeStates,
        mapping(PoolId => IBasedBidHook.HookFeeDistributionConfig) storage hookFeeDistCfgs,
        PoolId id,
        address sender, int24 tick
    ) public {
        IBasedBidHook.PoolConfig storage cfg = poolConfigs[id];
        IBasedBidHook.DynamicFeeConfig storage dfc = dynamicFeeConfigs[id];
        IBasedBidHook.VolumeConfig storage vc = volumeConfigs[id];
        IBasedBidHook.TieredFeeConfig storage tc = tieredFeeConfigs[id];
        IBasedBidHook.DynamicFeeState storage ds = dynamicFeeStates[id];
        IBasedBidHook.HookFeeDistributionConfig storage hfdc = hookFeeDistCfgs[id];
        cfg.poolOwner = sender;
        // F-02: default internal conversion swaps to a 5 % spot-price slippage tolerance so a
        // pool that later enables buyback/reward conversions is protected out of the box.
        cfg.maxConversionSlippageBps = 500;
        ds.maxTicksPerBlock = 100;
        ds.lastCapFreqTs = uint48(block.timestamp);
        ds.blockInitialTick = tick;
        hfdc.liquidityFeeBps = 10000;
        cfg.hookFeeBpsBuy = 100;
        cfg.hookFeeBpsSell = 100;

        // Storage struct pointers cannot be assigned from memory literals; write fields explicitly.
        dfc.minBaseFeeBpsBuy = 10;
        dfc.minBaseFeeBpsSell = 10;
        dfc.maxBaseFeeBpsBuy = 300;
        dfc.maxBaseFeeBpsSell = 300;
        // Dynamic defaults mirror the 1 % default hook fee (pool fee is static and not
        // part of the dynamic engine); factor = defaultBaseFee / maxTicksPerBlock.
        dfc.baseFeeFactorBuy = 1;
        dfc.baseFeeFactorSell = 1;
        dfc.defaultBaseFeeBpsBuy = 100;
        dfc.defaultBaseFeeBpsSell = 100;
        dfc.surgeDecayPeriodSeconds = 21600;
        dfc.surgeMultiplierPpm = 3_000_000;
        dfc.perSwapMode = true;
        dfc.capAutoTuneStepPpm = 20_000;
        dfc.capAutoTuneIntervalSeconds = 86400;

        vc.volumeIntervalSeconds = 86400;
        delete vc.volumeLevels;
        delete vc.volumeMultiplierBps;
        vc.volumeMultiplierBps.push(BPS);
        delete tc.buyFeesBps;
        delete tc.sellFeesBps;
        delete tc.buyFeeTierAmountLevels;
        delete tc.sellFeeTierAmountLevels;
        // Tier fees are ABSOLUTE hook-fee BPS; seed with the 1 % default hook fee.
        tc.buyFeesBps.push(100);
        tc.sellFeesBps.push(100);
    }

    // ═══════════════════ Helpers ═════════════════════

    /// @dev COR-008: emits the canonical project-fee event. The event itself is declared
    ///      in {IBasedBidHook} (which the hook implements) so it appears in the hook's
    ///      maintained ABI — a library-local event declaration never would.
    function emitProjectHookFee(PoolId poolId, address sender, uint128 amt) internal {
        emit IBasedBidHook.ProjectHookFee(PoolId.unwrap(poolId), sender, amt);
    }

    // ═══════════════════ Before-Swap Fee Computation ═════════════════

    /// @dev Computes the hook fee for the swap (STATIC rate, TIERED absolute tier fee, or
    ///      DYNAMIC engine output), applies the cooldown penalty, clamps the running total
    ///      to the 18 % `MAX_HOOK_FEE_BPS` cap at every step, and stores it in
    ///      `cfg.pendingHookFeeBps`. The pool (LP) fee is NOT managed by the hook.
    function computeBeforeSwapFee(
        IPoolManager poolManager,
        PoolKey memory key,
        SwapParams memory params,
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.DynamicFeeConfig storage dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.TieredFeeConfig storage tc,
        BeforeSwapFeeContext memory ctx
    ) internal {
        bool isBuy = cfg.projectTokenIsCurrency1 ? params.zeroForOne : !params.zeroForOne;
        uint24 activeHookFeeBps = isBuy ? cfg.hookFeeBpsBuy : cfg.hookFeeBpsSell;

        IBasedBidHook.FeeKind feeKind = cfg.feeKind;

        if (feeKind == IBasedBidHook.FeeKind.TIERED) {
            bool isExactInput = params.amountSpecified < 0;
            uint256 absAmount = isExactInput
                ? uint256(-params.amountSpecified)
                : uint256(params.amountSpecified);

            uint256 projectAmount;
            // Specified is the project token when (buy + exact-out) or (sell + exact-in).
            if (isBuy != isExactInput) {
                projectAmount = absAmount;
            } else {
                (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(ctx.poolId);
                if (cfg.projectTokenIsCurrency1) {
                    // Non-project is currency0 → project is currency1.
                    // amount1 ≈ amount0 × sqrtPriceX96² / 2¹⁹²
                    projectAmount = FullMath.mulDiv(
                        FullMath.mulDiv(absAmount, sqrtPriceX96, 1 << 96),
                        sqrtPriceX96,
                        1 << 96
                    );
                } else {
                    // Non-project is currency1 → project is currency0.
                    // amount0 ≈ amount1 × 2¹⁹² / sqrtPriceX96²
                    projectAmount = FullMath.mulDiv(
                        FullMath.mulDiv(absAmount, 1 << 96, sqrtPriceX96),
                        1 << 96,
                        sqrtPriceX96
                    );
                }
            }

            // Tier entries are the absolute hook fee for the resolved amount band.
            activeHookFeeBps = _getTieredFeeBps(tc, isBuy, projectAmount);
        } else if (feeKind == IBasedBidHook.FeeKind.DYNAMIC) {
            updateDynamicFeeState(dc, ds, cfg, ctx.currentTick, ctx.estimatedTickAfter, ctx.poolId);

            bool surgeSignMatches = (int256(ctx.estimatedTickAfter) > int256(ctx.currentTick))
                == ds.capTickDirectionPositive;

            // The dynamic engine drives the HOOK fee only; the pool fee stays static.
            (,, uint256 totalFee) = calcDynamicFees(dc, ds, surgeSignMatches, ctx.volumeMultiplierBps, isBuy);
            activeHookFeeBps = uint24(totalFee);
        }
        // 18 % total-hook-fee cap on the engine output (TIERED/STATIC values are already
        // config-validated below it; DYNAMIC is capped in calcDynamicFees — this is a
        // cheap uniform backstop).
        if (activeHookFeeBps > MAX_HOOK_FEE_BPS) activeHookFeeBps = MAX_HOOK_FEE_BPS;
        // Cooldown penalty joins the total hook fee and is corrected down where it would
        // breach the 18 % cap.
        {
            uint32 cd = cfg.cooldownSeconds;
            uint24 penalty = cfg.penaltyFeeBps;
            if (cd != 0 && penalty != 0 && ctx.lastTradeTs != 0 && block.timestamp < ctx.lastTradeTs + cd) {
                uint256 withPenalty;
                unchecked { withPenalty = uint256(activeHookFeeBps) + penalty; }
                activeHookFeeBps =
                    withPenalty > MAX_HOOK_FEE_BPS ? MAX_HOOK_FEE_BPS : uint24(withPenalty);
            }
        }
        cfg.pendingHookFeeBps = activeHookFeeBps;
    }

    /// @dev Absolute hook fee (BPS) for the tier matching `amount`.
    function _getTieredFeeBps(
        IBasedBidHook.TieredFeeConfig storage tc, bool isBuy, uint256 amount
    ) internal view returns (uint16) {
        uint256[] storage levels = isBuy ? tc.buyFeeTierAmountLevels : tc.sellFeeTierAmountLevels;
        uint16[] storage bps = isBuy ? tc.buyFeesBps : tc.sellFeesBps;

        uint256 len = levels.length;
        for (uint256 i; i < len;) {
            if (amount < levels[i]) return bps[i];
            unchecked { ++i; }
        }
        return bps[len];
    }

    function validateAndSetTieredFeeConfig(
        IBasedBidHook.TieredFeeConfig storage tc,
        IBasedBidHook.TieredFeeConfig calldata newCfg
    ) internal {
        if (newCfg.buyFeeTierAmountLevels.length + 1 != newCfg.buyFeesBps.length) {
            revert IBasedBidHook.InvalidTieredFeeConfig();
        }
        if (newCfg.sellFeeTierAmountLevels.length + 1 != newCfg.sellFeesBps.length) {
            revert IBasedBidHook.InvalidTieredFeeConfig();
        }
        // Tier entries are ABSOLUTE hook fees. `[0]` is the side's DEFAULT hook fee and is
        // bounded by the 10 % cap; buy tiers strictly decrease from it (so every buy tier
        // is under the cap) and sell tiers strictly increase, bounded by the 18 %
        // total-hook-fee cap on their largest (= last) entry.
        if (newCfg.buyFeesBps[0] > MAX_DEFAULT_HOOK_FEE_BPS) revert IBasedBidHook.HookFeeTooLarge();
        if (newCfg.sellFeesBps[0] > MAX_DEFAULT_HOOK_FEE_BPS) revert IBasedBidHook.HookFeeTooLarge();
        if (newCfg.sellFeesBps[newCfg.sellFeesBps.length - 1] > MAX_HOOK_FEE_BPS) {
            revert IBasedBidHook.HookFeeTooLarge();
        }

        for (uint256 i = 1; i < newCfg.buyFeeTierAmountLevels.length;) {
            if (newCfg.buyFeeTierAmountLevels[i] <= newCfg.buyFeeTierAmountLevels[i - 1]) {
                revert IBasedBidHook.InvalidTieredFeeConfig();
            }
            unchecked { ++i; }
        }
        for (uint256 i = 1; i < newCfg.sellFeeTierAmountLevels.length;) {
            if (newCfg.sellFeeTierAmountLevels[i] <= newCfg.sellFeeTierAmountLevels[i - 1]) {
                revert IBasedBidHook.InvalidTieredFeeConfig();
            }
            unchecked { ++i; }
        }

        for (uint256 i = 1; i < newCfg.buyFeesBps.length;) {
            if (newCfg.buyFeesBps[i] >= newCfg.buyFeesBps[i - 1]) {
                revert IBasedBidHook.InvalidTieredFeeConfig();
            }
            unchecked { ++i; }
        }
        for (uint256 i = 1; i < newCfg.sellFeesBps.length;) {
            if (newCfg.sellFeesBps[i] <= newCfg.sellFeesBps[i - 1]) {
                revert IBasedBidHook.InvalidTieredFeeConfig();
            }
            unchecked { ++i; }
        }

        delete tc.buyFeesBps;
        delete tc.sellFeesBps;
        delete tc.buyFeeTierAmountLevels;
        delete tc.sellFeeTierAmountLevels;

        uint256 len = newCfg.buyFeesBps.length;
        for (uint256 i; i < len;) {
            tc.buyFeesBps.push(newCfg.buyFeesBps[i]);
            unchecked { ++i; }
        }
        len = newCfg.sellFeesBps.length;
        for (uint256 i; i < len;) {
            tc.sellFeesBps.push(newCfg.sellFeesBps[i]);
            unchecked { ++i; }
        }
        len = newCfg.buyFeeTierAmountLevels.length;
        for (uint256 i; i < len;) {
            tc.buyFeeTierAmountLevels.push(newCfg.buyFeeTierAmountLevels[i]);
            unchecked { ++i; }
        }
        len = newCfg.sellFeeTierAmountLevels.length;
        for (uint256 i; i < len;) {
            tc.sellFeeTierAmountLevels.push(newCfg.sellFeeTierAmountLevels[i]);
            unchecked { ++i; }
        }
    }


    // ═══════════════════ Validation & Computation ═════════════════

    // `validateAndSetDistribution` lives in `BasedBidHookViewLib` (EIP-170 headroom).

    /// @dev After-swap percentage fee on the non-project unspecified leg:
    ///      `unspecifiedAbs × (hookFeeBps + adminFeeBps) / 10_000`, where `hookFeeBps` is
    ///      the pending fee computed in beforeSwap (<= 18 %) and the admin fee comes from
    ///      the admin formula over the total hook fee.
    ///      Returns 0 when nothing is chargeable or the output is zero.
    function computePercentageFee(
        IBasedBidHook.PoolConfig storage cfg, uint256 unspecifiedAbs,
        IBasedBidHook.ResolvedAdminFeeParams memory adminParams
    ) internal view returns (uint256 percentageFeeAmount, uint24 totalFeeBps, uint24 totalAdminFeeBps) {
        uint24 hookFeeBps = cfg.pendingHookFeeBps;
        totalAdminFeeBps = calcAdminFeeBps(adminParams, hookFeeBps);
        totalFeeBps = hookFeeBps + totalAdminFeeBps; // <= 18 % + 2 % = 20 %
        if (totalFeeBps == 0 || unspecifiedAbs == 0) return (0, 0, 0);

        percentageFeeAmount = FullMath.mulDiv(unspecifiedAbs, totalFeeBps, BPS);
    }

    /// @dev Reverts with `BuyLimitExceeded` if `tx.origin` has exceeded the cumulative
    ///      buy limit during the whitelist period.
    ///      During the whitelist period:
    ///        - All users are capped at `maxBuyPerOrigin`.
    ///        - Whitelisted users (verified via merkle proof) are capped at
    ///          `maxBuyPerOriginForWhitelistedUser` instead.
    ///        - If `isWhitelistPool` is true, non-whitelisted users cannot buy at all
    ///          (effectively maxBuy = 0 for them unless `maxBuyPerOrigin` is set).
    ///      No-ops outside the whitelist window.
    function enforceWhitelistBuyLimit(
        IBasedBidHook.PoolConfig storage cfg,
        mapping(address => uint256) storage boughtForPool,
        BalanceDelta delta,
        bool isWhitelistedForTradeLimit
    ) internal {
        if (cfg.launchTimestamp == 0) revert IBasedBidHook.PoolNotInitialized();
        uint48 period = cfg.whitelistPeriod;
        if (period == 0) return;
        unchecked {
            if (block.timestamp > uint256(cfg.launchTimestamp) + uint256(period)) return;
        }

        bool isCurrency1 = cfg.projectTokenIsCurrency1;
        int128 projectTokenDelta = isCurrency1 ? delta.amount1() : delta.amount0();
        if (projectTokenDelta <= 0) return;

        uint256 bought = uint256(uint128(projectTokenDelta));
        uint256 prev = boughtForPool[tx.origin];
        uint256 newTotal = prev + bought;

        uint256 maxBuy = cfg.maxBuyPerOrigin;

        if (cfg.isWhitelistPool && isWhitelistedForTradeLimit)
            maxBuy = cfg.maxBuyPerOriginForWhitelistedUser;

        if (newTotal > maxBuy) revert IBasedBidHook.BuyLimitExceeded();
        boughtForPool[tx.origin] = newTotal;
    }

    // ═══════════════════ Distribution ═════════════════════

    /// @dev Executes a real swap, reads the resulting tick, then reverts.
    ///      Called via DELEGATECALL from the hook's thin `simulateSwapTick` wrapper.
    function simulateSwapTickBody(
        IPoolManager poolManager,
        PoolKey calldata key,
        SwapParams calldata params
    ) public {
        poolManager.swap(key, params, "");
        (, int24 tickAfter, , ) = poolManager.getSlot0(key.toId());
        revert IBasedBidHook.RevertWithTick(tickAfter);
    }

    /// @dev Simulates the swap via a self-call that always reverts.
    ///      Extracts the resulting tick from the custom `RevertWithTick` error.
    function simulateSwapTickAfter(
        PoolKey calldata key,
        SwapParams calldata params
    ) internal returns (int24 tickAfter) {
        try IBasedBidHook(address(this)).simulateSwapTick(key, params) {
            revert IBasedBidHook.UnexpectedSimulationRevert();
        } catch (bytes memory reason) {
            bytes4 sel;
            assembly ("memory-safe") {
                sel := mload(add(reason, 0x20))
                tickAfter := mload(add(reason, 0x24))
            }
            if (sel != IBasedBidHook.RevertWithTick.selector)
                revert IBasedBidHook.UnexpectedSimulationRevert();
        }
    }

    /// @dev Entry point for `_beforeSwap` fee logic.  For DYNAMIC pools, reads the
    ///      current tick and simulates the swap to estimate the post-swap tick.  Then
    ///      computes the fee and, when the unspecified leg is the project token
    ///      (exact-in buy OR exact-out sell), takes all fees from the non-project
    ///      token upfront via `takeAllFeesFromInput`.
    ///      `feeExempt` traders (`isBuilderFeeExempt`) pay NO hook fee: the fee-kind
    ///      engines and the penalty are skipped and `pendingHookFeeBps` is zeroed, but
    ///      the ADMIN fee — resolved from the whitelist parameter set — is still charged.
    function handleBeforeSwapFees(
        IPoolManager poolManager,
        IWETH weth,
        IBasedBidHook.AdminConfig storage adminCfg,
        bool feeExempt,
        PoolKey calldata key,
        SwapParams calldata params,
        address sender,
        PoolId poolId,
        IBasedBidHook.PoolConfig storage cfg,
        mapping(PoolId => IBasedBidHook.DynamicFeeConfig) storage dynamicFeeConfigs,
        mapping(PoolId => IBasedBidHook.DynamicFeeState) storage dynamicFeeStates,
        mapping(PoolId => IBasedBidHook.TieredFeeConfig) storage tieredFeeConfigs,
        mapping(PoolId => IBasedBidHook.HookFeeDistributionConfig) storage hookFeeDistCfgs,
        mapping(PoolId => IBasedBidHook.PendingFees) storage pendingFees,
        mapping(PoolId => IBasedBidHook.RWASwapConfig) storage rewardSwapCfgs,
        mapping(PoolId => IBasedBidHook.VolumeState) storage volumeStates,
        mapping(PoolId => mapping(address => uint256)) storage lastTradeTimestamps
    ) public returns (BeforeSwapDelta beforeDelta) {
        if (feeExempt) {
            cfg.pendingHookFeeBps = 0;
        } else {
            BeforeSwapFeeContext memory ctx;
            ctx.poolId = poolId;
            ctx.volumeMultiplierBps = volumeStates[poolId].activeVolumeMultiplierBps;
            // GAS: the timestamp is only consumed by the cooldown penalty, so skip the
            // cold mapping read entirely when no cooldown is configured.
            ctx.lastTradeTs = cfg.cooldownSeconds == 0 ? 0 : lastTradeTimestamps[poolId][tx.origin];
            if (cfg.feeKind == IBasedBidHook.FeeKind.DYNAMIC) {
                (, ctx.currentTick, , ) = poolManager.getSlot0(poolId);
                ctx.estimatedTickAfter = simulateSwapTickAfter(key, params);
            }

            computeBeforeSwapFee(
                poolManager,
                key,
                params,
                cfg,
                dynamicFeeConfigs[poolId],
                dynamicFeeStates[poolId],
                tieredFeeConfigs[poolId],
                ctx
            );
        }

        beforeDelta = BeforeSwapDeltaLibrary.ZERO_DELTA;

        bool unspecifiedIsProject = params.amountSpecified < 0 ? (params.zeroForOne ==
            cfg.projectTokenIsCurrency1) : (params.zeroForOne !=
                cfg.projectTokenIsCurrency1);
        if (unspecifiedIsProject) {
            beforeDelta = takeAllFeesFromInput(
                poolManager,
                weth,
                resolveAdminFeeParams(adminCfg, cfg.isExternalFeeTrigger, feeExempt),
                key,
                params,
                poolId,
                cfg,
                sender,
                hookFeeDistCfgs[poolId],
                pendingFees[poolId],
                rewardSwapCfgs[poolId]
            );
        }

    }

    /// @dev Entry point for `_afterSwap` fee logic.  Computes the percentage fee on
    ///      the unspecified output (if non-project), distributes it, enforces whitelist-period
    ///      buy limits, updates volume state, and records the trade timestamp.
    ///      A-3 note: fee-whitelisted traders reach this path with `pendingHookFeeBps == 0`
    ///      and whitelist admin params, so they pay ONLY the admin fee; every other
    ///      post-swap obligation (launch buy limit, volume accounting, cooldown clock)
    ///      still applies to them.
    function handleAfterSwapFees(
        IPoolManager poolManager,
        IWETH weth,
        IBasedBidHook.AdminConfig storage adminCfg,
        bool feeExempt,
        address hook,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        address sender,
        PoolId poolId,
        IBasedBidHook.PoolConfig storage cfg,
        mapping(PoolId => IBasedBidHook.HookFeeDistributionConfig) storage hookFeeDistCfgs,
        mapping(PoolId => IBasedBidHook.PendingFees) storage pendingFees,
        mapping(PoolId => IBasedBidHook.RWASwapConfig) storage rewardSwapCfgs,
        mapping(PoolId => mapping(address => uint256)) storage boughtPerOrigin,
        mapping(PoolId => IBasedBidHook.VolumeConfig) storage volumeConfigs,
        mapping(PoolId => IBasedBidHook.VolumeState) storage volumeStates,
        mapping(PoolId => mapping(address => uint256)) storage lastTradeTimestamp,
        bool isWhitelistedForTradeLimit
    ) public returns (uint256 totalFeeAmount) {
        (Currency unspecified, int128 unspecifiedAmount) = (params
            .amountSpecified <
            0 ==
            params.zeroForOne)
            ? (key.currency1, delta.amount1())
            : (key.currency0, delta.amount0());

        if (unspecifiedAmount < 0) unspecifiedAmount = -unspecifiedAmount;
        uint256 unspecifiedAbs = uint256(uint128(unspecifiedAmount));

        {
            Currency projectToken = cfg.projectTokenIsCurrency1
                ? key.currency1
                : key.currency0;

            if (!(unspecified == projectToken)) {
                IBasedBidHook.ResolvedAdminFeeParams memory adminParams =
                    resolveAdminFeeParams(adminCfg, cfg.isExternalFeeTrigger, feeExempt);
                (uint256 percentageFeeAmount, uint24 totalFeeBps, uint24 totalAdminFeeBps) = computePercentageFee(
                    cfg,
                    unspecifiedAbs,
                    adminParams
                );
                if (percentageFeeAmount != 0) {
                    unspecified.take(
                        poolManager,
                        hook,
                        uint128(percentageFeeAmount),
                        true
                    );
                    PoolKey memory keyMem = key;
                    distributeHookFeeNP(
                        poolManager,
                        weth,
                        totalFeeBps,
                        totalAdminFeeBps,
                        adminParams.treasury,
                        adminParams.referralShareBps,
                        keyMem,
                        percentageFeeAmount,
                        cfg,
                        hookFeeDistCfgs[poolId],
                        pendingFees[poolId],
                        rewardSwapCfgs[poolId]
                    );
                    emitProjectHookFee(
                        poolId,
                        sender,
                        uint128(percentageFeeAmount)
                    );
                    totalFeeAmount += percentageFeeAmount;
                }
            } else if (params.amountSpecified > 0) {
                // L-1: the unspecified leg is the project token, so this swap paid its whole
                // fee UPFRONT in `takeAllFeesFromInput`, sized from the REQUESTED exact-output
                // amount. V4 does not guarantee an exact-output swap fills: it stops at the
                // price limit. On a short fill the hook would still have taken the full fee out
                // of the specified leg, so the trader receives less than they asked for while
                // paying a fee computed on the larger requested amount — an effective rate far
                // above the 20 % cap. Exact-output means exact: require the pool to have
                // produced the requested amount PLUS the fee, else revert the whole swap (the
                // trader pays nothing) rather than silently overcharging them.
                uint24 hookFeeBps = cfg.pendingHookFeeBps;
                uint24 totalBps = hookFeeBps
                    + calcAdminFeeBps(
                        resolveAdminFeeParams(adminCfg, cfg.isExternalFeeTrigger, feeExempt), hookFeeBps
                    );
                uint256 requested = uint256(params.amountSpecified);
                uint256 required = requested + FullMath.mulDiv(requested, totalBps, BPS);
                // Specified leg = the currency that is not the unspecified one; for an
                // exact-output swap the pool credits it, so its delta is positive.
                int128 specifiedDelta =
                    unspecified == key.currency1 ? delta.amount0() : delta.amount1();
                if (specifiedDelta <= 0 || uint256(uint128(specifiedDelta)) < required) {
                    revert IBasedBidHook.ExactOutputNotFilled();
                }
            }
        }
        // The pending fee has now served its consumer (percentage fee OR the upfront
        // take in beforeSwap) — always reset.
        cfg.pendingHookFeeBps = 0;

        enforceWhitelistBuyLimit(
            cfg,
            boughtPerOrigin[poolId],
            delta,
            isWhitelistedForTradeLimit
        );
        if(cfg.feeKind == IBasedBidHook.FeeKind.DYNAMIC)
        {
            int128 projectDelta = cfg.projectTokenIsCurrency1
                ? delta.amount1()
                : delta.amount0();
            uint256 projectVolume = projectDelta >= 0
                ? uint256(uint128(projectDelta))
                : uint256(uint128(-projectDelta));
            updateVolumeState(volumeConfigs[poolId], volumeStates[poolId], projectVolume);
        }

        lastTradeTimestamp[poolId][tx.origin] = block.timestamp;

        return totalFeeAmount;
    }

    /**
     * @dev Takes the entire hook fee from the non-project token (the specified
     *      side of the swap when the unspecified side is the project token).
     *      Works for both exact-in buys (non-project is the input) and
     *      exact-out sells (non-project is the output).
     *      The admin fee comes from the admin formula over `pendingHookFeeBps`.
     *      Distributes directly (admin, liquidity donation, accumulate rest) and emits
     *      `ProjectHookFee`. `cfg.pendingHookFeeBps` is intentionally left set —
     *      `handleAfterSwapFees` always zeroes it at the end of the swap.
     */
    function takeAllFeesFromInput(
        IPoolManager poolManager,
        IWETH weth,
        IBasedBidHook.ResolvedAdminFeeParams memory adminParams,
        PoolKey calldata key,
        SwapParams calldata params,
        PoolId poolId,
        IBasedBidHook.PoolConfig storage cfg,
        address sender,
        IBasedBidHook.HookFeeDistributionConfig storage hookFeeDistributionConfig,
        IBasedBidHook.PendingFees storage pendingFees,
        IBasedBidHook.RWASwapConfig storage rewardSwapCfg
    ) internal returns (BeforeSwapDelta) {
        uint256 inputAbs = params.amountSpecified < 0 ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
        uint24 hookFeeBps = cfg.pendingHookFeeBps;
        uint24 totalAdminFeeBps = calcAdminFeeBps(adminParams, hookFeeBps);
        uint24 totalFeeBps = hookFeeBps + totalAdminFeeBps; // <= 18 % + 2 % = 20 %

        uint256 totalFee = FullMath.mulDiv(
            inputAbs,
            uint256(totalFeeBps),
            BPS
        );
        if (totalFee == 0) return BeforeSwapDeltaLibrary.ZERO_DELTA;

        Currency specified = cfg.projectTokenIsCurrency1 ? key.currency0 : key.currency1;
        specified.take(poolManager, address(this), totalFee, true);

        PoolKey memory keyMem = key;
        distributeHookFeeNP(
            poolManager,
            weth,
            totalFeeBps,
            totalAdminFeeBps,
            adminParams.treasury,
            adminParams.referralShareBps,
            keyMem,
            totalFee,
            cfg,
            hookFeeDistributionConfig,
            pendingFees,
            rewardSwapCfg
        );

        emitProjectHookFee(poolId, sender, uint128(totalFee));

        return toBeforeSwapDelta(int128(uint128(totalFee)), 0);
    }

    /**
     * @dev Splits `totalNP` (non-project ERC-6909 already credited to this hook) into
     *      admin → `pf.adminFeeAmount`, liquidity → donated, rest → `pf.totalFeeAmount`.
     *      Auto-distributes when `feeThreshold` is reached.
     */
    function distributeHookFeeNP(
        IPoolManager poolManager,
        IWETH weth,
        uint24 totalFeeBps,
        uint24 totalAdminFeeBps,
        address treasury_,
        uint16 referralShareBps,
        PoolKey memory key,
        uint256 totalNP,
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.HookFeeDistributionConfig storage feeCfgStorage,
        IBasedBidHook.PendingFees storage pf,
        IBasedBidHook.RWASwapConfig storage rewardSwapCfg
    ) internal {
        if (totalNP == 0) return;

        Currency nonProjectToken = poolCfg.projectTokenIsCurrency1 ? key.currency0 : key.currency1;

        uint256 hookFeeNP;
        {
            uint256 adminAmount;
            if (totalAdminFeeBps != 0 && treasury_ != address(0) && totalFeeBps != 0) {
                unchecked { adminAmount = totalNP * uint256(totalAdminFeeBps) / uint256(totalFeeBps); }
                // Referral split happens ONCE here, at accrual: the referral's cut of this
                // swap's admin fee goes to its own accumulator and is paid out on
                // `distributeFees` runs. Splitting later (on the accrued balance) would
                // re-tax amounts that survive several distributions.
                uint256 referralAmount;
                if (referralShareBps != 0 && poolCfg.referral != address(0)) {
                    unchecked { referralAmount = adminAmount * referralShareBps / BPS; }
                    if (referralAmount != 0) pf.referralFeeAmount += uint128(referralAmount);
                }
                pf.adminFeeAmount += uint128(adminAmount - referralAmount);
            }

            unchecked { hookFeeNP = totalNP - adminAmount; }
        }
        if (hookFeeNP == 0) return;

        {
            uint16 liquidityBps = feeCfgStorage.liquidityFeeBps;
            if (liquidityBps != 0) {
                uint256 toLiquidity;
                unchecked { toLiquidity = hookFeeNP * liquidityBps / BPS; }
                if (toLiquidity != 0 && poolManager.getLiquidity(key.toId()) != 0) {
                    unchecked { hookFeeNP -= toLiquidity; }
                    (uint256 a0, uint256 a1) = nonProjectToken == key.currency0
                        ? (toLiquidity, uint256(0))
                        : (uint256(0), toLiquidity);
                    poolManager.donate(key, a0, a1, "");
                    nonProjectToken.settle(poolManager, address(this), toLiquidity, true);
                    emit IBasedBidHook.LiquidityAdded(key.toId(), a0, a1);
                }
            }
        }
        if (hookFeeNP != 0) {
            pf.totalFeeAmount += hookFeeNP;
        }

        if (pf.feeThreshold != 0 && pf.totalFeeAmount >= pf.feeThreshold) {
            // M-1: this runs INSIDE a user's swap callback. A direct call would propagate any
            // distribution failure — a blacklisted recipient, a route whose price impact trips
            // the F-02 slippage guard, a broken hop — straight out of `_beforeSwap`/`_afterSwap`
            // and revert that user's swap. Worse, the condition is sticky: once pending sits at
            // or above the threshold EVERY swap re-attempts the same failing distribution, so
            // the pool stops trading entirely, permanently if the owner has already renounced.
            // Route it through an external self-call so it can be `try`ed: on failure the whole
            // distribution frame reverts atomically (pending stays accounted in its source
            // currency, exactly the COR-004 defer semantics) and the swap proceeds.
            // `address(this)` is the hook — this library executes via delegatecall.
            try IBasedBidHook(address(this)).selfDistributeFees(key) {}
            catch {
                emit IBasedBidHook.PendingFeeDistributionDeferred(key.toId(), pf.totalFeeAmount);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ═══ Distribution & conversion (absorbed from the former BasedBidHookDistLib)
    //
    //     Single-library consolidation: the hook links ONLY BasedBidHookLib now.
    //     This code still executes in the hook's context via delegatecall exactly
    //     as before. `distributeFees` / `distributeAdminFees` remain `public`
    //     (delegatecall entry points for the hook's unlockCallback); every other
    //     function here is `internal`, so it ships no external dispatcher / ABI
    //     decoder and intra-library calls are plain JUMPs (smaller + cheaper than
    //     the previous Lib -> DistLib delegatecall hop).
    // ═══════════════════════════════════════════════════════════════════════════

    /// @dev GAS (EIP-1153): transient slot accumulating non-project-token payouts that are
    ///      delivered during a distribution but burned with a SINGLE `settle` at the end —
    ///      one ERC-6909 burn for the whole distribution (reward share + every no-swap custom
    ///      wallet) instead of one per recipient. Written only inside `_distributeNonLiquidityFees`,
    ///      drained + settled by `distributeFees`. Reverts roll it back (transient storage is
    ///      revert-scoped) and the `distributing` lock forbids any nested distribution, so it
    ///      cannot leak across distributions.
    ///      = uint256(keccak256("basedbid.hook.npToSettle.v1")); inlined as a numeric literal
    ///      because inline assembly only accepts direct number constants for slot ids.
    uint256 private constant NP_TO_SETTLE_TSLOT =
        0xb6362c691754afdf8e75ca49d1eba0ee444b20b7bc22ba25c5cff7abdea307e3;

    function _accrueNpToSettle(uint256 amount) private {
        if (amount == 0) return;
        assembly ("memory-safe") {
            tstore(NP_TO_SETTLE_TSLOT, add(tload(NP_TO_SETTLE_TSLOT), amount))
        }
    }

    /// @dev Reads and clears the accumulator in one shot.
    function _drainNpToSettle() private returns (uint256 v) {
        assembly ("memory-safe") {
            v := tload(NP_TO_SETTLE_TSLOT)
            if v { tstore(NP_TO_SETTLE_TSLOT, 0) }
        }
    }

    /// @dev Performs an internal exact-input swap between `sourceToken` and `targetToken`
    ///      within `key`, settling the consumed input via ERC-6909 burn.
    /// @return outputAmount Target-token amount produced by the swap (0 on failure).
    /// @return unusedInput  Source-token portion of `amountIn` that was *not* consumed by
    ///                      the swap (e.g. when the price limit was hit early).  Remains
    ///                      as ERC-6909 on the hook; callers must re-credit it to their
    ///                      pending-fee accounting so the next distribution can retry.
    function swapToken(
        IPoolManager poolManager,
        PoolKey memory key, Currency sourceToken, Currency targetToken, uint256 amountIn,
        uint16 maxSlippageBps
    ) internal returns (uint256 outputAmount, uint256 unusedInput) {
        if (amountIn == 0) return (0, 0);
        // M-2: a same-currency "swap" used to return `(amountIn, 0)` — a phantom output that
        // was never settled, so the caller then minted or delivered claims the hook does not
        // own and the whole unlock failed later with `CurrencyNotSettled` (an opaque brick).
        // The only way to reach it is a malformed hop whose two currencies are equal, which
        // `_validateHopKey` now rejects at configuration time; fail loudly if one ever gets
        // here so the accounting invariant "every payout is settled or accrued" holds.
        if (sourceToken == targetToken) revert IBasedBidHook.InvalidRewardSwapConfig();
        bool zeroForOne = sourceToken == key.currency0 && targetToken == key.currency1;
        if (!zeroForOne && !(sourceToken == key.currency1 && targetToken == key.currency0)) {
            return (0, amountIn);
        }

        // F-02: capture the pre-swap spot price so the realised output can be bounded. The
        // guard is skipped when `maxSlippageBps >= BPS` (explicitly disabled). Note this
        // bounds price impact and execution price against the *current* pool price; it is not
        // a TWAP oracle and cannot by itself defeat a same-block front-run that first moves
        // spot — see the F-02 remediation notes for the oracle/private-orderflow follow-up.
        uint160 sqrtPriceBeforeX96;
        if (maxSlippageBps < BPS) {
            (sqrtPriceBeforeX96,,,) = poolManager.getSlot0(key.toId());
        }

        setSwapping(true);
        BalanceDelta swapDelta = poolManager.swap(
            key,
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
            }),
            ""
        );
        setSwapping(false);

        int128 inputDelta = zeroForOne ? swapDelta.amount0() : swapDelta.amount1();
        uint256 actualInput = uint256(uint128(inputDelta < 0 ? -inputDelta : inputDelta));
        // F-07: an exact-input swap must consume at most the requested `amountIn`. Guard the
        // subtraction explicitly instead of computing it in an `unchecked` block, where a
        // (malicious-hook-induced) `actualInput > amountIn` would wrap `unusedInput` to a
        // huge value and corrupt the deferred-fee accounting.
        if (actualInput > amountIn) revert IBasedBidHook.InvalidRewardSwapConfig();
        unusedInput = amountIn - actualInput;
        if (actualInput != 0) {
            sourceToken.settle(poolManager, address(this), actualInput, true);
        }

        int128 targetDelta = zeroForOne ? swapDelta.amount1() : swapDelta.amount0();
        if (targetDelta > 0) {
            unchecked { outputAmount = uint256(uint128(targetDelta)); }
        }

        // F-02: require the output to clear a minimum derived from the pre-swap spot price
        // and the configured slippage tolerance, applied to the input actually consumed.
        if (maxSlippageBps < BPS && actualInput != 0) {
            uint256 expectedOut = zeroForOne
                ? FullMath.mulDiv(FullMath.mulDiv(actualInput, sqrtPriceBeforeX96, 1 << 96), sqrtPriceBeforeX96, 1 << 96)
                : FullMath.mulDiv(FullMath.mulDiv(actualInput, 1 << 96, sqrtPriceBeforeX96), 1 << 96, sqrtPriceBeforeX96);
            uint256 minOut;
            unchecked { minOut = expectedOut * (BPS - maxSlippageBps) / BPS; }
            if (outputAmount < minOut) revert IBasedBidHook.InsufficientConversionOutput();
        }
    }
    /**
     * @dev Distributes accumulated non-liquidity fees (`pf.totalFeeAmount`) among
     *      buyback, reward, and custom wallets based on their BPS ratios.
     *      Fees are already held as non-project token ERC-6909.
     */
    function distributeFees(
        IPoolManager poolManager, IWETH weth,
        PoolKey memory key,
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.HookFeeDistributionConfig storage feeCfg,
        IBasedBidHook.PendingFees storage pf,
        IBasedBidHook.RWASwapConfig storage rewardSwapCfg
    ) public {
        if (isDistributing()) return;
        setDistributing(true);

        // Referral payout rides on FEE distribution (not on the admin treasury sweep):
        // the amount was already split off the admin fee at ACCRUAL time (once per swap,
        // in `distributeHookFeeNP`) into `pf.referralFeeAmount`; here it is only paid out.
        _payReferralShare(poolManager, weth, key, poolCfg, pf);

        uint256 amount = pf.totalFeeAmount;
        if (amount == 0) {
            setDistributing(false);
            return;
        }

        Currency nonProjectToken =
            poolCfg.projectTokenIsCurrency1 ? key.currency0 : key.currency1;

        uint16 nonLiqBps;
        unchecked { nonLiqBps = BPS - feeCfg.liquidityFeeBps; }
        // 100 % LP split: any queued residue (accumulated when the pool had no liquidity)
        // can only be donated. Try to donate now; otherwise leave the accounting intact
        // so it remains claimable once the pool has active liquidity.
        if (nonLiqBps == 0) {
            if (poolManager.getLiquidity(key.toId()) != 0) {
                (uint256 a0, uint256 a1) = nonProjectToken == key.currency0
                    ? (amount, uint256(0))
                    : (uint256(0), amount);
                poolManager.donate(key, a0, a1, "");
                nonProjectToken.settle(poolManager, address(this), amount, true);
                pf.totalFeeAmount = 0;
                emit IBasedBidHook.LiquidityAdded(key.toId(), a0, a1);
            }
            setDistributing(false);
            return;
        }
        pf.totalFeeAmount = 0;

        uint256 deferred = _distributeNonLiquidityFees(
            poolManager, weth, key, poolCfg, feeCfg, rewardSwapCfg, nonProjectToken, amount, nonLiqBps
        );

        // GAS: one ERC-6909 burn for every non-project payout delivered above (reward share +
        // each no-swap custom wallet), instead of a separate `settle` per recipient. The
        // accumulator is transient (drained here) and delta-equivalent: each delivery took
        // (−delta); this single settle burns/credits (+delta) the same total within the unlock.
        uint256 npToSettle = _drainNpToSettle();
        if (npToSettle != 0) {
            nonProjectToken.settle(poolManager, address(this), npToSettle, true);
        }

        // C-01: additive reconciliation. Any fresh fees accrued into `pf.totalFeeAmount`
        // during the external reward/custom-wallet callbacks (a reentrant swap) must not be
        // clobbered by the leftover `deferred` — accumulate instead of overwrite so no
        // hook-owned ERC-6909 credit is orphaned from per-pool accounting.
        if (deferred != 0) pf.totalFeeAmount += deferred;
        setDistributing(false);
    }

    /// @dev Split out of `distributeFees` to keep via-IR stack depth bounded.
    ///      `internal` since the consolidation: only `distributeFees` calls it.
    function _distributeNonLiquidityFees(
        IPoolManager poolManager,
        IWETH weth,
        PoolKey memory key,
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.HookFeeDistributionConfig storage feeCfg,
        IBasedBidHook.RWASwapConfig storage rewardSwapCfg,
        Currency nonProjectToken,
        uint256 amount,
        uint16 nonLiqBps
    ) internal returns (uint256 deferred) {
        uint16 rewardBps = feeCfg.rewardFeeBps;
        address dividendTracker;
        bool rewardUsable;
        if (rewardBps > 0) {
            Currency projectToken =
                poolCfg.projectTokenIsCurrency1 ? key.currency1 : key.currency0;
            // Tolerate tokens that don't implement IDividendTracker so a
            // misconfiguration cannot indefinitely brick fee distribution.
            try IDividendTracker(Currency.unwrap(projectToken)).dividendTracker() returns (address dt) {
                dividendTracker = dt;
            } catch {
                dividendTracker = address(0);
            }
            if (dividendTracker != address(0)) {
                // Distributing to a zero-supply tracker would divide by zero, so
                // only treat it as usable once it has holders.
                try IERC20(dividendTracker).totalSupply() returns (uint256 supply) {
                    rewardUsable = supply != 0;
                } catch {
                    rewardUsable = false;
                }
            }
        }

        uint256 taken;
        {
            uint16 buybackBps = feeCfg.buybackFeeBps;
            if (buybackBps != 0) {
                uint256 buybackAmt;
                unchecked {
                    buybackAmt = amount * buybackBps / nonLiqBps;
                    taken = buybackAmt;
                }
                if (buybackAmt != 0) {
                    deferred = _executeBuyback(poolManager, key, poolCfg, nonProjectToken, buybackAmt);
                }
            }
        }

        if (rewardBps != 0) {
            uint256 rewardAmt;
            unchecked {
                rewardAmt = amount * rewardBps / nonLiqBps;
                taken += rewardAmt;
            }
            if (rewardAmt != 0) {
                if (rewardUsable) {
                    deferred += _distributeRWA(
                        poolManager, weth, key, rewardSwapCfg, nonProjectToken, rewardAmt,
                        dividendTracker, true, poolCfg.maxConversionSlippageBps
                    );
                } else {
                    // Tracker missing or has no holders yet: defer this reward share.
                    // It stays as ERC-6909 credit on the hook and is re-accumulated into
                    // pending fees, so it retries on the next distribution instead of being
                    // stranded (no recipient) or silently rerouted to other recipients.
                    deferred += rewardAmt;
                }
            }
        }

        deferred += _payCustomWalletFees(
            poolManager, weth, key, feeCfg, nonProjectToken, amount, taken, nonLiqBps,
            poolCfg.maxConversionSlippageBps
        );

        // C-06: when there are no custom wallets, the last-wallet branch that normally absorbs
        // the floor-division remainder never runs, leaving buyback+reward dust (`amount - taken`)
        // as untracked ERC-6909 credit. Defer it so it re-accumulates into pending fees next round
        // instead of being orphaned. (With custom wallets the final wallet already takes the exact
        // remainder, so `taken == amount` and this is a no-op.)
        if (feeCfg.customWalletBps.length == 0 && amount > taken) {
            unchecked { deferred += amount - taken; }
        }
    }

    /// @dev Pays each custom wallet its share through the wallet's own `RWASwapConfig`
    ///      when `feeCfg.customWalletSwapConfigs` is set — the exact same mechanism as the
    ///      reward share (method, rotating cursor, percents, multiple multi-hop paths), so
    ///      one wallet can receive several tokens. Unswappable shares are deferred (returned).
    function _payCustomWalletFees(
        IPoolManager poolManager,
        IWETH weth,
        PoolKey memory key,
        IBasedBidHook.HookFeeDistributionConfig storage feeCfg,
        Currency nonProjectToken,
        uint256 amount,
        uint256 taken,
        uint16 nonLiqBps,
        uint16 maxSlippageBps
    ) internal returns (uint256 deferred) {
        uint256 len = feeCfg.customWalletBps.length;
        bool hasCfgs = feeCfg.customWalletSwapConfigs.length == len && len != 0;
        for (uint256 i; i < len;) {
            uint256 share;
            address wallet = feeCfg.customWallets[i];
            if (i == len - 1) {
                share = amount - taken;
            } else {
                unchecked {
                    share = amount * feeCfg.customWalletBps[i] / nonLiqBps;
                    taken += share;
                }
            }
            if (share != 0) {
                if (hasCfgs) {
                    deferred += _distributeRWA(
                        poolManager, weth, key, feeCfg.customWalletSwapConfigs[i],
                        nonProjectToken, share, wallet, false, maxSlippageBps
                    );
                } else {
                    // GAS: deliver now; burn the ERC-6909 for the whole distribution (reward +
                    // every no-swap wallet) in a single `settle` in `distributeFees`.
                    _deliverTokens(poolManager, weth, key.toId(), nonProjectToken, wallet, share, false);
                    _accrueNpToSettle(share);
                }
            }
            unchecked { ++i; }
        }
    }

    function _executeBuyback(
        IPoolManager poolManager,
        PoolKey memory key, IBasedBidHook.PoolConfig storage poolCfg,
        Currency nonProjectToken, uint256 amount
    ) internal returns (uint256 unusedInput) {
        Currency projectToken = poolCfg.projectTokenIsCurrency1 ? key.currency1 : key.currency0;
        uint256 converted;
        (converted, unusedInput) = swapToken(
            poolManager, key, nonProjectToken, projectToken, amount, poolCfg.maxConversionSlippageBps
        );
        if (converted != 0) {
            poolManager.take(projectToken, DEAD_ADDRESS, converted);
            // Report the input actually spent on the swap, not the requested amount,
            // so off-chain consumers see the true buyback ratio when a partial fill occurs.
            emit IBasedBidHook.Buyback(key.toId(), converted, amount - unusedInput);
        }
    }

    /// @dev Distributes `amount` of the non-project token through an `RWASwapConfig` —
    ///      shared by the reward share (recipient = dividend tracker, `notifyTracker`)
    ///      and each custom wallet (recipient = wallet, no notify).
    function _distributeRWA(
        IPoolManager poolManager, IWETH weth,
        PoolKey memory key, IBasedBidHook.RWASwapConfig storage cfg,
        Currency nonProjectToken, uint256 amount, address recipient, bool notifyTracker,
        uint16 maxSlippageBps
    ) internal returns (uint256 unusedInput) {
        uint256 n = cfg.paths.length;
        if (n == 0) {
            if (amount != 0) {
                // GAS: deliver now; the ERC-6909 burn is batched into one `settle` for the
                // whole distribution (reward + every no-swap wallet) in `distributeFees`.
                _deliverTokens(poolManager, weth, key.toId(), nonProjectToken, recipient, amount, notifyTracker);
                _accrueNpToSettle(amount);
            }
            return 0;
        }

        if (!cfg.isSwapAll) {
            uint256 idx = cfg.swapForRewardNo;
            unusedInput = _swapPathAndDeliver(
                poolManager, weth, key, cfg.paths[idx].hops,
                nonProjectToken, amount, recipient, notifyTracker, maxSlippageBps
            );
        } else {
            // isSwapAll: split the amount across every configured path.
            uint256 taken;
            for (uint256 i; i < n;) {
                uint256 share;
                if (i == n - 1) {
                    share = amount - taken;
                } else {
                    unchecked {
                        share = amount * uint256(cfg.RWAPercentsBps[i]) / BPS;
                        taken += share;
                    }
                }
                if (share != 0) {
                    unusedInput += _swapPathAndDeliver(
                        poolManager, weth, key, cfg.paths[i].hops,
                        nonProjectToken, share, recipient, notifyTracker, maxSlippageBps
                    );
                }
                unchecked { ++i; }
            }
        }

        // Rotate the one-by-one cursor (kept in sync while `isSwapAll` so a mode change is seamless).
        unchecked {
            uint256 next = uint256(cfg.swapForRewardNo) + 1;
            cfg.swapForRewardNo = next >= n ? 0 : uint8(next);
        }
    }

    /// @dev Multi-hop swap along `hops`, then deliver the final token to `recipient`
    ///      (dividend tracker + notify when `notifyTracker`, plain custom-wallet payout
    ///      otherwise). Intermediate outputs are taken as ERC-6909 so the next hop can
    ///      settle them.
    /// @dev Route semantics:
    ///      - EMPTY `hops`  → no conversion at all; `startToken` (the pool's non-project
    ///        token) is settled and delivered to `recipient` as-is.
    ///      - `[key]`, i.e. a single hop that is the fee-originating pool itself → a REAL
    ///        swap in that pool: the non-project share is converted to the project token
    ///        and the project token is delivered. There is no "no-op" hop shape; every
    ///        entry in `hops` is executed, so no configured swap can be silently skipped
    ///        (this subsumes the F-07 look-alike-pool concern).
    /// @dev H-1 guard, shared by the execution path and by route configuration so a bad
    ///      route is rejected when it is set rather than silently deferring forever.
    ///      A hop served by THIS hook is only legal when it *is* the fee-originating pool;
    ///      see the call site in `_swapPathAndDeliver` for why.
    function _requireHopNotForeignSelfHooked(PoolKey memory hop, PoolId originId) internal view {
        if (
            address(hop.hooks) == address(this)
                && PoolId.unwrap(hop.toId()) != PoolId.unwrap(originId)
        ) revert IBasedBidHook.ForeignSelfHookedRoute();
    }

    function _swapPathAndDeliver(
        IPoolManager poolManager, IWETH weth,
        PoolKey memory key, PoolKey[] storage hops,
        Currency startToken, uint256 amountIn, address recipient, bool notifyTracker,
        uint16 maxSlippageBps
    ) internal returns (uint256 unusedInput) {
        if (amountIn == 0) return 0;
        PoolId poolId = key.toId();
        uint256 hLen = hops.length;
        // An EMPTY hop list is the only "no conversion" shape: settle the input and deliver
        // the non-project token as-is. Every other shape — including a single hop that is
        // the fee-originating pool itself — is executed as a real swap by the loop below.
        if (hLen == 0) {
            startToken.settle(poolManager, address(this), amountIn, true);
            _deliverTokens(poolManager, weth, poolId, startToken, recipient, amountIn, notifyTracker);
            return 0;
        }

        Currency current = startToken;
        uint256 amount = amountIn;
        for (uint256 i; i < hLen;) {
            PoolKey memory hop = hops[i];
            // H-1: the hook itself is `msg.sender` for these conversion swaps, and V4 skips
            // hook callbacks entirely in that case (`Hooks.beforeSwap`/`afterSwap` return
            // before dispatching when `msg.sender == address(self)`). A hop into a DIFFERENT
            // pool served by this hook would therefore execute there with no fee, no launch
            // buy limit, no whitelist gate and no cooldown — a permissionless bypass, since
            // anyone can initialise a pool on this hook, become its owner, and point a route
            // hop at someone else's pool. Routing through the fee-originating pool itself is
            // still allowed (the buyback needs exactly that), as is any pool NOT served by
            // this hook (there our callbacks are irrelevant and nothing is bypassed).
            _requireHopNotForeignSelfHooked(hop, poolId);
            if (!(current == hop.currency0 || current == hop.currency1)) {
                // First hop still holds non-project ERC-6909 — defer it. Later hops would
                // leave intermediate inventory that pending-fee accounting cannot represent.
                if (i == 0) return amount;
                revert IBasedBidHook.InvalidRewardSwapConfig();
            }
            Currency next = current == hop.currency0 ? hop.currency1 : hop.currency0;
            uint256 out;
            uint256 unusedHop;
            (out, unusedHop) = swapToken(poolManager, hop, current, next, amount, maxSlippageBps);
            if (i == 0) {
                unusedInput = unusedHop;
            } else if (unusedHop != 0) {
                revert IBasedBidHook.InvalidRewardSwapConfig();
            }
            if (out == 0) return unusedInput;
            // Mint ERC-6909 for intermediate hops so the next settle(burn) succeeds.
            if (i + 1 < hLen) {
                next.take(poolManager, address(this), out, true);
            }
            current = next;
            amount = out;
            unchecked { ++i; }
        }

        _deliverTokens(poolManager, weth, poolId, current, recipient, amount, notifyTracker);
    }

    /// @dev Final delivery leg shared by the reward and custom-wallet fee mechanisms.
    ///      COR-002: native ETH is NEVER pushed to a recipient. A non-payable or reverting
    ///      receiver would revert `PoolManager.take` (before the notify try/catch), which
    ///      could revert the user swap that triggered an automatic distribution and make a
    ///      broken recipient configuration impossible to replace. Native amounts are taken
    ///      to the hook, wrapped into canonical WETH, and delivered as a plain ERC-20
    ///      transfer — an ERC-20 credit cannot be refused by the receiving account.
    function _deliverTokens(
        IPoolManager poolManager,
        IWETH weth,
        PoolId poolId,
        Currency token,
        address recipient,
        uint256 amount,
        bool notifyTracker
    ) internal {
        address tokenAddr = Currency.unwrap(token);
        if (token.isAddressZero()) {
            poolManager.take(token, address(this), amount);
            weth.deposit{value: amount}();
            tokenAddr = address(weth);
            IERC20(tokenAddr).safeTransfer(recipient, amount);
        } else {
            poolManager.take(token, recipient, amount);
        }
        if (notifyTracker) {
            emit IBasedBidHook.RewardDistributed(poolId, tokenAddr, amount);
            // F-04: the reward tokens are already delivered above. Isolate the tracker
            // notification in try/catch so a reverting, incompatible or malicious recipient
            // can only skip its own bookkeeping — it can never revert the in-progress
            // distribution or the user swap that triggered it.
            try IRewardDistributor(recipient).distributeRewardDividends(tokenAddr, amount) {}
            catch {
                emit IBasedBidHook.RewardNotificationFailed(poolId, recipient, tokenAddr, amount);
            }
        } else {
            emit IBasedBidHook.CustomWalletFeeDistributed(poolId, recipient, tokenAddr, amount);
        }
    }

    /// @dev Sends accumulated admin fees to the treasury, calling `ITreasury.sync`.
    ///      Runs in the hook's context (delegatecall); `address(this)` is the hook.
    /// @dev Pays out the accumulated referral share (`pf.referralFeeAmount`, split off
    ///      the admin fee at accrual time) to the pool's CURRENT referral. If the
    ///      referral was cleared since accrual, the amount is folded back into the admin
    ///      accrual so nothing is stranded. COR-002 delivery rule: native is wrapped and
    ///      sent as WETH. Runs at the start of every `distributeFees`.
    function _payReferralShare(
        IPoolManager poolManager,
        IWETH weth,
        PoolKey memory key,
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.PendingFees storage pf
    ) internal {
        uint256 referralAmount = pf.referralFeeAmount;
        if (referralAmount == 0) return;
        pf.referralFeeAmount = 0;
        address referral = poolCfg.referral;
        if (referral == address(0)) {
            pf.adminFeeAmount += uint128(referralAmount);
            return;
        }

        Currency nonProjectToken = poolCfg.projectTokenIsCurrency1 ? key.currency0 : key.currency1;
        nonProjectToken.settle(poolManager, address(this), referralAmount, true);
        address deliveredToken;
        if (nonProjectToken.isAddressZero()) {
            poolManager.take(nonProjectToken, address(this), referralAmount);
            weth.deposit{value: referralAmount}();
            IERC20(address(weth)).safeTransfer(referral, referralAmount);
            deliveredToken = address(weth);
        } else {
            poolManager.take(nonProjectToken, referral, referralAmount);
            deliveredToken = Currency.unwrap(nonProjectToken);
        }
        emit IBasedBidHook.ReferralFeePaid(key.toId(), referral, deliveredToken, referralAmount);
    }

    /// @dev Pays the remaining accrued admin fee to the treasury (COR-002: native is
    ///      wrapped and synced as WETH). The referral share is NOT split here — it is
    ///      deducted and delivered during `distributeFees` runs; this sweep takes
    ///      whatever admin amount remains at call time.
    function distributeAdminFees(
        IPoolManager poolManager,
        IWETH weth,
        PoolKey memory key,
        address treasury_,
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.PendingFees storage pf
    ) public {
        if (treasury_ == address(0)) return;

        uint256 amount = pf.adminFeeAmount;
        if (amount == 0) return;
        pf.adminFeeAmount = 0;

        // L-3: this sweep makes external calls (the ERC-20 transfer of the fee token and
        // `ITreasury.sync`) while holding no reentrancy lock. Without the flag the F-01
        // `notDuringDistribution` modifier and the COR-001 swap guards are both inert, so a
        // malicious fee token or treasury could reenter with a swap or a config write from
        // inside those callbacks. Hold the same lock `distributeFees` does, for the same
        // reason. Transient storage is revert-scoped, so a failed sweep clears it too.
        // Save/restore rather than unconditionally clearing: this is unreachable from inside
        // a distribution today (V4 would reject the nested `unlock`), but clearing an outer
        // lock we did not take would silently disarm it if that ever changed.
        bool wasDistributing = isDistributing();
        setDistributing(true);
        Currency nonProjectToken = poolCfg.projectTokenIsCurrency1 ? key.currency0 : key.currency1;
        nonProjectToken.settle(poolManager, address(this), amount, true);
        _depositToTreasury(poolManager, weth, nonProjectToken, treasury_, amount);
        setDistributing(wasDistributing);
    }

    /// @dev COR-002: the treasury follows the same no-native-push rule as every other
    ///      recipient — native admin fees are wrapped and synced as WETH.
    function _depositToTreasury(
        IPoolManager poolManager,
        IWETH weth,
        Currency token,
        address treasury_,
        uint256 amount
    ) internal {
        if (token.isAddressZero()) {
            poolManager.take(token, address(this), amount);
            weth.deposit{value: amount}();
            IERC20(address(weth)).safeTransfer(treasury_, amount);
            ITreasury(treasury_).sync(address(weth));
        } else {
            poolManager.take(token, treasury_, amount);
            ITreasury(treasury_).sync(Currency.unwrap(token));
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ═══ Config validation, quotes & encoders (absorbed from the former
    //     BasedBidHookViewLib — single-library consolidation)
    //
    //     Kept in the library (not the hook) because these bodies are large and
    //     cold-path: config writes and view quotes tolerate one delegatecall.
    //     The former ViewLib's SMALL pool-owner setters + `setAdminConfig` +
    //     `getFeeHardLimits` moved into the hook itself instead — they are tiny,
    //     and inlining them there removes a delegatecall per admin action.
    // ═══════════════════════════════════════════════════════════════════════════

    function encodeAdminConfig(IBasedBidHook.AdminConfig storage ac)
        public
        pure
        returns (bytes memory)
    {
        return abi.encode(ac);
    }

    /// @dev Full body of the hook's `batchSetPoolFeeAndDistributionConfig` (EIP-170
    ///      headroom). Executes in the hook's context via delegatecall, so the COR-004
    ///      `poolManager.unlock` pre-distribution still calls back into the hook.
    function batchSetPoolFeeAndDistributionConfig(
        IPoolManager poolManager,
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.HookFeeDistributionConfig storage dist,
        IBasedBidHook.PendingFees storage pf,
        IBasedBidHook.TieredFeeConfig storage tc,
        IBasedBidHook.DynamicFeeConfig storage dc,
        IBasedBidHook.DynamicFeeState storage ds,
        IBasedBidHook.VolumeConfig storage vc,
        PoolKey calldata key,
        IBasedBidHook.HookFeeDistributionConfig calldata hookFeeDistributionCfg,
        uint256 feeThreshold,
        IBasedBidHook.FeeKind feeKind,
        IBasedBidHook.TieredFeeConfig calldata tieredConfig,
        IBasedBidHook.DynamicFeeConfig calldata dynamicConfig,
        IBasedBidHook.VolumeConfig calldata _volumeConfig,
        uint24 hookFeeBpsBuy,
        uint24 hookFeeBpsSell,
        bool isExternalFeeTrigger
    ) internal {
        PoolId id = key.toId();
        if (pf.totalFeeAmount != 0) {
            // COR-004: settling pending fees under the OLD config must not be able to block
            // replacing that config. If the pre-distribution reverts (e.g. a broken conversion
            // route), the failed unlock rolls back atomically, so the pending amount stays
            // accounted in its source (non-project) currency; it is retried through the
            // replacement config on the next distribution.
            try poolManager.unlock(abi.encode(IBasedBidHook.CallbackAction.DISTRIBUTE_FEE, key)) {}
            catch {
                emit IBasedBidHook.PendingFeeDistributionDeferred(id, pf.totalFeeAmount);
            }
        }
        validateAndSetDistribution(dist, hookFeeDistributionCfg, id);
        emit IBasedBidHook.HookFeeDistributionConfigUpdated(id, hookFeeDistributionCfg);

        pf.feeThreshold = feeThreshold;

        handleSetFeeConfig(
            cfg,
            tc,
            dc,
            ds,
            vc,
            id,
            feeKind,
            tieredConfig,
            dynamicConfig,
            _volumeConfig,
            hookFeeBpsBuy,
            hookFeeBpsSell,
            isExternalFeeTrigger
        );
        emit IBasedBidHook.ExternalFeeTriggerRequired(id, isExternalFeeTrigger);
    }

    /// @dev Body of the hook's `renounceOwnershipOfPool`. `internal`: compiles into the
    ///      hook (see `batchSetPoolFeeAndDistributionConfig` note). Settles any
    ///      pending (non-admin) fees first — manual `distributeFee` dies with the owner
    ///      role — deferring on failure (COR-004 semantics) rather than blocking the
    ///      renounce, then drops the owner permanently.
    function renounceOwnershipOfPool(
        IPoolManager poolManager,
        IBasedBidHook.PoolConfig storage cfg,
        IBasedBidHook.PendingFees storage pf,
        PoolKey calldata key
    ) internal {
        PoolId id = key.toId();
        // Also drain a referral-only accrual: with e.g. a 100 % LP split the referral
        // accumulator can be non-zero while totalFeeAmount is zero, and after the owner
        // role is gone only the totalFeeAmount-keyed threshold trigger remains — the
        // referral share would be stranded forever.
        if (pf.totalFeeAmount != 0 || pf.referralFeeAmount != 0) {
            try poolManager.unlock(abi.encode(IBasedBidHook.CallbackAction.DISTRIBUTE_FEE, key)) {}
            catch {
                emit IBasedBidHook.PendingFeeDistributionDeferred(id, pf.totalFeeAmount);
            }
        }
        cfg.poolOwner = address(0);
        emit IBasedBidHook.PoolOwnerTransferred(id, address(0));
    }

    /**
     * @dev Quote the fee breakdown for a hypothetical swap (see IBasedBidHook.quoteSwapFees).
     *      The total mirrors the runtime pipeline: fee-kind engine → 18 % cap → + penalty
     *      → 18 % correction → admin formula over the corrected total. For DYNAMIC pools
     *      the surge is included whenever it is active (sign assumed to match — the
     *      conservative upper bound).
     *
     *      Reporting split: `builderFeeBps` is the mode's DEFAULT fee only — STATIC
     *      `hookFeeBps*`, TIERED `buyFeesBps[0]` / `sellFeesBps[0]`, DYNAMIC
     *      `defaultBaseFeeBps*` — and every increase over it (tiered/dynamic movement,
     *      cooldown penalty) is reported under `protectionFeeBps`.
     *      When the charged total falls BELOW the default (e.g. a cheaper large-buy
     *      tier), the builder is clamped down to the total so
     *      builder + protection + admin == total always holds.
     *      Takes the hook's whole mappings so the per-pool lookups happen here, keeping
     *      the hook wrapper minimal.
     */
    function quoteSwapFees(
        mapping(PoolId => IBasedBidHook.PoolConfig) storage poolConfig,
        mapping(PoolId => IBasedBidHook.DynamicFeeConfig) storage dynamicFeeConfig,
        mapping(PoolId => IBasedBidHook.DynamicFeeState) storage dynamicFeeState,
        mapping(PoolId => IBasedBidHook.TieredFeeConfig) storage tieredFeeConfig,
        mapping(PoolId => IBasedBidHook.VolumeState) storage volumeState,
        mapping(PoolId => mapping(address => IBasedBidHook.Whitelist)) storage isWhitelisted,
        mapping(PoolId => mapping(address => uint256)) storage lastTradeTimestamp,
        IBasedBidHook.AdminConfig storage adminCfg,
        PoolId id,
        bool isBuy,
        uint256 projectTokenAmount,
        address trader
    )
        internal
        view
        returns (uint24 builderFeeBps, uint24 protectionFeeBps, uint24 adminFeeBps, uint24 totalFeeBps)
    {
        IBasedBidHook.PoolConfig storage cfg = poolConfig[id];
        bool feeExempt = isWhitelisted[id][trader].isBuilderFeeExempt;
        uint24 maxHook = MAX_HOOK_FEE_BPS;
        uint256 hookFee;
        uint256 defaultFee;
        if (!feeExempt) {
            IBasedBidHook.FeeKind feeKind = cfg.feeKind;
            if (feeKind == IBasedBidHook.FeeKind.TIERED) {
                IBasedBidHook.TieredFeeConfig storage tc = tieredFeeConfig[id];
                hookFee = _getTieredFeeBps(tc, isBuy, projectTokenAmount);
                defaultFee = isBuy ? tc.buyFeesBps[0] : tc.sellFeesBps[0];
            } else if (feeKind == IBasedBidHook.FeeKind.DYNAMIC) {
                (,, hookFee) = calcDynamicFees(
                    dynamicFeeConfig[id],
                    dynamicFeeState[id],
                    true,
                    volumeState[id].activeVolumeMultiplierBps,
                    isBuy
                );
                defaultFee = isBuy
                    ? dynamicFeeConfig[id].defaultBaseFeeBpsBuy
                    : dynamicFeeConfig[id].defaultBaseFeeBpsSell;
            } else {
                hookFee = isBuy ? cfg.hookFeeBpsBuy : cfg.hookFeeBpsSell;
                defaultFee = hookFee;
            }
            if (hookFee > maxHook) hookFee = maxHook;

            // Cooldown penalty (skipped for fee-exempt traders, like at swap time).
            uint32 cd = cfg.cooldownSeconds;
            uint24 penalty = cfg.penaltyFeeBps;
            uint256 lastTradeTs = lastTradeTimestamp[id][trader];
            if (cd != 0 && penalty != 0 && lastTradeTs != 0 && block.timestamp < lastTradeTs + cd) {
                hookFee += penalty;
                if (hookFee > maxHook) hookFee = maxHook;
            }
        }

        builderFeeBps = uint24(defaultFee > hookFee ? hookFee : defaultFee);
        protectionFeeBps = uint24(hookFee) - builderFeeBps;

        adminFeeBps = calcAdminFeeBps(
            resolveAdminFeeParams(adminCfg, cfg.isExternalFeeTrigger, feeExempt),
            hookFee
        );
        totalFeeBps = uint24(hookFee) + adminFeeBps;
    }

    function encodePoolFullConfig(
        IBasedBidHook.PoolConfig storage poolCfg,
        IBasedBidHook.HookFeeDistributionConfig storage feeDist,
        IBasedBidHook.DynamicFeeConfig storage dynCfg,
        IBasedBidHook.DynamicFeeState storage dynState,
        IBasedBidHook.VolumeConfig storage volCfg,
        IBasedBidHook.VolumeState storage volState,
        IBasedBidHook.TieredFeeConfig storage tieredCfg,
        IBasedBidHook.PendingFees storage pf,
        IBasedBidHook.RWASwapConfig storage rewardSwapCfg
    ) public pure returns (bytes memory) {
        return abi.encode(poolCfg, feeDist, dynCfg, dynState, volCfg, volState, tieredCfg, pf, rewardSwapCfg);
    }

    /// @dev Verifies the distribution BPS sum to 10 000 and that all wallets/bps/labels are valid,
    ///      then persists the new config. `internal`: only `batchSetPoolFeeAndDistributionConfig`
    ///      (same library) calls it.
    function validateAndSetDistribution(
        IBasedBidHook.HookFeeDistributionConfig storage dist,
        IBasedBidHook.HookFeeDistributionConfig calldata _hookFeeDistributionConfig,
        PoolId originId
    ) internal {
        uint256 len = _hookFeeDistributionConfig.customWalletBps.length;
        if (_hookFeeDistributionConfig.customWallets.length != len) revert IBasedBidHook.InvalidFeeSplit();
        if (_hookFeeDistributionConfig.customWalletLabels.length != len) revert IBasedBidHook.InvalidFeeSplit();
        uint256 cfgsLen = _hookFeeDistributionConfig.customWalletSwapConfigs.length;
        // Either no swap configs at all (all wallets paid in the non-project token) or
        // one full RWASwapConfig per custom wallet.
        if (cfgsLen != 0 && cfgsLen != len) revert IBasedBidHook.InvalidFeeSplit();
        // F-01: accumulate every share in uint256 with checked arithmetic and bound each
        // component at 100 %.  A prior version summed into a uint16 inside an `unchecked`
        // block, so a total above 65 535 could wrap back to 10 000 and pass validation
        // while the real allocation was far above 100 %.
        if (_hookFeeDistributionConfig.liquidityFeeBps > BPS) revert IBasedBidHook.InvalidFeeSplit();
        if (_hookFeeDistributionConfig.buybackFeeBps > BPS) revert IBasedBidHook.InvalidFeeSplit();
        if (_hookFeeDistributionConfig.rewardFeeBps > BPS) revert IBasedBidHook.InvalidFeeSplit();
        uint256 total = uint256(_hookFeeDistributionConfig.liquidityFeeBps)
            + uint256(_hookFeeDistributionConfig.buybackFeeBps)
            + uint256(_hookFeeDistributionConfig.rewardFeeBps);
        for (uint256 i; i < len; ) {
            uint256 bps = _hookFeeDistributionConfig.customWalletBps[i];
            if (bps > BPS) revert IBasedBidHook.InvalidFeeSplit();
            total += bps; // checked add: cannot silently wrap
            unchecked { ++i; }
        }
        if (total != BPS) revert IBasedBidHook.InvalidFeeSplit();
        dist.liquidityFeeBps = _hookFeeDistributionConfig.liquidityFeeBps;
        dist.buybackFeeBps = _hookFeeDistributionConfig.buybackFeeBps;
        dist.rewardFeeBps = _hookFeeDistributionConfig.rewardFeeBps;

        delete dist.customWallets;
        delete dist.customWalletBps;
        delete dist.customWalletLabels;
        {
            uint256 oldCfgs = dist.customWalletSwapConfigs.length;
            for (uint256 i; i < oldCfgs; ) {
                _clearRWASwapConfig(dist.customWalletSwapConfigs[i]);
                unchecked { ++i; }
            }
            delete dist.customWalletSwapConfigs;
        }

        for (uint256 i; i < len; ) {
            if (_hookFeeDistributionConfig.customWallets[i] == address(0)) revert IBasedBidHook.InvalidFeeSplit();
            if (_hookFeeDistributionConfig.customWalletBps[i] == 0) revert IBasedBidHook.InvalidFeeSplit();
            dist.customWallets.push(_hookFeeDistributionConfig.customWallets[i]);
            dist.customWalletBps.push(_hookFeeDistributionConfig.customWalletBps[i]);
            dist.customWalletLabels.push(_hookFeeDistributionConfig.customWalletLabels[i]);
            unchecked { ++i; }
        }

        for (uint256 i; i < cfgsLen; ) {
            dist.customWalletSwapConfigs.push();
            _validateAndCopyRWASwapConfig(
                dist.customWalletSwapConfigs[i], _hookFeeDistributionConfig.customWalletSwapConfigs[i], originId
            );
            unchecked { ++i; }
        }
    }

    /// @dev Clears the dynamic members of a stored RWASwapConfig (nested arrays must be
    ///      emptied innermost-first).
    function _clearRWASwapConfig(IBasedBidHook.RWASwapConfig storage cfg) internal {
        uint256 n = cfg.paths.length;
        for (uint256 i; i < n; ) {
            delete cfg.paths[i].hops;
            unchecked { ++i; }
        }
        delete cfg.paths;
        delete cfg.RWAPercentsBps;
    }

    /// @dev Configuration-time hop validation (H-1 + M-2). Rejects, for every hop:
    ///        * a pool served by THIS hook that is not the fee-originating pool — those
    ///          swaps run with hook callbacks skipped by V4, so they would bypass the
    ///          target pool's fees and launch protections (see `_swapPathAndDeliver`);
    ///        * a malformed key whose currencies are equal or mis-ordered — no such V4
    ///          pool can exist, and the equal case used to produce a phantom, unsettled
    ///          conversion output.
    ///      Checking here (as well as at execution time) turns a bad route into an
    ///      immediate, explicit configuration error instead of a distribution that
    ///      silently defers forever.
    function _validateHopKey(PoolKey calldata hop, PoolId originId) internal view {
        if (hop.currency0 >= hop.currency1) revert IBasedBidHook.InvalidRewardSwapConfig();
        _requireHopNotForeignSelfHooked(hop, originId);
    }

    /// @dev Validates `src` with the exact same rules as `validateAndSetRWASwapConfig`
    ///      and copies it into `dst`. Used for the per-custom-wallet swap configs.
    function _validateAndCopyRWASwapConfig(
        IBasedBidHook.RWASwapConfig storage dst,
        IBasedBidHook.RWASwapConfig calldata src,
        PoolId originId
    ) internal {
        uint256 n = src.paths.length;
        // C-07: the rotating cursor `swapForRewardNo` is uint8, so paths at index >= 256 could
        // never be selected (and the rotation truncates). Cap the count so every route is reachable.
        if (n > 256) revert IBasedBidHook.InvalidRewardSwapConfig();
        dst.isSwapAll = src.isSwapAll;
        // The cursor is only READ in one-by-one mode, where it is bounds-checked below. In
        // swap-all mode an out-of-range value would sit in storage until the first rotation
        // fixed it, so normalise on write and keep `swapForRewardNo < paths.length` true at
        // rest for every stored config.
        dst.swapForRewardNo = (n != 0 && src.swapForRewardNo >= n) ? 0 : src.swapForRewardNo;

        if (!src.isSwapAll) {
            if (n != 0 && src.swapForRewardNo >= n) revert IBasedBidHook.InvalidRewardSwapConfig();
        } else {
            if (src.RWAPercentsBps.length != n) revert IBasedBidHook.InvalidRewardSwapConfig();
            uint256 sum;
            for (uint256 i; i < n;) {
                sum += src.RWAPercentsBps[i];
                unchecked { ++i; }
            }
            if (n != 0 && sum != BPS) revert IBasedBidHook.InvalidRewardSwapConfig();
        }

        for (uint256 i; i < n;) {
            PoolKey[] calldata hops = src.paths[i].hops;
            uint256 hLen = hops.length;
            // An EMPTY hop list is a valid route: it means "no conversion" — the share is
            // delivered in the pool's non-project token (see `_swapPathAndDeliver`).
            if (src.isSwapAll) {
                dst.RWAPercentsBps.push(src.RWAPercentsBps[i]);
            }
            dst.paths.push();
            for (uint256 j; j < hLen;) {
                _validateHopKey(hops[j], originId);
                dst.paths[i].hops.push(hops[j]);
                unchecked { ++j; }
            }
            unchecked { ++i; }
        }
    }

    /// @dev Validates and stores a multi-token / multi-hop RWA swap config (flat args,
    ///      used by `setRewardSwapConfig` for the reward share).
    function validateAndSetRWASwapConfig(
        IBasedBidHook.RWASwapConfig storage cfg,
        bool isSwapAll,
        uint8 swapForRewardNo,
        uint16[] calldata RWAPercentsBps,
        PoolKey[][] calldata paths,
        PoolId originId
    ) public {
        uint256 n = paths.length;
        // C-07: cap paths so the uint8 rotating cursor can reach every route (see above).
        if (n > 256) revert IBasedBidHook.InvalidRewardSwapConfig();
        _clearRWASwapConfig(cfg);

        cfg.isSwapAll = isSwapAll;
        // Normalised for the same reason as in `_validateAndCopyRWASwapConfig`.
        cfg.swapForRewardNo = (n != 0 && swapForRewardNo >= n) ? 0 : swapForRewardNo;

        if (!isSwapAll) {
            if (n != 0 && swapForRewardNo >= n) revert IBasedBidHook.InvalidRewardSwapConfig();
        } else {
            if (RWAPercentsBps.length != n) revert IBasedBidHook.InvalidRewardSwapConfig();
            uint256 sum;
            for (uint256 i; i < n;) {
                sum += RWAPercentsBps[i];
                unchecked { ++i; }
            }
            if (n != 0 && sum != BPS) revert IBasedBidHook.InvalidRewardSwapConfig();
        }

        for (uint256 i; i < n;) {
            PoolKey[] calldata hops = paths[i];
            // An EMPTY hop list is a valid route: it means "no conversion" — the share is
            // delivered in the pool's non-project token (see `_swapPathAndDeliver`).
            if (isSwapAll) {
                cfg.RWAPercentsBps.push(RWAPercentsBps[i]);
            }
            cfg.paths.push();
            uint256 hLen = hops.length;
            for (uint256 j; j < hLen;) {
                _validateHopKey(hops[j], originId);
                cfg.paths[i].hops.push(hops[j]);
                unchecked { ++j; }
            }
            unchecked { ++i; }
        }
    }
}

src/IBasedBidHook.sol

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

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

/// @notice Minimal WETH deposit interface for wrapping native ETH before transfer.
interface IWETH {
    function deposit() external payable;
}

/// @notice Callback interface on the dividend tracker to notify it of incoming reward dividends.
///         `token` is the ERC-20 actually transferred (WETH when the fee asset was native ETH).
interface IRewardDistributor {
    function distributeRewardDividends(address token, uint256 amount) external;
}

interface ITreasury {
    function sync(address token) external payable;
}

interface IDividendTracker {
    function dividendTracker() external view returns (address);
}

/**
 * @title IBasedBidHook
 * @notice Interface for the BasedBidHook Uniswap V4 hook contract.
 *
 *   Provides:
 *   - Hook fee collection and distribution (LP, buyback, reward, custom wallets)
 *   - dynamic fee engine (adaptive base + surge)
 *   - Cooldown penalty for rapid repeat trades
 *   - Whitelist-period buy limits (per-wallet whitelist flags with separate caps)
 */
interface IBasedBidHook {
    // ──────────────────────── Errors ────────────────────────

    /// @dev Hook fee exceeds the V4 maximum (100 % in hundredths-of-a-bip).
    error HookFeeTooLarge();
    /// @dev Distribution bps do not sum to 10 000 or array lengths mismatch.
    error InvalidFeeSplit();
    /// @dev Caller is not the pool owner.
    error NotPoolOwner();
    /// @dev Pool has not been initialised yet.
    error PoolNotInitialized();
    /// @dev Buy limit exceeded during the whitelist period.
    error BuyLimitExceeded();
    /// @dev Sentinel revert carrying the simulated post-swap tick.
    error RevertWithTick(int24 tick);
    /// @dev `simulateSwapTick` succeeded (should always revert) or returned unexpected selector.
    error UnexpectedSimulationRevert();
    /// @dev Attempted to set an address to zero where not allowed.
    error InvalidZeroAddress();
    /// @dev Volume config arrays have mismatched lengths or are not sorted ascending.
    error InvalidVolumeConfig();
    /// @dev Tiered fee config arrays have invalid lengths or are not sorted ascending.
    error InvalidTieredFeeConfig();
    /// @dev Reward-swap paths / percents / method are inconsistent.
    error InvalidRewardSwapConfig();
    /// @dev Fee/distribution configuration cannot be mutated while a distribution or
    ///      internal conversion swap is in progress (blocks callback reentrancy on the
    ///      configuration a live distribution depends on).
    error ConfigLockedDuringDistribution();
    /// @dev Internal conversion swap returned less than the caller-supplied minimum output
    ///      (spot-price slippage / sandwich protection).
    error InsufficientConversionOutput();
    /// @dev The project-token currency side is locked while the pool holds unsettled
    ///      (scalar) fee obligations; re-pointing it would reinterpret those amounts as the
    ///      other currency. Distribute all pending/admin fees to zero first.
    error ProjectTokenSideLocked();
    /// @dev COR-001: a swap NOT initiated by the hook itself arrived while a distribution
    ///      or internal conversion was executing. Processing it under the hook-wide
    ///      execution flags would waive its fees and launch protections (for ANY pool
    ///      served by this hook), so such nested swaps are rejected outright.
    error SwapBlockedDuringDistribution();
    /// @dev H-1: a reward/custom-wallet conversion route named a hop pool that is served by
    ///      THIS hook but is not the fee-originating pool. V4 skips hook callbacks when the
    ///      hook itself is the swap caller, so such a hop would trade in the target pool with
    ///      its fees, launch buy limit, whitelist gate and cooldown all bypassed.
    error ForeignSelfHookedRoute();
    /// @dev L-4: liquidity may not be added or removed while one of this hook's own
    ///      conversion swaps or a fee distribution is in flight (JIT sandwich guard).
    error LiquidityLockedDuringDistribution();
    /// @dev L-5: the contract owner may not be renounced — `distributeAdminFees` and
    ///      `updateAdminFee` are owner-only, so an ownerless hook would accrue admin fees
    ///      forever with no way to sweep them or to stop the accrual.
    error OwnershipCannotBeRenounced();
    /// @dev L-1: an exact-OUTPUT swap could not be filled in full once the hook fee was
    ///      added to the requested amount. The fee is sized from the requested output, so a
    ///      partial fill would charge the full fee against a short delivery.
    error ExactOutputNotFilled();
    /// @dev Admin fee configuration is invalid: `minAdminFeeBps` is not strictly below
    ///      the 2 % hard cap, a divisor (`bbb`) is zero, or the referral share exceeds
    ///      100 %.
    error InvalidAdminFeeConfig();

    // ──────────────────────── Enums ─────────────────────────

    /// @dev Discriminator for `unlockCallback` dispatch.
    enum CallbackAction { DISTRIBUTE_FEE, DISTRIBUTE_ADMIN_FEES }

    /// @dev Fee computation mode for a pool.
    enum FeeKind { STATIC, DYNAMIC, TIERED }

    // RWA swap behaviour is controlled by `RWASwapConfig.isSwapAll`:
    //   false → swap the full amount into a single path (`swapForRewardNo`, rotating);
    //   true  → split across every path by `RWAPercentsBps`.
    // `PoolConfig.isExternalFeeTrigger` (set via `setFeeThreshold`) substitutes
    // `AdminConfig.dddExternal` for `standardMath.ddd` in the admin-fee formula
    // (off-chain script triggers fee distribution).

    // ──────────────────────── Structs ───────────────────────

    /**
     * @dev Per-pool core configuration. The pool (LP) fee is NOT managed by the hook —
     *      pools carry whatever fee their PoolKey declares.
     *
     *  Slot 0 (28 B): poolOwner(20) + hookFeeBpsBuy(3) + hookFeeBpsSell(3) +
     *                  projectTokenIsCurrency1(1) + feeKind(1)
     *  Slot 1 (26 B): penaltyFeeBps(3) + launchTimestamp(6) + whitelistPeriod(6) +
     *                  pendingHookFeeBps(3) + lastAutoTuneTs(4) + cooldownSeconds(4)
     *  Slot 2 (32 B): maxBuyPerOrigin
     *  Slot 3 (24 B): isWhitelistPool(1) + isExternalFeeTrigger(1) +
     *                  maxConversionSlippageBps(2) + referral(20)
     *  Slot 4 (32 B): maxBuyPerOriginForWhitelistedUser
     */
    struct PoolConfig {
        address poolOwner;
        uint24 hookFeeBpsBuy;
        uint24 hookFeeBpsSell;
        bool projectTokenIsCurrency1;
        FeeKind feeKind;
        uint24 penaltyFeeBps;
        uint48 launchTimestamp;
        uint48 whitelistPeriod;
        uint24 pendingHookFeeBps;
        uint32 lastAutoTuneTs;
        uint32 cooldownSeconds;
        uint256 maxBuyPerOrigin;
        bool isWhitelistPool;
        /// @dev True → the admin-fee formula uses `AdminConfig.dddExternal` instead of
        ///      `standardMath.ddd` (off-chain script triggers fee distribution).
        ///      Set via `setFeeThreshold`.
        bool isExternalFeeTrigger;
        /// @dev F-02: maximum tolerated slippage (in BPS) for internal buyback/reward
        ///      conversion swaps, measured against the pool's pre-swap spot price. A
        ///      conversion whose output falls below `expectedSpotOut * (10000 - bps) / 10000`
        ///      reverts. `bps >= 10000` disables the guard (minimum output 0). Packs into the
        ///      same slot as the two bools above.
        uint16 maxConversionSlippageBps;
        /// @dev Pool-owner-set referral. When non-zero, `AdminConfig.referralShareBps` of
        ///      each swap's admin fee is split off at accrual into
        ///      `PendingFees.referralFeeAmount` and delivered to this address on
        ///      `distributeFees` runs (the treasury gets the remainder via
        ///      `distributeAdminFees`).
        address referral;
        uint256 maxBuyPerOriginForWhitelistedUser;
    }

    /**
     * @dev How the hook fee is split among recipients.
     *      Contains dynamic arrays so stored in its own mapping.
     *      All bps fields must sum to exactly 10 000 (100 %).
     */
    struct HookFeeDistributionConfig {
        uint16 liquidityFeeBps;
        uint16 buybackFeeBps;
        uint16 rewardFeeBps;
        address[] customWallets;
        uint16[] customWalletBps;
        /// @dev Human-readable label per custom wallet (same length as `customWallets`),
        ///      e.g. "marketing", "dev fund". Readable via `getPoolFullConfig` and emitted
        ///      in `HookFeeDistributionConfigUpdated`.
        string[] customWalletLabels;
        /// @dev Optional full swap config per custom wallet — the exact same mechanism as
        ///      the reward fee (`RWASwapConfig`): method, rotating cursor, percents and
        ///      multiple multi-hop paths, so one wallet can receive several tokens.
        ///      Either empty (all wallets are paid in the non-project token) or the same
        ///      length as `customWallets`. A config with no paths pays that wallet in the
        ///      non-project token. Shares that cannot be swapped are deferred back into
        ///      pending fees, exactly like the reward share.
        RWASwapConfig[] customWalletSwapConfigs;
    }

    /**
     * @dev dynamic-fee parameters.  Packed into 2 storage slots.
     *      baseFee  = clamp(maxTicksPerBlock × baseFeeFactor, min, max)
     *      surgeFee = baseFee × surgeMultiplierPpm / PPM × remaining / duration
     *
     *  Slot 0 (30 B): minBaseFeeBpsBuy(3) + minBaseFeeBpsSell(3) +
     *                  maxBaseFeeBpsBuy(3) + maxBaseFeeBpsSell(3) +
     *                  baseFeeFactorBuy(4) + baseFeeFactorSell(4) +
     *                  defaultBaseFeeBpsBuy(3) + defaultBaseFeeBpsSell(3) +
     *                  surgeDecayPeriodSeconds(4)
     *  Slot 1 (13 B): surgeMultiplierPpm(4) + perSwapMode(1) +
     *                  capAutoTuneStepPpm(4) + capAutoTuneIntervalSeconds(4)
     */
    struct DynamicFeeConfig {
        uint24 minBaseFeeBpsBuy;
        uint24 minBaseFeeBpsSell;
        uint24 maxBaseFeeBpsBuy;
        uint24 maxBaseFeeBpsSell;
        uint32 baseFeeFactorBuy;
        uint32 baseFeeFactorSell;
        uint24 defaultBaseFeeBpsBuy;
        uint24 defaultBaseFeeBpsSell;
        uint32 surgeDecayPeriodSeconds;
        uint32 surgeMultiplierPpm;
        bool perSwapMode;
        uint32 capAutoTuneStepPpm;
        uint32 capAutoTuneIntervalSeconds;
    }

    /**
     * @dev Per-pool surge / cap mutable state.  2 storage slots.
     *      Slot 0 (27 B): packed small fields.
     *      Slot 1 (16 B): block numbers as uint64.
     */
    struct DynamicFeeState {
        uint24 maxTicksPerBlock;
        uint40 capStartTime;
        bool inCap;
        bool capTickDirectionPositive;
        uint64 capFreq;
        uint48 lastCapFreqTs;
        int24 blockInitialTick;
        uint64 lastCapEventBlock;
        uint64 lastObservationBlock;
    }

    /**
     * @dev Volume-based fee multiplier configuration.
     *      `volumeMultiplierBps.length == volumeLevels.length + 1` (one multiplier per
     *      tier boundary, plus the default below the first level).
     *      `volumeLevels` must be sorted ascending.  Multipliers are in bps (10_000 = 1×).
     */
    struct VolumeConfig {
        uint32 volumeIntervalSeconds;
        uint256[] volumeLevels;
        uint16[] volumeMultiplierBps;
    }

    /**
     * @dev Per-pool volume tracking state.
     *      activeVolumeMultiplierBps caches the resolved multiplier from the last completed interval.
     */
    struct VolumeState {
        uint48 lastVolumeTs;
        uint256 volumeRecorded;
        uint16 activeVolumeMultiplierBps;
    }

    struct Whitelist {
        bool isWhitelistedForTradeLimit;
        bool isBuilderFeeExempt;
    }

    /**
     * @dev Tiered fee configuration.  Each entry is the ABSOLUTE hook fee in BPS for its
     *      tier (project-token amount bands), NOT a multiplier on another rate.
     *      `buyFeeTierAmountLevels` / `sellFeeTierAmountLevels` define boundaries.
     *      `buyFeesBps` / `sellFeesBps` have one extra element (the tier *below* the
     *      first level and the tier *above* the last level).
     *      `buyFeesBps[0]` / `sellFeesBps[0]` are the DEFAULT hook fee for their side and
     *      must not exceed the 10 % default-hook-fee cap; buy tiers decrease and sell
     *      tiers increase strictly, every tier bounded by the 18 % total-hook-fee cap.
     */
    struct TieredFeeConfig {
        uint16[] buyFeesBps;
        uint16[] sellFeesBps;
        uint256[] buyFeeTierAmountLevels;
        uint256[] sellFeeTierAmountLevels;
    }

    /**
     * @dev Accumulated fee amounts per pool.
     *      `totalFeeAmount` accumulates buyback + reward + custom-wallet shares
     *      (all in non-project token ERC-6909).  When it reaches `feeThreshold`
     *      the fees are auto-distributed.
     */
    struct PendingFees {
        /// @dev GAS: admin + referral accumulators share one slot (fee amounts are
        ///      int128-bounded by the pool manager, so uint128 cannot truncate; the
        ///      checked `+=` reverts long before an overflow could matter).
        uint128 adminFeeAmount;
        /// @dev Referral share split off the admin fee at ACCRUAL time (once per swap, in
        ///      `distributeHookFeeNP`) and paid out on `distributeFees` runs. Kept in its
        ///      own accumulator so repeated distributions can never re-tax the same
        ///      admin amount.
        uint128 referralFeeAmount;
        uint256 totalFeeAmount;
        uint256 feeThreshold;
    }

    /**
     * @dev One admin-fee formula parameter set. The admin fee (in BPS) charged on a swap is
     *
     *          min(max(minAdminFeeBps, calcFee(hookFeeBps)), MAX_ADMIN_FEE_BPS)
     *          calcFee(x) = (x * aaa / bbb) * ccc + ddd        (integer division)
     *
     *      where `hookFeeBps` is the total hook fee excluding the admin fee (base fee plus
     *      penalty). `bbb` must be non-zero. All parameters are contract-owner settable.
     */
    struct AdminFeeMathConfig {
        uint32 aaa;
        uint32 bbb;
        uint32 ccc;
        uint16 ddd;
    }

    /**
     * @dev Global admin-fee configuration.
     *      - `treasury == address(0)` disables the admin fee entirely (F-05).
     *      - `minAdminFeeBps` is the owner-settable floor; must be strictly below the
     *        2 % `MAX_ADMIN_FEE_BPS` hard cap.
     *      - `standardMath` prices regular swaps; pools with `isExternalFeeTrigger`
     *        substitute `dddExternal` for `standardMath.ddd`.
     *      - `whitelistMath` prices swaps by `isBuilderFeeExempt` traders, who pay no
     *        hook fee — only the admin fee derived from this set.
     *      - `referralShareBps` (<= 10 000): share of each swap's admin fee split off at
     *        accrual for the pool's `PoolConfig.referral` (when set), paid out on
     *        `distributeFees` runs.
     */
    struct AdminConfig {
        address treasury;
        uint16 minAdminFeeBps;
        uint16 dddExternal;
        uint16 referralShareBps;
        AdminFeeMathConfig standardMath;
        AdminFeeMathConfig whitelistMath;
    }

    /// @dev Admin-fee inputs fully resolved for one swap: the math set is already chosen
    ///      for the trader (standard vs whitelist) and `ddd` already substituted for
    ///      external-trigger pools. `treasury == address(0)` means "no admin fee".
    ///      Carries `referralShareBps` so the accrual-time referral split in
    ///      `distributeHookFeeNP` needs no extra admin-config read.
    struct ResolvedAdminFeeParams {
        address treasury;
        uint16 minAdminFeeBps;
        uint32 aaa;
        uint32 bbb;
        uint32 ccc;
        uint16 ddd;
        uint16 referralShareBps;
    }

    /// @dev One multi-hop route that ends in a reward token.
    ///      `hops[0]` must include the pool's non-project token; subsequent hops chain
    ///      intermediate tokens when no direct reward/non-project pool exists.
    ///      An EMPTY `hops` array is valid and means "no conversion": the share allocated
    ///      to this route is delivered as-is in the pool's non-project token.
    ///      A single hop equal to the pool's OWN key is a real swap in that pool: the share
    ///      is converted to the project token and the project token is delivered.
    struct RewardPath {
        PoolKey[] hops;
    }

    /**
     * @dev Per-pool reward conversion config.
     *      `paths.length` = number of reward tokens.
     *      When `isSwapAll` is true, `RWAPercentsBps.length == paths.length` and
     *      the percents must sum to 10_000.
     *      When `isSwapAll` is false, `swapForRewardNo` selects the path and is
     *      incremented after each reward distribution (wraps to 0 at `paths.length`).
     */
    struct RWASwapConfig {
        bool isSwapAll;
        uint8 swapForRewardNo;
        uint16[] RWAPercentsBps;
        RewardPath[] paths;
    }

    // ──────────────────────── Events ────────────────────────

    event ExternalFeeTriggerRequired(PoolId indexed poolId, bool isExternalFeeTrigger);

    /// @dev Emitted when a pool's initial config is set via `setInitialConfig`.
    event PoolConfigured(
        PoolId indexed poolId, address indexed poolOwner, uint48 launchTimestamp,
        uint48 whitelistPeriod, bool projectTokenIsCurrency1, uint256 maxBuyPerOrigin
    );

    /// @dev Emitted when the whitelist config is updated.
    event WhitelistConfigUpdated(
        PoolId indexed poolId, bool isWhitelistPool, 
        uint256 maxBuyPerOriginForWhitelistedUser
    );

    /// @dev Emitted when the hook-fee distribution split is updated.
    event HookFeeDistributionConfigUpdated(
        PoolId indexed poolId, HookFeeDistributionConfig hookFeeDistributionConfig
    );

    /// @dev Emitted when pool-admin rights are transferred.
    event PoolOwnerTransferred(PoolId indexed poolId, address indexed newOwner);

    /// @dev Emitted when the fee computation mode is changed.
    event FeeKindUpdated(PoolId indexed poolId, FeeKind feeKind);

    /// @dev Emitted when the tiered-fee config is updated.
    event TieredFeeConfigUpdated(PoolId indexed poolId);

    /// @dev Emitted when the dynamic-fee config is replaced.
    event DynamicFeeConfigUpdated(PoolId indexed poolId);

    /// @dev Emitted when the surge cap is entered or exited.
    event CapToggled(PoolId indexed poolId, bool inCap);

    /// @dev Emitted when the volume-based fee config is updated.
    event VolumeConfigUpdated(PoolId indexed poolId);

    /// @dev Emitted when the contract owner replaces the admin-fee configuration
    ///      (treasury, floor, referral share, and the formula parameter sets).
    event AdminFeeUpdated(
        address indexed treasury,
        uint16 minAdminFeeBps,
        AdminFeeMathConfig standardMath,
        uint16 dddExternal,
        AdminFeeMathConfig whitelistMath,
        uint16 referralShareBps
    );

    /// @dev Emitted when a pool owner sets or clears the pool's referral address.
    event ReferralUpdated(PoolId indexed poolId, address indexed referral);

    /// @dev Emitted when a referral share is delivered during admin-fee distribution.
    ///      `token` is the ERC-20 actually transferred (WETH when the fee asset was
    ///      native — COR-002 delivery rule).
    event ReferralFeePaid(
        PoolId indexed poolId, address indexed referral, address indexed token, uint256 amount
    );

    /// @dev Emitted when the per-direction hook fee bps are updated.
    event HookFeeBpsUpdated(PoolId indexed poolId, uint24 hookFeeBpsBuy, uint24 hookFeeBpsSell);

    /// @dev Emitted when a pool's internal-conversion slippage tolerance is updated (F-02).
    event ConversionSlippageUpdated(PoolId indexed poolId, uint16 maxConversionSlippageBps);

    /// @dev COR-004: the pre-replacement distribution of pending fees through the OLD
    ///      config failed and was rolled back. The pending amount remains accounted in its
    ///      source (non-project) currency and is retried through the replacement config.
    event PendingFeeDistributionDeferred(PoolId indexed poolId, uint256 amount);

    /// @dev COR-008: canonical project-fee event — the hook + admin fee taken on a swap,
    ///      denominated in the non-project currency.
    ///      Emitted from linked-library code, so it is declared here to appear in the
    ///      hook's canonical ABI. (Topic migration: replaces the previously undeclared
    ///      3-argument `HookFee(bytes32,address,uint128)` library event.)
    event ProjectHookFee(bytes32 indexed poolId, address indexed sender, uint128 feeAmount);


    event LiquidityAdded(PoolId indexed poolId, uint256 liquidity0, uint256 liquidity1);
    event Buyback(PoolId indexed poolId, uint256 projectTokenAmount, uint256 ETHAmount);
    event RewardDistributed(PoolId indexed poolId, address indexed token, uint256 amount);
    /// @dev The reward tokens were delivered but the tracker's `distributeRewardDividends`
    ///      notification reverted; distribution is not rolled back (F-04).
    event RewardNotificationFailed(
        PoolId indexed poolId, address indexed tracker, address indexed token, uint256 amount
    );
    event RewardSwapConfigUpdated(
        PoolId indexed poolId,
        bool isSwapAll,
        uint8 swapForRewardNo,
        uint16[] RWAPercentsBps,
        PoolKey[][] paths
    );
    event CustomWalletFeeDistributed(
        PoolId indexed poolId, address indexed wallet, address indexed token, uint256 amount
    );
    event WhitelistWalletsUpdated(PoolId indexed poolId, address[] wallets, Whitelist[] _isWhitelisted);

    // ──────────────────────── Admin Functions ────────────────

    /**
     * @notice One-shot setter for initial pool configuration.
     * @dev Only callable by the pool owner in the same block as pool initialization.
     */
    function setInitialConfig(
        PoolKey calldata key,
        uint48 whitelistPeriod,
        bool projectTokenIsCurrency1,
        uint256 maxBuyPerOrigin
    ) external;

    /// @notice Configure or update the whitelist settings for a pool.
    function setWhitelistConfig(
        PoolKey calldata key,
        bool isWhitelistPool,
        uint256 maxBuyPerOriginForWhitelistedUser
    ) external;

    /// @notice Pool owner: set whitelist flags for a batch of wallets.
    function updateWhitelistWallets(
        PoolKey calldata key,
        address[] calldata wallets,
        Whitelist[] calldata _isWhitelisted
    ) external;

    /**
     * @notice Set the fee-distribution threshold and whether this pool uses the external
     *         admin-fee DDD (`AdminConfig.dddExternal` via `PoolConfig.isExternalFeeTrigger`).
     */
    function setFeeThreshold(PoolKey calldata key, uint256 threshold, bool isExternalFeeTrigger) external;

    /**
     * @notice Configure multi-reward / multi-hop reward-swap paths for a pool.
     * @param isSwapAll false → one path per distribution (rotating cursor); true → split across all paths.
     * @param paths 2-D pool-key routes: `paths[rewardIndex]` is the ordered hop list for that reward.
     */
    function setRewardSwapConfig(
        PoolKey calldata key,
        bool isSwapAll,
        uint8 swapForRewardNo,
        uint16[] calldata RWAPercentsBps,
        PoolKey[][] calldata paths
    ) external;

    /**
     * @notice Pool owner: updates hook fee distribution, fee threshold, fee mode and rates
     *         (`handleSetFeeConfig`) in one transaction.
     *         If `pendingFees.totalFeeAmount != 0`, distributes under the prior config first.
     * @dev Reward-swap config is set separately via `setRewardSwapConfig` to keep this
     *      entry-point small.
     */
    function batchSetPoolFeeAndDistributionConfig(
        PoolKey calldata key,
        HookFeeDistributionConfig calldata hookFeeDistributionCfg,
        uint256 feeThreshold,
        FeeKind feeKind,
        TieredFeeConfig calldata tieredConfig,
        DynamicFeeConfig calldata dynamicConfig,
        VolumeConfig calldata _volumeConfig,
        uint24 hookFeeBpsBuy,
        uint24 hookFeeBpsSell,
        bool isExternalFeeTrigger
    ) external;

    /// @notice Configure the cooldown penalty: extra fee when the same origin trades within `cooldownSeconds`.
    function setCooldownConfig(PoolKey calldata key, uint32 cooldownSeconds, uint24 penaltyFeeBps) external;

    /// @notice Pool owner: set the maximum tolerated slippage (BPS) for internal buyback/reward
    ///         conversion swaps, measured against the pool's pre-swap spot price (F-02).
    /// @dev A value >= 10000 disables the guard (minimum output 0).
    function setConversionSlippage(PoolKey calldata key, uint16 maxConversionSlippageBps) external;

    /// @notice Transfer pool-admin rights to a new address.  Cannot be set to address(0).
    function transferOwnershipOfPool(PoolId id, address newOwner) external;

    /// @notice Pool owner: permanently renounce pool-admin rights.
    /// @dev Any pending (non-admin) fees are distributed first when possible — a failing
    ///      distribution is deferred (COR-004 semantics) rather than blocking the
    ///      renounce. Afterwards every pool-owner function reverts (`PoolNotInitialized`),
    ///      so manual `distributeFee` is gone; only a non-zero `feeThreshold` keeps
    ///      auto-distribution alive.
    function renounceOwnershipOfPool(PoolKey calldata key) external;

    /// @notice Pool owner: set (or clear with address(0)) the pool's referral address.
    ///         When set, `AdminConfig.referralShareBps` of the pool's admin fee is
    ///         delivered to it during admin-fee distribution.
    function setReferral(PoolKey calldata key, address referral) external;

    /// @notice Contract-owner-only: replace the admin-fee configuration.
    /// @dev `_minAdminFeeBps` must be strictly below the 2 % hard cap, both math sets
    ///      need a non-zero `bbb` divisor, and `_referralShareBps <= 10_000`.
    ///      `_treasury == address(0)` disables the admin fee.
    function updateAdminFee(
        address _treasury,
        uint16 _minAdminFeeBps,
        AdminFeeMathConfig calldata _standardMath,
        uint16 _dddExternal,
        AdminFeeMathConfig calldata _whitelistMath,
        uint16 _referralShareBps
    ) external;


    // ──────────────────── View / Pure Functions ──────────────

    /// @notice Returns pool-level configuration, state, pending fees and the reward
    ///         `RWASwapConfig` (method, cursor, percents and full multi-hop paths) in one call.
    function getPoolFullConfig(PoolId id) external view returns (
        PoolConfig memory,
        HookFeeDistributionConfig memory,
        DynamicFeeConfig memory,
        DynamicFeeState memory,
        VolumeConfig memory,
        VolumeState memory,
        TieredFeeConfig memory,
        PendingFees memory,
        RWASwapConfig memory
    );

    /// @notice Read the current dynamic-fee breakdown (base, surge, total) for a pool.
    function getDynamicFeeState(PoolId poolId, bool surgeSignMatches, bool isBuy)
        external view returns (uint256 baseFee, uint256 surgeFee, uint256 totalFee);

    /**
     * @notice Current fee hard limits.
     * @return defaultHookFeeCapBps Cap on each mode's DEFAULT hook fee (10 %): STATIC
     *         `hookFeeBpsBuy/Sell`, DYNAMIC `defaultBaseFeeBpsBuy/Sell`, TIERED
     *         `buyFeesBps[0]` / `sellFeesBps[0]`.
     * @return maxHookFeeBps Cap on the total hook fee excluding the admin fee (18 %),
     *         inclusive of the cooldown penalty — corrected down at its application
     *         step if it would breach it.
     * @return maxAdminFeeBps Hard cap on the admin fee (2 %).
     * @return maxTotalFeeBps Overall cap on hook + admin fee (20 %).
     * @return minAdminFeeBps Current owner-set admin-fee floor (< `maxAdminFeeBps`).
     */
    function getFeeHardLimits()
        external
        view
        returns (
            uint24 defaultHookFeeCapBps,
            uint24 maxHookFeeBps,
            uint24 maxAdminFeeBps,
            uint24 maxTotalFeeBps,
            uint16 minAdminFeeBps
        );

    /**
     * @notice Quote the fee breakdown, in BPS, for a hypothetical swap under the pool's
     *         current configuration and state.
     * @param id Pool to quote.
     * @param isBuy True for a buy (non-project → project token), false for a sell.
     * @param projectTokenAmount Project-token trade size used to resolve the TIERED tier
     *        (ignored by STATIC/DYNAMIC pools).
     * @param trader Wallet the quote is for — resolves the fee whitelist and the cooldown
     *        penalty; pass address(0) for a generic quote.
     * @return builderFeeBps The mode's DEFAULT hook fee only — STATIC `hookFeeBps*`,
     *         TIERED `buyFeesBps[0]`/`sellFeesBps[0]`, DYNAMIC `defaultBaseFeeBps*` —
     *         clamped down to the charged total when a cheaper tier applies; 0 for
     *         builder-fee-exempt traders.
     * @return protectionFeeBps Everything charged above the default: tiered/dynamic
     *         movement and the cooldown penalty, after the 18 % total-hook-fee correction.
     * @return adminFeeBps Admin fee derived from builder + protection via the admin formula.
     * @return totalFeeBps builder + protection + admin (bounded by the 20 % overall cap).
     */
    function quoteSwapFees(
        PoolId id,
        bool isBuy,
        uint256 projectTokenAmount,
        address trader
    )
        external
        view
        returns (uint24 builderFeeBps, uint24 protectionFeeBps, uint24 adminFeeBps, uint24 totalFeeBps);

    /// @notice Current admin-fee configuration (treasury, floor, and formula sets).
    function getAdminFeeConfig() external view returns (AdminConfig memory);

    // ──────────────────── Distribution Triggers ─────────────

    /// @notice Distribute accumulated non-liquidity fees (buyback, reward, custom wallets).
    function distributeFee(PoolKey calldata key) external;

    /// @notice Distribute accumulated admin fees to the treasury.  Callable by admin.
    function distributeAdminFees(PoolKey calldata key) external;

    // ──────────────────── Simulation ─────────────────────────

    /**
     * @notice Simulates a swap and reverts with the resulting tick.
     * @dev Only callable by this contract itself.  Always reverts with `RevertWithTick`.
     */
    function simulateSwapTick(PoolKey calldata key, SwapParams calldata params) external;

    /// @notice Self-only entry point used to run a threshold-triggered fee distribution in
    ///         its own call frame so the caller can `try` it (M-1).
    /// @dev Reverts unless `msg.sender == address(this)`.
    function selfDistributeFees(PoolKey calldata key) external;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/BasedBidHook.sol": {
      "BasedBidHookLib": "0x1bf2adfcad4c1200fc56dcf9e5c074fa0f36db7a"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
    "@uniswap/v4-core/=lib/uniswap-hooks/lib/v4-core/",
    "@openzeppelin/contracts/=lib/uniswap-hooks/lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-core/node_modules/@ensdomains/",
    "@uniswap/v4-periphery/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-periphery/",
    "ds-test/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=/root/V4Hook/Uniswap/lib/forge-std/src/",
    "halmos-cheatcodes/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/openzeppelin-contracts/",
    "permit2/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-periphery/lib/permit2/",
    "solmate/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-core/lib/solmate/",
    "uniswap-hooks/=/root/V4Hook/Uniswap/lib/uniswap-hooks/src/",
    "v4-core/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-core/src/",
    "v4-periphery/=/root/V4Hook/Uniswap/lib/uniswap-hooks/lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.