Skip to content
Verified contractExactUNLICENSED

PangeaGapRegistry

Address0x510e4af8136dcd18c794cdc4b7aba3af13c57c3a
Balance

0 ETH

 

Transactions

193

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

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

src/v3/gap/PangeaGapRegistry.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IPangeaGapRegistry} from "./IPangeaGapRegistry.sol";
import {IGapReader} from "./IGapReader.sol";
import {GapMath} from "./GapMath.sol";
import {GapPriceLog} from "./GapPriceLog.sol";
import {GapCoverLib} from "./GapCoverLib.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {
    DELIVERY_COST_MAX_WEI,
    DELIVERY_COST_MAX_BNB_WEI,
    SOLANA_PREPAY_RENT_PER_BYTE,
    SOLANA_PREPAY_RECEIPT_FIXED,
    SOLANA_PREPAY_MAX_COMPOSE,
    SOLANA_PREPAY_RETURN_GAS_MAX,
    PREPAY_COST_MAX_WEI,
    PREPAY_COST_MAX_BNB_WEI,
    PREPAY_COST_MAX_ETHEREUM_WEI
} from "./IGapDelivery.sol";

/// @title PangeaGapRegistry -- one per EVM chain: the gap fee's readers, stables, margin, USD routes
///        and official pools (docs/v3-gap-fee-spec.md §5, §7)
/// @notice Shared by every v3 token on the chain. Roles:
///         - owner (Ownable2Step): readers, stables, the fixed margin (AMENDMENT 6: default 0.1%, at
///           most 10%), the gas cover (units, basefee floor/cap, cover cap, cover window), quote
///           classes, per-token gap escapes, the V2 hop record age (12..86,400 s, default 30 s),
///           registrar, hook kinds, factories;
///         - registrar (our server key): a quote's USD route, replaced or cleared at any time, and
///           applied to live tokens at once;
///         - a listed factory: a token's official pool, once, at launch.
///         Owner decision 2026-10-28: the admin-key trade-off is accepted; routes are ours, never a
///         creator's.
///
/// READS NEVER GUESS. `usdPerQuoteE18` and `poolFeePpm` answer 0 / not-ok on every failure (no
/// route, an unlisted reader, a reader that reverts, runs out of its gas cap, returns anything but
/// exactly 32 bytes, or a value outside [1, 2^128-1]) and never a non-zero they did not read; v3c:
/// the token turns that 0 into a retriable revert (GapUnreadable / GapSourceUnreadable), never fee 0.
/// The one revert is `GapGasTooLow` (owner Q1): before each external read the caller must have
/// left enough gas for its whole cap, so a starved read cannot be passed off as a failed one by
/// whoever chose the gas (the executor), and the message stays retriable instead.
contract PangeaGapRegistry is IPangeaGapRegistry, Ownable2Step {
    /// @notice The gas cap of one hook-fee read (`configs` on a V1 hook, `feeOf` on a V2 hook).
    ///         Checked like a route hop: gasleft() >= cap * 64 / 63 + GapMath.HOP_GAS_RESERVE.
    uint32 public constant HOOK_READ_GAS = 30_000;

    /// @inheritdoc IPangeaGapRegistry
    address public immutable poolManager;
    /// @inheritdoc IPangeaGapRegistry
    address public immutable wrappedNative;
    /// @notice The 0xEeee... placeholder many tools use for the native coin; never a stable.
    address public constant NATIVE_SENTINEL = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /// @inheritdoc IPangeaGapRegistry
    address public registrar;
    /// @inheritdoc IPangeaGapRegistry
    uint32 public marginPpm;
    /// @inheritdoc IPangeaGapRegistry
    uint32 public v2RecordMaxAge;
    /// @dev AMENDMENT 6: this chain's gas cover (one slot: 4 + 4 + 8 + 8 + 2 + 4 bytes).
    GasCover internal _gasCover;
    /// @inheritdoc IPangeaGapRegistry
    uint16 public bridgeFeeBps;
    /// @inheritdoc IPangeaGapRegistry
    uint32 public quoteGas;
    /// @inheritdoc IPangeaGapRegistry
    uint128 public costMaxUsdE18;

    /// @inheritdoc IPangeaGapRegistry
    mapping(address => bool) public isReader;
    /// @inheritdoc IPangeaGapRegistry
    mapping(address => bool) public isStable;
    /// @inheritdoc IPangeaGapRegistry
    mapping(address => bool) public isFactory;
    /// @inheritdoc IPangeaGapRegistry
    mapping(address => HookKind) public hookKind;
    /// @inheritdoc IPangeaGapRegistry
    mapping(address => bool) public gapEscape;
    /// @dev The admin class of a non-stable quote (2..255; 0 none). A stable reads class 1 whatever
    ///      is stored here (see quoteClass), so setStable alone decides class 1.
    mapping(address => uint8) internal _quoteClass;

    mapping(address => Hop[]) internal _routes;
    /// @dev A pool is set iff its poolId is non-zero (setOfficialPool refuses a zero id).
    mapping(address => OfficialPool) internal _pools;
    /// @dev AMENDMENT 5: the v4 position key of each official pool's LOCKED launch liquidity (the
    ///      listing factory's locker's position, read once at `setOfficialPool`); 0 = unknown.
    mapping(address => bytes32) internal _positions;

    // ---- v3c-evm-log: the price log's settings (GapPriceLog) and re-pointing
    /// @dev Packed: kMode | kFlatPpm | kFactorPpm | windowSec | minBlocks | rewardBps | merge.
    uint8 internal _logKMode;
    uint32 internal _logKFlatPpm;
    uint32 internal _logKFactorPpm;
    uint32 internal _logWindowSec;
    uint8 internal _logMinBlocks;
    uint16 internal _logRewardBps;
    bool internal _logMerge;
    /// @dev E5 (audit M-2): k_mode 1's fee cap (ppm of volume).
    uint32 internal _logPlatformFloorPpm;
    /// @inheritdoc IPangeaGapRegistry
    address public migrationLocker;
    /// @inheritdoc IPangeaGapRegistry
    mapping(address => uint32) public officialEpoch;

    error ZeroAddress();
    error ZeroPoolId();
    error RenounceDisabled();

    constructor(address owner_, address poolManager_, address wrappedNative_) Ownable(owner_) {
        if (poolManager_ == address(0) || wrappedNative_ == address(0)) revert ZeroAddress();
        poolManager = poolManager_;
        wrappedNative = wrappedNative_;
        marginPpm = GapMath.MARGIN_DEFAULT_PPM;
        emit MarginSet(GapMath.MARGIN_DEFAULT_PPM);
        // AMENDMENT 6: no cover until the owner sets this chain's measured figures; the window 30 s.
        _gasCover.coverWindowSeconds = GapMath.COVER_WINDOW_SECONDS_DEFAULT;
        emit GasCoverSet(_gasCover);
        bridgeFeeBps = GapMath.BRIDGE_FEE_DEFAULT_BPS;
        emit BridgeFeeSet(GapMath.BRIDGE_FEE_DEFAULT_BPS);
        quoteGas = GapMath.QUOTE_GAS_DEFAULT;
        emit QuoteGasSet(GapMath.QUOTE_GAS_DEFAULT);
        costMaxUsdE18 = uint128(GapMath.COST_MAX_USD_E18);
        emit CostMaxSet(GapMath.COST_MAX_USD_E18);
        v2RecordMaxAge = GapMath.V2_RECORD_MAX_AGE_DEFAULT;
        emit V2RecordMaxAgeSet(GapMath.V2_RECORD_MAX_AGE_DEFAULT);
        // e6-r2fix (owner 2026-10-30): W per chain -- Ethereum's default is its minimum, 384 s (32 blocks)
        uint32 w0 = windowMinSec();
        _setLogParams(
            GapPriceLog.K_MODE_DEFAULT,
            GapPriceLog.K_FLAT_DEFAULT_PPM,
            GapPriceLog.K_FACTOR_DEFAULT_PPM,
            w0 > GapPriceLog.WINDOW_DEFAULT_SEC ? w0 : GapPriceLog.WINDOW_DEFAULT_SEC,
            GapPriceLog.MIN_BLOCKS_DEFAULT,
            GapPriceLog.REWARD_DEFAULT_BPS,
            true,
            GapPriceLog.PLATFORM_FLOOR_DEFAULT_PPM
        );
    }

    // ------------------------------------------------------------------ v3c-evm-log

    /// @inheritdoc IPangeaGapRegistry
    function setLogParams(
        uint8 kMode,
        uint32 kFlatPpm,
        uint32 kFactorPpm,
        uint32 windowSec,
        uint8 minBlocks,
        uint16 rewardBps,
        bool merge,
        uint32 platformFloorPpm
    ) external onlyOwner {
        _setLogParams(kMode, kFlatPpm, kFactorPpm, windowSec, minBlocks, rewardBps, merge, platformFloorPpm);
    }

    function _setLogParams(
        uint8 kMode,
        uint32 kFlatPpm,
        uint32 kFactorPpm,
        uint32 windowSec,
        uint8 minBlocks,
        uint16 rewardBps,
        bool merge,
        uint32 platformFloorPpm
    ) internal {
        if (
            kMode > 1 || kFlatPpm < GapPriceLog.K_PPM_MIN || kFlatPpm > GapPriceLog.K_PPM_MAX || kFactorPpm == 0
                || kFactorPpm > GapPriceLog.K_FACTOR_MAX_PPM || windowSec < GapPriceLog.WINDOW_MIN_SEC
                || windowSec > GapPriceLog.WINDOW_MAX_SEC || minBlocks < GapPriceLog.MIN_BLOCKS_MIN
                || minBlocks > GapPriceLog.MIN_BLOCKS_MAX || rewardBps > GapPriceLog.REWARD_MAX_BPS
                || platformFloorPpm < GapPriceLog.PLATFORM_FLOOR_MIN_PPM || platformFloorPpm > GapPriceLog.PLATFORM_FLOOR_MAX_PPM
        ) revert BadLogParams();
        // E5 (audit L-2): a window that can hold minBlocks seconds. E6 (lead #3, the Solana bounds:
        // flat k 100..=100,000 ppm, factor 1..=333,333, i.e. at most 1/3 of the fee): k_mode 1's k is
        // never below GapPriceLog.K_PPM_MIN (100 ppm) at a readable fee, so no factor x floor gives
        // every entry 0. (e6-r2fix, audit R2 B I-1: this comment said factor 1..=1e6.)
        // e6-r2fix (owner 2026-10-30): and at least this chain's windowMinSec (Ethereum 384 s).
        if (windowSec < minBlocks || windowSec < windowMinSec()) revert BadLogParams();
        // E6 (lead #3): the flat k at most a third of the platform floor (factor <= 1/3 above).
        if (kFlatPpm > platformFloorPpm / 3) revert BadLogParams();
        (_logKMode, _logKFlatPpm, _logKFactorPpm, _logWindowSec, _logMinBlocks, _logRewardBps, _logMerge) =
            (kMode, kFlatPpm, kFactorPpm, windowSec, minBlocks, rewardBps, merge);
        _logPlatformFloorPpm = platformFloorPpm;
        emit LogParamsSet(kMode, kFlatPpm, kFactorPpm, windowSec, minBlocks, rewardBps, merge, platformFloorPpm);
    }

    /// @dev e6-r2fix: Ethereum's least W, 32 blocks of 12 s (the ring's 32 entries).
    uint32 public constant ETHEREUM_WINDOW_MIN_SEC = 384;

    /// @inheritdoc IPangeaGapRegistry
    function windowMinSec() public view returns (uint32) {
        return block.chainid == 1 || block.chainid == 11_155_111 ? ETHEREUM_WINDOW_MIN_SEC : GapPriceLog.WINDOW_MIN_SEC;
    }

    /// @inheritdoc IPangeaGapRegistry
    function setLogWindow(uint32 windowSec) external onlyOwner {
        _setLogParams(
            _logKMode, _logKFlatPpm, _logKFactorPpm, windowSec, _logMinBlocks, _logRewardBps, _logMerge, _logPlatformFloorPpm
        );
        emit LogWindowSet(windowSec);
    }

    /// @inheritdoc IPangeaGapRegistry
    function logParams() external view returns (uint8, uint32, uint32, uint32, uint8, uint16, bool, uint32) {
        return (
            _logKMode, _logKFlatPpm, _logKFactorPpm, _logWindowSec, _logMinBlocks, _logRewardBps, _logMerge,
            _logPlatformFloorPpm
        );
    }

    /// @inheritdoc IPangeaGapRegistry
    function setMigrationLocker(address locker) external onlyOwner {
        if (locker == address(0)) revert ZeroAddress();
        migrationLocker = locker;
        emit MigrationLockerSet(locker);
    }

    /// @inheritdoc IPangeaGapRegistry
    /// @dev Why codes (BadRepoint): 1 no pool yet / same pool / zero id; 2 hook not V2; 3 quote not
    ///      pricable; 4 no migration locker, or the hook does not list it as a liquidity adder;
    ///      5 the locker's key or pool key does not match `pool` and `token`; 6 liquidity below the
    ///      old locked position's (or zero).
    function repointOfficialPool(address token, OfficialPool calldata pool, bytes32 positionKey) external onlyOwner {
        OfficialPool memory old = _pools[token];
        if (old.poolId == bytes32(0) || pool.poolId == bytes32(0) || pool.poolId == old.poolId) revert BadRepoint(1);
        if (hookKind[pool.hook] != HookKind.V2) revert BadRepoint(2);
        if (!quotePricable(pool.quote)) revert BadRepoint(3);
        address lk = migrationLocker;
        if (lk == address(0) || !_hookListsAdder(pool.hook, lk)) revert BadRepoint(4);
        if (positionKey == bytes32(0) || !_lockerHolds(lk, token, pool, positionKey)) revert BadRepoint(5);
        uint128 liq = _positionLiquidity(pool.poolId, positionKey);
        if (liq == 0 || liq < _positionLiquidity(old.poolId, _positions[token])) revert BadRepoint(6);
        // E5 (audit L-3): the locked position must be IN RANGE now (tickLower <= tick < tickUpper),
        // so its liquidity is the depth the price log's capacity counts, not an idle out-of-range one.
        if (!_inRange(lk, pool.poolId)) revert BadRepoint(7);
        _pools[token] = pool;
        _positions[token] = positionKey;
        uint32 e = officialEpoch[token] + 1;
        officialEpoch[token] = e;
        emit OfficialPoolRepointed(token, e, pool, positionKey);
    }

    /// @dev E5 (audit L-3): the migration locker's position ticks of `poolId` (positions(bytes32):
    ///      tickLower, tickUpper, set) hold the pool's current tick (v4 slot0 by extsload: bits
    ///      [160, 184) of pools[poolId]'s first word, signed): tickLower <= tick < tickUpper.
    function _inRange(address lk, bytes32 poolId) internal view returns (bool) {
        (bool ok, bytes memory r) = lk.staticcall{gas: 30_000}(abi.encodeWithSignature("positions(bytes32)", poolId));
        if (!ok || r.length != 96) return false;
        (int256 lo, int256 hi, uint256 set) = abi.decode(r, (int256, int256, uint256));
        if (set != 1) return false;
        bytes32 slot = keccak256(abi.encodePacked(poolId, POOLS_SLOT));
        (ok, r) = poolManager.staticcall(abi.encodeWithSignature("extsload(bytes32)", slot));
        if (!ok || r.length != 32) return false;
        uint256 w = uint256(abi.decode(r, (bytes32)));
        if (uint160(w) == 0) return false; // not initialized
        int256 tick = int256(int24(uint24(w >> 160)));
        return lo <= tick && tick < hi;
    }

    /// @dev The V2 hook's `isLiquidityAdder(locker)` (the migration locker is named by setLiquidityAdder).
    function _hookListsAdder(address hook, address lk) internal view returns (bool) {
        (bool ok, bytes memory r) = hook.staticcall{gas: 20_000}(abi.encodeWithSignature("isLiquidityAdder(address)", lk));
        return ok && r.length == 32 && abi.decode(r, (uint256)) == 1;
    }

    /// @dev The migration locker's `positionKey(poolId) == key` and its recorded PoolKey for the pool
    ///      hashes to `pool.poolId`, holds `token` and `pool.quote` in `pool.tokenIsCurrency0`'s order,
    ///      on `pool.hook` with `pool.lpFee`.
    function _lockerHolds(address lk, address token, OfficialPool calldata pool, bytes32 key) internal view returns (bool) {
        (bool ok, bytes memory r) = lk.staticcall{gas: 30_000}(abi.encodeWithSignature("positionKey(bytes32)", pool.poolId));
        if (!ok || r.length != 32 || abi.decode(r, (bytes32)) != key) return false;
        (ok, r) = lk.staticcall{gas: 30_000}(abi.encodeWithSignature("poolKeyOf(bytes32)", pool.poolId));
        if (!ok || r.length != 160) return false;
        (address c0, address c1, uint24 fee, int24 spacing, address hooks) =
            abi.decode(r, (address, address, uint24, int24, address));
        if (keccak256(abi.encode(c0, c1, fee, spacing, hooks)) != pool.poolId) return false;
        (address t, address q) = pool.tokenIsCurrency0 ? (c0, c1) : (c1, c0);
        return t == token && q == pool.quote && hooks == pool.hook && fee == pool.lpFee;
    }

    // ------------------------------------------------------------------ ownership

    function owner() public view override(IPangeaGapRegistry, Ownable) returns (address) {
        return super.owner();
    }

    /// @dev The interface's own error, so every owner-gated call fails the same way.
    function _checkOwner() internal view override {
        if (owner() != msg.sender) revert NotOwner();
    }

    /// @notice Disabled: an ownerless registry could never add a reader, stable or factory again.
    function renounceOwnership() public view override onlyOwner {
        revert RenounceDisabled();
    }

    /// @notice evm-lows2 (evm-lows-r1 L-1): a co-signer (the co-sign API's hot key) is never offered the ownership
    ///         (CoSignerRefused); 0 still cancels a pending transfer. setCoSigner refuses the pending owner, so the
    ///         two never meet; acceptOwnership refuses a co-signer as well (defence in depth).
    function transferOwnership(address newOwner) public override onlyOwner {
        if (isCoSigner(newOwner)) revert CoSignerRefused(newOwner);
        super.transferOwnership(newOwner);
    }

    /// @notice evm-lows2 (evm-lows-r1 L-1): a co-signer never accepts the ownership (CoSignerRefused).
    function acceptOwnership() public override {
        if (isCoSigner(msg.sender)) revert CoSignerRefused(msg.sender);
        super.acceptOwnership();
    }

    // ------------------------------------------------------------------ owner

    /// @dev Listing = the owner's statement that the reader is flash-proof (see the interface);
    ///      only listed readers can be in a route (setRoute) and read (usdPerQuoteE18).
    function setReader(address reader, bool allowed) external onlyOwner {
        if (reader == address(0)) revert ZeroAddress();
        isReader[reader] = allowed;
        emit ReaderSet(reader, allowed);
    }

    /// @dev A stable is exactly $1 with no route. Native (address(0)), the 0xEeee... native placeholder
    ///      and this chain's wrapped native (ETH / BNB) are never stables (owner rule: WSOL/WETH/native
    ///      are never $1): listing one is refused (NotAStable); they are priced through a route.
    ///      Unlisting (stable = false) is always allowed.
    function setStable(address token, bool stable) external onlyOwner {
        if (stable && (token == address(0) || token == NATIVE_SENTINEL || token == wrappedNative)) revert NotAStable(token);
        isStable[token] = stable;
        emit StableSet(token, stable);
    }

    /// @dev AMENDMENT 6: the fixed margin, <= GapMath.MARGIN_MAX_PPM (10%). Read by this chain's receives.
    function setMargin(uint32 ppm) external onlyOwner {
        if (ppm > GapMath.MARGIN_MAX_PPM) revert MarginTooHigh(ppm);
        marginPpm = ppm;
        emit MarginSet(ppm);
    }

    /// @dev AMENDMENT 6: this chain's gas cover, within GapCoverLib.validGasCover (the hard caps).
    function setGasCover(GasCover calldata c) external onlyOwner {
        if (!GapCoverLib.validGasCover(c)) revert BadGasCover();
        _gasCover = c;
        emit GasCoverSet(c);
    }

    /// @dev v3c-evm-final: the bridge fee every v3 token on this chain charges at send (and carries in
    ///      its header), 0..=50 bps, default 20. The recipient stays each token's immutable bridgeFeeTo.
    function setBridgeFeeBps(uint16 bps) external onlyOwner {
        if (bps > GapMath.BRIDGE_FEE_MAX_BPS) revert BridgeFeeTooHigh(bps);
        bridgeFeeBps = bps;
        emit BridgeFeeSet(bps);
    }

    /// @dev v3c-evm-final: the gas cap of the send's LayerZero quote, [150,000, 1,000,000], default 400,000.
    function setQuoteGas(uint32 gas_) external onlyOwner {
        if (gas_ < GapMath.QUOTE_GAS_MIN || gas_ > GapMath.QUOTE_GAS_MAX) revert BadQuoteGas(gas_);
        quoteGas = gas_;
        emit QuoteGasSet(gas_);
    }

    /// @dev v3c-evm-final: the LayerZero cost term's cap (USD 1e18), 0..=$50, default $20.
    function setCostMax(uint256 usdE18) external onlyOwner {
        if (usdE18 > GapMath.COST_MAX_LIMIT_USD_E18) revert CostMaxTooHigh(usdE18);
        costMaxUsdE18 = uint128(usdE18);
        emit CostMaxSet(usdE18);
    }

    /// @notice Class 255 is the expired-compose refund marker (AMENDMENT 2): only Solana's
    ///         return_expired_compose emits it, so no quote may ever have it.
    uint8 public constant REFUND_CLASS = 255;

    /// @dev Class 1 (USD) is only ever a stable's (setStable), so it is refused here; 255 is the
    ///      refund marker and refused; 0 clears; a stable cannot be given another class (it reads 1
    ///      while it is a stable). address(0) (native) is allowed: ETH-class (2) on an ETH chain.
    function setQuoteClass(address quote, uint8 class_) external onlyOwner {
        if (class_ == 1 || class_ == REFUND_CLASS || (class_ != 0 && isStable[quote])) revert BadQuoteClass(quote, class_);
        _quoteClass[quote] = class_;
        emit QuoteClassSet(quote, class_);
    }

    /// @dev Per token: on, a receive whose price is unreadable credits in full at fee 0 (spec §3.2).
    function setGapEscape(address token, bool on) external onlyOwner {
        if (token == address(0)) revert ZeroAddress();
        gapEscape[token] = on;
        emit GapEscapeSet(token, on);
    }

    // ------------------------------------------------------------------ E6 (audit E5 M-B)

    /// @inheritdoc IPangeaGapRegistry
    mapping(address => bool) public gapExecutor;
    /// @inheritdoc IPangeaGapRegistry
    address[2] public deliveryKeys;

    /// @notice E6: the delivery key slot is not 0 or 1.
    error BadDeliverySlot(uint8 slot);

    /// @inheritdoc IPangeaGapRegistry
    function setGapExecutor(address executor, bool trusted) external onlyOwner {
        if (executor == address(0)) revert ZeroAddress();
        // e6-r2fix (audit R2 L-1): LayerZero's permissionless LzExecutor helper (commitAndExecute) is the
        // lzReceive caller of ANY receive run through it: trusting it would trust everyone.
        if (trusted && isLzExecutorHelper(executor)) revert LzExecutorHelperRefused(executor);
        // evm-lows (xa-final-evm I-2): a co-signer stays a signer only.
        if (trusted && isCoSigner(executor)) revert CoSignerRefused(executor);
        gapExecutor[executor] = trusted;
        emit GapExecutorSet(executor, trusted);
    }

    /// @inheritdoc IPangeaGapRegistry
    function setDeliveryKey(uint8 slot, address key) external onlyOwner {
        if (slot > 1) revert BadDeliverySlot(slot);
        if (isLzExecutorHelper(key)) revert LzExecutorHelperRefused(key);
        // evm-lows (xa-final-evm I-2): a co-signer never becomes a (funded) delivery key.
        if (isCoSigner(key)) revert CoSignerRefused(key);
        deliveryKeys[slot] = key;
        emit DeliveryKeySet(slot, key);
    }

    /// @inheritdoc IPangeaGapRegistry
    function isTrustedExecutor(address executor) external view returns (bool) {
        if (executor == address(0)) return false;
        return gapExecutor[executor] || executor == deliveryKeys[0] || executor == deliveryKeys[1];
    }

    /// @inheritdoc IPangeaGapRegistry
    function isDeliveryKey(address key) public view returns (bool) {
        return key != address(0) && (key == deliveryKeys[0] || key == deliveryKeys[1]);
    }

    /// @inheritdoc IPangeaGapRegistry
    function canLandOversized(address a) external view returns (bool) {
        return a == owner() || isDeliveryKey(a);
    }

    /// @inheritdoc IPangeaGapRegistry
    function deliveryKeysSet() external view returns (bool) {
        (address k0, address k1) = (deliveryKeys[0], deliveryKeys[1]);
        return k0 != address(0) && k1 != address(0) && k0 != k1;
    }

    // ---- evm-lows (xa-final-evm I-2, lead decision: match Solana's dedicated unfunded co-signers,
    //      GapGlobal.cosigners). The co-sign API's key signs only; it is not the funded delivery key
    //      that is also a trusted executor and an oversized lander.
    //      Declared HERE, not in IPangeaGapRegistry: every v3 token / gap module / log module imports that
    //      interface, so any edit to it (comments included) moves their metadata hash, the TokenDeployerV3
    //      GAP_LOG_MODULE_CODEHASH pin and the token's CREATE2 address. Only this (undeployed) registry changes.
    //      NOTE: IPangeaGapRegistry's NatSpec of coSignValid / coSignCheck / isDeliveryKey still says "a
    //      delivery key": the registry below is authoritative -- ONLY a co-signer's signature is valid.

    /// @notice evm-lows: co-sign key slot `slot` (0 or 1) is now `key` (never 0).
    event CoSignerSet(uint8 indexed slot, address indexed key);
    /// @notice evm-lows: the co-signer slot is not 0 or 1.
    error BadCoSignerSlot(uint8 slot);
    /// @notice evm-lows: the keys stay separate, as on Solana (BadCosigner): a co-signer may not be the owner,
    ///         a delivery key, a trusted executor, a LayerZero helper or the other slot's co-signer
    ///         (setCoSigner); a co-signer may not become a delivery key or a trusted executor
    ///         (setDeliveryKey / setGapExecutor). evm-lows2 (evm-lows-r1 L-1): nor the registrar or the pending
    ///         owner (setCoSigner), and a co-signer may not become the registrar (setRegistrar) or the owner
    ///         (transferOwnership / acceptOwnership).
    error CoSignerRefused(address key);

    /// @notice evm-lows: the two dedicated co-sign keys, the only signers `coSignValid` / `coSignCheck`
    ///         accept. Unfunded keys of the co-sign API (script/cosign-evm.mjs, DELIVERY_COSIGN_EVM_KEY),
    ///         never a delivery key. Empty (0) until set.
    address[2] public coSigners;

    /// @notice evm-lows: set co-sign key slot `slot` (0 or 1) to `key`. Owner only; 0 refused (ZeroAddress);
    ///         CoSignerRefused as above. Emits CoSignerSet. Rotation: set the slot to the new key.
    function setCoSigner(uint8 slot, address key) external onlyOwner {
        if (slot > 1) revert BadCoSignerSlot(slot);
        if (key == address(0)) revert ZeroAddress();
        if (
            key == owner() || isDeliveryKey(key) || gapExecutor[key] || isLzExecutorHelper(key)
                || key == coSigners[1 - slot]
            // evm-lows2 (evm-lows-r1 L-1): nor the registrar (route power) nor the pending owner (as Solana's BadCosigner)
            || key == registrar || key == pendingOwner()
        ) revert CoSignerRefused(key);
        coSigners[slot] = key;
        emit CoSignerSet(slot, key);
    }

    /// @notice evm-lows: `key` is one of the two co-signers (address(0) never).
    function isCoSigner(address key) public view returns (bool) {
        return key != address(0) && (key == coSigners[0] || key == coSigners[1]);
    }

    /// @notice evm-lows (golive read-back): both co-signers are set and distinct.
    function coSignersSet() external view returns (bool) {
        (address k0, address k1) = (coSigners[0], coSigners[1]);
        return k0 != address(0) && k1 != address(0) && k0 != k1;
    }

    // ------------------------------------------------------------------ eth-fallback (owner Q24 / Q34)
    //
    // KEYS-ONLY destinations (src/v3/gap/IGapDelivery.sol): a destination whose LayerZero Executor is not
    // proven gated (Ethereum) is delivered by our delivery keys only, and the user pays that delivery here,
    // at the source, once: `deliveryCost[dstEid]` (native wei of THIS chain) is added to every v3 token's
    // quoteSend native fee and paid by its send to `deliveryFeeTo`; the v3 factory wires such a route with
    // the minimal executor gas, so LayerZero's own fee covers almost no destination gas (never a double
    // charge). Zero = not keys-only (LayerZero's executor delivers; nothing extra is charged).

    /// @notice Our delivery cost of one message toward each destination eid, in this chain's native wei
    ///         (0 = not keys-only). Owner-set (`setDeliveryCost`), at most `deliveryCostMax()`.
    mapping(uint32 => uint256) public deliveryCost;

    /// @notice Where every token's send pays `deliveryCost` (our delivery fee recipient on this chain).
    ///         Owner-set, never zero once set; a non-zero cost needs it set.
    address public deliveryFeeTo;

    /// @notice The delivery cost toward `dstEid` changed (0 = keys-only off).
    event GapDeliveryCostSet(uint32 indexed dstEid, uint256 costWei);
    /// @notice The delivery fee recipient changed.
    event GapDeliveryFeeToSet(address indexed to);

    /// @notice The cost is above `deliveryCostMax()`.
    error DeliveryCostAboveMax(uint256 costWei, uint256 maxWei);
    /// @notice A delivery cost toward eid 0 or Solana (whose arrivals carry their own, GapGlobal
    ///         delivery_lamports, oft-q7), or a non-zero cost while `deliveryFeeTo` is unset.
    error DeliveryCostRefused(uint32 dstEid);

    /// @notice The most `setDeliveryCost` accepts: 0.0064 ETH (DELIVERY_COST_MAX_WEI, the owner's per-
    ///         transaction ceiling of our Ethereum delivery spend) on ETH-native chains; on BNB Chain
    ///         (56 / 97) the same in BNB at the go-live price ratio, 0.032 BNB (DELIVERY_COST_MAX_BNB_WEI).
    function deliveryCostMax() public view returns (uint256) {
        return block.chainid == 56 || block.chainid == 97 ? DELIVERY_COST_MAX_BNB_WEI : DELIVERY_COST_MAX_WEI;
    }

    /// @notice Set where the delivery cost is paid. Owner only; never zero.
    function setDeliveryFeeTo(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        deliveryFeeTo = to;
        emit GapDeliveryFeeToSet(to);
    }

    /// @notice Set our delivery cost toward `dstEid` (native wei of this chain); non-zero makes it a
    ///         keys-only destination, zero turns that off. Owner only; refuses above `deliveryCostMax()`,
    ///         eid 0, Solana (30168 / 40168) and a non-zero cost with no `deliveryFeeTo`.
    function setDeliveryCost(uint32 dstEid, uint256 costWei) external onlyOwner {
        if (dstEid == 0 || dstEid == 30168 || dstEid == 40168 || (costWei != 0 && deliveryFeeTo == address(0))) {
            revert DeliveryCostRefused(dstEid);
        }
        uint256 max = deliveryCostMax();
        if (costWei > max) revert DeliveryCostAboveMax(costWei, max);
        deliveryCost[dstEid] = costWei;
        emit GapDeliveryCostSet(dstEid, costWei);
    }

    /// @notice Whether `dstEid` is keys-only (our delivery keys deliver; the user pays `deliveryCost`).
    function keysOnly(uint32 dstEid) external view returns (bool) {
        return deliveryCost[dstEid] != 0;
    }

    /// @notice `deliveryCost[dstEid]` and the address it is paid to (zero when the cost is zero).
    function deliveryCharge(uint32 dstEid) external view returns (uint256 costWei, address to) {
        costWei = deliveryCost[dstEid];
        if (costWei != 0) to = deliveryFeeTo;
    }

    // ------------------------------------------------------------------ q7b (owner Q52): the L4 prepay P
    //
    // A composed v3 send INTO Solana prepays its compose's way home (L4: P = R + floor(1.1 X) + Y lamports),
    // no longer as a LayerZero lzNativeDrop: every v3 token's quoteSend adds P's cost here in this chain's
    // native wei and its send pays it to `deliveryFeeTo` (event GapPrepayPaid in the token); our delivery key
    // funds the GapPrepay PDA with exactly P in the receive's own Solana transaction (src/v3/gap/IGapDelivery.sol).

    /// @notice X: LayerZero's fee home (Solana -> this chain) the return of an expired compose pays, in lamports
    ///         (owner-set from a live quote). P carries floor(11 X / 10).
    uint64 public prepayReturnFeeLamports;
    /// @notice Y: GapGlobal.return_gas_lamports (25,000 at init), the return caller's gas.
    uint32 public prepayReturnGasLamports;
    /// @notice This chain's native wei per lamport (31,000,000 at the go-live $93 SOL / $3,000 ETH;
    ///         155,000,000 on BNB Chain at $600). 0 = unset: composed v3 sends into Solana are refused.
    uint64 public prepayWeiPerLamport;

    /// @notice P's figures changed (weiPerLamport 0 = unset).
    event GapPrepayConfigSet(uint64 returnFeeLamports, uint32 returnGasLamports, uint64 weiPerLamport);
    /// @notice Y above SOLANA_PREPAY_RETURN_GAS_MAX, a set figure with no `deliveryFeeTo`, or the 512-byte
    ///         worst case above `prepayCostMax()`.
    error PrepayConfigRefused(uint256 worstWei, uint256 maxWei);

    /// @notice The most one P may cost (its 512-byte worst case): 0.002 ETH on ETH-native chains, Ethereum's own
    ///         bound on chain id 1 (owner Q72 refined: min(0.0025, P_needed x 1.2), never below 0.002 = 0.002 ETH at
    ///         the measured X), 0.01 BNB on BNB Chain (56 / 97).
    function prepayCostMax() public view returns (uint256) {
        if (block.chainid == 56 || block.chainid == 97) return PREPAY_COST_MAX_BNB_WEI;
        return block.chainid == 1 ? PREPAY_COST_MAX_ETHEREUM_WEI : PREPAY_COST_MAX_WEI;
    }

    /// @notice Set P's figures: X `returnFeeLamports`, Y `returnGasLamports`, `weiPerLamport` (0 unsets all:
    ///         every composed v3 send into Solana is then refused). Owner only; a set figure needs
    ///         `deliveryFeeTo`, Y <= 1,000,000 and the 512-byte worst case <= `prepayCostMax()`.
    function setPrepayConfig(uint64 returnFeeLamports, uint32 returnGasLamports, uint64 weiPerLamport)
        external
        onlyOwner
    {
        if (weiPerLamport == 0) {
            (returnFeeLamports, returnGasLamports) = (0, 0);
        } else {
            uint256 worst = _prepayLamports(SOLANA_PREPAY_MAX_COMPOSE, returnFeeLamports, returnGasLamports)
                * weiPerLamport;
            uint256 max = prepayCostMax();
            if (
                deliveryFeeTo == address(0) || returnGasLamports > SOLANA_PREPAY_RETURN_GAS_MAX || worst > max
            ) revert PrepayConfigRefused(worst, max);
        }
        (prepayReturnFeeLamports, prepayReturnGasLamports, prepayWeiPerLamport) =
            (returnFeeLamports, returnGasLamports, weiPerLamport);
        emit GapPrepayConfigSet(returnFeeLamports, returnGasLamports, weiPerLamport);
    }

    /// @notice P for a `composeLen`-byte composeMsg toward `dstEid` (Solana 30168 / 40168): its lamports, its
    ///         cost in native wei (lamports x weiPerLamport, exact) and `deliveryFeeTo`. All zero toward any
    ///         other eid, past the 512-byte compose cap, and while unset.
    function prepayCharge(uint32 dstEid, uint256 composeLen)
        external
        view
        returns (uint256 lamports, uint256 costWei, address to)
    {
        uint256 rate = prepayWeiPerLamport;
        if ((dstEid != 30168 && dstEid != 40168) || rate == 0 || composeLen > SOLANA_PREPAY_MAX_COMPOSE) {
            return (0, 0, address(0));
        }
        lamports = _prepayLamports(composeLen, prepayReturnFeeLamports, prepayReturnGasLamports);
        costWei = lamports * rate;
        to = deliveryFeeTo;
    }

    /// @dev L4's P (solana/client gap-v3.mjs prepayLamports): (387 + len) x 6,960 + floor(11 X / 10) + Y.
    function _prepayLamports(uint256 composeLen, uint256 x, uint256 y) internal pure returns (uint256) {
        return (SOLANA_PREPAY_RECEIPT_FIXED + composeLen) * SOLANA_PREPAY_RENT_PER_BYTE + (11 * x) / 10 + y;
    }

    /// @dev LayerZero's LzExecutor (commitAndExecute) on Ethereum, Base, BSC and Robinhood
    ///      (script/lz-delivery.mjs LZ_EXECUTORS, script/DELIVERY-BOT.md).
    address internal constant LZ_HELPER_ETHEREUM = 0xbF2E102Fb382d6EC52823C8F81A45e9Caa951320;
    address internal constant LZ_HELPER_BASE = 0x125BD5c6C5066dcb4BB448b6eA8b9234Ed60e160;
    address internal constant LZ_HELPER_BSC = 0x821A99C061C00f6C9da0302AAec348945Ba40284;
    address internal constant LZ_HELPER_ROBINHOOD = 0x41Bdb4aa4A63a5b2Efc531858d3118392B1A1C3d;

    /// @inheritdoc IPangeaGapRegistry
    function isLzExecutorHelper(address a) public pure returns (bool) {
        return a == LZ_HELPER_ETHEREUM || a == LZ_HELPER_BASE || a == LZ_HELPER_BSC || a == LZ_HELPER_ROBINHOOD;
    }

    // ---- e6-r2fix (owner 2026-10-30): the EIP-712 co-sign of an oversized send (evm-lows: by the
    //      dedicated co-signers, `coSigners`)
    bytes32 public constant CO_SIGN_TYPEHASH = keccak256(
        "GapCoSign(uint256 chainId,address token,uint32 dstEid,address sender,uint256 amountLD,uint256 minCreditedLD,uint256 maxPsE18,uint64 deadline,uint256 nonce)"
    );
    bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 internal constant CO_SIGN_NAME_HASH = keccak256("Pangea Gap Co-Sign");
    bytes32 internal constant CO_SIGN_VERSION_HASH = keccak256("1");

    /// @inheritdoc IPangeaGapRegistry
    function coSignDomainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, CO_SIGN_NAME_HASH, CO_SIGN_VERSION_HASH, block.chainid, address(this)));
    }

    /// @inheritdoc IPangeaGapRegistry
    function coSignDigest(CoSign calldata c) external view returns (bytes32) {
        return _coSignDigestM(c);
    }

    function _coSignDigestM(CoSign memory c) internal view returns (bytes32) {
        bytes32 h = keccak256(
            abi.encode(
                CO_SIGN_TYPEHASH, block.chainid, c.token, c.dstEid, c.sender, c.amountLD, c.minCreditedLD, c.maxPsE18, c.deadline, c.nonce
            )
        );
        return keccak256(abi.encodePacked(hex"1901", coSignDomainSeparator(), h));
    }

    /// @inheritdoc IPangeaGapRegistry
    /// @dev evm-lows: the signer must be a co-signer (`isCoSigner`); a delivery key alone is refused.
    function coSignValid(CoSign calldata c, uint8 v, bytes32 r, bytes32 s) external view returns (bool) {
        return _coSignValid(_coSignDigestM(c), v, r, s);
    }

    function _coSignValid(bytes32 digest, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
        (address signer, ECDSA.RecoverError e,) = ECDSA.tryRecover(digest, v, r, s);
        // evm-lows (xa-final-evm I-2): the dedicated co-signers only, not the delivery keys.
        return e == ECDSA.RecoverError.NoError && isCoSigner(signer);
    }

    /// @inheritdoc IPangeaGapRegistry
    function coSignCheck(
        address token,
        uint32 dstEid,
        address sender,
        uint256 amountLD,
        uint256 nonce,
        uint256 psE18,
        bytes calldata oftCmd
    ) external view returns (uint8 why) {
        if (oftCmd.length != 224) return 3;
        (uint256 w, uint256 maxPs, uint64 deadline, uint256 n, uint8 v, bytes32 r, bytes32 s) =
            abi.decode(oftCmd, (uint256, uint256, uint64, uint256, uint8, bytes32, bytes32));
        if (block.timestamp > deadline) return 1;
        if (n != nonce) return 2;
        CoSign memory c = CoSign(token, dstEid, sender, amountLD, w & ((uint256(1) << 248) - 1), maxPs, deadline, n);
        if (!_coSignValid(_coSignDigestM(c), v, r, s)) return 3;
        if (psE18 > maxPs) return 4;
    }

    function setV2RecordMaxAge(uint32 seconds_) external onlyOwner {
        if (seconds_ < GapMath.V2_RECORD_MAX_AGE_MIN || seconds_ > GapMath.V2_RECORD_MAX_AGE_MAX) {
            revert BadV2RecordMaxAge(seconds_);
        }
        v2RecordMaxAge = seconds_;
        emit V2RecordMaxAgeSet(seconds_);
    }

    /// @dev address(0) disables route changes until a registrar is named again.
    ///      evm-lows2 (evm-lows-r1 L-1): a co-signer (the co-sign API's hot key) is never the registrar (CoSignerRefused).
    function setRegistrar(address registrar_) external onlyOwner {
        if (isCoSigner(registrar_)) revert CoSignerRefused(registrar_);
        registrar = registrar_;
        emit RegistrarSet(registrar_);
    }

    /// @notice What a recording hook (PangeaFeeHookV2) answers to `RECORD_GAS()`.
    uint256 public constant RECORDING_HOOK_GAS = 250_000;

    /// @dev V2 means a RECORDING hook (its swaps record the official pool's price, spec §5.2), so
    ///      the hook must say so itself: `RECORD_GAS()` answers 250,000 (round-2 audit Info: a
    ///      non-recording hook marked V2 by mistake would bring back the same-transaction pump, H-2).
    function setHookKind(address hook, HookKind kind) external onlyOwner {
        if (hook == address(0)) revert ZeroAddress();
        if (kind == HookKind.V2) {
            (bool ok, bytes memory ret) = hook.staticcall{gas: 10_000}(abi.encodeWithSignature("RECORD_GAS()"));
            if (!ok || ret.length != 32 || abi.decode(ret, (uint256)) != RECORDING_HOOK_GAS) revert NotRecordingHook(hook);
        }
        hookKind[hook] = kind;
        emit HookKindSet(hook, kind);
    }

    function setFactory(address factory, bool listed) external onlyOwner {
        if (factory == address(0)) revert ZeroAddress();
        isFactory[factory] = listed;
        emit FactorySet(factory, listed);
    }

    // ------------------------------------------------------------------ registrar

    function setRoute(address quote, Hop[] calldata hops) external {
        if (msg.sender != registrar || msg.sender == address(0)) revert NotRegistrar();
        uint256 n = hops.length;
        if (n == 0 || n > 2 || hops[0].tokenIn != quote) revert BadRoute();
        for (uint256 i; i < n; i++) {
            Hop calldata h = hops[i];
            if (!isReader[h.reader] || h.gasCap == 0 || h.gasCap > GapMath.MAX_HOP_GAS) revert BadRoute();
            if (i > 0 && hops[i - 1].tokenOut != h.tokenIn) revert BadRoute();
        }
        if (!isStable[hops[n - 1].tokenOut]) revert BadRoute();

        delete _routes[quote];
        Hop[] storage r = _routes[quote];
        for (uint256 i; i < n; i++) {
            r.push(hops[i]);
        }
        emit RouteSet(quote, hops);
    }

    function clearRoute(address quote) external {
        if (msg.sender != registrar || msg.sender == address(0)) revert NotRegistrar();
        delete _routes[quote];
        emit RouteCleared(quote);
    }

    // ------------------------------------------------------------------ listed factory

    function setOfficialPool(address token, OfficialPool calldata pool) external {
        if (!isFactory[msg.sender]) revert NotListedFactory();
        if (token == address(0)) revert ZeroAddress();
        if (pool.poolId == bytes32(0)) revert ZeroPoolId();
        if (_pools[token].poolId != bytes32(0)) revert PoolAlreadySet(token);
        if (!quotePricable(pool.quote)) revert QuoteNotPricable(pool.quote);
        // v3c-evm-final: the pool's hook must be a listed kind (V1 or V2): a NONE hook could never
        // price (every send refused, every receive held). The listing factory is ours (isFactory), so
        // no own-launch-record check is made here (an attack would need our own keys: accepted).
        if (hookKind[pool.hook] == HookKind.NONE) revert HookNotListed(pool.hook);
        // AMENDMENT 5 (audit r1 L-1): the margin's depth is this position's liquidity, so a pool
        // listed without a readable locked position would hold every receive and refuse every send
        // for good. Refused up front instead: the factory must answer locker() and its locker
        // positionKey(poolId), and the position must already hold liquidity (the venue seeds the
        // locker before it lists the pool, in the same transaction).
        bytes32 key = _lockedPosition(pool.poolId);
        if (key == bytes32(0)) revert NoLockedPosition(token);
        if (_positionLiquidity(pool.poolId, key) == 0) revert NoLockedLiquidity(token);
        _pools[token] = pool;
        _positions[token] = key;
        emit OfficialPoolSet(token, msg.sender, pool);
    }

    // ------------------------------------------------------------------ views

    /// @notice 1 for a stable (automatically); else the admin class (2..255); 0 none.
    function quoteClass(address quote) external view returns (uint8) {
        if (isStable[quote]) return 1;
        return _quoteClass[quote];
    }

    /// @dev AMENDMENT 5 (audit r1 L-2): both sides value the locked depth in USD, so a quote needs a
    ///      USD price whatever its class: a stable, or a route ending in a stable through listed
    ///      readers. A class alone (no route) is not enough: every send would revert
    ///      GapSourceUnreadable (no depth) and every receive would hold.
    function quotePricable(address quote) public view returns (bool) {
        if (isStable[quote]) return true;
        Hop[] storage hs = _routes[quote];
        uint256 n = hs.length;
        if (n == 0 || !isStable[hs[n - 1].tokenOut]) return false;
        for (uint256 i; i < n; i++) {
            if (!isReader[hs[i].reader]) return false;
        }
        return true;
    }

    function route(address quote) external view returns (Hop[] memory) {
        return _routes[quote];
    }

    /// @inheritdoc IPangeaGapRegistry
    function gasCover() external view returns (GasCover memory) {
        return _gasCover;
    }

    /// @inheritdoc IPangeaGapRegistry
    function officialPosition(address token) external view returns (bytes32) {
        return _positions[token];
    }

    /// @dev The listing factory's locker (`locker()`) and its position key for `poolId`
    ///      (`positionKey(bytes32)`, LiquidityLocker), each under a gas cap; 0 when either does not
    ///      answer (setOfficialPool then refuses the pool: NoLockedPosition).
    function _lockedPosition(bytes32 poolId) internal view returns (bytes32 key) {
        (bool ok, bytes memory r) = msg.sender.staticcall{gas: 20_000}(abi.encodeWithSignature("locker()"));
        if (!ok || r.length != 32) return 0;
        address lk = abi.decode(r, (address));
        if (lk.code.length == 0) return 0;
        (ok, r) = lk.staticcall{gas: 30_000}(abi.encodeWithSignature("positionKey(bytes32)", poolId));
        if (!ok || r.length != 32) return 0;
        key = abi.decode(r, (bytes32));
    }

    /// @dev v4's `pools` mapping slot (StateLibrary.POOLS_SLOT) and Pool.State's positions offset,
    ///      as the token's module reads the same position (PangeaOFTV3GapModule._positionLiquidity).
    uint256 internal constant POOLS_SLOT = 6;
    uint256 internal constant POSITIONS_OFFSET = 6;

    /// @dev v4 `pools[poolId].positions[key].liquidity` by extsload on this registry's PoolManager
    ///      (StateLibrary.getPositionLiquidity); 0 when the read fails.
    function _positionLiquidity(bytes32 poolId, bytes32 key) internal view returns (uint128 liq) {
        bytes32 slot = keccak256(abi.encodePacked(key, bytes32(uint256(keccak256(abi.encodePacked(poolId, POOLS_SLOT))) + POSITIONS_OFFSET)));
        (bool ok, bytes memory r) = poolManager.staticcall(abi.encodeWithSignature("extsload(bytes32)", slot));
        if (!ok || r.length != 32) return 0;
        liq = uint128(uint256(abi.decode(r, (bytes32))));
    }

    function hasOfficialPool(address token) external view returns (bool) {
        return _pools[token].poolId != bytes32(0);
    }

    function officialPool(address token) external view returns (bool set, OfficialPool memory pool) {
        pool = _pools[token];
        set = pool.poolId != bytes32(0);
    }

    /// @notice USD per whole `quote`, 1e18 (spec §5.2). A stable is exactly 1e18. Otherwise the
    ///         route: rounded up (`roundUp`, the source) as mulUp over srcFactor(each hop), rounded
    ///         down (the destination) as mulDown over each hop. 0 on any failure, including a
    ///         route whose reader has since been removed or whose last token is no longer a stable.
    ///         Reverts only with GapGasTooLow.
    function usdPerQuoteE18(address quote, bool roundUp) external view returns (uint256) {
        (uint256 down, uint256 up,) = _usd(quote, roundUp, !roundUp);
        return roundUp ? up : down;
    }

    /// @inheritdoc IPangeaGapRegistry
    function usdPerQuoteBothE18(address quote) external view returns (uint256 down, uint256 up) {
        (down, up,) = _usd(quote, true, true);
    }

    /// @inheritdoc IPangeaGapRegistry
    function usdPerQuoteBothNativeE18(address quote) external view returns (uint256 down, uint256 up, uint256 nativeDown) {
        uint256 lastHop;
        (down, up, lastHop) = _usd(quote, true, true);
        if (down == 0) return (down, up, 0);
        if (quote == address(0)) return (down, up, down);
        // quote -> native -> stable whose second hop IS the native route (one hop): that hop's price,
        // read once, is the native route rounded down (a 1-hop route's down is its hop as read).
        Hop[] storage hs = _routes[quote];
        Hop[] storage nr = _routes[address(0)];
        if (hs.length != 2 || nr.length != 1 || hs[1].tokenIn != address(0)) return (down, up, 0);
        Hop memory a = hs[1];
        Hop memory b = nr[0];
        if (a.reader != b.reader || a.poolRef != b.poolRef || a.tokenOut != b.tokenOut || a.gasCap != b.gasCap) {
            return (down, up, 0);
        }
        nativeDown = lastHop;
    }

    /// @dev The route's USD per whole `quote`, each hop read ONCE: `down` = mulDown over each hop as
    ///      read, `up` = mulUp over srcFactor(each hop) (only the ones asked for are computed). Each
    ///      0 on its own failure; both 0 when a hop does not read.
    function _usd(address quote, bool wantUp, bool wantDown) internal view returns (uint256 down, uint256 up, uint256 last) {
        if (isStable[quote]) return (GapMath.E18, GapMath.E18, GapMath.E18);
        Hop[] storage hs = _routes[quote];
        uint256 n = hs.length;
        if (n == 0 || !isStable[hs[n - 1].tokenOut]) return (0, 0, 0);
        for (uint256 i; i < n; i++) {
            Hop memory h = hs[i];
            if (!isReader[h.reader]) return (0, 0, 0);
            uint256 p = _readHop(h);
            if (p == 0) return (0, 0, 0);
            last = p;
            if (wantUp && (i == 0 || up != 0)) {
                uint256 f = GapMath.srcFactor(p);
                up = i == 0 ? f : GapMath.mulUp(up, f);
            }
            if (wantDown && (i == 0 || down != 0)) {
                down = i == 0 ? p : GapMath.mulDown(down, p);
            }
            if (up == 0 && down == 0) return (0, 0, 0);
        }
    }

    /// @notice The official pool's fee, ppm: GapMath.evmPoolFeePpm(hook fee bps, lpFee). Not ok on
    ///         no pool, HookKind.NONE, or a failed hook read (a revert, the wrong return size, an
    ///         unregistered V1 pool, a value above uint16). The V2 hook is read through `feeOf`, so
    ///         a pending fee change counts from its first block. Reverts only with GapGasTooLow.
    function poolFeePpm(address token) external view returns (bool ok, uint32 ppm) {
        OfficialPool memory p = _pools[token];
        if (p.poolId == bytes32(0)) return (false, 0);
        HookKind kind = hookKind[p.hook];
        if (kind == HookKind.NONE) return (false, 0);
        uint256 bps;
        if (kind == HookKind.V1) {
            // configs(PoolId) -> (splitter, quoteIsCurrency0, feeBps, registered, edgeTick)
            (bool r, uint256 w2, uint256 w3) = _readHook(p.hook, abi.encodeWithSelector(V1_CONFIGS, p.poolId), 160, 2, 3);
            if (!r || w3 != 1) return (false, 0);
            bps = w2;
        } else {
            // feeOf(PoolId) -> uint16; reverts for an unregistered pool
            (bool r, uint256 w0,) = _readHook(p.hook, abi.encodeWithSelector(V2_FEE_OF, p.poolId), 32, 0, 0);
            if (!r) return (false, 0);
            bps = w0;
        }
        if (bps > type(uint16).max) return (false, 0);
        return GapMath.evmPoolFeePpm(uint16(bps), p.lpFee);
    }

    // ------------------------------------------------------------------ reads

    bytes4 internal constant V1_CONFIGS = 0xce8f6078; // configs(bytes32)
    bytes4 internal constant V2_FEE_OF = 0x430062bd; // feeOf(bytes32)

    /// @dev One hop: `staticcall{gas: gasCap}`; the answer only if the call succeeded, returned
    ///      exactly 32 bytes and is in [1, PRICE_MAX]; 0 otherwise. Return data is never copied
    ///      beyond 32 bytes, so a reader cannot make the caller pay for a large answer.
    function _readHop(Hop memory h) internal view returns (uint256 v) {
        uint256 cap = h.gasCap;
        _requireGas(cap);
        bytes memory cd = abi.encodeCall(IGapReader.priceE18, (h.poolRef, h.tokenIn, h.tokenOut));
        address reader = h.reader;
        bool ok;
        uint256 size;
        assembly ("memory-safe") {
            ok := staticcall(cap, reader, add(cd, 32), mload(cd), 0, 0)
            size := returndatasize()
            if and(ok, eq(size, 32)) {
                returndatacopy(0, 0, 32)
                v := mload(0)
            }
        }
        if (!ok || size != 32 || v > GapMath.PRICE_MAX) return 0;
    }

    /// @dev A hook read under HOOK_READ_GAS: ok only if it succeeded and returned exactly `size`
    ///      bytes; then words `a` and `b` of the answer.
    function _readHook(address hook, bytes memory cd, uint256 size, uint256 a, uint256 b)
        internal
        view
        returns (bool ok, uint256 wa, uint256 wb)
    {
        uint256 cap = HOOK_READ_GAS;
        _requireGas(cap);
        uint256 got;
        assembly ("memory-safe") {
            ok := staticcall(cap, hook, add(cd, 32), mload(cd), 0, 0)
            got := returndatasize()
            if and(ok, eq(got, size)) {
                let m := mload(0x40)
                returndatacopy(m, 0, size)
                wa := mload(add(m, mul(a, 32)))
                wb := mload(add(m, mul(b, 32)))
            }
        }
        ok = ok && got == size;
    }

    /// @dev Spec §6.2: enough gas for the whole cap of the next call, or revert (retriable).
    function _requireGas(uint256 cap) internal view {
        uint256 needed = cap * 64 / 63 + GapMath.HOP_GAS_RESERVE;
        uint256 left = gasleft();
        if (left < needed) revert GapGasTooLow(needed, left);
    }
}

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/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

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

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

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

