Skip to content
Verified contractExactUNLICENSED

PangeaOFTV3LogModule

Address0x8bc151631f744fd1e04e17aaa4b850b0ab2bdf2b
Balance

0 ETH

 

Transactions

0

 

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,499
Creation transaction
0x01b82f2a96…b431935145

src/v3/gap/PangeaOFTV3LogModule.sol

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

import {IPangeaGapRegistry} from "./IPangeaGapRegistry.sol";
import {IPangeaOFTV3Gap} from "./IPangeaOFTV3Gap.sol";
import {GapMath} from "./GapMath.sol";
import {GapCoverLib} from "./GapCoverLib.sol";
import {GapPriceLog} from "./GapPriceLog.sol";
import {PangeaOFTV3Storage as S} from "./PangeaOFTV3Storage.sol";
import {GapModuleBase, IPangeaOFTV3Self} from "./GapModuleBase.sol";

/// @title PangeaOFTV3LogModule -- the price log's code of a v3 token (v3c-evm-log; GapPriceLog)
/// @notice Run ONLY by DELEGATECALL as a PangeaOFTV3, through PangeaOFTV3GapModule's fallback
///         (split from it for size, EIP-170). One per chain, no owner, no storage of its own, no
///         immutables (TokenDeployerV3 pins its code hash). What it does: the permissionless
///         `poke`, the factory's `gapSeedLog`, a send's consumption (`gapDebit`, the token's
///         _debit only), the writer reward claim (`gapClaimTake`, the token's claimWriterRewards
///         only), the consumption plan as a view (`gapLogQuote`, which the gap module prices sends
///         and receives with) and the log views. E5: also the permissionless `gapLogResync`, the
///         cover view `gapCoverAvailable`, and (moved here from the gap module for size, EIP-170) the
///         metadata calls and the plain storage views.
contract PangeaOFTV3LogModule is GapModuleBase {
    error NotListedFactory();

    /// @notice Only the token itself (the gap module, running as it, calling the token).
    error NotSelf();
    /// @notice `recordPrice` from anyone but the official pool's hook, or for another pool.
    error NotOfficialHook();

    // ------------------------------------------------------------- moved from the gap module (E5)

    event MetadataURISet(string uri);
    event MetadataAuthorityProposed(address indexed from, address indexed to);
    event MetadataAuthorityChanged(address indexed from, address indexed to);

    error NotMetadataAuthority();
    error NotPendingAuthority();
    error ZeroAuthority();

    function SUPPLY_SLICE() external pure returns (uint8) {
        return 0;
    }

    function SUPPLY_TOTAL() external pure returns (uint8) {
        return 1;
    }

    /// @notice A compose message above this toward Solana is refused (spec section 4).
    function MAX_SOLANA_COMPOSE_MSG_LEN() external pure returns (uint256) {
        return 512;
    }

    function metadataURI() external view returns (string memory) {
        return S.layout().metadataURI;
    }

    function metadataAuthority() external view returns (address) {
        return S.layout().metadataAuthority;
    }

    function pendingMetadataAuthority() external view returns (address) {
        return S.layout().pendingMetadataAuthority;
    }

    function setMetadataURI(string calldata uri) external {
        S.Layout storage l = S.layout();
        if (msg.sender != l.metadataAuthority) revert NotMetadataAuthority();
        l.metadataURI = uri;
        emit MetadataURISet(uri);
    }

    function proposeMetadataAuthority(address to) external {
        S.Layout storage l = S.layout();
        if (msg.sender != l.metadataAuthority) revert NotMetadataAuthority();
        if (to == address(0)) revert ZeroAuthority();
        l.pendingMetadataAuthority = to;
        emit MetadataAuthorityProposed(l.metadataAuthority, to);
    }

    function acceptMetadataAuthority() external {
        S.Layout storage l = S.layout();
        if (msg.sender != l.pendingMetadataAuthority) revert NotPendingAuthority();
        emit MetadataAuthorityChanged(l.metadataAuthority, msg.sender);
        l.metadataAuthority = msg.sender;
        l.pendingMetadataAuthority = address(0);
    }

    function gapBurnedLD() external view returns (uint256) {
        return S.layout().gapBurnedLD;
    }

    function gapWithheld(bytes32 guid) external view returns (uint256) {
        return S.layout().gapWithheld[guid];
    }

    /// @notice The price records, for monitoring: the latest record's block, the latest record (the
    ///         close so far of that block), the record before `prevClose`, and `prevClose`, the
    ///         record before the latest (all sqrtPriceX96 of the official pool; 0 = none).
    function gapRecords() external view returns (uint48 blockNumber, uint160 last, uint160 prevClose2, uint160 prevClose) {
        S.Layout storage l = S.layout();
        S.Record memory r = l.rec;
        return (r.blockNumber, r.last, l.recPrev2, l.recPrev);
    }

    /// @notice The blocks of the three records: the latest, `prevClose`'s and `prevClose2`'s
    ///         (0 for the opening price, or no record).
    function gapRecordBlocks() external view returns (uint48 last, uint48 prevClose, uint48 prevClose2) {
        S.Layout storage l = S.layout();
        return (l.rec.blockNumber, l.recPrevBlock, l.recPrev2Block);
    }

    /// @notice The hook fees (bps) in force at the three records: the latest, `prevClose`'s and
    ///         `prevClose2`'s; for the opening price the first swap's own fee while the pool's fee was
    ///         never changed, else 30 (PangeaFeeHookV2.MIN_FEE_BPS); all 0 before any record.
    function gapRecordFees() external view returns (uint16 last, uint16 prevClose, uint16 prevClose2) {
        S.Layout storage l = S.layout();
        return (l.rec.feeBps, l.recPrevFee, l.recPrev2Fee);
    }

    /// @notice v3c-evm-final: the registry's live bridge fee (bps; unreadable: 20).
    function BRIDGE_FEE_BPS() external view returns (uint16) {
        return _bridgeFeeBps(IPangeaOFTV3Self(address(this)).gapRegistry());
    }

    /// @notice IPangeaOFTV3Gap.bridgeFeePpm: BRIDGE_FEE_BPS x 100 (live, the registry's).
    function bridgeFeePpm() external view returns (uint32) {
        return uint32(_bridgeFeeBps(IPangeaOFTV3Self(address(this)).gapRegistry())) * 100;
    }

    // ------------------------------------------------------------- the record (swap time; E5: moved here from the gap module, EIP-170)

    /// @notice The official pool's price, recorded by its HOOK after every swap (PangeaFeeHookV2
    ///         afterSwap): `sqrtBefore` the pool's sqrtPrice before the swap, `sqrtAfter` after.
    ///         Only the official pool's hook, for the official pool, is heard (`NotOfficialHook`
    ///         otherwise, which the hook ignores); so a record is a real swap's outcome, ordered as
    ///         the swaps were. A block's first record moves the previous record into `recPrev`
    ///         (the close of the latest earlier recorded window) and `recPrev` into `recPrev2`,
    ///         with their blocks; the very first record ever puts `sqrtBefore` in both, block 0 --
    ///         the price before the pool's first swap, its opening price. `feeBps` is the hook fee
    ///         this swap is charged, kept with the record (the allowance's fee, round-4 audit M-1);
    ///         the opening price's is that fee too while the pool's fee was never changed since it
    ///         was registered (it is then the launch fee), else HOOK_MIN_FEE_BPS (`_openingFeeBps`).
    function recordPrice(bytes32 poolId, uint160 sqrtBefore, uint160 sqrtAfter, uint16 feeBps) external {
        S.Layout storage l = S.layout();
        // v3c-evm-log: a record from another pool than the cached one may be the re-pointed pool's
        // (registry repointOfficialPool): on an epoch change the cache and the log are dropped and
        // the pool is learned again.
        if (l.rec.known && (msg.sender != l.poolHook || poolId != l.poolId)) {
            (bool okE, uint32 e) = _registryEpoch(IPangeaOFTV3Self(address(this)).gapRegistry());
            if (okE && e != l.logEpoch) _resync(l, e);
        }
        if (!l.rec.known && !_learn(l)) revert NotOfficialHook();
        if (msg.sender != l.poolHook || poolId != l.poolId) revert NotOfficialHook();
        S.Record memory r = l.rec;
        uint48 b = uint48(block.number);
        if (r.blockNumber == 0) {
            uint16 openFee = _openingFeeBps(l.poolHook, poolId, feeBps);
            (l.recPrev, l.recPrevBlock, l.recPrevFee) = (sqrtBefore, 0, openFee);
            (l.recPrev2, l.recPrev2Block, l.recPrev2Fee) = (sqrtBefore, 0, openFee);
        } else if (r.blockNumber != b) {
            (l.recPrev2, l.recPrev2Block, l.recPrev2Fee) = (l.recPrev, l.recPrevBlock, l.recPrevFee);
            (l.recPrev, l.recPrevBlock, l.recPrevFee) = (r.last, r.blockNumber, r.feeBps);
        }
        l.rec = S.Record({blockNumber: b, last: sqrtAfter, known: true, tokenIs0: r.tokenIs0, feeBps: feeBps});
        // v3c §5: the record is written first; then the V2 hops of the routes both sides read (the
        // pool quote's and the native's, for the bridge cost) are poked, best effort -- once per
        // recorded window: on a block's first record (a later swap of the same block would find the
        // same untouched reserves, or a touched pair, where a poke is a no-op), so same-block swaps
        // pay nothing for it. Not on the first record ever (it copies the pool and reads the
        // quote's decimals: the costliest record, kept inside RECORD_GAS as before).
        if (r.blockNumber != 0 && r.blockNumber != b) _pokeRoutes(l.poolQuote);
    }



    /// @dev Copy the official pool (and its hook) from the registry, once it is set. Quote decimals
    ///      that cannot be read are kept as 255 (every price unknown) rather than refusing the copy,
    ///      so a record is never lost to them.
    function _learn(S.Layout storage l) internal returns (bool) {
        address reg = IPangeaOFTV3Self(address(this)).gapRegistry();
        (bool okE, uint32 e) = _registryEpoch(reg);
        if (!okE) return false;
        if (e != l.logEpoch) _resync(l, e);
        (bool ok, bytes memory ret) = reg.staticcall(
            abi.encodeCall(IPangeaGapRegistry.officialPool, (address(this)))
        );
        if (!ok || ret.length != 192) return false;
        (bool set, IPangeaGapRegistry.OfficialPool memory p) = abi.decode(ret, (bool, IPangeaGapRegistry.OfficialPool));
        if (!set || p.poolId == bytes32(0)) return false;
        (bool okDec, uint8 dec) = _quoteDecimalsOf(p.quote);
        l.poolId = p.poolId;
        l.poolQuote = p.quote;
        l.quoteDecimals = okDec ? dec : 255;
        l.poolHook = p.hook;
        l.poolLpFee = p.lpFee;
        l.rec = S.Record({blockNumber: 0, last: 0, known: true, tokenIs0: p.tokenIsCurrency0, feeBps: 0});
        return true;
    }

    // ------------------------------------------------------------- the price log

    /// @notice The price a send (`receive_` false: the lowest token price of the live price and
    ///         the entries it would consume, E5 audit H-1) or a receive (the highest) of `amountLD`
    ///         would get from the log now at pool fee `feeNow`; ok false when the log cannot price it
    ///         (GapNeedRecords / the NEED_RECORDS hold). `cons` (receive only, E5 audit M-3): the most
    ///         conservative price, max(live, every window entry's highest) -- what a receive is first
    ///         priced at (0: the live price is unknown or the window holds fewer than minBlocks entries).
    function gapLogQuote(bool receive_, uint256 amountLD, uint32 feeNow)
        external
        view
        returns (bool ok, uint160 sqrt, uint160 cons)
    {
        GapPriceLog.Plan memory r = _logPlan(_pool(), receive_, amountLD, feeNow);
        return (r.ok, r.sqrt, r.cons);
    }

    /// @notice E5 (AMENDMENT 6 requireCover): whether a send to `dstEid` in THIS block would be
    ///         granted the gas cover -- exactly the send's decision (GapCoverLib.sourceCover on the
    ///         same reads): this chain's cover cap is set, the route's window cover is not spent
    ///         (lastCoverWindowP1[dstEid] != the window + 1), and the native USD price reads when the
    ///         cover needs it (units and the counted basefee non-zero). A send with the requireCover
    ///         flag (oftCmd) reverts GapCoverNotGranted exactly when this answers false. Reverts only
    ///         with GapGasTooLow (from the registry's route guard).
    function gapCoverAvailable(uint32 dstEid) external view returns (bool) {
        address reg = IPangeaOFTV3Self(address(this)).gapRegistry();
        IPangeaGapRegistry.GasCover memory c = _gasCover(reg);
        uint64 last = S.layout().lastCoverWindowP1[dstEid];
        uint256 usd;
        if (GapCoverLib.sourceNeedsNativePrice(c, block.basefee, block.timestamp, last)) {
            usd = _registryUsd(reg, address(0), false);
        }
        GapCoverLib.Source memory s = GapCoverLib.sourceCover(c, block.basefee, block.timestamp, last, usd);
        return !s.refuse && s.srcCoverCapCents != 0;
    }

    /// @notice E6 (audit E5 M-A, gas): a receive's plan for the gap module's receive (gapReceive /
    ///         gapPreview), with the official pool the module has already read passed in (`id`, `pm`,
    ///         `reg`, `tokenIs0`, `epoch`: the module's _pool(), on this same state), so the plan does
    ///         not read it again. Answers gapLogQuote(true, ...)'s (ok, walk, cons), the plan's
    ///         liveCounts (GapPriceLog.Plan: the walk can depend on the live price, audit E5 M-B) and its
    ///         takes packed as logCaps lanes (`add`, what gapLogConsume applies). A view: a caller
    ///         passing other values only gets a plan for them.
    function gapLogPlanR(bytes32 id, address pm, address reg, bool tokenIs0, uint32 epoch, uint256 amountLD, uint32 feeNow)
        external
        view
        returns (bool ok, uint160 walk, uint160 cons, bool liveCounts, uint256[6] memory add)
    {
        P memory p;
        (p.known, p.id, p.pm, p.reg, p.tokenIs0, p.epoch) = (true, id, pm, reg, tokenIs0, epoch);
        GapPriceLog.Plan memory r = _logPlan(p, true, amountLD, feeNow);
        if (r.ok) add = GapPriceLog.packTakes(r);
        return (r.ok, r.sqrt, r.cons, r.liveCounts, add);
    }

    /// @notice A priced receive's consumption: the takes its plan (gapLogPlanR, on this same state in
    ///         the same receive: nothing writes the log between the two) packed as logCaps lanes, added
    ///         to the entries' caps (no writer reward). E6 (audit E5 M-A, gas): applied as planned, not
    ///         planned again. Only the token itself (gapReceive).
    function gapLogConsume(uint256[6] calldata add) external {
        if (msg.sender != address(this)) revert NotSelf();
        GapPriceLog.addCaps(S.layout(), add);
    }

    /// @notice On a new official epoch, empty the log and drop the pool copy (`_resync`, O(1)).
    ///         PERMISSIONLESS (E5, audit M-1): anyone may run it with all the gas they like; it acts
    ///         only when the registry's officialEpoch differs from the log's. The token also runs it
    ///         from recordPrice when a record comes from another pool. Until it has run (or a send,
    ///         poke or the new pool's first swap ran it), nothing prices: a send reverts and a receive
    ///         holds (never the live price on an epoch mismatch).
    function gapLogResync() external {
        (bool okE, uint32 e) = _registryEpoch(IPangeaOFTV3Self(address(this)).gapRegistry());
        S.Layout storage l = S.layout();
        if (okE && e != l.logEpoch) _resync(l, e);
    }

    /// @notice A permissionless price-log write (GapPriceLog): the official pool's live price into
    ///         this second's entry, by a top-level EOA (msg.sender == tx.origin, no code: a 7702
    ///         account is excluded) while the PoolManager is LOCKED; then the V2 hops of the routes
    ///         are poked (spec 5). Anything else is skipped (returns false), never reverted. The writer
    ///         earns `rewardBps` of every send its entry later prices (claimWriterRewards).
    ///         E6 (rehearsal a9e6e, lead #4): never a skip for want of gas -- GapGasTooLow instead
    ///         (below LOG_WRITE_MIN_GAS at the write, or below POKE_ROUTES_GAS for the route pokes
    ///         after it), so a gas estimate lands on a writing gas, never on a mined no-op. The skips
    ///         that remain (false, no revert) mean "nothing to write": no official pool, a contract /
    ///         7702 / non-top-level caller, the PoolManager unlocked, an unknown price, the fee, the
    ///         log settings or the epoch unreadable.
    function poke() external returns (bool wrote) {
        P memory p = _pool();
        if (!p.known) return false;
        wrote = _logWrite(p, msg.sender, false);
        if (wrote) {
            uint256 left = gasleft();
            if (left < POKE_ROUTES_GAS) revert IPangeaOFTV3Gap.GapGasTooLow(POKE_ROUTES_GAS, left);
            _pokeRoutes(p.quote);
        }
    }

    /// @dev E6: what _pokeRoutes may use at most: two routes, each one route read and two hop pokes
    ///      (each with its isReader check), every cap with its 64/63 and POKE_FLOOR (GapModuleBase).
    ///      e6-r2fix (audit R2 L-2): + POKE_ROUTES_HEADROOM for what the caps do not count (the cold
    ///      CALLs, the route's ABI copy and the loop), so the LAST hop's poke is never skipped by a poke
    ///      sent at exactly its estimate (322,124 alone left ~0.5k).
    uint256 internal constant POKE_ROUTES_HEADROOM = 10_000;
    uint256 internal constant POKE_ROUTES_GAS = 2 * (ROUTE_READ_GAS * 64 / 63 + POKE_FLOOR + 2 * (POKE_GAS * 64 / 63 + POKE_FLOOR + ISREADER_GAS))
        + POKE_ROUTES_HEADROOM;

    /// @notice The listing factory's first entry, right after the launch buys (no writer, no
    ///         reward; the EOA rule does not apply, the lock rule does). Only a registry-listed factory.
    function gapSeedLog() external {
        P memory p = _pool();
        if (!p.known || !_registryFlag(p.reg, abi.encodeCall(IPangeaGapRegistry.isFactory, (msg.sender)))) {
            revert NotListedFactory();
        }
        _logWrite(p, address(0), true);
    }

    /// @notice Run by the token's `_debit` only (its fallback refuses this selector): a V1-hook
    ///         pool's send CONSUMES the price log for `amountSD` (GapNeedRecords when it cannot:
    ///         nothing moves; anyone pokes and it lands a second later), owes the consumed entries'
    ///         writers their reward out of `feeLD` (the bridge fee; returned: the token keeps it for
    ///         them), and leaves the price for `gapMessage` in transient storage (LOG_T). Then the
    ///         sender's own entry is written (rules as `poke`). A V2 pool consumes nothing.
    ///         e6-r2fix: a send ABOVE the window's free capacity whose window holds minBlocks entries is
    ///         not refused here: it is marked co-signed (LOG_T bit 253, the window minimum, nothing
    ///         consumed) and the sender's coSignNonce raised; its gapMessage then requires a delivery
    ///         key's co-sign for that nonce (else GapNeedRecords, the whole send reverting).
    ///         AMENDMENT 6 (lead decision 1): the route's cover window -- when this chain's cover cap and
    ///         window are set and the window of `block.timestamp` was not yet covered for `dstEid`, it is
    ///         marked covered here (lastCoverWindowP1[dstEid] = w + 1): the one state write of the cover,
    ///         made only by a real send (a send that then refuses, GapSourceUnreadable, reverts it).
    ///         The state BEFORE it, the bridge fee `feeBps` the token charged and `dstEid` go to the send's
    ///         gapMessage in transient storage (COVER_T), so the header carries exactly this send's cover
    ///         and fee. The writers' reward rate is capped at `feeBps` (the live fee), and the reward
    ///         total at `feeLD` (this send's fee).
    /// @dev Payable: the token's send runs it by DELEGATECALL inside a payable send, whose msg.value
    ///      (the LayerZero fee) the delegatecall keeps; nothing here moves value.
    function gapDebit(uint64 amountSD, uint256 feeLD, uint32 dstEid, uint16 feeBps) external payable returns (uint256 rewardLD) {
        _requireGapGas();
        P memory p = _pool();
        uint256 t = (uint256(1) << 255) | (uint256(amountSD) << 160);
        if (p.known && p.kind == uint8(IPangeaGapRegistry.HookKind.V1)) {
            (bool okFee, uint32 fee) = _registryPoolFee(p.reg);
            if (okFee && fee < GapMath.PPM) {
                uint256 amountLD = uint256(amountSD) * DECIMAL_CONVERSION_RATE;
                GapPriceLog.Plan memory r = _logPlan(p, false, amountLD, fee);
                if (r.ok) {
                    (, GapPriceLog.Params memory prm) = _logParams(p.reg);
                    uint16 rb = prm.rewardBps < feeBps ? prm.rewardBps : feeBps;
                    rewardLD = GapPriceLog.apply_(S.layout(), r, amountLD, rb, feeLD);
                    t |= (uint256(1) << 254) | uint256(r.sqrt);
                } else if (r.cons != 0) {
                    // e6-r2fix (owner 2026-10-30): OVERSIZED -- above the window's free capacity. It
                    // lands only CO-SIGNED by a registry delivery key (gapMessage checks the co-sign in
                    // the send's oftCmd against the nonce this raises; without one the whole send
                    // reverts GapNeedRecords, this included), priced at the WINDOW MINIMUM (r.cons: the
                    // lowest of live and every window entry's lo, never the current second), consuming
                    // NO capacity and paying no writer reward. Bit 253: the co-signed price.
                    S.layout().coSignNonce[msg.sender]++;
                    t |= (uint256(1) << 254) | (uint256(1) << 253) | uint256(r.cons);
                } else {
                    revert IPangeaOFTV3Gap.GapNeedRecords();
                }
            }
        }
        bytes32 slot = LOG_T;
        assembly ("memory-safe") {
            tstore(slot, t)
        }
        _coverWindow(p.reg, dstEid, feeBps, amountSD);
        if (p.known) _logWrite(p, msg.sender, false);
    }

    /// @dev AMENDMENT 6: mark the route's window covered (see gapDebit) and leave COVER_T (E5 audit
    ///      I-2: keyed by (amountSD, dstEid), so only this send's own gapMessage reads it and LOG_T).
    function _coverWindow(address reg, uint32 dstEid, uint16 feeBps, uint64 amountSD) internal {
        S.Layout storage l = S.layout();
        uint64 last = l.lastCoverWindowP1[dstEid];
        IPangeaGapRegistry.GasCover memory c = _gasCover(reg);
        if (c.coverCapCents != 0 && c.coverWindowSeconds != 0) {
            uint64 w = GapCoverLib.coverWindowIndex(block.timestamp, c.coverWindowSeconds);
            if (GapCoverLib.coverGranted(last, w)) l.lastCoverWindowP1[dstEid] = w + 1;
        }
        uint256 t = (uint256(1) << 255) | (uint256(feeBps) << 208) | (uint256(dstEid) << 160) | (uint256(amountSD) << 64)
            | uint256(last);
        bytes32 slot = COVER_T;
        assembly ("memory-safe") {
            tstore(slot, t)
        }
    }

    /// @notice What this token's route toward `dstEid` last carried a cover in (window index + 1; 0 never).
    function gapLastCoverWindowP1(uint32 dstEid) external view returns (uint64) {
        return S.layout().lastCoverWindowP1[dstEid];
    }

    /// @notice e6-r2fix (owner 2026-10-30): the largest single send the price log prices now WITHOUT a
    ///         co-sign -- `maxAmountLD`, the amount the send carries (LD, net of the bridge fee: OFT
    ///         quoteOFT's amountReceivedLD; a whole amountSD), every amount up to it fits and every one
    ///         above it reverts GapNeedRecords unless co-signed; `perEntryLD`, what ONE fresh entry's
    ///         full capacity (at the pool fee now) covers at the live price over the window's lowest lo
    ///         (the regrowth per poked entry); the log's `windowSec` and `minBlocks`. A pool not priced
    ///         by the log (V2 hook): (max, max, 0, 0). Nothing reads (no pool, another epoch, settings,
    ///         fee, liquidity or live price unreadable): all 0. JS mirror: script/gap/gap-evm-split.mjs.
    function gapMaxSend() external view returns (uint256 maxAmountLD, uint256 perEntryLD, uint32 windowSec, uint8 minBlocks) {
        P memory p = _pool();
        if (!p.known) return (0, 0, 0, 0);
        if (p.kind != uint8(IPangeaGapRegistry.HookKind.V1)) return (type(uint256).max, type(uint256).max, 0, 0);
        S.Layout storage l = S.layout();
        (bool okP, GapPriceLog.Params memory prm) = _logParams(p.reg);
        (bool okFee, uint32 fee) = _registryPoolFee(p.reg);
        if (p.epoch != l.logEpoch || !okP || !okFee || fee >= GapMath.PPM) return (0, 0, 0, 0);
        uint128 liq = _lockedLiquidity(p);
        uint160 live = _liveSqrt(p.pm, p.id);
        if (liq == 0 || !_knownSqrt(live)) return (0, 0, 0, 0);
        (uint256 m, uint160 dLo) = GapPriceLog.maxSend(l, prm, p.tokenIs0, liq, fee, block.timestamp, live);
        uint256 per = GapPriceLog.maxForFree(GapPriceLog.capacity(prm, fee, fee), live, dLo == 0 ? live : dLo, liq, p.tokenIs0);
        return (m / DECIMAL_CONVERSION_RATE * DECIMAL_CONVERSION_RATE, per / DECIMAL_CONVERSION_RATE * DECIMAL_CONVERSION_RATE, prm.window, prm.minBlocks);
    }

    /// @notice e6-r2fix: the nonce `sender`'s next co-signed oversized send must carry (the GapCoSign
    ///         struct's `nonce`; raised by one by each such send).
    function gapCoSignNonce(address sender) external view returns (uint256) {
        return S.layout().coSignNonce[sender];
    }

    /// @notice Run by the token's `claimWriterRewards` only (fallback refuses it): everything owed
    ///         to msg.sender, zeroed here; the token then transfers it from its own balance.
    function gapClaimTake() external returns (uint256) {
        return GapPriceLog.take(S.layout(), msg.sender);
    }

    /// @notice What `writer` could claim now.
    function writerRewards(address writer) external view returns (uint256) {
        return GapPriceLog.owedTo(S.layout(), writer);
    }

    /// @notice Every writer reward owed and unclaimed (held in the token's own balance).
    function gapRewardsOwed() external view returns (uint256) {
        return S.layout().rewardsOwedLD;
    }

    /// @notice The log's latest entry index, entries in use, and epoch.
    function gapLog() external view returns (uint8 head, uint8 count, uint32 epoch) {
        S.Layout storage l = S.layout();
        return (l.logHead, l.logCount, l.logEpoch);
    }

    /// @notice Ring entry `i` (GapPriceLog): lowSqrt / highSqrt the sqrt of the lowest / highest
    ///         TOKEN price of its second.
    function gapLogEntry(uint256 i)
        external
        view
        returns (uint40 key, uint160 lowSqrt, uint160 highSqrt, uint32 feePpm, uint64 capUsed, address writer, uint96 owedLD)
    {
        S.Layout storage l = S.layout();
        uint256 j = 3 * (i % GapPriceLog.ENTRIES);
        uint256 a = l.logRing[j];
        uint256 b = l.logRing[j + 1];
        key = uint40(GapPriceLog.key(a));
        lowSqrt = GapPriceLog.lo(a);
        feePpm = GapPriceLog.fee(a);
        capUsed = uint64(GapPriceLog.capOf(l, i % GapPriceLog.ENTRIES));
        highSqrt = GapPriceLog.hi(b);
        owedLD = uint96(GapPriceLog.owed(b));
        writer = address(uint160(l.logRing[j + 2]));
    }

    /// @dev The consumption a send or receive of `amountLD` would make now; none (ok false) when the
    ///      log is of another epoch, the settings or the locked liquidity do not read, or it is short.
    function _logPlan(P memory p, bool receive_, uint256 amountLD, uint32 feeNow)
        internal
        view
        returns (GapPriceLog.Plan memory r)
    {
        S.Layout storage l = S.layout();
        if (p.epoch != l.logEpoch) return r;
        (bool ok, GapPriceLog.Params memory prm) = _logParams(p.reg);
        if (!ok) return r;
        uint128 liq = _lockedLiquidity(p);
        if (liq == 0) return r;
        // E5 (audit H-1): the live price joins the run (send: the lower; receive: the higher); an
        // unknown live price prices nothing (a send refuses, a receive holds).
        uint160 live = _liveSqrt(p.pm, p.id);
        if (!_knownSqrt(live)) return r;
        return GapPriceLog.plan(l, prm, receive_, amountLD, p.tokenIs0, liq, feeNow, block.timestamp, live);
    }

    /// @dev One log write (GapPriceLog.write) of the pool's live price, or a skip (false): not a
    ///      top-level EOA (unless `seed`), too little gas left, the PoolManager unlocked (a write
    ///      inside an unlock could record a mid-callback price), an unknown price, the fee or the
    ///      settings unreadable. A new epoch empties the log first (`_resync`).
    function _logWrite(P memory p, address writer, bool seed) internal returns (bool) {
        if (!seed && (msg.sender != tx.origin || tx.origin.code.length != 0)) return false;
        // E6 (rehearsal a9e6e, lead #4): never skipped for the caller's gas choice (poke, a send's own
        // write, the factory's seed): GapGasTooLow, retriable, so estimates size a writing gas. A
        // successful send always has more here (its gapMessage needs GAP_READ_GAS after it).
        {
            uint256 left = gasleft();
            if (left < LOG_WRITE_MIN_GAS) revert IPangeaOFTV3Gap.GapGasTooLow(LOG_WRITE_MIN_GAS, left);
        }
        if (!_pmLocked(p.pm)) return false;
        uint160 s = _liveSqrt(p.pm, p.id);
        if (!_knownSqrt(s)) return false;
        (bool okFee, uint32 fee) = _registryPoolFee(p.reg);
        if (!okFee || fee >= GapMath.PPM) return false;
        (bool okP, GapPriceLog.Params memory prm) = _logParams(p.reg);
        if (!okP) return false;
        (bool okE, uint32 e) = _registryEpoch(p.reg);
        if (!okE) return false;
        S.Layout storage l = S.layout();
        if (e != l.logEpoch) _resync(l, e);
        GapPriceLog.write(l, prm, block.timestamp, s, fee, seed ? address(0) : writer, p.tokenIs0);
        return true;
    }

    /// @dev The PoolManager is locked: exttload(Lock.IS_UNLOCKED_SLOT) answers 0.
    function _pmLocked(address pm) internal view returns (bool locked) {
        bytes4 sel = EXTTLOAD;
        bytes32 slot = PM_UNLOCKED_SLOT;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), slot)
            let ok := staticcall(20000, pm, m, 36, 0, 32)
            locked := and(and(ok, eq(returndatasize(), 32)), iszero(mload(0)))
        }
    }

    /// @dev The registry's log settings; ok false unless it answers eight in-range words.
    function _logParams(address reg) internal view returns (bool ok, GapPriceLog.Params memory prm) {
        (bool success, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.logParams, ()));
        if (!success || ret.length != 256) return (false, prm);
        (uint256 km, uint256 kf, uint256 kx, uint256 w, uint256 mb, uint256 rb, uint256 mg, uint256 pf) =
            abi.decode(ret, (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256));
        if (
            km > 1 || kf < GapPriceLog.K_PPM_MIN || kf > GapPriceLog.K_PPM_MAX || kx > GapPriceLog.K_FACTOR_MAX_PPM || w == 0
                || w > GapPriceLog.WINDOW_MAX_SEC || mb < GapPriceLog.MIN_BLOCKS_MIN || mb > GapPriceLog.MIN_BLOCKS_MAX
                || rb > GapPriceLog.REWARD_MAX_BPS || mg > 1 || pf < GapPriceLog.PLATFORM_FLOOR_MIN_PPM || pf > GapPriceLog.PLATFORM_FLOOR_MAX_PPM
        ) return (false, prm);
        if (kf > pf / 3) return (false, prm); // E6: the flat k bound (setLogParams)
        prm = GapPriceLog.Params(uint8(km), uint32(kf), uint32(kx), uint32(w), uint8(mb), uint16(rb), mg == 1, uint32(pf));
        ok = true;
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import {IGapReader} from "./IGapReader.sol";
import {IPangeaGapRegistry} from "./IPangeaGapRegistry.sol";
import {IPangeaOFTV3Gap} from "./IPangeaOFTV3Gap.sol";
import {GapMath} from "./GapMath.sol";
import {GapCoverLib} from "./GapCoverLib.sol";
import {GapPriceLog} from "./GapPriceLog.sol";
import {GapPriceLib} from "./GapPriceLib.sol";
import {PangeaOFTV3Storage as S} from "./PangeaOFTV3Storage.sol";