lib/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/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

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

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

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/v3/gap/GapCoverLib.sol

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

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

/// @title GapCoverLib -- AMENDMENT 6: the gas cover in the gap fee's allowance (EVM)
/// @notice The arb's real gas on both legs is part of the allowance, so the arb nets about the margin and
///         never less for its gas: the SOURCE counts its own send and one swap at its block's basefee and
///         carries it in the header (offset 90 srcGasMicroUsd, offset 94 srcCoverCapCents); the DESTINATION adds its
///         own swap at its block's basefee and turns the whole into ppm of the value (`coverPpm`), the
///         8th input of GapMath.gapFee. A route (source token, dstEid) is covered AT MOST ONCE per window
///         (lead decision 1: splitting cannot farm the swap cover).
///         Same functions, same vectors as script/gap/gap-math.mjs (`gasCover` in
///         test/fixtures/gap-vectors.json) and the Solana port. Every step rounds DOWN (a smaller cover
///         is a larger fee). Never fee 0 and never over-allowing on an unreadable input: the source
///         refuses (GapSourceUnreadable), the destination holds (DST_PRICE_FAILED, retriable); a cap,
///         units or a counted basefee of 0 count 0 (less allowance, never more).
/// @dev All pure. The module reads the registry (`gasCover()`, `marginPpm()`, the native route rounded
///      down) and its own `lastCoverWindowP1[dstEid]`, and passes them in; nothing here reads state.
///
///      SOURCE (send and gapSendQuote), after the pool / price / LayerZero reads:
///          (bool needUsd) = GapCoverLib.sourceNeedsNativePrice(c, block.basefee, block.timestamp, last);
///          (usdPerNative is the same native route read the LayerZero cost uses, rounded down)
///          GapCoverLib.Source memory s = GapCoverLib.sourceCover(c, block.basefee, block.timestamp, last, usdPerNative);
///          if (s.refuse) revert GapSourceUnreadable();
///          q.srcGasMicroUsd = s.srcGasMicroUsd; q.srcCoverCapCents = s.srcCoverCapCents;
///          send only (never the quote): if (s.carried) lastCoverWindowP1[dstEid] = s.lastCoverWindowP1;
///
///      DESTINATION (receive and gapPreview), at rule 6, after Pd:
///          GapCoverLib.In memory a = GapCoverLib.In(amountLD, ps, pd, h.psE18, feeSrc, feeDst, b, marginPpm,
///              TOKEN_DECIMALS, h.srcGasMicroUsd, h.srcCoverCapCents);
///          (GapCoverLib.Priced memory r0, bool needUsd) = GapCoverLib.priceStep(a, c, block.basefee);
///          uint256 usd = needUsd ? <native route rounded down, under NATIVE_ROUTE_MIN_GAS> : 0;
///          GapCoverLib.Priced memory r = GapCoverLib.priceFinish(r0, a, c, block.basefee, usd);
///          if (r.holds) revert GapUnreadable(r.reason);   // DST_PRICE_FAILED
library GapCoverLib {
    // ---------------------------------------------------------------- settings (registry setGasCover)

    /// @notice The registry's bounds (AMENDMENT 6 §2, lead decisions): units at most 2,000,000 / 4,000,000,
    ///         floor <= 1 gwei, cap <= 1,000 gwei, floor <= cap when the cap is set, cover cap <= $200,
    ///         window 12..=86,400 s. (gap-math.mjs checkEvmGasCover == null.)
    function validGasCover(IPangeaGapRegistry.GasCover memory c) internal pure returns (bool) {
        if (c.coverWindowSeconds < GapMath.COVER_WINDOW_SECONDS_MIN || c.coverWindowSeconds > GapMath.COVER_WINDOW_SECONDS_MAX) {
            return false;
        }
        if (c.swapUnits > GapMath.SWAP_GAS_UNITS_MAX || c.sendUnits > GapMath.SEND_GAS_UNITS_MAX) return false;
        if (c.baseFeeFloorWei > GapMath.BASEFEE_FLOOR_MAX_WEI || c.baseFeeCapWei > GapMath.BASEFEE_CAP_MAX_WEI) return false;
        if (c.baseFeeCapWei != 0 && c.baseFeeFloorWei > c.baseFeeCapWei) return false;
        if (c.coverCapCents > GapMath.COVER_CAP_MAX_CENTS) return false;
        return true;
    }

    // ---------------------------------------------------------------- EVM gas in USD

    /// @notice The basefee counted: min(max(baseFeeWei, floor), cap); cap 0 (unset) -> 0 (no cover).
    function effectiveBaseFee(uint256 baseFeeWei, uint64 floorWei, uint64 capWei) internal pure returns (uint256) {
        if (capWei == 0) return 0;
        uint256 b = baseFeeWei > floorWei ? baseFeeWei : floorWei;
        return b > capWei ? capWei : b;
    }

    /// @notice Whether evmGasUsdE18 needs the native price: units != 0 and the counted basefee != 0.
    function needsNativePrice(uint256 baseFeeWei, uint64 floorWei, uint64 capWei, uint64 units) internal pure returns (bool) {
        return units != 0 && effectiveBaseFee(baseFeeWei, floorWei, capWei) != 0;
    }

    /// @notice EVM gas in USD 1e18, rounded DOWN: floor(effectiveBaseFee * units * usdPerNative / 1e18) (the
    ///         native has 18 decimals on every EVM chain we run). 0 without the price when units or the
    ///         counted basefee is 0; `ok == false` when the price is needed and is 0 or above PRICE_MAX.
    /// @dev b <= 2^64 and units < 2^64: b * units < 2^128, and the product with usd is a 512-bit mulDiv
    ///      whose result fits (< 2^256 / 1e18): never overflows.
    function evmGasUsdE18(uint256 baseFeeWei, uint64 floorWei, uint64 capWei, uint64 units, uint256 usdPerNativeE18)
        internal
        pure
        returns (bool ok, uint256 gasUsdE18)
    {
        if (units == 0) return (true, 0);
        uint256 b = effectiveBaseFee(baseFeeWei, floorWei, capWei);
        if (b == 0) return (true, 0);
        if (usdPerNativeE18 == 0 || usdPerNativeE18 > GapMath.PRICE_MAX) return (false, 0);
        return (true, Math.mulDiv(b * uint256(units), usdPerNativeE18, GapMath.E18));
    }

    // ---------------------------------------------------------------- the cover window (lead decision 1)

    /// @notice w = floor(timestamp / coverWindowSeconds). The registry keeps the window in 12..=86,400; a 0
    ///         (no registry answer) is never divided by: sourceCover treats it as "no cover".
    function coverWindowIndex(uint256 timestamp, uint32 coverWindowSeconds) internal pure returns (uint64) {
        return uint64(timestamp / coverWindowSeconds);
    }

    /// @notice A route's cover is granted unless it was already carried in window w (state = w + 1).
    function coverGranted(uint64 lastCoverWindowP1, uint64 windowIndex) internal pure returns (bool) {
        return lastCoverWindowP1 != windowIndex + 1;
    }

    // ---------------------------------------------------------------- the source (send)

    /// @notice The header fields (gap-math.mjs sourceGasFields) for a send that is (or is not) granted its
    ///         window's cover. capC = min(coverCapCents, 20,000); capC 0 or not granted -> (0, 0), nothing
    ///         read, not carried. Else gasUsd = evmGasUsdE18(basefee, floor, cap, swapUnits + sendUnits,
    ///         usdPerNative rounded down); unreadable -> refuse (GapSourceUnreadable, nothing written);
    ///         srcGasMicroUsd = min(floor(gasUsd / 1e12), capC * 1e4); carried.
    function sourceFields(IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei, bool granted, uint256 usdPerNativeE18)
        internal
        pure
        returns (bool refuse, uint32 srcGasMicroUsd, uint16 srcCoverCapCents, bool carried)
    {
        uint16 capC = c.coverCapCents > GapMath.COVER_CAP_MAX_CENTS ? GapMath.COVER_CAP_MAX_CENTS : c.coverCapCents;
        if (capC == 0 || !granted) return (false, 0, 0, false);
        (bool ok, uint256 gas) =
            evmGasUsdE18(baseFeeWei, c.baseFeeFloorWei, c.baseFeeCapWei, uint64(c.swapUnits) + c.sendUnits, usdPerNativeE18);
        if (!ok) return (true, 0, 0, false);
        uint256 micro = gas / GapMath.MICRO_USD_E18;
        uint256 capMicro = uint256(capC) * 10_000; // <= 200,000,000 < 2^32
        return (false, uint32(micro > capMicro ? capMicro : micro), capC, true);
    }

    /// @notice What a send from this chain carries, given the route's window state.
    struct Source {
        /// the send must revert GapSourceUnreadable (a needed native price is unreadable); nothing is written
        bool refuse;
        uint32 srcGasMicroUsd;
        uint16 srcCoverCapCents;
        /// the send carries a cover: it stores lastCoverWindowP1[dstEid] = lastCoverWindowP1 (below)
        bool carried;
        /// the state after this send (= the input unless carried; then the window index + 1)
        uint64 lastCoverWindowP1;
    }

    /// @notice The whole source step: window, grant, fields. `lastCoverWindowP1` is the token's
    ///         lastCoverWindowP1[dstEid] (0 = never covered). The send stores `s.lastCoverWindowP1` when
    ///         `s.carried`; gapSendQuote stores nothing (it answers what the next send in this block carries).
    ///         A window of 0 seconds (a registry that did not answer) gives no cover.
    function sourceCover(
        IPangeaGapRegistry.GasCover memory c,
        uint256 baseFeeWei,
        uint256 timestamp,
        uint64 lastCoverWindowP1,
        uint256 usdPerNativeE18
    ) internal pure returns (Source memory s) {
        s.lastCoverWindowP1 = lastCoverWindowP1;
        if (c.coverCapCents == 0 || c.coverWindowSeconds == 0) return s;
        uint64 w = coverWindowIndex(timestamp, c.coverWindowSeconds);
        (s.refuse, s.srcGasMicroUsd, s.srcCoverCapCents, s.carried) =
            sourceFields(c, baseFeeWei, coverGranted(lastCoverWindowP1, w), usdPerNativeE18);
        if (s.carried) s.lastCoverWindowP1 = w + 1;
    }

    /// @notice Whether sourceCover will need the native price (so a module that reads it only for the
    ///         cover can skip the read). The LayerZero cost reads the same route whenever its fee is non-zero.
    function sourceNeedsNativePrice(IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei, uint256 timestamp, uint64 lastCoverWindowP1)
        internal
        pure
        returns (bool)
    {
        if (c.coverCapCents == 0 || c.coverWindowSeconds == 0) return false;
        if (!coverGranted(lastCoverWindowP1, coverWindowIndex(timestamp, c.coverWindowSeconds))) return false;
        return needsNativePrice(baseFeeWei, c.baseFeeFloorWei, c.baseFeeCapWei, uint64(c.swapUnits) + c.sendUnits);
    }

    // ---------------------------------------------------------------- the destination (receive)

    /// @notice The destination's own part: its swap only, at its block's basefee (gap-math.mjs
    ///         destinationGasUsdE18). `ok == false`: needed and unreadable (the receive holds).
    function destinationGasUsdE18(IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei, uint256 usdPerNativeE18)
        internal
        pure
        returns (bool ok, uint256 gasUsdE18)
    {
        return evmGasUsdE18(baseFeeWei, c.baseFeeFloorWei, c.baseFeeCapWei, c.swapUnits, usdPerNativeE18);
    }

    /// @notice The gas cover as ppm of the gross amount at the SOURCE price (gap-math.mjs gasCoverPpm):
    ///             capUsd   = min(srcCoverCapCents, dstCoverCapCents, 20,000) * 1e16
    ///             coverUsd = min(srcGasMicroUsd * 1e12 + dstGasUsd, capUsd)
    ///             coverLD  = floor(coverUsd * 10^tokenDecimals / psUsd)
    ///             coverPpm = min(2^32 - 1, floor(coverLD * (1e6 - b') / amountLD)),  b' = b < 1e6 ? b : 0
    ///         0 when coverUsd, psUsd or amountLD is 0 (or tokenDecimals > 36). No 1e6 cap. Never reverts.
    function coverPpm(
        uint32 srcGasMicroUsd,
        uint16 srcCoverCapCents,
        uint256 dstGasUsdE18,
        uint16 dstCoverCapCents,
        uint256 psUsdE18,
        uint8 tokenDecimals,
        uint256 amountLD,
        uint32 bridgeFeePpm
    ) internal pure returns (uint32 ppm, uint256 coverUsdE18) {
        uint256 capC = srcCoverCapCents < dstCoverCapCents ? srcCoverCapCents : dstCoverCapCents;
        if (capC > GapMath.COVER_CAP_MAX_CENTS) capC = GapMath.COVER_CAP_MAX_CENTS;
        uint256 capUsd = capC * GapMath.CENT_E18;
        uint256 src = uint256(srcGasMicroUsd) * GapMath.MICRO_USD_E18;
        // min(src + dst, cap) without overflow whatever dstGasUsdE18 is
        coverUsdE18 = (src >= capUsd || dstGasUsdE18 >= capUsd - src) ? capUsd : src + dstGasUsdE18;
        if (coverUsdE18 == 0 || psUsdE18 == 0 || amountLD == 0 || tokenDecimals > 36) return (0, 0);
        // coverUsd <= 2e20, 10^tokenDecimals <= 1e36: the product fits; Ps >= 1.
        uint256 coverLD = Math.mulDiv(coverUsdE18, 10 ** tokenDecimals, psUsdE18);
        uint256 den = bridgeFeePpm < GapMath.PPM ? GapMath.PPM - bridgeFeePpm : GapMath.PPM;
        uint256 v = Math.mulDiv(coverLD, den, amountLD); // coverLD <= 2e56: coverLD * den fits
        ppm = v > type(uint32).max ? type(uint32).max : uint32(v);
    }

    /// @notice The destination's priced step's inputs. `psE18`/`pdE18` are the pair the formula compares
    ///         (GapMath.pickPair); `psUsdE18` is the HEADER's psUsd whatever the pair (the cover is USD).
    struct In {
        uint256 amountLD;
        uint128 psE18;
        uint256 pdE18;
        uint128 psUsdE18;
        uint32 feeSrcPpm;
        uint32 feeDstPpm;
        uint32 bridgeFeePpm;
        uint32 marginPpm;
        uint8 tokenDecimals;
        uint32 srcGasMicroUsd;
        uint16 srcCoverCapCents;
    }

    /// @notice The priced step's outcome (gap-math.mjs gapPriced). `holds`: revert GapUnreadable(reason)
    ///         (DST_PRICE_FAILED), the rest 0. `nativeRead`: the destination's native price was needed.
    struct Priced {
        uint256 withheld;
        uint32 gapPpm;
        uint64 allowPpm;
        uint8 reason;
        bool holds;
        uint32 coverPpm;
        uint256 coverUsdE18;
        uint256 dstGasUsdE18;
        bool nativeRead;
    }

    /// @notice Step 1 (no read): r0 = gapFee(..., margin, cover 0). `needsNativePrice` is true only when the
    ///         cover can change the outcome AND the destination's own part needs a price: r0 CHARGED, the
    ///         header's srcCoverCapCents != 0, min(src, dst cap) != 0, swapUnits != 0 and the counted
    ///         basefee != 0. NO_GAP / WITHIN_ALLOWANCE never read and never hold for it.
    function priceStep(In memory a, IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei)
        internal
        pure
        returns (Priced memory r0, bool needsNative)
    {
        (r0.withheld, r0.gapPpm, r0.allowPpm, r0.reason) =
            GapMath.gapFee(a.amountLD, a.psE18, a.pdE18, a.feeSrcPpm, a.feeDstPpm, a.bridgeFeePpm, a.marginPpm, 0);
        needsNative = _coverApplies(r0, a, c.coverCapCents)
            && needsNativePrice(baseFeeWei, c.baseFeeFloorWei, c.baseFeeCapWei, c.swapUnits);
    }

    /// @notice Step 2: the cover, given the native price (0 when step 1 said it is not needed). Returns r0
    ///         unchanged when the cover cannot apply; HOLDS (DST_PRICE_FAILED) when the price was needed and
    ///         is 0 / above PRICE_MAX; else gapFee(..., margin, coverPpm).
    function priceFinish(Priced memory r0, In memory a, IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei, uint256 usdPerNativeE18)
        internal
        pure
        returns (Priced memory)
    {
        if (!_coverApplies(r0, a, c.coverCapCents)) return r0;
        (bool ok, uint256 dstGas) = destinationGasUsdE18(c, baseFeeWei, usdPerNativeE18);
        return priceWithDestinationGas(r0, a, c.coverCapCents, ok, dstGas, needsNativePrice(baseFeeWei, c.baseFeeFloorWei, c.baseFeeCapWei, c.swapUnits));
    }

    /// @notice Step 2 for any destination kind, given its own gas (EVM: destinationGasUsdE18; the Solana
    ///         port's lamports x SOL/USD): `dstGasOk == false` holds. Returns r0 when the cover cannot apply.
    function priceWithDestinationGas(
        Priced memory r0,
        In memory a,
        uint16 dstCoverCapCents,
        bool dstGasOk,
        uint256 dstGasUsdE18,
        bool nativeRead
    ) internal pure returns (Priced memory r) {
        if (!_coverApplies(r0, a, dstCoverCapCents)) return r0;
        if (!dstGasOk) {
            r.reason = GapMath.DST_PRICE_FAILED;
            r.holds = true;
            r.nativeRead = true;
            return r;
        }
        (r.coverPpm, r.coverUsdE18) = coverPpm(
            a.srcGasMicroUsd, a.srcCoverCapCents, dstGasUsdE18, dstCoverCapCents, a.psUsdE18, a.tokenDecimals, a.amountLD, a.bridgeFeePpm
        );
        (r.withheld, r.gapPpm, r.allowPpm, r.reason) =
            GapMath.gapFee(a.amountLD, a.psE18, a.pdE18, a.feeSrcPpm, a.feeDstPpm, a.bridgeFeePpm, a.marginPpm, r.coverPpm);
        r.dstGasUsdE18 = dstGasUsdE18;
        r.nativeRead = nativeRead;
    }

    /// @notice Both steps, for a caller that already holds the native price (tests, views).
    function priced(In memory a, IPangeaGapRegistry.GasCover memory c, uint256 baseFeeWei, uint256 usdPerNativeE18)
        internal
        pure
        returns (Priced memory)
    {
        (Priced memory r0,) = priceStep(a, c, baseFeeWei);
        return priceFinish(r0, a, c, baseFeeWei, usdPerNativeE18);
    }

    /// @dev The cover can change the outcome: r0 CHARGED, the header carries a cap (lead decision 1: the
    ///      destination adds its own swap only then) and min(src cap, dst cap, max) != 0.
    function _coverApplies(Priced memory r0, In memory a, uint16 dstCoverCapCents) private pure returns (bool) {
        return r0.reason == GapMath.CHARGED && a.srcCoverCapCents != 0 && dstCoverCapCents != 0;
    }
}

src/v3/gap/GapMath.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

    error GapMsgTooShort(uint256 length);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/v3/gap/GapPriceLog.sol

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

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

/// @title GapPriceLog -- the hook-independent EVM price log of a v3 token (v3c-evm-log, owner
///        2026-10-30; docs/v3c-gap-spec.md §9), the EVM twin of the Solana PriceLog
/// @notice A ring of ENTRIES per-second entries of the official pool's price, written by anyone
///         who pokes (and by every v3 send, and by the listing factory after the launch buys), and
///         CONSUMED by sends and receives: each entry prices at most k x D of flow, D the pool's
///         LOCKED launch liquidity. The token prices a V1-hook official pool (the live
///         PangeaFeeHook, which records nothing) from this log only.
///
/// ENTRY i (three words of `logRing`, all prices the official pool's sqrtPriceX96, and a lane of
/// `logCaps`):
///   A = key uint40 [0,40) | lo uint160 [40,200) | fee uint20 [200,220) | [220,256) zero
///   B = hi uint160 [0,160) | owed uint96 [160,256)
///   C = writer address [0,160)
///   cap uint40 = logCaps[i / 6] bits [(i % 6) * 40, (i % 6) * 40 + 40)
///   (E6, audit E5 M-A: the caps are packed six a word, so a consumption of the whole ring
///   writes at most CAP_WORDS words, not one per entry; the values and every rule are unchanged.)
///   key: block.timestamp of the write (seconds; on every chain, so Robinhood's L1 block.number
///   never matters and same-second blocks share one entry). lo / hi: the sqrt of the LOWEST /
///   HIGHEST TOKEN price written in that second (for a token that is currency1 the lowest token
///   price is the highest sqrt). fee: the official pool fee (ppm) read at the write (the lowest of
///   the second's writes). cap: capacity consumed, pico (1e-12) of the locked depth. owed: the
///   writer reward (token units) the entry earned and has not paid. writer: the first writer of
///   the second (0 = no reward, the factory's seed).
///
/// THE WINDOW: entries with key in [now - W, now - 1]. The current second never counts.
///
/// THE MERGE RULE (as Solana's): a write for a NEW second into a FULL ring looks at the oldest
/// entry O. O.key < now - W (outside the window), or merge off: O is dropped. Otherwise O and the
/// next-oldest N become one entry at N's place: key = N's, lo = the lower token price of both, hi
/// = the higher, fee = the lower, cap and writer = N's; O's owed goes to N when N has the same
/// writer, else to writerOwed[O.writer]. The write then takes O's place. Any dropped entry's owed
/// goes to writerOwed[its writer].
///
/// CONSUMPTION (`plan`), NEWEST FIRST, never the current second (owner-approved design, 2026-10-31,
/// audit R2 I-1: an earlier doc said oldest first; the code was and is newest first). A send / receive
/// is priced from the live price and the entries it CONSUMES only -- never from an entry it does not
/// consume (except `cons`, below):
///   1. dLo = the LOWEST token price (lo) of EVERY window entry (D's price: never a single entry's).
///   2. walk the window entries newest first, skipping those with no unused capacity
///      (capacity = kPpm(entry) x 1e6 pico, kPpm = kFlatPpm (mode 0) or
///      max(floor(min(entry fee, fee now, platform floor) x kFactorPpm / 1e6), K_PPM_MIN) (mode 1;
///      0 when a fee is 0, unreadable), both at most K_PPM_MAX -- E6, the Solana rule exactly);
///      P starts at the live price (E5 audit H-1); after each, P = send: the lowest token price of
///      live and the consumed lo's; receive: the highest of live and the consumed hi's; once at least minBlocks entries are consumed and their unused capacity
///      reaches f = need(amountLD, P, dLo, L), stop: takes are filled newest first.
///   3. none: the send reverts GapNeedRecords (unless CO-SIGNED, below), the receive holds (retriable).
///   A send's plan also answers `cons` = the WINDOW MINIMUM, the lowest token price of the live price
///   and every window entry's lo (0 when the window holds fewer than minBlocks entries): what a
///   CO-SIGNED oversized send is priced at (e6-r2fix, owner 2026-10-30: never the current second,
///   never above live, consuming no capacity; PangeaOFTV3LogModule.gapDebit).
/// MAX SEND (`maxSend`, the token's gapMaxSend): the largest amount `plan` can price now without a
///   co-sign -- the same walk, each prefix of at least minBlocks free entries giving the exact inverse
///   of `need` at its price (`maxForFree`), the largest prefix answer winning.
///   need, pico, rounded up: S = amountLD (token raw), L = locked liquidity,
///     token currency0: f = ceil(ceil(S * 1e12 * sP / sD) * sP / (L * 2^96))
///     token currency1: f = ceil(ceil(ceil(S * 1e12 * sD / sP) * 2^96 / sP) / L)
///   (= the flow's quote value at P over the locked quote reserve at dLo), u64::MAX past 2^64-1, and
///   (e6-r2fix, audit R2 I-3) u64::MAX too when a step would pass 2^256 (an extreme price ratio over a
///   tiny L): never a Panic, so a send reverts GapNeedRecords and a receive holds NEED_RECORDS.
/// REWARD (sends only): each consumed entry with a writer earns floor(covered * rewardBps / 1e4),
///   covered = floor(amountLD * take / f), all capped at the send's bridge fee.
library GapPriceLog {
    uint256 internal constant ENTRIES = 32;
    uint256 internal constant PICO_PER_PPM = 1e6;
    /// @dev cap is 40 bits: K_PPM_MAX * 1e6 = 1e11 < 2^40 (E6: K_PPM_MAX 100,000, as Solana's).
    uint256 internal constant CAP_MAX = (1 << 40) - 1;
    /// @dev E6: the caps' packing (logCaps): CAP_LANES 40-bit lanes a word, CAP_WORDS words.
    uint256 internal constant CAP_BITS = 40;
    uint256 internal constant CAP_LANES = 6;
    uint256 internal constant CAP_WORDS = 6;
    /// @dev E6 (gas): bit 255 of every caps word a write has touched stays set, so a word is never
    ///      zero once its first entry is written and a receive's consumption is a non-zero to
    ///      non-zero store (2,900 gas), never a zero to non-zero one (20,000). Lanes never see it.
    uint256 internal constant CAP_SENTINEL = uint256(1) << 255;

    // ---- registry bounds and defaults (setLogParams)
    /// @dev E6 (lead #3, parity with Solana CAPACITY_K_MIN_PPM / CAPACITY_K_MAX_PPM): every entry's k
    ///      is in [K_PPM_MIN, K_PPM_MAX] (10% of the locked depth at most), except k_mode 1 with an
    ///      unreadable (0) fee, which gives 0. The flat k is bounded the same (setLogParams).
    uint32 internal constant K_PPM_MIN = 100;
    uint32 internal constant K_PPM_MAX = 100_000;
    uint32 internal constant K_FLAT_DEFAULT_PPM = 666; // E6: <= PLATFORM_FLOOR_DEFAULT_PPM / 3
    /// @dev E6 (lead #3, the Solana bound): k_mode 1's factor is at most 1/3 of the fee, and the flat
    ///      k at most a third of the platform floor (setLogParams), so no setting lets one planted
    ///      entry price more than a third of the platform's own take of flow (the capacity is the
    ///      only bound on a pump-poke-unpump entry; there is no capacity-off mode on EVM).
    uint32 internal constant K_FACTOR_MAX_PPM = 333_333;
    uint32 internal constant K_FACTOR_DEFAULT_PPM = 333_333;
    uint8 internal constant K_MODE_DEFAULT = 1;
    uint32 internal constant WINDOW_MIN_SEC = 2;
    uint32 internal constant WINDOW_MAX_SEC = 3_600;
    uint32 internal constant WINDOW_DEFAULT_SEC = 30;
    uint8 internal constant MIN_BLOCKS_MIN = 2;
    uint8 internal constant MIN_BLOCKS_MAX = 16;
    uint8 internal constant MIN_BLOCKS_DEFAULT = 2;
    uint16 internal constant REWARD_MAX_BPS = 20;
    uint16 internal constant REWARD_DEFAULT_BPS = 1;
    /// @dev E5 (audit M-2): k_mode 1's fee is capped at the platform's own take (ppm of volume):
    ///      a creator who is paid most of the hook fee must not buy capacity with it. [300, 2,600]
    ///      (the Solana port's bounds, lead #3), default 2,000.
    uint32 internal constant PLATFORM_FLOOR_DEFAULT_PPM = 2_000;
    uint32 internal constant PLATFORM_FLOOR_MIN_PPM = 300;
    uint32 internal constant PLATFORM_FLOOR_MAX_PPM = 2_600;

    struct Params {
        uint8 kMode;
        uint32 kFlatPpm;
        uint32 kFactorPpm;
        uint32 window;
        uint8 minBlocks;
        uint16 rewardBps;
        bool merge;
        uint32 platformFloorPpm;
    }

    /// @dev A consumption: `sqrt` the price it gives (send: the lowest token price of the live
    ///      price and the entries consumed; receive: the highest), `need` f (pico), and per consumed
    ///      entry its index and take. `cons`, the most conservative price: a receive's (E5 audit M-3) the
    ///      highest token price of the live price and EVERY window entry's hi; a send's (e6-r2fix, what
    ///      a co-signed oversized send is priced at) the lowest token price of the live price and every
    ///      window entry's lo; 0 when the live price is unknown or the window holds fewer than minBlocks
    ///      entries.
    ///      `liveCounts` (receive only, E6 audit E5 M-B): the live price is strictly DEARER than every
    ///      hi of the first minBlocks consumed entries, i.e. the walk's price when f is first computed
    ///      is the live price, so the walk (f, the entries it takes, its Pd) can depend on it. When
    ///      false the plan is exactly the plan without the live price (nothing a pump of the pool
    ///      before the receive can move).
    struct Plan {
        bool ok;
        uint160 sqrt;
        uint256 need;
        uint256 n;
        uint256[ENTRIES] idx;
        uint256[ENTRIES] take;
        uint160 cons;
        bool liveCounts;
    }

    // ------------------------------------------------------------------ packing

    function key(uint256 a) internal pure returns (uint256) {
        return a & 0xFFFFFFFFFF;
    }

    function lo(uint256 a) internal pure returns (uint160) {
        return uint160(a >> 40);
    }

    function fee(uint256 a) internal pure returns (uint32) {
        return uint32((a >> 200) & 0xFFFFF);
    }

    function packA(uint256 k, uint160 l, uint32 f) internal pure returns (uint256) {
        return (k & 0xFFFFFFFFFF) | (uint256(l) << 40) | (uint256(f & 0xFFFFF) << 200);
    }

    /// @notice Entry i's consumed capacity (pico), from its logCaps lane.
    function capOf(S.Layout storage l, uint256 i) internal view returns (uint256) {
        return (l.logCaps[i / CAP_LANES] >> ((i % CAP_LANES) * CAP_BITS)) & CAP_MAX;
    }

    /// @dev Entry i's lane of the caps word `w`.
    function _lane(uint256 w, uint256 i) private pure returns (uint256) {
        return (w >> ((i % CAP_LANES) * CAP_BITS)) & CAP_MAX;
    }

    /// @notice Add each lane of `add` (packed as logCaps: entry i's take in word i / 6, lane i % 6)
    ///         to the entries' caps, each saturating at CAP_MAX. One SSTORE per word that changes.
    function addCaps(S.Layout storage l, uint256[CAP_WORDS] memory add) internal {
        for (uint256 w; w < CAP_WORDS; w++) {
            uint256 a = add[w];
            if (a == 0) continue;
            uint256 v = l.logCaps[w];
            uint256 out = CAP_SENTINEL;
            for (uint256 k; k < CAP_LANES; k++) {
                uint256 sh = k * CAP_BITS;
                uint256 c = ((v >> sh) & CAP_MAX) + ((a >> sh) & CAP_MAX);
                if (c > CAP_MAX) c = CAP_MAX;
                out |= c << sh;
            }
            l.logCaps[w] = out;
        }
    }

    /// @notice A plan's takes packed as logCaps lanes (entry i's take in word i / 6, lane i % 6).
    ///         Takes are below 2^40 (each at most an entry's capacity, <= K_PPM_MAX * 1e6).
    function packTakes(Plan memory r) internal pure returns (uint256[CAP_WORDS] memory add) {
        for (uint256 q; q < r.n; q++) {
            uint256 t = r.take[q];
            if (t == 0) continue;
            if (t > CAP_MAX) t = CAP_MAX;
            uint256 i = r.idx[q];
            add[i / CAP_LANES] |= t << ((i % CAP_LANES) * CAP_BITS);
        }
    }

    function hi(uint256 b) internal pure returns (uint160) {
        return uint160(b);
    }

    function owed(uint256 b) internal pure returns (uint256) {
        return b >> 160;
    }

    function packB(uint160 h, uint256 o) internal pure returns (uint256) {
        if (o > type(uint96).max) o = type(uint96).max;
        return uint256(h) | (o << 160);
    }

    /// @dev `a` is a LOWER token price than `b` (sqrtPriceX96 of the pool).
    function lowerTok(uint160 a, uint160 b, bool tokenIs0) internal pure returns (bool) {
        return tokenIs0 ? a < b : a > b;
    }

    // ------------------------------------------------------------------ capacity

    /// @notice An entry's capacity, pico of the locked depth.
    ///         E5 (audit M-2): k_mode 1 is min(feeAtRecord, feeNow, platformFloorPpm) x kFactorPpm / 1e6.
    ///         E6 (lead #3, Solana's entry_k_ppm exactly): k_mode 1 is never below K_PPM_MIN, and is 0
    ///         when that fee is 0 (unreadable); both modes are capped at K_PPM_MAX.
    function capacity(Params memory p, uint32 feeAtRecord, uint32 feeNow) internal pure returns (uint256) {
        uint256 k;
        if (p.kMode == 1) {
            uint256 f = feeAtRecord < feeNow ? feeAtRecord : feeNow;
            if (p.platformFloorPpm < f) f = p.platformFloorPpm;
            if (f == 0) return 0;
            k = f * p.kFactorPpm / 1e6;
            if (k < K_PPM_MIN) k = K_PPM_MIN;
        } else {
            k = p.kFlatPpm;
        }
        if (k > K_PPM_MAX) k = K_PPM_MAX;
        return k * PICO_PER_PPM;
    }

    /// @notice f: the flow of `amountLD` at sqrt price `sP` over the locked quote reserve of
    ///         liquidity `liq` at `sD`, pico, rounded up; type(uint64).max when unusable.
    function need(uint256 amountLD, uint160 sP, uint160 sD, uint128 liq, bool tokenIs0) internal pure returns (uint256 f) {
        if (amountLD == 0) return 0;
        if (liq == 0 || sP == 0 || sD == 0) return type(uint64).max;
        uint256 x = amountLD * 1e12; // amountLD < 2^74
        bool ok;
        // e6-r2fix (audit R2 I-3): a step past 2^256 (an extreme price ratio over a tiny L) is
        // "unusable" (u64::MAX: GapNeedRecords / the NEED_RECORDS hold), never a Panic.
        if (tokenIs0) {
            (ok, x) = mulDivSat(x, sP, sD, true);
            if (ok) (ok, f) = mulDivSat(x, sP, uint256(liq) << 96, true);
        } else {
            (ok, x) = mulDivSat(x, sD, sP, true);
            if (ok) (ok, x) = mulDivSat(x, 1 << 96, sP, true);
            if (ok) f = Math.ceilDiv(x, liq);
        }
        if (!ok || f > type(uint64).max) f = type(uint64).max;
    }

    /// @notice e6-r2fix (audit R2 I-3): floor (or, `up`, ceil) of a * b / d, ok false when the result
    ///         does not fit 256 bits (Math.mulDiv would Panic). d != 0.
    function mulDivSat(uint256 a, uint256 b, uint256 d, bool up) internal pure returns (bool ok, uint256 r) {
        uint256 p0;
        uint256 p1;
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            p0 := mul(a, b)
            p1 := sub(sub(mm, p0), lt(mm, p0))
        }
        if (p1 == 0) {
            // the common case (the product fits 256 bits): one division, no second 512-bit product --
            // `need` runs this for every prefix of the walk, inside the receive's enforced gas. A
            // remainder means d >= 2, so r + 1 fits.
            assembly ("memory-safe") {
                r := div(p0, d)
                if and(up, gt(mod(p0, d), 0)) { r := add(r, 1) }
            }
            return (true, r);
        }
        if (p1 >= d) return (false, 0);
        r = Math.mulDiv(a, b, d);
        if (up && mulmod(a, b, d) != 0) {
            if (r == type(uint256).max) return (false, 0);
            r++;
        }
        ok = true;
    }

    /// @notice e6-r2fix: the largest amountLD whose `need` at (`sP`, `sD`, `liq`) is at most `free`
    ///         pico -- the exact inverse of `need` (each ceil(x / d) <= k iff x <= k x d):
    ///           token currency0: floor(floor(F * L * 2^96 / sP) * sD / sP) / 1e12
    ///           token currency1: floor(floor(F * L * sP / 2^96) * sP / sD) / 1e12
    ///         with F = min(free, 2^64 - 2) (need's u64::MAX means unusable, never a fit), capped at
    ///         MAX_SEND_LD (a uint64 amountSD x 1e3); 0 when nothing prices.
    function maxForFree(uint256 free, uint160 sP, uint160 sD, uint128 liq, bool tokenIs0) internal pure returns (uint256 s) {
        if (free >= type(uint64).max) free = type(uint64).max - 1;
        if (free == 0 || liq == 0 || sP == 0 || sD == 0) return 0;
        bool ok;
        if (tokenIs0) {
            (ok, s) = mulDivSat(free, uint256(liq) << 96, sP, false);
            if (ok) (ok, s) = mulDivSat(s, sD, sP, false);
        } else {
            (ok, s) = mulDivSat(free * liq, sP, 1 << 96, false); // free < 2^64, liq < 2^128
            if (ok) (ok, s) = mulDivSat(s, sP, sD, false);
        }
        if (!ok) return MAX_SEND_LD;
        s /= 1e12;
        if (s > MAX_SEND_LD) s = MAX_SEND_LD;
    }

    /// @dev The largest amount a send carries: a uint64 amountSD x 1e3 (the token's 9 decimals over 6 shared).
    uint256 internal constant MAX_SEND_LD = uint256(type(uint64).max) * 1e3;

    // ------------------------------------------------------------------ consumption

    /// @notice The consumption a send (`receive_` false) or a receive of `amountLD` would make
    ///         now (module doc, CONSUMPTION). Reads only. E5 (audit H-1): the price starts at
    ///         `live` (the pool's live sqrt; 0 = unknown: no plan, no `cons`), so a send's price is
    ///         min(live, consumed lo's) and a receive's max(live, consumed hi's), and `f` is computed
    ///         at that price. E5 (audit M-3): a receive also answers `cons` (Plan).
    function plan(
        S.Layout storage l,
        Params memory p,
        bool receive_,
        uint256 amountLD,
        bool tokenIs0,
        uint128 liq,
        uint32 feeNow,
        uint256 now_,
        uint160 live
    ) internal view returns (Plan memory r) {
        if (live == 0) return r;
        uint256 count = l.logCount;
        uint256 head = l.logHead;
        uint256 window = p.window;
        uint256 minBlocks = p.minBlocks;
        // pass 1: the window (newest first: keys only fall), dLo and (receive) the highest hi.
        // E6 (gas): each entry's words are read ONCE (A always, B for a receive) and kept for pass 2.
        uint256[ENTRIES] memory wa;
        uint256[ENTRIES] memory wh;
        uint256[ENTRIES] memory wi;
        uint256 m;
        uint160 dLo;
        uint160 cons = live;
        unchecked {
            // every index below ENTRIES; k, m <= count <= ENTRIES; t + window < 2^41
            for (uint256 k; k < count; k++) {
                uint256 i = (head + ENTRIES - k) % ENTRIES;
                uint256 a = l.logRing[3 * i];
                uint256 t = a & 0xFFFFFFFFFF;
                if (t >= now_) continue;
                if (t + window < now_) break;
                wa[m] = a;
                wi[m] = i;
                uint160 x = uint160(a >> 40);
                if (dLo == 0 || lowerTok(x, dLo, tokenIs0)) dLo = x;
                if (receive_) {
                    uint160 h = uint160(l.logRing[3 * i + 1]);
                    wh[m] = h;
                    if (lowerTok(cons, h, tokenIs0)) cons = h;
                }
                m++;
            }
        }
        if (m >= minBlocks) {
            // receive: max(live, every hi); send (e6-r2fix, a co-signed oversized send): min(live, every lo)
            if (receive_) r.cons = cons;
            else r.cons = lowerTok(dLo, live, tokenIs0) ? dLo : live;
        }
        // pass 2: newest first, skipping used-up entries; the price starts at the live price.
        // E6 (gas): the caps words (logCaps) are read once each, when the walk first needs one.
        uint256[ENTRIES] memory free_;
        uint256[CAP_WORDS] memory capw;
        uint256 loaded; // bit w: capw[w] read
        uint256 freeSum;
        uint160 price = live;
        uint160 firstHi; // receive: the dearest hi of the first minBlocks consumed entries
        uint256 lastNeedAt; // the price `f` was computed at (0: none)
        uint256 f = type(uint64).max;
        uint256 n;
        // E6 (gas): `capacity` with its per-plan terms hoisted (the same value for every entry:
        // min(fee at the entry, fee now, floor) is min(fee at the entry, min(fee now, floor))).
        bool feeK = p.kMode == 1;
        uint256 kFlat = p.kFlatPpm > K_PPM_MAX ? K_PPM_MAX : p.kFlatPpm;
        uint256 fNow = p.platformFloorPpm < feeNow ? p.platformFloorPpm : feeNow;
        uint256 factor = p.kFactorPpm;
        for (uint256 j; j < m; j++) {
            uint256 a = wa[j];
            uint256 c;
            unchecked {
                // fee < 2^20, factor <= 1e6: no overflow
                if (feeK) {
                    uint256 fe = (a >> 200) & 0xFFFFF;
                    if (fNow < fe) fe = fNow;
                    if (fe != 0) {
                        uint256 k = fe * factor / 1e6;
                        if (k < K_PPM_MIN) k = K_PPM_MIN;
                        if (k > K_PPM_MAX) k = K_PPM_MAX;
                        c = k * PICO_PER_PPM;
                    }
                } else {
                    c = kFlat * PICO_PER_PPM;
                }
            }
            uint256 i = wi[j];
            uint256 w = i / CAP_LANES;
            if ((loaded >> w) & 1 == 0) {
                capw[w] = l.logCaps[w];
                loaded |= uint256(1) << w;
            }
            uint256 used = _lane(capw[w], i);
            if (used >= c) continue;
            uint160 s = receive_ ? uint160(wh[j]) : lo(a);
            if (receive_ ? lowerTok(price, s, tokenIs0) : lowerTok(s, price, tokenIs0)) price = s;
            if (receive_ && n < minBlocks && (n == 0 || lowerTok(firstHi, s, tokenIs0))) firstHi = s;
            r.idx[n] = i;
            unchecked {
                // c - used <= K_PPM_MAX * 1e6; at most ENTRIES of them
                free_[n] = c - used;
                freeSum += c - used;
                n++;
            }
            if (n < minBlocks) continue;
            if (uint256(price) != lastNeedAt) {
                f = need(amountLD, price, dLo, liq, tokenIs0);
                lastNeedAt = price;
            }
            if (f != type(uint64).max && freeSum >= f) {
                uint256 left = f;
                for (uint256 q; q < n; q++) {
                    uint256 t = free_[q] < left ? free_[q] : left;
                    r.take[q] = t;
                    left -= t;
                }
                (r.ok, r.sqrt, r.need, r.n) = (true, price, f, n);
                r.liveCounts = receive_ && lowerTok(firstHi, live, tokenIs0);
                return r;
            }
        }
        r.n = 0;
    }

    /// @notice e6-r2fix (owner 2026-10-30, EVM parity of the Solana M-1 decision): the largest amountLD
    ///         a SEND can be priced for now without a co-sign (`plan(..., false, ...)` is ok for every
    ///         amount up to it, and refuses every amount above it), and dLo (the window's lowest lo; 0:
    ///         an empty window). The same two passes as `plan`; at each prefix of at least minBlocks
    ///         entries with unused capacity, `maxForFree` of its free capacity at its price (the lowest
    ///         of live and the prefix's lo's) over dLo; the largest wins. 0 when the live price is
    ///         unknown or the window holds fewer than minBlocks usable entries.
    function maxSend(S.Layout storage l, Params memory p, bool tokenIs0, uint128 liq, uint32 feeNow, uint256 now_, uint160 live)
        internal
        view
        returns (uint256 best, uint160 dLo)
    {
        if (live == 0) return (0, 0);
        uint256 count = l.logCount;
        uint256 head = l.logHead;
        uint256[ENTRIES] memory wi;
        uint256 m;
        for (uint256 k; k < count; k++) {
            uint256 i = (head + ENTRIES - k) % ENTRIES;
            uint256 t = key(l.logRing[3 * i]);
            if (t >= now_) continue;
            if (t + p.window < now_) break;
            wi[m++] = i;
            uint160 x = lo(l.logRing[3 * i]);
            if (dLo == 0 || lowerTok(x, dLo, tokenIs0)) dLo = x;
        }
        uint160 price = live;
        uint256 freeSum;
        uint256 n;
        for (uint256 j; j < m; j++) {
            uint256 i = wi[j];
            uint256 a = l.logRing[3 * i];
            uint256 c = capacity(p, fee(a), feeNow);
            uint256 used = capOf(l, i);
            if (used >= c) continue;
            if (lowerTok(lo(a), price, tokenIs0)) price = lo(a);
            freeSum += c - used;
            if (++n < p.minBlocks) continue;
            uint256 s = maxForFree(freeSum, price, dLo, liq, tokenIs0);
            if (s > best) best = s;
        }
    }

    /// @notice Apply `r`: each consumed entry's cap grows by its take (addCaps, saturating at
    ///         CAP_MAX as before); for a send (`rewardBps` > 0)
    ///         each consumed entry with a writer is owed its reward, all capped at `feeCap`.
    ///         Returns the reward total added (the module moves it out of the bridge fee).
    function apply_(S.Layout storage l, Plan memory r, uint256 amountLD, uint16 rewardBps, uint256 feeCap)
        internal
        returns (uint256 total)
    {
        uint256 left = feeCap;
        addCaps(l, packTakes(r));
        for (uint256 q; q < r.n; q++) {
            uint256 i = r.idx[q];
            uint256 t = r.take[q];
            if (t == 0) continue;
            if (rewardBps == 0 || left == 0 || r.need == 0) continue;
            if (address(uint160(l.logRing[3 * i + 2])) == address(0)) continue;
            uint256 rw = (amountLD * t / r.need) * rewardBps / 10_000;
            if (rw > left) rw = left;
            if (rw == 0) continue;
            uint256 b = l.logRing[3 * i + 1];
            uint256 o = owed(b) + rw;
            if (o > type(uint96).max) {
                rw -= o - type(uint96).max;
                o = type(uint96).max;
            }
            l.logRing[3 * i + 1] = packB(hi(b), o);
            left -= rw;
            total += rw;
        }
        if (total != 0) l.rewardsOwedLD += total;
    }

    // ------------------------------------------------------------------ writing

    /// @notice Record `s` (the pool's live sqrt) at second `now_` with fee `feePpm` by `writer`
    ///         (module doc: one entry per second, min / max widened; the merge rule on a full ring).
    function write(
        S.Layout storage l,
        Params memory p,
        uint256 now_,
        uint160 s,
        uint32 feePpm,
        address writer,
        bool tokenIs0
    ) internal {
        uint256 count = l.logCount;
        uint256 head = l.logHead;
        if (count != 0) {
            uint256 a = l.logRing[3 * head];
            if (key(a) == now_) {
                uint160 x = lo(a);
                uint32 fa = fee(a);
                bool chA;
                if (lowerTok(s, x, tokenIs0)) (x, chA) = (s, true);
                if (feePpm < fa) (fa, chA) = (feePpm, true);
                if (chA) l.logRing[3 * head] = packA(now_, x, fa);
                uint256 b = l.logRing[3 * head + 1];
                if (lowerTok(hi(b), s, tokenIs0)) l.logRing[3 * head + 1] = packB(s, owed(b));
                return;
            }
        }
        uint256 i = count == 0 ? 0 : (head + 1) % ENTRIES;
        if (count >= ENTRIES) {
            // i is the oldest entry of a full ring
            uint256 oa = l.logRing[3 * i];
            uint256 ob = l.logRing[3 * i + 1];
            address ow = address(uint160(l.logRing[3 * i + 2]));
            uint256 oOwed = owed(ob);
            if (p.merge && key(oa) + p.window >= now_) {
                uint256 n = (i + 1) % ENTRIES;
                uint256 na = l.logRing[3 * n];
                uint256 nb = l.logRing[3 * n + 1];
                address nw = address(uint160(l.logRing[3 * n + 2]));
                uint160 nl = lowerTok(lo(oa), lo(na), tokenIs0) ? lo(oa) : lo(na);
                uint160 nh = lowerTok(hi(nb), hi(ob), tokenIs0) ? hi(ob) : hi(nb);
                uint32 nf = fee(oa) < fee(na) ? fee(oa) : fee(na);
                l.logRing[3 * n] = packA(key(na), nl, nf); // n keeps its own cap (its lane)
                uint256 no = owed(nb);
                if (nw == ow && oOwed != 0) {
                    no += oOwed;
                    if (no > type(uint96).max) {
                        l.writerOwed[ow] += no - type(uint96).max;
                        no = type(uint96).max;
                    }
                    oOwed = 0;
                }
                l.logRing[3 * n + 1] = packB(nh, no);
            }
            if (oOwed != 0) l.writerOwed[ow] += oOwed;
        } else {
            // E5 (audit M-1): a ring emptied by a re-point (`reset`, O(1)) keeps its old entries'
            // owed rewards in place; each is flushed to its writer when its slot is written again.
            uint256 sOwed = owed(l.logRing[3 * i + 1]);
            if (sOwed != 0) l.writerOwed[address(uint160(l.logRing[3 * i + 2]))] += sOwed;
        }
        l.logRing[3 * i] = packA(now_, s, feePpm);
        l.logRing[3 * i + 1] = packB(s, 0);
        // the new entry's cap starts at 0 (its lane cleared; no write when it already is)
        {
            uint256 w = i / CAP_LANES;
            uint256 sh = (i % CAP_LANES) * CAP_BITS;
            uint256 v = l.logCaps[w];
            uint256 nv = (v & ~(CAP_MAX << sh)) | CAP_SENTINEL;
            if (nv != v) l.logCaps[w] = nv;
        }
        l.logRing[3 * i + 2] = uint256(uint160(writer));
        l.logHead = uint8(i);
        l.logCount = uint8(count + 1 > ENTRIES ? ENTRIES : count + 1);
    }

    /// @notice Empty the log (a re-point), O(1) (E5, audit M-1: it runs inside the V2 hook's
    ///         RECORD_GAS): the entries stop counting (count 0) but stay in their slots with their
    ///         owed rewards, which `take` / `owedTo` still see (they scan every slot) and `write`
    ///         flushes to writerOwed when it reuses a slot. No reward is lost.
    function reset(S.Layout storage l) internal {
        (l.logHead, l.logCount) = (0, 0);
    }

    /// @notice Everything owed to `w` (writerOwed and every ring slot, live or emptied by a reset),
    ///         zeroed; rewardsOwedLD reduced.
    function take(S.Layout storage l, address w) internal returns (uint256 total) {
        total = l.writerOwed[w];
        if (total != 0) l.writerOwed[w] = 0;
        for (uint256 i; i < ENTRIES; i++) {
            if (address(uint160(l.logRing[3 * i + 2])) != w) continue;
            uint256 b = l.logRing[3 * i + 1];
            uint256 o = owed(b);
            if (o == 0) continue;
            l.logRing[3 * i + 1] = packB(hi(b), 0);
            total += o;
        }
        if (total != 0) l.rewardsOwedLD -= total;
    }

    /// @notice What `w` could claim now.
    function owedTo(S.Layout storage l, address w) internal view returns (uint256 total) {
        total = l.writerOwed[w];
        for (uint256 i; i < ENTRIES; i++) {
            if (address(uint160(l.logRing[3 * i + 2])) == w) total += owed(l.logRing[3 * i + 1]);
        }
    }
}