/// @dev What the module asks of the token it runs as (its own address): its per-chain immutables,
///      its endpoint, its OApp peers and enforced options, and the credit, which only the token
///      itself may call.
interface IPangeaOFTV3Self {
    function poolManager() external view returns (address);
    function gapRegistry() external view returns (address);
    function endpoint() external view returns (address);
    function peers(uint32 eid) external view returns (bytes32);
    function enforcedOptions(uint32 eid, uint16 msgType) external view returns (bytes memory);
    function gapCredit(address to, uint256 amountLD, uint32 srcEid) external returns (uint256 credited);
    function gapLogModule() external view returns (address);
}

/// @title GapModuleBase -- the internals PangeaOFTV3GapModule and PangeaOFTV3LogModule share
/// @notice Both modules run ONLY by DELEGATECALL as a PangeaOFTV3 (the log module through the gap
///         module's fallback): the official pool as both read it, the registry reads, the
///         PoolManager reads, the V2 hop pokes and the epoch resync. No state of its own.
abstract contract GapModuleBase {
    /// @dev PangeaFeeHookV2.MIN_FEE_BPS: the hook fee counted for the opening price, and while the
    ///      pool has no record, once its fee has been changed (round-4 audit M-1; a test pins it to
    ///      the hook's). A COPY of PangeaFeeHookV2's constant, the one hook of HookKind.V2: if another
    ///      V2-kind hook is ever listed with a different minimum, read it from that hook instead
    ///      (round-5 Info). Kept as a constant: one hook kind, and no extra call on the record path.
    uint16 internal constant HOOK_MIN_FEE_BPS = 30;
    /// @dev PangeaFeeHookV2.feeChanged(bytes32) and the gas its read may use.
    bytes4 internal constant FEE_CHANGED = bytes4(keccak256("feeChanged(bytes32)"));
    uint256 internal constant FEE_CHANGED_GAS = 10_000;
    /// @dev The gas a quote token's `decimals()` may use when the pool is first cached.
    uint256 internal constant DECIMALS_GAS = 30_000;
    uint8 internal constant TOKEN_DECIMALS = 9;
    /// @dev extsload(bytes32): the v4 PoolManager's raw storage read.
    bytes4 internal constant EXTSLOAD = 0x1e2eaeaf;
    /// @dev v4's `pools` mapping slot (StateLibrary.POOLS_SLOT) and Pool.State's positions offset.
    uint256 internal constant POOLS_SLOT = 6;
    uint256 internal constant POSITIONS_OFFSET = 6;
    // --- the V2 hop pokes (v3c §5) on a record
    /// @dev The gas cap of one `IGapReader.poke` and of one `registry.route` read in `recordPrice`.
    uint256 internal constant POKE_GAS = 50_000;
    uint256 internal constant ROUTE_READ_GAS = 30_000;
    /// @dev The gas cap of the registry's `isReader` check before each poke (audit I-1).
    uint256 internal constant ISREADER_GAS = 10_000;
    /// @dev What `recordPrice` keeps for itself after the last poke (its return).
    uint256 internal constant POKE_FLOOR = 3_000;

    // --- the price log (v3c-evm-log, GapPriceLog)
    /// @dev The transient word gapDebit leaves for the send's gapMessage (a staticcall, which may tload).
    bytes32 internal constant LOG_T = bytes32(uint256(keccak256("pangea.oft.v3.log.send")) - 1);
    /// @dev v4 Lock.IS_UNLOCKED_SLOT and IExttload.exttload(bytes32).
    bytes32 internal constant PM_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;
    bytes4 internal constant EXTTLOAD = bytes4(keccak256("exttload(bytes32)"));
    /// @dev A log write starts only with this much gas left (E6: else GapGasTooLow, never a silent skip).
    uint256 internal constant LOG_WRITE_MIN_GAS = 150_000;
    /// @dev PangeaOFTV3's: nine local decimals, LayerZero's six shared, so amountLD = amountSD x 1e3.
    uint256 internal constant DECIMAL_CONVERSION_RATE = 1e3;

    /// @dev Poke every hop of `quote`'s route and of the native route (v3c §5): a V2-style reader
    ///      stores its pair's price from reserves not touched in this block; any other reader
    ///      reverts or does nothing. Gas-capped (POKE_GAS each, ROUTE_READ_GAS per route read) and
    ///      every failure ignored; a poke starts only while its whole cap is left over POKE_FLOOR,
    ///      so the record above is never lost to them (the hook gives recordPrice RECORD_GAS and
    ///      ignores its result). The record does not depend on a poke: a skipped poke only leaves
    ///      the reader with an older record (spec: unreadable once older than v2RecordMaxAge).
    function _pokeRoutes(address quote) internal {
        address reg = IPangeaOFTV3Self(address(this)).gapRegistry();
        _pokeRoute(reg, quote);
        if (quote != address(0)) _pokeRoute(reg, address(0));
    }

    function _pokeRoute(address reg, address quote) internal {
        if (gasleft() < ROUTE_READ_GAS * 64 / 63 + POKE_FLOOR) return;
        (bool ok, bytes memory ret) = reg.staticcall{gas: ROUTE_READ_GAS}(abi.encodeCall(IPangeaGapRegistry.route, (quote)));
        // A Hop[] of n static 160-byte hops is offset | n | hops (reader, poolRef, tokenIn,
        // tokenOut, gasCap): anything else is skipped. Read by hand, never abi.decode (which
        // reverts on a malformed answer, and no failure here may revert the record).
        if (!ok || ret.length < 64) return;
        uint256 off;
        uint256 n;
        assembly ("memory-safe") {
            off := mload(add(ret, 32))
            n := mload(add(ret, 64))
        }
        if (off != 32 || n == 0 || n > 2 || ret.length != 64 + n * 160) return;
        for (uint256 i; i < n; i++) {
            if (gasleft() < POKE_GAS * 64 / 63 + POKE_FLOOR + ISREADER_GAS) return;
            address reader;
            bytes32 poolRef;
            assembly ("memory-safe") {
                let h := add(add(ret, 96), mul(i, 160))
                reader := and(mload(h), 0xffffffffffffffffffffffffffffffffffffffff)
                poolRef := mload(add(h, 32))
            }
            // Audit I-1: only a reader the registry still lists is poked.
            {
                (bool okR, bytes memory rr) =
                    reg.staticcall{gas: ISREADER_GAS}(abi.encodeCall(IPangeaGapRegistry.isReader, (reader)));
                if (!okR || rr.length != 32 || abi.decode(rr, (uint256)) != 1) continue;
            }
            bytes memory cd = abi.encodeCall(IGapReader.poke, (poolRef));
            assembly ("memory-safe") {
                pop(call(POKE_GAS, reader, 0, add(cd, 32), mload(cd), 0, 0))
            }
        }
    }

    /// @dev The official pool's LOCKED liquidity: the registry's officialPosition, read in the
    ///      PoolManager. 0 when unknown.
    function _lockedLiquidity(P memory p) internal view returns (uint128) {
        (bool ok, bytes memory ret) = _registryCall(p.reg, abi.encodeCall(IPangeaGapRegistry.officialPosition, (address(this))));
        if (!ok || ret.length != 32) return 0;
        bytes32 key = abi.decode(ret, (bytes32));
        if (key == bytes32(0)) return 0;
        return _positionLiquidity(p.pm, p.id, key);
    }

    /// @dev v4 `pools[id].positions[key].liquidity` by extsload (StateLibrary.getPositionLiquidity).
    function _positionLiquidity(address pm, bytes32 id, bytes32 key) internal view returns (uint128 liq) {
        bytes32 slot = keccak256(abi.encodePacked(key, bytes32(uint256(keccak256(abi.encodePacked(id, POOLS_SLOT))) + POSITIONS_OFFSET)));
        bytes4 sel = EXTSLOAD;
        bool ok;
        uint256 w;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), slot)
            ok := staticcall(gas(), pm, m, 36, 0, 32)
            if and(ok, eq(returndatasize(), 32)) { w := mload(0) }
        }
        liq = uint128(w);
    }

    /// @dev Inside TickMath's range (0, no record, is outside it).
    function _knownSqrt(uint160 s) internal pure returns (bool) {
        return s >= GapPriceLib.MIN_SQRT_PRICE && s <= GapPriceLib.MAX_SQRT_PRICE;
    }

    /// @dev The official pool as both sides price it.
    struct P {
        bool known;
        bytes32 id;
        address quote;
        bool tokenIs0;
        uint8 quoteDecimals;
        address hook;
        uint24 lpFee;
        address pm;
        address reg;
        /// @dev The registry did not answer whether there is an official pool (known is false).
        bool unreadable;
        /// @dev The registry's HookKind of `hook` (0 NONE on any failure): V1 prices from the
        ///      price log (GapPriceLog), V2 from the hook's records.
        uint8 kind;
        /// @dev The registry's officialEpoch of this token (0 when unreadable).
        uint32 epoch;
    }

    /// @dev The official pool from the token's copy, or (before the first record) from the
    ///      registry; and the token's PoolManager and registry (its immutables, asked of itself).
    function _pool() internal view returns (P memory p) {
        p.pm = IPangeaOFTV3Self(address(this)).poolManager();
        p.reg = IPangeaOFTV3Self(address(this)).gapRegistry();
        S.Layout storage l = S.layout();
        S.Record memory r = l.rec;
        (, p.epoch) = _registryEpoch(p.reg);
        // v3c-evm-log: a cached pool of an earlier epoch (re-pointed since) is not used.
        if (r.known && p.epoch == l.logEpoch) {
            (p.known, p.id, p.quote, p.tokenIs0, p.quoteDecimals, p.hook) =
                (true, l.poolId, l.poolQuote, r.tokenIs0, l.quoteDecimals, l.poolHook);
            p.lpFee = l.poolLpFee;
            p.kind = _registryHookKind(p.reg, p.hook);
            return p;
        }
        (bool ok, bytes memory ret) = _registryCall(p.reg, abi.encodeCall(IPangeaGapRegistry.officialPool, (address(this))));
        if (!ok || ret.length != 192) {
            p.unreadable = true;
            return p;
        }
        (bool set, IPangeaGapRegistry.OfficialPool memory o) = abi.decode(ret, (bool, IPangeaGapRegistry.OfficialPool));
        if (!set || o.poolId == bytes32(0)) return p;
        (bool okDec, uint8 dec) = _quoteDecimalsOf(o.quote);
        (p.known, p.id, p.quote, p.tokenIs0, p.quoteDecimals, p.hook) =
            (true, o.poolId, o.quote, o.tokenIsCurrency0, okDec ? dec : 255, o.hook);
        p.lpFee = o.lpFee;
        p.kind = _registryHookKind(p.reg, p.hook);
    }

    /// @dev The official pool's live sqrtPriceX96 (slot0's low 160 bits); 0 on any failure.
    function _liveSqrt(address pm, bytes32 id) internal view returns (uint160 s) {
        bytes32 slot = keccak256(abi.encodePacked(id, POOLS_SLOT));
        bytes4 sel = EXTSLOAD;
        bool ok;
        uint256 w;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), slot)
            ok := staticcall(gas(), pm, m, 36, 0, 32)
            if and(ok, eq(returndatasize(), 32)) { w := mload(0) }
        }
        s = uint160(w);
    }

    function _quoteDecimalsOf(address quote) internal view returns (bool ok, uint8 d) {
        if (quote == address(0)) return (true, 18);
        uint256 w;
        uint256 size;
        assembly ("memory-safe") {
            mstore(0, 0x313ce56700000000000000000000000000000000000000000000000000000000) // decimals()
            ok := staticcall(DECIMALS_GAS, quote, 0, 4, 0, 32)
            size := returndatasize()
            if and(ok, eq(size, 32)) { w := mload(0) }
        }
        if (!ok || size != 32 || w > type(uint8).max) return (false, 0);
        return (true, uint8(w));
    }

    /// @dev The registry's HookKind for `hook` (0 = NONE on any failure); GapGasTooLow passed on.
    function _registryHookKind(address reg, address hook) internal view returns (uint8 kind) {
        (bool ok, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.hookKind, (hook)));
        if (!ok || ret.length != 32) return 0;
        uint256 v = abi.decode(ret, (uint256));
        return v > type(uint8).max ? 0 : uint8(v);
    }

    function _registryPoolFee(address reg) internal view returns (bool ok, uint32 ppm) {
        (bool success, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.poolFeePpm, (address(this))));
        if (!success || ret.length != 64) return (false, 0);
        (uint256 o, uint256 v) = abi.decode(ret, (uint256, uint256));
        if (o != 1 || v > type(uint32).max) return (false, 0);
        return (true, uint32(v));
    }

    /// @dev A registry bool (gapEscape, isFactory): true only for exactly abi.encode(true); any
    ///      failure is false (the escape off, not a seeder: never the free direction).
    function _registryFlag(address reg, bytes memory data) internal view returns (bool) {
        (bool ok, bytes memory ret) = _registryCall(reg, data);
        return ok && ret.length == 32 && abi.decode(ret, (uint256)) == 1;
    }

    /// @dev A registry read. Its GapGasTooLow is passed on (retriable); any other failure is
    ///      returned as `ok == false` and costs the fee, never the receive.
    function _registryCall(address reg, bytes memory data) internal view returns (bool ok, bytes memory ret) {
        (ok, ret) = reg.staticcall(data);
        if (!ok && ret.length >= 4 && bytes4(ret) == IPangeaOFTV3Gap.GapGasTooLow.selector) {
            assembly ("memory-safe") {
                revert(add(ret, 32), mload(ret))
            }
        }
    }

    /// @dev AMENDMENT 6: the transient word a send's gapDebit leaves for its gapMessage (a staticcall):
    ///      bit 255 set | bridge fee bps << 208 | dstEid << 160 | lastCoverWindowP1[dstEid] BEFORE the
    ///      send's own store. The token clears it once the send is built.
    bytes32 internal constant COVER_T = bytes32(uint256(keccak256("pangea.oft.v3.cover.send")) - 1);

    /// @dev A registry word (one 32-byte answer); ok false on any failure; GapGasTooLow passed on.
    function _registryWord(address reg, bytes memory data) internal view returns (bool ok, uint256 v) {
        bytes memory ret;
        (ok, ret) = _registryCall(reg, data);
        if (!ok || ret.length != 32) return (false, 0);
        v = abi.decode(ret, (uint256));
    }

    /// @dev v3c-evm-final: the registry's bridge fee (bps); unreadable or above the bound: the default
    ///      20, never 0 for want of an answer (the token's own read is the same rule, gas-capped).
    function _bridgeFeeBps(address reg) internal view returns (uint16) {
        (bool ok, uint256 v) = _registryWord(reg, abi.encodeCall(IPangeaGapRegistry.bridgeFeeBps, ()));
        return ok && v <= GapMath.BRIDGE_FEE_MAX_BPS ? uint16(v) : GapMath.BRIDGE_FEE_DEFAULT_BPS;
    }

    /// @dev AMENDMENT 6: the registry's gas cover. Any failure, a value out of its type, or a setting
    ///      outside the hard caps (GapCoverLib.validGasCover) is the zero struct: no cover (less
    ///      allowance, never more).
    function _gasCover(address reg) internal view returns (IPangeaGapRegistry.GasCover memory c) {
        (bool ok, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.gasCover, ()));
        if (!ok || ret.length != 192) return c;
        (uint256 su, uint256 se, uint256 fl, uint256 cp, uint256 cc, uint256 w) =
            abi.decode(ret, (uint256, uint256, uint256, uint256, uint256, uint256));
        if (su > type(uint32).max || se > type(uint32).max || fl > type(uint64).max || cp > type(uint64).max) return c;
        if (cc > type(uint16).max || w > type(uint32).max) return c;
        IPangeaGapRegistry.GasCover memory x =
            IPangeaGapRegistry.GasCover(uint32(su), uint32(se), uint64(fl), uint64(cp), uint16(cc), uint32(w));
        if (GapCoverLib.validGasCover(x)) c = x;
    }

    /// @dev The opening price's fee at the first record: the swap's own fee while the pool's fee
    ///      was never changed since registration (it is the launch fee), else HOOK_MIN_FEE_BPS.
    function _openingFeeBps(address hook, bytes32 id, uint16 feeBps) internal view returns (uint16) {
        return _feeEverChanged(hook, id) ? HOOK_MIN_FEE_BPS : feeBps;
    }

    /// @dev The hook's `feeChanged(id)`, capped at FEE_CHANGED_GAS; any failure counts as changed
    ///      (the lower fee: toward the gap fee).
    function _feeEverChanged(address hook, bytes32 id) internal view returns (bool) {
        (bool ok, bytes memory ret) = hook.staticcall{gas: FEE_CHANGED_GAS}(abi.encodeWithSelector(FEE_CHANGED, id));
        if (!ok || ret.length != 32) return true;
        return abi.decode(ret, (uint256)) != 0;
    }

    /// @dev The registry's usdPerQuoteE18(quote, roundUp); 0 on any failure; GapGasTooLow passed on.
    function _registryUsd(address reg, address quote, bool roundUp) internal view returns (uint256 usd) {
        (bool ok, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.usdPerQuoteE18, (quote, roundUp)));
        if (!ok || ret.length != 32) return 0;
        usd = abi.decode(ret, (uint256));
    }

    /// @dev Spec §6.2: the gap reads need GAP_READ_GAS, or the call reverts (retriable).
    function _requireGapGas() internal view {
        uint256 left = gasleft();
        if (left < GapMath.GAP_READ_GAS) revert IPangeaOFTV3Gap.GapGasTooLow(GapMath.GAP_READ_GAS, left);
    }

    /// @dev A new official epoch (registry repointOfficialPool): the log is emptied (owed rewards
    ///      kept for their writers) and the cached pool and its records dropped, to be learned again.
    function _resync(S.Layout storage l, uint32 e) internal {
        GapPriceLog.reset(l);
        l.logEpoch = e;
        l.rec = S.Record({blockNumber: 0, last: 0, known: false, tokenIs0: false, feeBps: 0});
        (l.recPrev, l.recPrevBlock, l.recPrevFee) = (0, 0, 0);
        (l.recPrev2, l.recPrev2Block, l.recPrev2Fee) = (0, 0, 0);
    }

    /// @dev The registry's officialEpoch(this token); ok false on any failure.
    function _registryEpoch(address reg) internal view returns (bool ok, uint32 e) {
        (bool success, bytes memory ret) = _registryCall(reg, abi.encodeCall(IPangeaGapRegistry.officialEpoch, (address(this))));
        if (!success || ret.length != 32) return (false, 0);
        uint256 v = abi.decode(ret, (uint256));
        if (v > type(uint32).max) return (false, 0);
        return (true, uint32(v));
    }
}