src/v3/gap/IGapDelivery.sol

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

// eth-fallback (owner Q24 fallback, main 2026-10-31 "after execgate", Q34): KEYS-ONLY destinations.
//
// A destination whose LayerZero Executor is not proven gated (execgate: Ethereum, eid 30101) is delivered
// by our delivery keys only. The user pays for that delivery ONCE, to us, and LayerZero almost nothing:
//   - the SOURCE chain's PangeaGapRegistry holds, per destination eid, our delivery cost in the source's
//     native coin (`deliveryCost(dstEid)`, owner-set, bounded by `deliveryCostMax()`, event
//     GapDeliveryCostSet). Non-zero = the destination is KEYS-ONLY (`keysOnly(dstEid)`); zero = LayerZero's
//     executor delivers and nothing extra is charged (never a double charge);
//   - every v3 token's quoteSend adds it to the native fee and its send pays it to the registry's
//     `deliveryFeeTo` (the rest goes to the endpoint, which refunds any excess to the refund address);
//   - the token's own combineOptions puts the minimal executor lzReceive gas (KEYS_ONLY_LZ_RECEIVE_GAS_V3) in
//     place of the route's stored enforced floor at send time (the factory still sets the floor, which applies
//     again once the cost is cleared), so LayerZero's quote prices almost no destination gas; PangeaFastBridgeV3
//     then adds no lzReceive gas of its own to an order or refund (eth-fallback-fix, r1 M-1);
//   - the gap module counts it in the send's bridge cost (feeSrcPpm), as it counted LayerZero's receive gas.
// This file is not imported by the price log module (its runtime codehash is pinned in TokenDeployerV3).