src/v3/gap/GapPriceLib.sol

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

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

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

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

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

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

src/v3/gap/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/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/IPangeaOFTV3Gap.sol

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

/// @title IPangeaOFTV3Gap -- the gap-fee surface of a v3 token (docs/v3c-gap-spec.md, codec v3)
/// @notice Implemented by the v3 EVM OFT (its gap module); read by FastBridge V3, the web and the
///         server. All amounts are local decimals (LD); USD prices are USD per whole token 1e18,
///         class prices are the class asset per whole token 1e18.
interface IPangeaOFTV3Gap {
    /// @notice A v3 message was received and the formula withheld something (`withheldLD` may be 0
    ///         by rounding). `psE18`/`pdE18` are the pair compared: USD when `pairClass == 0`, else
    ///         the class asset of class `pairClass` (both quotes of that class, no hop).
    event GapCharged(
        bytes32 indexed guid,
        uint32 indexed srcEid,
        address indexed to,
        uint256 amountLD,
        uint256 withheldLD,
        uint128 psE18,
        uint256 pdE18,
        uint32 gapPpm,
        uint64 allowPpm,
        uint8 pairClass
    );

    /// @notice A receive credited in full for `reason` (GapMath: ESCAPED 9, SEED_NO_POOL 10, REFUND 11,
    ///         NO_GAP 6 or WITHIN_ALLOWANCE 7). Every other outcome either charged (GapCharged) or reverted.
    event GapSkipped(bytes32 indexed guid, uint32 indexed srcEid, uint8 reason);