/// @dev The most a registry on an ETH-native chain (Ethereum, Base, Robinhood) accepts as one delivery's cost:
///      0.0064 ETH, the owner's per-transaction ceiling of our Ethereum delivery spend
///      (DELIVERY_MAX_TX_COST_ETHEREUM, Q31 (a): 1,664,000 gas x 3.8 gwei). The setter refuses anything higher.
uint256 constant DELIVERY_COST_MAX_WEI = 0.0064 ether;

/// @dev The same ceiling on BNB Chain (chain id 56 / 97), in BNB wei: 0.0064 ETH at the go-live config's
///      ETH/BNB price ratio (script/golive/v3c-gap.json prices: $3,000 / $600 = 5), 0.032 BNB.
uint256 constant DELIVERY_COST_MAX_BNB_WEI = 0.032 ether;

/// @dev What the registry's delivery views answer (the token reads `deliveryCharge`; PangeaFastBridgeV3 reads it too).
interface IGapDelivery {
    /// @notice Our delivery cost of one message toward `dstEid`, in this chain's native wei (0: not keys-only).
    function deliveryCost(uint32 dstEid) external view returns (uint256);

    /// @notice `deliveryCost(dstEid)` and where it is paid (the registry's `deliveryFeeTo`; zero when the
    ///         cost is zero).
    function deliveryCharge(uint32 dstEid) external view returns (uint256 costWei, address to);
}

// q7b (owner Q52, main 2026-10-31): the L4 prepay P of a composed v3 send INTO Solana is no longer a
// LayerZero lzNativeDrop in the user's options (LayerZero could keep it, oft-q7 Q7-b). The source chain's
// registry holds P's figures (`setPrepayConfig`), every v3 token's quoteSend adds P (in this chain's native
// wei) to the native fee and its send pays exactly it to the registry's `deliveryFeeTo` with the event
// GapPrepayPaid(guid, dstEid, to, lamports, costWei) -- the delivery bot's signal: our delivery key then funds
// the guid's GapPrepay PDA with exactly `lamports` in the SAME Solana transaction as the receive (never
// unpaid: no event, no funding; the arrival waits, retriable). P is computed exactly as L4's (solana/client
// gap-v3.mjs prepayLamports): P = (128 + 259 + composeLen) x 6,960 + floor(11 X / 10) + Y lamports, X the
// LayerZero fee home (Solana -> this chain), Y GapGlobal.return_gas_lamports; costWei = P x weiPerLamport.
// Unset (weiPerLamport 0): every composed v3 send into Solana is refused (PrepayUnset), never unpaid.

/// @dev Solana's rent-exempt lamports per byte (2 years x 3,480) and a GapReceipt's fixed bytes with the
///      account overhead (128 + 219 + L4's 40): R = (387 + composeLen) x 6,960.
uint256 constant SOLANA_PREPAY_RENT_PER_BYTE = 6_960;
uint256 constant SOLANA_PREPAY_RECEIPT_FIXED = 387;
/// @dev The longest composeMsg a Solana receive takes (ComposeTooLong above it).
uint256 constant SOLANA_PREPAY_MAX_COMPOSE = 512;
/// @dev Y's bound (GapGlobal set_gap_return_gas: RETURN_GAS_MAX_LAMPORTS).
uint256 constant SOLANA_PREPAY_RETURN_GAS_MAX = 1_000_000;
/// @dev The most one P may cost (the 512-byte worst case at the configured figures): 0.002 ETH on ETH-native
///      chains (about 9.5x the go-live worst case: 6,816,708 lamports x 31,000,000 wei = 0.000211 ETH at
///      $93 SOL / $3,000 ETH); on BNB Chain (56 / 97) the same at the $3,000 / $600 ratio, 0.01 BNB.
uint256 constant PREPAY_COST_MAX_WEI = 0.002 ether;
uint256 constant PREPAY_COST_MAX_BNB_WEI = 0.01 ether;
/// @dev Owner Q72 (refined, main 2026-11-01): Ethereum's (chain id 1) per-P cap is the smaller of 0.0025 ETH and
///      P_needed x 1.2, never below 0.002 ETH, where P_needed is the 512-byte P at the MEASURED X
///      (script/v3-mainnet/prepay-x-measured.json; x-measure: 27,560,146 lamports x 31,000,000 wei = 0.000854 ETH,
///      x 1.2 = 0.001025 ETH) -> 0.002 ETH. Go-live recomputes the rule from the committed X record and REFUSES when
///      this constant differs (script/v3-mainnet/check-prepay-x.mjs q72CapProblems), so a re-measured X that needs
///      more fails closed and goes back to the owner. Kept as its own constant so that change is one line.
uint256 constant PREPAY_COST_MAX_ETHEREUM_WEI = 0.002 ether;