    /// @notice gasleft() was below what the gap reads need, on send or receive: a starved read
    ///         would mean a lower fee, so it reverts instead (retriable).
    error GapGasTooLow(uint256 needed, uint256 left);
    /// @notice The message is not codec v3 (any other version byte, or a header below 96 bytes).
    error GapBadVersion();
    /// @notice No official pool on this chain yet and `to` is not a listed seeder: retriable.
    error GapNoPool();
    /// @notice A price, fee, margin or route the receive needs is unreadable (GapMath reason):
    ///         retriable, never fee 0. A fixed route, a new reader or the escape lands it.
    error GapUnreadable(uint8 reason);
    /// @notice The send could price neither in USD nor in its quote's class (fails closed).
    error GapSourceUnreadable();
    /// @notice v3c-evm-log: the price log has too few entries or too little unused capacity for
    ///         this send (nothing moves) or receive (it holds); retriable: anyone pokes, and it
    ///         lands from the next second.
    error GapNeedRecords();

    /// @notice The registry this token reads (immutable).
    function gapRegistry() external view returns (address);

    /// @notice The bridge fee the source takes before sending, ppm: the registry's live bridgeFeeBps() x 100
    ///         (default 20 bps = 2,000 ppm; v3c-evm-final).
    function bridgeFeePpm() external view returns (uint32);