/// @dev What the registry's prepay view answers (the token reads it on composed sends into Solana).
interface IGapPrepay {
    /// @notice P for a `composeLen`-byte composeMsg toward `dstEid`: its lamports, its cost in this chain's
    ///         native wei and where it is paid (`deliveryFeeTo`). All zero toward a non-Solana eid and while
    ///         unset (the token then refuses a composed send into Solana: PrepayUnset).
    function prepayCharge(uint32 dstEid, uint256 composeLen)
        external
        view
        returns (uint256 lamports, uint256 costWei, address to);
}

src/v3/gap/IGapReader.sol

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

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

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

src/v3/gap/IPangeaGapRegistry.sol

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

/// @title IPangeaGapRegistry -- per-chain gap-fee config: readers, stables, margin, USD routes,
///        official pools (docs/v3-gap-fee-spec.md §7)
/// @notice FROZEN (work item 1). One registry per EVM chain, shared by every v3 token on it.
///         Roles: `owner` (readers, stables, margin, registrar, hook kinds, factories) and
///         `registrar` (routes). Routes apply to live tokens at once; nothing is frozen per token.
interface IPangeaGapRegistry {
    /// @notice One conversion step: the price of one whole `tokenIn` in `tokenOut`, read by
    ///         `reader.priceE18(poolRef, tokenIn, tokenOut)` under `staticcall{gas: gasCap}`.
    struct Hop {
        address reader;
        bytes32 poolRef;
        address tokenIn;
        address tokenOut;
        uint32 gasCap;
    }

    /// @notice A token's official launch pool (Uniswap v4). Set once, by a listed factory.
    struct OfficialPool {
        bytes32 poolId; // the v4 PoolId
        address hook; // its fee hook; the fee is read as `hookKind(hook)` says
        address quote; // the pool's other currency; address(0) is native
        uint24 lpFee; // the v4 static LP fee, ppm
        bool tokenIsCurrency0;
    }

    /// @notice How the official pool's hook fee is read. NONE means fee read failed (fee 0).
    enum HookKind {
        NONE,
        V1, // PangeaFeeHook: configs(id).feeBps
        V2 // PangeaFeeHookV2: feeOf(id), live
    }

    /// @notice AMENDMENT 6: this chain's gas cover settings (GapCoverLib). Each chain sets its OWN figures.
    ///         swapUnits = the MEASURED MINIMUM gasUsed of one swap on this chain's official pool through
    ///         the plain router path (receipt gasUsed, never a gas limit); sendUnits = the measured minimum
    ///         gasUsed of one v3 OFT send (gap quote included); re-measure after any hook/token/router
    ///         change. The counted basefee is min(max(block.basefee, baseFeeFloorWei), baseFeeCapWei)
    ///         (cap 0 = no cover); the floor must never exceed the minimum gas price the chain accepts
    ///         (BSC: its validators' minimum). coverCapCents bounds one message's cover (min of both
    ///         sides'). coverWindowSeconds: a route (token, dstEid) is covered at most once per window.
    struct GasCover {
        uint32 swapUnits;
        uint32 sendUnits;
        uint64 baseFeeFloorWei;
        uint64 baseFeeCapWei;
        uint16 coverCapCents;
        uint32 coverWindowSeconds;
    }

    /// @notice e6-r2fix (owner 2026-10-30): what a delivery key co-signs for ONE oversized v3 send
    ///         (EIP-712 struct GapCoSign, domain PangeaGapRegistry.coSignDomainSeparator(); the chain id
    ///         is the struct's first field, block.chainid). `token` the v3 token sending; `sender` its
    ///         caller (OFT send's msg.sender); `amountLD` what the send carries (net of the bridge fee,
    ///         amountSD x 1e3: OFT quoteOFT's amountReceivedLD); `minCreditedLD` the oftCmd's minimum
    ///         (0 none); `maxPsE18` the co-signer's ceiling on the carried Ps (USD 1e18 per whole token);
    ///         `deadline` the last block.timestamp it is good for; `nonce` the sender's
    ///         gapCoSignNonce (one use, in order).
    struct CoSign {
        address token;
        uint32 dstEid;
        address sender;
        uint256 amountLD;
        uint256 minCreditedLD;
        uint256 maxPsE18;
        uint64 deadline;
        uint256 nonce;
    }

    // ------------------------------------------------------------------ events

    event ReaderSet(address indexed reader, bool allowed);
    event StableSet(address indexed token, bool stable);
    /// @notice AMENDMENT 6: the fixed margin (ppm) this chain's receives allow.
    event MarginSet(uint32 ppm);
    /// @notice AMENDMENT 6: this chain's gas cover settings.
    event GasCoverSet(GasCover c);
    /// @notice v3c-evm-final: the bridge fee (bps) v3 tokens on this chain charge at send.
    event BridgeFeeSet(uint16 bps);
    /// @notice v3c-evm-final: the gas cap of the send's LayerZero quote.
    event QuoteGasSet(uint32 gas_);
    /// @notice v3c-evm-final: the LayerZero cost term's cap (USD 1e18).
    event CostMaxSet(uint256 usdE18);
    /// @notice v3c (2026-10-30): a quote's price class (0 none, 1 USD stable -- every stable is class 1, 2 ETH, 3..255
    ///         admin canonical assets). Same class on both chains -> the token prices compare directly, no hop.
    event QuoteClassSet(address indexed quote, uint8 class_);
    /// @notice v3c (4b): the per-token escape. On, a receive whose price is unreadable credits in full at fee 0.
    event GapEscapeSet(address indexed token, bool on);
    /// @notice v3c (5): how old (seconds) a V2 hop's recorded price may be when the pair was touched this block.
    event V2RecordMaxAgeSet(uint32 seconds_);
    event RegistrarSet(address indexed registrar);
    event HookKindSet(address indexed hook, HookKind kind);
    event FactorySet(address indexed factory, bool listed);
    event RouteSet(address indexed quote, Hop[] hops);
    event RouteCleared(address indexed quote);
    event OfficialPoolSet(address indexed token, address indexed factory, OfficialPool pool);

    /// @notice v3c-evm-log: the price log's settings (GapPriceLog; docs/v3c-gap-spec.md §9).
    ///         E5 (audit M-2): platformFloorPpm, k_mode 1's fee cap.
    event LogParamsSet(
        uint8 kMode,
        uint32 kFlatPpm,
        uint32 kFactorPpm,
        uint32 windowSec,
        uint8 minBlocks,
        uint16 rewardBps,
        bool merge,
        uint32 platformFloorPpm
    );
    /// @notice v3c-evm-log: the permanent no-remove locker a re-pointed pool's position must sit in.
    event MigrationLockerSet(address indexed locker);
    /// @notice v3c-evm-log: `token`'s official pool moved to `pool` (a V2-hook pool), epoch `epoch`.
    event OfficialPoolRepointed(address indexed token, uint32 epoch, OfficialPool pool, bytes32 positionKey);
    /// @notice E6 (audit E5 M-B): `executor` (a caller of EndpointV2.lzReceive: this chain's LayerZero
    ///         Executor contract) is (or no longer is) trusted to land a charged price-log receive whose
    ///         walk counts the live price.
    event GapExecutorSet(address indexed executor, bool trusted);
    /// @notice E6 (audit E5 M-B): delivery key slot `slot` (0 or 1) is now `key` (0 = empty).
    event DeliveryKeySet(uint8 indexed slot, address indexed key);
    /// @notice e6-r2fix (owner 2026-10-30): the price log's window W is now `windowSec` (setLogWindow;
    ///         LogParamsSet is emitted with it, carrying every setting).
    event LogWindowSet(uint32 windowSec);

    // ------------------------------------------------------------------ errors

    /// @notice setLogParams / setLogWindow outside its bounds (see setLogParams).
    error BadLogParams();
    /// @notice e6-r2fix (audit R2 L-1): setGapExecutor / setDeliveryKey with one of LayerZero's
    ///         permissionless LzExecutor helpers (commitAndExecute: anyone can run a receive through it,
    ///         so it must never be trusted).
    error LzExecutorHelperRefused(address helper);
    /// @notice repointOfficialPool refused: the token has no pool, the new pool is not on a V2 hook,
    ///         its quote is not pricable, the hook does not name the migration locker as a liquidity
    ///         adder, the locker does not hold `positionKey` for that pool (or its key does not match
    ///         the pool), or the locked liquidity is below the old pool's; E5 (audit L-3): 7 = the
    ///         locked position is not in range at the pool's current tick (tickLower <= tick < tickUpper).
    error BadRepoint(uint8 why);

    error NotOwner();
    error NotRegistrar();
    error NotListedFactory();
    error MarginTooHigh(uint32 ppm); // > GapMath.MARGIN_MAX_PPM (100,000)
    /// @notice setGasCover: swapUnits > 2,000,000, sendUnits > 4,000,000, floor > 1 gwei, cap > 1,000 gwei,
    ///         cap != 0 and floor > cap, coverCapCents > 20,000 ($200), or coverWindowSeconds outside 12..=86,400.
    error BadGasCover();
    /// @notice v3c-evm-final: setBridgeFeeBps above 50 bps.
    error BridgeFeeTooHigh(uint16 bps);
    /// @notice v3c-evm-final: setQuoteGas outside [150,000, 1,000,000].
    error BadQuoteGas(uint32 gas_);
    /// @notice v3c-evm-final: setCostMax above $50 (50e18).
    error CostMaxTooHigh(uint256 usdE18);
    /// @notice v3c-evm-final: setOfficialPool with a hook whose hookKind is NONE.
    error HookNotListed(address hook);
    error BadQuoteClass(address quote, uint8 class_); // class 1 is only for stables (setStable), via setQuoteClass refused
    error BadV2RecordMaxAge(uint32 seconds_); // outside [12, 86_400]
    /// @notice setOfficialPool: the pool's quote has no USD price this chain can read (not a stable,
    ///         no route ending in a stable through listed readers; a class alone is not enough).
    error QuoteNotPricable(address quote);
    /// @notice setOfficialPool (audit r1 L-1): the listing factory has no `locker()`, or its locker
    ///         gives no `positionKey(poolId)` (0): the margin's locked depth could never be read.
    error NoLockedPosition(address token);
    /// @notice setStable: native (address(0)), the 0xEeee... placeholder and this chain's wrapped native
    ///         are never $1 stables (they are priced through a route).
    error NotAStable(address token);
    /// @notice setOfficialPool (audit r1 L-1): the locked position holds no liquidity (the locker
    ///         must be seeded before the pool is listed).
    error NoLockedLiquidity(address token);
    error BadRoute(); // 0 or > 2 hops, a gap between hops, an unlisted reader, gasCap 0 or > MAX_HOP_GAS, or not ending in a stable
    error PoolAlreadySet(address token);
    error NotRecordingHook(address hook); // setHookKind V2: RECORD_GAS() does not answer 250,000
    /// @notice The caller left less gas than a reader's cap needs (spec §6, Q1): the receive
    ///         reverts and stays retriable instead of charging fee 0.
    ///         Checked before each reader call: gasleft() >= gasCap * 64 / 63 + GapMath.HOP_GAS_RESERVE.
    error GapGasTooLow(uint256 needed, uint256 left);

    // ------------------------------------------------------------------ owner