    /// @notice Exactly what a send of `amountSD` (net of the bridge fee, shared decimals) to
    ///         `dstEid` now carries: psE18 = the lower of the two recorded closes (rounded up)
    ///         times the route (0 = unreadable); feeSrcPpm = this pool's fee (held rule) + the
    ///         bridge cost (costPpm: LayerZero's quote for the ENFORCED SEND options of `dstEid`, capped at
    ///         the registry's costMaxUsdE18); bridgeFeePpm_ = the live bridge fee; priceClass = the pool quote's class (0 none); psClassE18 = the
    ///         lower close in quote units (0 unless class != 0); srcGasMicroUsd / srcCoverCapCents = AMENDMENT 6's source gas cover
    ///         (this chain's swap + send gas at this block's basefee, micro-USD, and its cover cap in
    ///         cents; (0, 0) when no cover is set or the route's window cover is spent). Reverts
    ///         GapSourceUnreadable (also: psUsd 0, or the native price unreadable on a granted cover),
    ///         GapNoOfficialPool, GapRegistryUnreadable or GapGasTooLow as the send does.
    function gapSendQuote(uint32 dstEid, uint64 amountSD)
        external
        view
        returns (
            uint128 psE18,
            uint32 feeSrcPpm,
            uint32 bridgeFeePpm_,
            uint8 priceClass,
            uint128 psClassE18,
            uint32 srcGasMicroUsd,
            uint16 srcCoverCapCents
        );