    function owner() external view returns (address);
    /// @notice Listing a reader is the owner's statement that it is FLASH-PROOF (spec §5): nothing
    ///         earlier in the same transaction moves its answer (UniV3Reader, V2PairReader). A live
    ///         spot reader (a v4 pool's slot0, a v2 pair's raw reserves) must never be listed: audit
    ///         H-1 (EVM-B) showed a depth gate on a live pool is passed inside one transaction by JIT
    ///         liquidity. setRoute accepts listed readers only.
    function setReader(address reader, bool allowed) external;
    /// @notice Refused (NotAStable) for address(0), 0xEeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE and
    ///         wrappedNative() when `stable` is true.
    function setStable(address token, bool stable) external;
    /// @notice AMENDMENT 6: the fixed margin this chain's receives allow, ppm. Default 1,000 (0.1%);
    ///         above GapMath.MARGIN_MAX_PPM (100,000, 10%) reverts MarginTooHigh.
    function setMargin(uint32 ppm) external;
    /// @notice AMENDMENT 6: this chain's gas cover (see GasCover). Default all 0 (no cover) except
    ///         coverWindowSeconds = 30. Out of bounds reverts BadGasCover.
    function setGasCover(GasCover calldata c) external;
    /// @notice v3c-evm-final: the bridge fee, 0..=50 bps (default 20); above: BridgeFeeTooHigh.
    function setBridgeFeeBps(uint16 bps) external;
    /// @notice v3c-evm-final: the send's LayerZero quote gas cap, [150,000, 1,000,000] (default 400,000).
    function setQuoteGas(uint32 gas_) external;
    /// @notice v3c-evm-final: the LayerZero cost term's cap, USD 1e18, <= 50e18 (default 20e18).
    function setCostMax(uint256 usdE18) external;
    /// @notice 0 clears; 1 is refused (stables are class 1 by setStable); 255 is refused (the refund marker,
    ///         AMENDMENT 2); 2..254 allowed.
    function setQuoteClass(address quote, uint8 class_) external;
    function setGapEscape(address token, bool on) external;
    /// @notice Default GapMath.V2_RECORD_MAX_AGE_DEFAULT (30 s); [12, 86_400].
    function setV2RecordMaxAge(uint32 seconds_) external;
    function setRegistrar(address registrar) external;
    function setHookKind(address hook, HookKind kind) external;
    function setFactory(address factory, bool listed) external;
    /// @notice v3c-evm-log price log settings, each with a hard bound (BadLogParams otherwise):
    ///         kMode 0 (flat) or 1 (fee-linked); kFlatPpm in [100, platformFloorPpm / 3] (E6; default 666);
    ///         kFactorPpm in [1, 333_333] (E6; default 333_333 = 1/3); windowSec in [windowMinSec(), 3_600]
    ///         (default 30; e6-r2fix: on Ethereum at least 384 = 32 blocks of 12 s, its default) and
    ///         >= minBlocks; minBlocks in [2, 16] (default 2); rewardBps in [0, 20] (default 1); merge
    ///         (default on); E5 (audit M-2) platformFloorPpm in [300, 2_600] (default 2_000 = 0.2%; the
    ///         Solana port's bounds). k_mode 1 is max(min(fee at the entry, fee now, platformFloorPpm) x
    ///         kFactorPpm / 1e6, 100) (0 at an unreadable fee), every k at most 100_000 (E6, Solana's
    ///         entry_k_ppm). Default kMode 1 (the go-live configuration). (e6-r2fix, audit R2 B I-1: this
    ///         doc stated E5's bounds.)
    function setLogParams(
        uint8 kMode,
        uint32 kFlatPpm,
        uint32 kFactorPpm,
        uint32 windowSec,
        uint8 minBlocks,
        uint16 rewardBps,
        bool merge,
        uint32 platformFloorPpm
    ) external;
    /// @notice The permanent no-remove locker (PangeaMigrationLocker) re-pointed pools must lock in.
    function setMigrationLocker(address locker) external;
    /// @notice Owner only: move `token`'s official pool to `pool`, which must be on a HookKind.V2
    ///         hook, quote-pricable, with `positionKey` held by the migration locker for exactly that
    ///         pool and at least the old locked position's liquidity. Bumps officialEpoch(token);
    ///         the token re-learns its pool and resets its price log on the change.
    function repointOfficialPool(address token, OfficialPool calldata pool, bytes32 positionKey) external;

    // ------------------------------------------------------------------ registrar

    function registrar() external view returns (address);
    /// @notice Replaces `quote`'s route to USD. 1 or 2 hops; hops[0].tokenIn == quote;
    ///         hops[i].tokenOut == hops[i+1].tokenIn; the last tokenOut is a stable; every reader
    ///         allowed; every gasCap in [1, GapMath.MAX_HOP_GAS]. A stable quote needs no route.
    function setRoute(address quote, Hop[] calldata hops) external;
    function clearRoute(address quote) external;

    // ------------------------------------------------------------------ listed factory

    /// @notice Once per token, only from a listed factory (msg.sender), at launch. Refused
    ///         (QuoteNotPricable) unless `quotePricable(pool.quote)`; refused (NoLockedPosition /
    ///         NoLockedLiquidity) unless the factory's locker names the pool's locked position and
    ///         that position already holds liquidity (AMENDMENT 5: the margin's depth).
    function setOfficialPool(address token, OfficialPool calldata pool) external;

    // ------------------------------------------------------------------ views

    function poolManager() external view returns (address);
    /// @notice This chain's wrapped native (WETH / WBNB), set at construction: never a stable.
    function wrappedNative() external view returns (address);
    function isReader(address reader) external view returns (bool);
    function isStable(address token) external view returns (bool);
    function isFactory(address factory) external view returns (bool);
    /// @notice AMENDMENT 6: the fixed margin, ppm (default 1,000).
    function marginPpm() external view returns (uint32);
    /// @notice AMENDMENT 6: this chain's gas cover settings (6 words).
    function gasCover() external view returns (GasCover memory);
    /// @notice v3c-evm-final: the bridge fee (bps) a v3 token charges at send and carries (x100 ppm).
    function bridgeFeeBps() external view returns (uint16);
    /// @notice v3c-evm-final: the gas cap of the send's LayerZero quote.
    function quoteGas() external view returns (uint32);
    /// @notice v3c-evm-final: the LayerZero cost term's cap, USD 1e18.
    function costMaxUsdE18() external view returns (uint128);
    /// @notice The v4 position key of `token`'s official pool's LOCKED launch liquidity (0 unknown).
    ///         AMENDMENT 6: no longer read by the fee (kept: the listing check and the Solana capacity rule).
    function officialPosition(address token) external view returns (bytes32);
    /// @notice 1 for a stable; else the admin class; 0 none.
    function quoteClass(address quote) external view returns (uint8);
    function gapEscape(address token) external view returns (bool);
    function v2RecordMaxAge() external view returns (uint32);
    /// @notice E6 (audit E5 M-B, parity with Solana R1'): whether `executor` -- the caller of
    ///         EndpointV2.lzReceive, as the token's receive sees it -- may land a CHARGED price-log
    ///         receive whose walk counts the live price: an allow-listed executor (setGapExecutor) or
    ///         one of the two delivery keys (setDeliveryKey). address(0) never.
    function isTrustedExecutor(address executor) external view returns (bool);
    function gapExecutor(address executor) external view returns (bool);
    function deliveryKeys(uint256 slot) external view returns (address);
    function setGapExecutor(address executor, bool trusted) external;
    function setDeliveryKey(uint8 slot, address key) external;
    /// @notice e6-r2fix: `key` is one of the two delivery keys (address(0) never). Delivery keys co-sign
    ///         oversized sends (coSignValid) and land oversized receives with a floor (the 36-byte land tag).
    function isDeliveryKey(address key) external view returns (bool);
    /// @notice e6-r2fix (owner 2026-10-30): `a` may land an oversized charged v3 receive with the 36-byte
    ///         tag (GAP_LAND_OVERSIZED | uint256 floor, floor > 0) at max(r0, floor): the owner or a delivery key.
    function canLandOversized(address a) external view returns (bool);
    /// @notice e6-r2fix (golive x1 hook): both delivery keys are set and distinct.
    function deliveryKeysSet() external view returns (bool);
    /// @notice e6-r2fix (audit R2 L-1): `a` is one of LayerZero's permissionless LzExecutor helpers on
    ///         Ethereum, Base, BSC or Robinhood (never trusted: setGapExecutor / setDeliveryKey refuse it).
    function isLzExecutorHelper(address a) external pure returns (bool);
    /// @notice e6-r2fix: the EIP-712 domain separator of the co-sign (name "Pangea Gap Co-Sign", version
    ///         "1", this chain's id, this registry).
    function coSignDomainSeparator() external view returns (bytes32);
    /// @notice e6-r2fix: the EIP-712 digest a delivery key signs for `c` (keccak256(0x1901 | domain |
    ///         hashStruct(GapCoSign(block.chainid, c...)))).
    function coSignDigest(CoSign calldata c) external view returns (bytes32);
    /// @notice e6-r2fix: (v, r, s) is a valid signature (low s, v 27 / 28) of coSignDigest(c) by a delivery
    ///         key. Deadline and nonce are the token's to check.
    function coSignValid(CoSign calldata c, uint8 v, bytes32 r, bytes32 s) external view returns (bool);
    /// @notice e6-r2fix: the token's check of a co-signed send (PangeaOFTV3GapModule): `oftCmd` the send's
    ///         224-byte SendParam.oftCmd (abi.encode(uint256 w, uint256 maxPsE18, uint64 deadline, uint256
    ///         nonce, uint8 v, bytes32 r, bytes32 s), minCreditedLD = w's low 248 bits), `nonce` the one the
    ///         sender must carry now, `psE18` the Ps the send carries. `why` 0 = valid, 1 = expired
    ///         (block.timestamp > deadline), 2 = not `nonce`, 3 = not a delivery key's signature over exactly
    ///         (chain, token, dstEid, sender, amountLD, minCreditedLD, maxPsE18, deadline, nonce) (or not 224
    ///         bytes), 4 = psE18 above maxPsE18 (the co-signer's ceiling).
    function coSignCheck(
        address token,
        uint32 dstEid,
        address sender,
        uint256 amountLD,
        uint256 nonce,
        uint256 psE18,
        bytes calldata oftCmd
    ) external view returns (uint8 why);
    /// @notice e6-r2fix (owner 2026-10-30): set the price log's window W alone (bounds as setLogParams);
    ///         emits LogWindowSet and LogParamsSet. Owner only.
    function setLogWindow(uint32 windowSec) external;
    /// @notice e6-r2fix: the smallest W this chain accepts: 384 s on Ethereum mainnet and Sepolia (32
    ///         blocks of 12 s, the ring's 32 entries), else 2.
    function windowMinSec() external view returns (uint32);
    /// @notice A stable, or a quote whose route ends in a stable through listed readers only, whatever
    ///         its class (AMENDMENT 5: the depth needs USD on both sides; setOfficialPool's
    ///         precondition; whether it reads right now is not checked).
    function quotePricable(address quote) external view returns (bool);
    function hookKind(address hook) external view returns (HookKind);
    function route(address quote) external view returns (Hop[] memory);
    /// @notice `set == false` means no official pool on this chain yet (fee 0).
    function officialPool(address token) external view returns (bool set, OfficialPool memory pool);
    /// @notice officialPool(token).set, reading one slot (V2PairReader.poke's caller check, under its gas cap).
    function hasOfficialPool(address token) external view returns (bool);

    /// @notice USD per whole `quote`, 1e18. A stable is exactly 1e18. Otherwise the route, chained
    ///         with GapMath.mulUp over srcFactor(each hop) when `roundUp` (source), and with
    ///         GapMath.mulDown over each hop as read otherwise (destination). 0 on any failure (no
    ///         route, a reader failure, an overflow). Reverts only with GapGasTooLow.
    function usdPerQuoteE18(address quote, bool roundUp) external view returns (uint256);

    /// @notice Both roundings of usdPerQuoteE18 from ONE read of each hop: `down` = (quote, false),
    ///         `up` = (quote, true). The destination prices Pd with `down` and values its locked
    ///         depth with `up` (AMENDMENT 5: D rounds up, toward the fee). Reverts only with
    ///         GapGasTooLow.
    function usdPerQuoteBothE18(address quote) external view returns (uint256 down, uint256 up);
    /// @notice v3c-evm-final: usdPerQuoteBothE18 and, when the same reads give it, the native route
    ///         rounded down (`nativeDown`): `quote` is the native (address(0)), or its 2-hop route's second
    ///         hop is exactly the native's 1-hop route; else 0 (the caller reads the native route itself).
    function usdPerQuoteBothNativeE18(address quote) external view returns (uint256 down, uint256 up, uint256 nativeDown);

    /// @notice v3c-evm-log: the price log's settings (see setLogParams).
    function logParams()
        external
        view
        returns (
            uint8 kMode,
            uint32 kFlatPpm,
            uint32 kFactorPpm,
            uint32 windowSec,
            uint8 minBlocks,
            uint16 rewardBps,
            bool merge,
            uint32 platformFloorPpm
        );
    /// @notice How many times `token`'s official pool was re-pointed (0 = the launch pool).
    function officialEpoch(address token) external view returns (uint32);
    function migrationLocker() external view returns (address);

    /// @notice The official pool's fee, ppm: GapMath.evmPoolFeePpm(hook fee bps, lpFee).
    ///         `ok == false` on no pool, HookKind.NONE, or a failed hook read.
    function poolFeePpm(address token) external view returns (bool ok, uint32 ppm);
}

src/v3/gap/PangeaOFTV3Storage.sol

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

/// @title PangeaOFTV3Storage -- the state PangeaOFTV3 shares with its gap module
/// @notice One ERC-7201 namespace, read and written by the token (its price records, the receive's
///         withholding, the metadata it sets in its constructor) and by PangeaOFTV3GapModule, which
///         runs in the token's context by DELEGATECALL (the gap reads, the gap views and the
///         metadata calls). Nothing else of the token's storage is touched by the module: the OFT,
///         ERC20 and Ownable state stays where their own bases put it.
library PangeaOFTV3Storage {
    /// @dev The latest price record, and whether the official pool is known yet, in one slot (the
    ///      gap reads take this and the pool fields `_learn` copies from the registry on the
    ///      first record). `last` is a sqrtPriceX96 of the pool.
    struct Record {
        uint48 blockNumber; // the block of the latest record; 0 = none yet
        uint160 last; // the latest record: the close of `blockNumber` so far
        bool known; // the official pool is cached below
        bool tokenIs0; // this token is the pool's currency0
        uint16 feeBps; // the hook fee in force at the latest record (round-4 M-1)
    }

    /// @custom:storage-location erc7201:pangea.oft.v3
    struct Layout {
        Record rec;
        /// @dev The close of the latest recorded window (block) before `rec`'s, and that block; for
        ///      the first record ever, the pool's price before its first swap (its opening price,
        ///      block 0). 0 = no record.
        uint160 recPrev;
        uint48 recPrevBlock;
        /// @dev The hook fee (bps) in force at `recPrev`'s record; for the opening price, the first
        ///      swap's own fee while the pool's fee was never changed, else HOOK_MIN_FEE_BPS. 0 = no record.
        uint16 recPrevFee;
        /// @dev The close of the latest recorded window before `recPrev`'s, and that block (owner
        ///      2026-10-28, two block closes over recorded windows); the opening price, block 0,
        ///      when there is none. 0 = no record.
        uint160 recPrev2;
        uint48 recPrev2Block;
        /// @dev The hook fee (bps) in force at `recPrev2`'s record; for the opening price, as `recPrevFee`. 0 = no record.
        uint16 recPrev2Fee;
        /// @dev The official pool, copied from the registry by `_learn` on the first record.
        bytes32 poolId;
        address poolQuote;
        /// @dev 255 when the quote's decimals could not be read: every price is then 0 (unknown).
        uint8 quoteDecimals;
        /// @dev The official pool's static LP fee (ppm), copied with it (the allowance's recorded fee).
        uint24 poolLpFee;
        /// @dev The official pool's hook: the one address whose `recordPrice` counts.
        address poolHook;
        uint256 gapBurnedLD;
        mapping(bytes32 guid => uint256 withheldLD) gapWithheld;
        string metadataURI;
        address metadataAuthority;
        address pendingMetadataAuthority;
        // ---- v3c-evm-log (hook-independent price log, GapPriceLog.sol) ----
        /// @dev The latest entry's index and the entries in use (<= GapPriceLog.ENTRIES), and the
        ///      registry's `officialEpoch` the log (and the pool copy above) belongs to; packed
        ///      with `pendingMetadataAuthority`'s slot remainder.
        uint8 logHead;
        uint8 logCount;
        uint32 logEpoch;
        /// @dev The ring: entry i is words 3i (A), 3i+1 (B), 3i+2 (C), packed by GapPriceLog.
        uint256[96] logRing;
        /// @dev Writer rewards (token units, LD) flushed out of the ring (evicted, merged or reset
        ///      entries), claimable by `claimWriterRewards`.
        mapping(address writer => uint256 owedLD) writerOwed;
        /// @dev Every writer reward owed and not yet claimed (ring + writerOwed): what the token
        ///      holds of its own balance for the writers.
        uint256 rewardsOwedLD;
        /// @dev AMENDMENT 6 (lead decision 1): per destination eid, the last cover window a send carried
        ///      a gas cover in, + 1 (0 = never): a route (token, dstEid) is covered at most once per window.
        ///      Written only by a real send (the log module's gapDebit), never by a view.
        mapping(uint32 dstEid => uint64 windowP1) lastCoverWindowP1;
        /// @dev E6 (audit E5 M-A, gas): every ring entry's consumed capacity (pico of the locked depth),
        ///      40 bits each, six entries a word (entry i: word i / 6, bits (i % 6) * 40): a full
        ///      consumption writes at most 6 words instead of one per entry (GapPriceLog).
        uint256[6] logCaps;
        /// @dev e6-r2fix (owner 2026-10-30): per sender, the nonce its next CO-SIGNED oversized send must
        ///      carry (a delivery key's EIP-712 co-sign, PangeaGapRegistry.coSignValid). Raised by one by
        ///      each such send (the log module's gapDebit), so a co-sign lands at most once.
        mapping(address sender => uint256 nonce) coSignNonce;
    }

    /// @dev keccak256(abi.encode(uint256(keccak256("pangea.oft.v3")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant SLOT = 0xa977c9fff4ee198cada9c4c15e7802401dd97f938fa5b108fb13732a58ea3d00;

    function layout() internal pure returns (Layout storage l) {
        bytes32 s = SLOT;
        assembly ("memory-safe") {
            l.slot := s
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
    "@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
    "@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v4-core/=lib/uniswap-v4-core/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "layerzero/=lib/layerzero/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/",
    "uniswap-v4-core/=lib/uniswap-v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.