    /// @notice The receive's code path as a view, for a v3 message carrying these header values.
    ///         `holds == true`: the receive would revert retriably (GapNoPool: reason DST_NO_POOL;
    ///         GapUnreadable: reason PS_ZERO / DST_FEE_FAILED / DST_PRICE_FAILED); withheld and
    ///         credited are then 0. The escape on: reason ESCAPED, withheld 0. A no-pool chain
    ///         answers holds (a seeder `to` is credited in full by the receive; the preview has no
    ///         `to`). `pdE18` is the pair's destination price (class units when the class pair is
    ///         used). Never reverts except GapGasTooLow. minCredited is the caller's.
    function gapPreview(
        uint128 psE18,
        uint32 feeSrcPpm,
        uint32 bridgeFeePpm_,
        uint8 priceClass,
        uint128 psClassE18,
        uint32 srcGasMicroUsd,
        uint16 srcCoverCapCents,
        uint256 amountLD
    )
        external
        view
        returns (
            uint256 withheldLD,
            uint256 creditedLD,
            uint256 pdE18,
            uint32 gapPpm,
            uint64 allowPpm,
            uint8 reason,
            bool holds
        );

    /// @notice What the receive of `guid` withheld (0 if none, or not received yet). For
    ///         FastBridge V3, which fronts the credit and reconciles against this.
    function gapWithheld(bytes32 guid) external view returns (uint256 withheldLD);

    /// @notice Everything this token has withheld (= never minted) since deploy.
    function gapBurnedLD() external view returns (uint256);
}

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.