Skip to content
Verified contractPartialUNLICENSED

BridgeRoleV4

Address0xa57e5ec5239d3fa1ff65a6b1a3026bae57da73b8
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
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,399,266
Creation transaction
0x21544edefc…40311fd746

46 files

src/v4/bridge/BridgeRoleV4.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {CoinPreimageV4 as Pre} from "./CoinPreimageV4.sol";
import {PangeaCoinV4} from "./PangeaCoinV4.sol";
import {IBridgeForAdaptersV4} from "./ITransportV4.sol";
import {BridgeStateV4} from "./BridgeStateV4.sol";
import {BridgeCodecV4 as Codec} from "./BridgeCodecV4.sol";
import {ITransportAdapterV4} from "./ITransportV4.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IGapRegistryV4} from "../gap/IGapRegistryV4.sol";
import {IGapOracleV4} from "./gap/IGapOracleV4.sol";
import {BridgeGapV4} from "./gap/BridgeGapV4.sol";
import {GapMathV4} from "../gap/GapMathV4.sol";
import {GapPriceSigV4 as Sig} from "./gap/GapPriceSigV4.sol";

interface IDecodeViewV4 {
    function decodeView(bytes calldata m) external pure returns (Codec.Header memory h, bytes memory tail);
}

/// @notice The bridge's own immutables, read back by the module (it runs as the bridge: address(this)).
interface IPendingCfgRoleV4 {
    function pending() external view returns (bytes memory);
}

interface ICoinGenuineV4 {
    function genuine(address token, bytes32 coinId, address bridge, uint64 createdAt) external view returns (bool);
}

interface IBridgeImmV4 {
    function localPcid() external view returns (uint32);
    function gap() external view returns (BridgeGapV4);
    function oracle() external view returns (IGapOracleV4);
    function core() external view returns (address);
    function rowsHash(uint32[] calldata chains, uint16 mask, uint128 chainTids) external view returns (bytes32);
}

interface IComposerV4 {
    function pangeaCompose(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, uint256 creditedLD, bytes calldata composeMsg)
        external;
}

interface ICoinRingV4 {
    function gapPrices() external view returns (uint256 plast, uint256 pref, uint256 pdRef, uint256 live);
}

/// @title BridgeRoleV4 -- the creator role functions of PangeaBridgeV4 (§11.6), run by DELEGATECALL from the bridge
/// @notice Executes only as the bridge (its storage, its owner); called directly it acts on its own empty storage and
///         holds nothing. Same address on every EVM chain (PangeaDeployerV4; local pcid from `pending()`).
contract BridgeRoleV4 is BridgeStateV4, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    /// @dev No immutables (B1-M5): the same runtime code, hence the same code hash, on every chain.
    /// @dev UPGRADEABLE COIN CREATION: the immutable CoinCodeRegistryV4 registerCoin asks (the bridge's `codeRegistry`;
    ///      from this module's deployer's pending(), so its init code stays constant; VerifyBridgeV4 rebuilds it).
    ICoinGenuineV4 internal immutable _codeRegistry;

    constructor() Ownable(address(0xdead)) {
        _codeRegistry = ICoinGenuineV4(abi.decode(IPendingCfgRoleV4(msg.sender).pending(), (address)));
    }

    /// @dev G-EVMB-1 L-2: the gas a refund's best-effort delivery-charge payment may use (a burner cannot block it).
    uint256 internal constant SOFT_PAY_GAS = 100_000;

    function _local() internal view override returns (uint32) {
        return IBridgeImmV4(address(this)).localPcid();
    }

    function routeOf(uint32, uint8) external pure returns (Route memory) {
        revert NotAdapter();
    }

    function pcidOf(uint8, uint32) external pure returns (uint32) {
        revert NotAdapter();
    }

    function receiveFromTransport(uint32, bytes32, bytes calldata, bytes32, address) external pure {
        revert NotAdapter();
    }

    // ================================================================== open (moved from the bridge, round 4 size)

    // rowsHash (validation + packing of the creation sets): in PangeaBridgeV4 (T17-SIZE, EIP-170), read below by a
    // static self-call (this module runs as the bridge: address(this)).

    /// @notice Registers `pre` on this chain with its freshly deployed `token`, for `opener`, after the §11.5.3 rules:
    ///         (a) home chain: the preimage creator; (b) another listed chain within 1 h of createdAt: the preimage
    ///         creator; (c) otherwise an open authorisation from the home chain naming `opener`, not expired.
    function registerCoin(Pre.Preimage calldata pre, address token, address opener, OfficialPool calldata pool)
        external
        nonReentrant
        returns (bytes32 coinId)
    {
        if (msg.sender != IBridgeImmV4(address(this)).core()) revert NotCore();
        uint32 localPcid = _local();
        Pre.check(pre);
        coinId = Pre.coinId(pre);
        Coin storage c = _coins[coinId];
        if (c.token != address(0)) revert CoinAlreadyOpen(coinId);
        // UPGRADEABLE COIN CREATION: the token must be the GENUINE coin (CoinCodeRegistryV4: the recorded code version of
        // pre.createdAt at its one CREATE2 address under the coin-deployer proxy, naming this bridge and PoolManager), so
        // an upgraded core can never register a token of its own for any coinId.
        if (!_codeRegistry.genuine(token, coinId, address(this), pre.createdAt)) revert TokenMismatch();
        if (!Pre.listed(pre, localPcid)) revert ChainNotListed(localPcid);
        if (pre.createdAt > block.timestamp) revert OpenNotAuthorized();
        // ELY-TRANSPORT (row 17) + T17-FIX: every tid of THIS chain's creation set must be live here (an adapter, never
        // replaceable: no transport can be installed later under an open coin, AUD-T17 M-2); a tid outside it
        // (LayerZero on Elysium) is never used to or from this chain (`_checkPair`).
        bytes32 h = IBridgeImmV4(address(this)).rowsHash(pre.chains, pre.transportMask, pre.chainTids);
        uint256 ct = pre.chainTids; // the normalised sets (rowsHash above validated them): 0 -> the mask on every chain
        if (ct == 0) {
            for (uint256 i = 0; i < pre.chains.length; i++) {
                ct |= uint256(pre.transportMask) << (16 * i);
            }
        }
        uint256 own;
        uint256 home;
        for (uint256 i = 0; i < pre.chains.length; i++) {
            if (pre.chains[i] == localPcid) own = uint16(ct >> (16 * i));
            if (pre.chains[i] == pre.homePcid) home = uint16(ct >> (16 * i));
        }
        for (uint8 t = 1; t < 16; t++) {
            if ((own >> t) & 1 == 1 && adapterOf[t] == address(0)) revert TransportNotListed(t);
        }
        if (h != pre.rowsHash) revert RowsMismatch();

        bytes32 op = bytes32(uint256(uint160(opener)));
        // B1-H1: only what came FROM THE HOME CHAIN over a transport of the route home <-> here (T17-FIX) counts. B2-L1: `a` = the
        // highest role among them (an authorisation's, or a mode-2 mirror stored while unopened). B2-L2: the original
        // creator's direct 1 h window closes once any role change from home has arrived here. B3-L1: an open
        // authorisation counts only if it was issued under that newest role (a handover / renounce voids older ones).
        // META-OPENLATER (G-ROLL 18 M-2): an authorised leg opens only with the home URI as it was at authorizeOpen
        // (`uh` = keccak256 of the deployed token's first metadataURI = OpenArgs.metadataURI); `okUri` = some valid
        // authorisation for `op` carries that hash.
        bytes32 uh = keccak256(bytes(PangeaCoinV4(token).metadataURI()));
        OpenAuth memory a;
        bool ok;
        bool okUri;
        bytes32 authUh;
        for (uint8 t = 1; t < 16; t++) {
            if (((own & home) >> t) & 1 == 0) continue;
            OpenAuth memory x = _openAuth[keccak256(abi.encode(coinId, pre.homePcid, t))];
            if (x.roleNonce > a.roleNonce) (a, ok, okUri) = (x, false, false);
            if (x.roleNonce == a.roleNonce && x.opener == op && op != bytes32(0) && block.timestamp <= x.deadline) {
                (ok, authUh) = (true, x.uriHash);
                if (x.uriHash == uh) okUri = true;
            }
        }
        bool byCreator = op == pre.creatorEvm && pre.creatorEvm != bytes32(0);
        if (localPcid == pre.homePcid) {
            if (!byCreator) revert OpenNotAuthorized();
        } else if (!(byCreator && a.roleNonce == 0 && block.timestamp <= pre.createdAt + FIRST_OPEN_WINDOW)) {
            // not the creator's own direct open in its window (that one chooses its URI: it is the authority)
            if (!ok) revert OpenNotAuthorized();
            if (!okUri) revert OpenURINotHome(uh, authUh);
        }

        c.token = token;
        c.homePcid = pre.homePcid;
        c.transportMask = pre.transportMask;
        c.nChains = uint8(pre.chains.length);
        for (uint256 i = 0; i < pre.chains.length; i++) {
            c.chains[i] = pre.chains[i];
        }
        c.rowsHash = pre.rowsHash;
        c.chainTids = uint128(ct);
        c.openedAt = uint64(block.timestamp);
        if (a.roleNonce != 0) {
            (c.creatorEvm, c.creatorSvm, c.roleNonce, c.renounced) = (a.creatorEvm, a.creatorSvm, a.roleNonce, a.renounced);
        } else {
            (c.creatorEvm, c.creatorSvm) = (pre.creatorEvm, pre.creatorSvm);
        }

        coinOfToken[token] = coinId;
        _officialPool[coinId] = pool;
        emit CoinRegistered(coinId, token, pre.homePcid, pre.chains, pre.transportMask, pre.rowsHash);
        emit ChainOpened(coinId, localPcid, token, opener);
        // OB9-R1: the role this chain opened with is an on-chain event (E4 books from it; by 3 = the open)
        if (c.renounced) emit CreatorRenounced(coinId, c.roleNonce);
        else emit CreatorChanged(coinId, c.creatorEvm, c.creatorSvm, c.roleNonce, 3);
    }

    // ================================================================== send views (moved from the bridge, A-D8 size)

    function isSendPaused(bytes32 coinId, uint32 dstPcid, uint8 tid) external view returns (bool) {
        return _isSendPaused(coinId, dstPcid, tid);
    }

    /// @notice The native fee `send` takes for `a` (transport quote + A-D8 keys-only delivery charge, exactly what the
    ///         send pays out), the credit preview (exact for a signed price) and the price source.
    function quoteSend(SendArgs calldata a, Sig.SignedGapPrice calldata gp)
        external
        view
        returns (uint256 nativeFee, uint256 previewCreditedLD, uint8 priceSource)
    {
        (Coin storage c, ITransportAdapterV4 adapter) = _route(a);
        IBridgeImmV4 b = IBridgeImmV4(address(this));
        IGapOracleV4.Params memory p = b.oracle().params(a.coinId);
        (,, uint64 sd) = _amounts(a.amountLD, p.bridgeFeeBps);
        Codec.Header memory h = _header(a, sd, p.bridgeFeeBps, Codec.MODE_PLAIN);
        if (p.gapOn) (h.priceSource, h.psUsdE18, h.p2E18,) = b.gap().sourcePrice(gp, h.coinId, h.srcPcid, h.dstPcid, c.token);
        (uint256 d,) = _deliveryCharge(b.oracle(), a.dstPcid, a.transportId);
        nativeFee = adapter.quote(a.dstPcid, Codec.encode(h, a.composeMsg), a.extraOptions) + d;
        previewCreditedLD = h.priceSource == Codec.PS_SIGNED
            ? b.gap().creditPlain(uint256(sd) * LD_PER_SD, h.psUsdE18, h.p2E18)
            : uint256(sd) * LD_PER_SD;
        priceSource = h.priceSource;
    }

    // ================================================================== admin (moved from the bridge, size split)
    // SIZE-17 TRACK B: setTransport + setComposer are in PangeaBridgeV4 again (EIP-170 room there after the buy dedup).

    /// @notice Append-only: the chain's kind (once) and routes, each (pcid, tid) once. EVM peers must be canonical.
    function addChain(uint32 pcid, uint8 kind, RouteIn[] calldata rs) external onlyOwner {
        uint8 k = chainKind[pcid];
        if (kind == 0 || kind > KIND_MOVE || (k != 0 && k != kind)) revert BadKind();
        if (k == 0) {
            chainKind[pcid] = kind;
            _pcids.push(pcid);
            emit ChainAdded(pcid, kind);
        }
        for (uint256 i = 0; i < rs.length; i++) {
            RouteIn calldata r = rs[i];
            if (r.tid == 0 || r.tid > 15) revert TransportNotListed(r.tid);
            if (_routes[pcid][r.tid].peer != bytes32(0)) revert RowExists(pcid, r.tid);
            if (r.peer == bytes32(0) || r.remoteDomain == 0) revert ZeroAddress();
            if (kind == KIND_EVM) {
                address a = adapterOf[r.tid];
                if (a == address(0) || r.peer != bytes32(uint256(uint160(a)))) revert PeerNotCanonical(pcid, r.tid);
            }
            if (_pcidOfDomain[r.tid][r.remoteDomain] != 0) revert RowExists(pcid, r.tid);
            _routes[pcid][r.tid] = Route(r.remoteDomain, r.peer);
            _pcidOfDomain[r.tid][r.remoteDomain] = pcid;
            emit RouteSet(pcid, r.tid, r.remoteDomain, r.peer);
        }
    }

    /// @notice scope 0 global (key 0), 1 transport (key = tid), 2 coin (key = coinId), 3 coin+dst (key = keccak(coinId, dst)).
    function setSendPaused(uint8 scope, bytes32 key, bool paused) external onlyOwner {
        sendPaused[keccak256(abi.encode(scope, key))] = paused;
        emit SendPausedSet(scope, key, paused);
    }

    /// @notice E4-R5: the owner grants / revokes a PAUSE-ONLY key (the supply watcher's).
    function setPauser(address pauser, bool on) external onlyOwner {
        if (pauser == address(0)) revert ZeroAddress();
        if (_pauser[pauser] != on) _pauserCount = on ? _pauserCount + 1 : _pauserCount - 1; // B4-I3
        _pauser[pauser] = on;
        emit PauserSet(pauser, on);
    }

    function isPauser(address a) external view returns (bool) {
        return _pauser[a];
    }

    /// @notice E4-R5: a pauser (or the owner) PAUSES new sends for a scope (0 global, 1 transport, 2 coin, 3 coin+dst;
    ///         key as setSendPaused). It can never unpause: only the owner's setSendPaused(.., false) does.
    function pauseSends(uint8 scope, bytes32 key) external {
        if (!_pauser[msg.sender] && msg.sender != owner()) revert NotPauser();
        if (scope > 3) revert BadKind();
        sendPaused[keccak256(abi.encode(scope, key))] = true;
        emit SendPausedSet(scope, key, true);
    }

    function setBridgeFeeTo(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        bridgeFeeTo = to;
        emit BridgeFeeToSet(to);
    }

    /// @notice The creator payee of `coinId` here (FeeSplitterV4.creator()): 0xdEaD after a renounce.
    function creatorOf(bytes32 coinId) external view returns (address) {
        Coin storage c = _coins[coinId];
        if (c.renounced) return DEAD;
        return address(uint160(uint256(c.creatorEvm)));
    }

    /// @notice The EIP-712 digest our signer signs (§11.3.1; verifyingContract = this bridge).
    function gapPriceDigest(Sig.GapPrice calldata p) external view returns (bytes32) {
        return IBridgeImmV4(address(this)).gap().digest(p, address(this));
    }

    // ================================================================== creator role (§11.6)

    function transferCreator(bytes32 coinId, bytes32 newEvm, bytes32 newSvm) external {
        Coin storage c = _home(coinId);
        if (c.renounced) revert Renounced();
        if (bytes32(uint256(uint160(msg.sender))) != c.creatorEvm) revert NotCreator();
        if (newEvm == bytes32(0) && newSvm == bytes32(0)) revert ZeroAddress();
        if (uint256(newEvm) >> 160 != 0) revert BadRecipient(); // B2-L3: an EVM payee is 20 bytes
        _applyRole(c, coinId, Codec.Role(newEvm, newSvm, c.roleNonce + 1, false), 0);
    }

    function renounceCreator(bytes32 coinId) external {
        Coin storage c = _home(coinId);
        if (c.renounced) revert Renounced();
        if (bytes32(uint256(uint160(msg.sender))) != c.creatorEvm) revert NotCreator();
        c.renounced = true;
        c.roleNonce++;
        emit CreatorRenounced(coinId, c.roleNonce);
    }

    function adminProposeCreator(bytes32 coinId, bytes32 evm, bytes32 svm) external onlyOwner {
        Coin storage c = _home(coinId);
        (c.adminPendingEvm, c.adminPendingSvm) = (evm, svm);
        emit AdminProposedCreator(coinId, evm, svm);
    }

    function acceptCreator(bytes32 coinId) external {
        Coin storage c = _home(coinId);
        if (c.adminPendingEvm == bytes32(0) || bytes32(uint256(uint160(msg.sender))) != c.adminPendingEvm) revert NotPendingCreator();
        bytes32 svm = c.adminPendingSvm;
        (c.adminPendingEvm, c.adminPendingSvm) = (bytes32(0), bytes32(0));
        _applyRole(c, coinId, Codec.Role(bytes32(uint256(uint160(msg.sender))), svm, c.roleNonce + 1, false), 1);
    }

    /// @notice Anyone: mirrors the current role to `dstPcid` (mode 2). msg.value pays the transport.
    function pushCreator(bytes32 coinId, uint32 dstPcid, uint8 tid, bytes calldata extraOptions) external payable returns (bytes32) {
        Coin storage c = _coins[coinId];
        if (c.token == address(0)) revert CoinNotOpenHere(coinId);
        return _control(c, coinId, dstPcid, tid, Codec.MODE_ROLE, bytes32(0), Codec.encodeRole(_role(c)), extraOptions);
    }

    /// @notice Home chain: the current creator (anyone after a renounce) authorises `opener` to open `dstPcid` until
    ///         `deadline` (mode 3, carrying the current role and, META-OPENLATER, keccak256 of the home coin's current
    ///         metadataURI: the far leg must open with exactly that URI).
    function authorizeOpen(bytes32 coinId, uint32 dstPcid, uint8 tid, bytes32 opener, uint64 deadline, bytes calldata extraOptions)
        external
        payable
        returns (bytes32)
    {
        Coin storage c = _home(coinId);
        if (!c.renounced && bytes32(uint256(uint160(msg.sender))) != c.creatorEvm) revert NotCreator();
        if (deadline > block.timestamp + MAX_OPEN_AUTH) revert OpenAuthTooLong(deadline); // B3-L1: at most 7 days
        emit OpenAuthorized(coinId, dstPcid, opener, deadline);
        return _control(
            c,
            coinId,
            dstPcid,
            tid,
            Codec.MODE_OPEN_AUTH,
            keccak256(bytes(PangeaCoinV4(c.token).metadataURI())), // META-OPENLATER: the home URI's hash, in the recipient slot
            abi.encodePacked(opener, deadline, Codec.encodeRole(_role(c)), uint64(block.timestamp)),
            extraOptions
        );
    }


    /// @dev A mode-2 / mode-3 control message (pushCreator, authorizeOpen).
    /// META-OPENLATER: `recipient` = a mode 3's uriHash (0 for mode 2).
    function _control(
        Coin storage c,
        bytes32 coinId,
        uint32 dst,
        uint8 tid,
        uint8 mode,
        bytes32 recipient,
        bytes memory tail,
        bytes calldata extraOptions
    ) internal returns (bytes32) {
        _checkPair(c, dst, tid);
        address adapter = adapterOf[tid];
        if (adapter == address(0) || _routes[dst][tid].peer == bytes32(0)) revert RouteMissing(dst, tid);
        Codec.Header memory h;
        h.mode = mode;
        h.transportId = tid;
        h.srcPcid = _local();
        h.dstPcid = dst;
        h.coinId = coinId;
        h.recipient = recipient;
        h.sender = bytes32(uint256(uint160(msg.sender)));
        return _paidSend(adapter, dst, tid, Codec.encode(h, tail), extraOptions, false);
    }

    /// @dev A2-D14: a control / refund message toward a keys-only (dst, tid) pays our delivery charge out of msg.value
    ///      (we deliver it), the transport gets the rest; toward an ordinary route nothing extra (charge 0).
    ///      G-EVMB-1 L-2 (invariant iii): a REFUND (`soft`) pays the charge only when it can -- readable, with a
    ///      recipient, covered by msg.value and accepted by the recipient -- and otherwise goes without it, so no
    ///      delivery-charge setting can block the only exit of a held arrival.
    function _paidSend(address adapter, uint32 dst, uint8 tid, bytes memory message, bytes calldata extraOptions, bool soft)
        internal
        returns (bytes32 id)
    {
        IGapOracleV4 o = IBridgeImmV4(address(this)).oracle();
        uint256 d;
        address to;
        if (soft) {
            (bool ok, bytes memory ret) = address(o).staticcall(abi.encodeCall(IGapOracleV4.deliveryCharge, (dst, tid)));
            if (ok && ret.length == 64) (d, to) = abi.decode(ret, (uint256, address));
            if (to == address(0) || d > msg.value) d = 0;
            if (d != 0) (ok,) = to.call{value: d, gas: SOFT_PAY_GAS}("");
            if (!ok) d = 0;
        } else {
            (d, to) = _deliveryCharge(o, dst, tid);
            if (msg.value < d) revert DeliveryFeeUnpaid(msg.value, d);
        }
        bytes32 t = ITransportAdapterV4(adapter).send{value: msg.value - d}(dst, message, extraOptions, msg.sender);
        id = Codec.msgId(tid, t);
        if (d != 0) {
            if (!soft) {
                (bool ok,) = to.call{value: d}("");
                if (!ok) revert DeliveryPayFailed(to);
            }
            emit DeliveryPaid(id, dst, tid, to, d);
        }
    }

    /// @notice What a control / refund message toward (dst, tid) costs in native: the transport quote of `message`
    ///         (with `extraOptions`) + the keys-only delivery charge (A2-D14). Helper for clients.
    function quoteControl(uint32 dst, uint8 tid, bytes calldata message, bytes calldata extraOptions) external view returns (uint256) {
        address adapter = adapterOf[tid];
        if (adapter == address(0) || _routes[dst][tid].peer == bytes32(0)) revert RouteMissing(dst, tid);
        (uint256 d,) = _deliveryCharge(IBridgeImmV4(address(this)).oracle(), dst, tid);
        return ITransportAdapterV4(adapter).quote(dst, message, extraOptions) + d;
    }

    // ------------------------------------------------------------------ views + refund (size split)

    function coin(bytes32 coinId) external view returns (Coin memory) {
        return _coins[coinId];
    }

    /// @notice F2-REQ coinInfo.
    function coinInfo(bytes32 coinId)
        external
        view
        returns (address token, uint32 homePcid, uint16 transportMask, uint8 nChains, uint32[] memory chains)
    {
        Coin storage c = _coins[coinId];
        chains = new uint32[](c.nChains);
        for (uint256 i = 0; i < c.nChains; i++) {
            chains[i] = c.chains[i];
        }
        return (c.token, c.homePcid, c.transportMask, c.nChains, chains);
    }

    /// @notice The open authorisation for `coinId` that arrived from (srcPcid, tid) (used only if srcPcid is home).
    function openAuthOf(bytes32 coinId, uint32 srcPcid, uint8 tid) external view returns (OpenAuth memory) {
        return _openAuth[keccak256(abi.encode(coinId, srcPcid, tid))];
    }

    function heldOf(bytes32 msgId) external view returns (HeldArrival memory) {
        return _held[msgId];
    }

    function pcids() external view returns (uint32[] memory) {
        return _pcids;
    }

    /// @notice Sends a HELD arrival back to its source as mode 0xFF on the same transport (the caller pays the return
    ///         fee); the source credits the sender in full. Who may (AB1-R1; window = HELD_REFUND_WINDOW from heldAt):
    ///         - the recipient: always;
    ///         - reason 2 (below minCredited): otherwise only the ORIGINAL SENDER, after the window;
    ///         - reason 1 (coin not open here): anyone after the window, while the coin is still unopened here;
    ///         - an arrival of a coin that IS open here (reason 3, or a reason 1 whose coin opened since): the
    ///           recipient only (evm-b1 I-5).
    function refundHeld(bytes32 msgId, bytes calldata extraOptions) external payable returns (bytes32 refundId) {
        HeldArrival memory hd = _held[msgId];
        if (hd.message.length == 0) revert NotHeld();
        (Codec.Header memory o,) = IDecodeViewV4(address(this)).decodeView(hd.message);
        bytes32 me = bytes32(uint256(uint160(msg.sender)));
        if (me != o.recipient) {
            uint64 at = hd.heldAt + HELD_REFUND_WINDOW;
            if (hd.reason == 2 ? me != o.sender : _coins[o.coinId].token != address(0)) revert NotRefundable();
            if (block.timestamp < at) revert RefundWindow(at);
        }
        delete _held[msgId];
        address adapter = adapterOf[o.transportId];
        if (adapter == address(0) || _routes[hd.srcPcid][o.transportId].peer == bytes32(0)) revert RouteMissing(hd.srcPcid, o.transportId);
        Codec.Header memory h;
        h.mode = Codec.MODE_REFUND;
        h.transportId = o.transportId;
        h.srcPcid = _local();
        h.dstPcid = hd.srcPcid;
        h.coinId = o.coinId;
        h.recipient = o.sender;
        h.sender = o.sender;
        h.amountSD = o.amountSD;
        refundId = _paidSend(adapter, hd.srcPcid, o.transportId, Codec.encode(h, ""), extraOptions, true);
        emit HeldRefunded(msgId, refundId);
    }

    // ------------------------------------------------------------------ retryable compose (B1-M4)

    /// @notice The bridge itself, inline right after the mint (try/catch there): runs the stored compose.
    function composeExec(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, address to, uint256 creditedLD, bytes calldata composeMsg)
        external
    {
        if (msg.sender != address(this)) revert NotSelf();
        _runCompose(msgId, coinId, srcPcid, composeFrom, to, creditedLD, composeMsg, true);
    }

    /// @notice Anyone, any time while it is stored: re-runs a stored compose with the caller's gas. The tokens move to
    ///         `to` and its pangeaCompose runs in the same call; a failure reverts the whole call (the compose stays).
    ///         Runs outside the bridge's reentrancy lock, so the composer may bridge onward (evm-b1 I-6).
    function retryCompose(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, address to, uint256 creditedLD, bytes calldata composeMsg)
        external
    {
        _runCompose(msgId, coinId, srcPcid, composeFrom, to, creditedLD, composeMsg, true);
    }

    /// @notice Anyone, after COMPOSE_WINDOW: the stored tokens go to the recipient `to`, without the call.
    function releaseCompose(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, address to, uint256 creditedLD, bytes calldata composeMsg)
        external
    {
        uint64 after_ = pendingCompose[msgId].releaseAfter;
        if (block.timestamp < after_) revert ComposeTooEarly(after_);
        _runCompose(msgId, coinId, srcPcid, composeFrom, to, creditedLD, composeMsg, false);
    }

    function _runCompose(
        bytes32 msgId,
        bytes32 coinId,
        uint32 srcPcid,
        bytes32 composeFrom,
        address to,
        uint256 creditedLD,
        bytes calldata composeMsg,
        bool call_
    ) internal {
        PendingCompose memory pc = pendingCompose[msgId];
        if (pc.hash == bytes32(0) || pc.hash != keccak256(abi.encode(msgId, coinId, srcPcid, composeFrom, to, creditedLD, composeMsg))) {
            revert ComposeUnknown();
        }
        delete pendingCompose[msgId];
        if (creditedLD != 0) IERC20(_coins[coinId].token).safeTransfer(to, creditedLD);
        if (call_) IComposerV4(to).pangeaCompose(msgId, coinId, srcPcid, composeFrom, creditedLD, composeMsg);
        emit ComposeDone(msgId, call_);
    }

    // ------------------------------------------------------------------ F2-REQ previews

    /// @notice What `message` would credit if delivered here now (by a delivery key): (credited, withheld, reason,
    ///         holds, belowMin). reason: 0 lands, 1 not open here (held), 2 below minCredited (held unless the
    ///         recipient accepted), 3 buy mode (lands at once only by a delivery key; else held for the window).
    function previewCreditMessage(bytes calldata message)
        external
        view
        returns (uint256 creditedLD, uint256 withheldLD, uint8 reason, bool holds, bool belowMin)
    {
        // EIP-170 (EVM-SIZE2): the bridge's own decodeView (as refundHeld), not a second inlined decoder
        (Codec.Header memory h,) = IDecodeViewV4(address(this)).decodeView(message);
        Coin storage c = _coins[h.coinId];
        uint256 a = uint256(h.amountSD) * LD_PER_SD;
        if (c.token == address(0)) return (0, 0, 1, true, false);
        creditedLD = h.mode == Codec.MODE_REFUND ? a : IBridgeImmV4(address(this)).gap().credit(h, c.token, a);
        if (creditedLD > a) creditedLD = a;
        withheldLD = a - creditedLD;
        belowMin = creditedLD < uint256(h.minCreditedSD) * LD_PER_SD;
        holds = belowMin;
        reason = belowMin ? 2 : (h.mode == Codec.MODE_BUY ? 3 : 0);
    }

    /// @notice The coin's recorded fallback prices here, USD x 1e18 per whole token (0 = none): Plast (the newest
    ///         earlier-block record), Pref (the source read: min over L), Pd_ref (the destination read: max rule),
    ///         live (the pool now). From the coin's own GapRecorderV4 ring (B1-M1) x the quote's USD (oracle).
    function gapPrices(bytes32 coinId) external view returns (uint256 plastE18, uint256 prefE18, uint256 pdRefE18, uint256 liveE18) {
        address t = _coins[coinId].token;
        if (t == address(0)) return (0, 0, 0, 0);
        IGapOracleV4 o = IBridgeImmV4(address(this)).oracle();
        address q = _officialPool[coinId].quote;
        uint256 dn = o.assetUsd(q, false);
        uint256 up = o.assetUsd(q, true);
        (uint256 pl, uint256 pr, uint256 pd, uint256 lv) = ICoinRingV4(t).gapPrices();
        return (GapMathV4.mulDown(pl, dn), GapMathV4.mulDown(pr, dn), GapMathV4.mulUp(pd, up), GapMathV4.mulDown(lv, dn));
    }

    /// @notice The coin's official pool here (set once at the open).
    function officialPool(bytes32 coinId) external view returns (OfficialPool memory) {
        return _officialPool[coinId];
    }

    /// @notice The coin's official pool in GapRegistryV4's shape (PangeaCoinV4's recorder learns it from here once,
    ///         GapRecorderV4.learn). lockedPositionKey 0 (the recorder does not read it).
    function officialPool(address token) external view returns (bool set, IGapRegistryV4.OfficialPool memory p) {
        bytes32 id = coinOfToken[token];
        OfficialPool storage op = _officialPool[id];
        if (id == bytes32(0) || op.hook == address(0)) return (false, p);
        bool t0 = token < op.quote;
        (address c0, address c1) = t0 ? (token, op.quote) : (op.quote, token);
        p.poolId = keccak256(abi.encode(c0, c1, op.lpFee, op.tickSpacing, op.hook));
        (p.hook, p.quote, p.lpFee, p.tokenIsCurrency0, p.tickSpacing) = (op.hook, op.quote, op.lpFee, t0, op.tickSpacing);
        set = true;
    }

}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol

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

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.20;

import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";

/**
 * @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Permit deadline has expired.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev Mismatched signature.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC-20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @inheritdoc IERC20Permit
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
        return super.nonces(owner);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

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

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

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

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        assembly ("memory-safe") {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/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))
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @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, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

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/v4/bridge/BridgeCodecV4.sol

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

/// @title BridgeCodecV4 -- codec 0x05 (V4-INTERFACES §11.2.5), transport-neutral, big-endian
///   0 ver 0x05 | 1 mode (0 plain, 1 buy, 2 creator mirror, 3 open authorisation, 0xFF refund) | 2 transportId |
///   3 priceSource (0 none, 1 signed, 2 on-chain fallback) | 4 srcPcid u32 | 8 dstPcid u32 | 12 coinId | 44 recipient |
///   76 sender | 108 amountSD u64 (shared decimals 6) | 116 psUsdE18 u128 | 132 p2E18 u128 | 148 bridgeFeePpm u32 |
///   152 coverSrcMicroUsd u32 | 156 minCreditedSD u64 | 164 priceClass u8 | 165 reserved 3 = 0 | 168 tail
///   tail: mode 0/1 composeMsg (composed iff length > 168); mode 2 creatorEvm 32 | creatorSvm 32 | u64 roleNonce |
///   u8 renounced (241 B); mode 3 opener 32 | u64 deadline | the mode-2 role fields | u64 issuedAt (unix s at the
///   home's authorizeOpen; B4-I1: appended, 289 B); mode 0xFF none.
///   META-OPENLATER (audit G-ROLL 18 M-2): a mode 3's header recipient (44..76, zero before) = uriHash = keccak256 of the
///   home coin's metadataURI at authorizeOpen; the far chain opens the authorised leg only with that URI. The length is
///   unchanged (289 B = the LayerZero maxMessageSize pin toward Solana).
library BridgeCodecV4 {
    uint8 internal constant VERSION = 0x05;
    uint8 internal constant MODE_PLAIN = 0;
    uint8 internal constant MODE_BUY = 1;
    uint8 internal constant MODE_ROLE = 2;
    uint8 internal constant MODE_OPEN_AUTH = 3;
    uint8 internal constant MODE_REFUND = 0xFF;
    uint8 internal constant PS_NONE = 0;
    uint8 internal constant PS_SIGNED = 1;
    uint8 internal constant PS_FALLBACK = 2;
    uint256 internal constant HEADER = 168;
    uint256 internal constant ROLE_LEN = 73;
    uint256 internal constant OPEN_AUTH_LEN = 121;
    uint8 internal constant SHARED_DECIMALS = 6;

    struct Header {
        uint8 mode;
        uint8 transportId;
        uint8 priceSource;
        uint32 srcPcid;
        uint32 dstPcid;
        bytes32 coinId;
        bytes32 recipient;
        bytes32 sender;
        uint64 amountSD;
        uint128 psUsdE18;
        uint128 p2E18;
        uint32 bridgeFeePpm;
        uint32 coverSrcMicroUsd;
        uint64 minCreditedSD;
        uint8 priceClass;
    }

    struct Role {
        bytes32 creatorEvm;
        bytes32 creatorSvm;
        uint64 roleNonce;
        bool renounced;
    }

    error BadVersion();
    error BadReserved();
    error BadMessage(uint8 why);

    function encode(Header memory h, bytes memory tail) internal pure returns (bytes memory) {
        return abi.encodePacked(
            abi.encodePacked(VERSION, h.mode, h.transportId, h.priceSource, h.srcPcid, h.dstPcid, h.coinId, h.recipient, h.sender),
            abi.encodePacked(h.amountSD, h.psUsdE18, h.p2E18, h.bridgeFeePpm, h.coverSrcMicroUsd, h.minCreditedSD, h.priceClass),
            bytes3(0),
            tail
        );
    }

    function encodeRole(Role memory r) internal pure returns (bytes memory) {
        return abi.encodePacked(r.creatorEvm, r.creatorSvm, r.roleNonce, r.renounced ? uint8(1) : uint8(0));
    }

    /// @notice Strict: version, reserved, mode-specific length and fields. why: 1 short, 2 unknown mode, 3 tail length,
    ///         4 cover in mode 0, 5 priceSource / class, 6 bridge fee >= 1e6, 7 refund / control fields not zero.
    function decode(bytes calldata b) internal pure returns (Header memory h, bytes calldata tail) {
        if (b.length < HEADER) revert BadMessage(1);
        if (uint8(b[0]) != VERSION) revert BadVersion();
        if (bytes3(b[165:168]) != bytes3(0)) revert BadReserved();
        h.mode = uint8(b[1]);
        h.transportId = uint8(b[2]);
        h.priceSource = uint8(b[3]);
        h.srcPcid = uint32(bytes4(b[4:8]));
        h.dstPcid = uint32(bytes4(b[8:12]));
        h.coinId = bytes32(b[12:44]);
        h.recipient = bytes32(b[44:76]);
        h.sender = bytes32(b[76:108]);
        h.amountSD = uint64(bytes8(b[108:116]));
        h.psUsdE18 = uint128(bytes16(b[116:132]));
        h.p2E18 = uint128(bytes16(b[132:148]));
        h.bridgeFeePpm = uint32(bytes4(b[148:152]));
        h.coverSrcMicroUsd = uint32(bytes4(b[152:156]));
        h.minCreditedSD = uint64(bytes8(b[156:164]));
        h.priceClass = uint8(b[164]);
        tail = b[168:];
        uint8 m = h.mode;
        if (m > MODE_OPEN_AUTH && m != MODE_REFUND) revert BadMessage(2);
        if (m == MODE_ROLE && tail.length != ROLE_LEN) revert BadMessage(3);
        if (m == MODE_OPEN_AUTH && tail.length != OPEN_AUTH_LEN) revert BadMessage(3);
        if ((m == MODE_REFUND) && tail.length != 0) revert BadMessage(3);
        if (m == MODE_PLAIN && h.coverSrcMicroUsd != 0) revert BadMessage(4);
        if (h.priceSource > PS_FALLBACK || (h.priceSource != PS_FALLBACK && h.priceClass != 0)) revert BadMessage(5);
        if (h.priceSource == PS_NONE && (h.psUsdE18 != 0 || h.p2E18 != 0)) revert BadMessage(5);
        if (h.bridgeFeePpm >= 1_000_000) revert BadMessage(6);
        if (m >= MODE_ROLE && (h.priceSource != PS_NONE || h.coverSrcMicroUsd != 0 || h.minCreditedSD != 0)) revert BadMessage(7);
        if (m == MODE_ROLE || m == MODE_OPEN_AUTH) {
            if (h.amountSD != 0) revert BadMessage(7);
        }
    }

    function decodeRole(bytes calldata t) internal pure returns (Role memory r) {
        r.creatorEvm = bytes32(t[0:32]);
        r.creatorSvm = bytes32(t[32:64]);
        r.roleNonce = uint64(bytes8(t[64:72]));
        r.renounced = uint8(t[72]) != 0;
    }

    /// @notice msgId = keccak256(u8 transportId | bytes32 transportMsgId) (LZ guid / Hyperlane message id).
    function msgId(uint8 transportId, bytes32 transportMsgId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(transportId, transportMsgId));
    }
}

src/v4/bridge/BridgeStateV4.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {BridgeCodecV4 as Codec} from "./BridgeCodecV4.sol";
import {CoinPreimageV4 as Pre} from "./CoinPreimageV4.sol";
import {PangeaCoinV4} from "./PangeaCoinV4.sol";
import {IPendingConfigV4} from "./PangeaDeployerV4.sol";
import {ITransportAdapterV4, IBridgeForAdaptersV4} from "./ITransportV4.sol";
import {IGapOracleV4} from "./gap/IGapOracleV4.sol";
import {GapPriceSigV4 as Sig} from "./gap/GapPriceSigV4.sol";
import {BridgeGapV4} from "./gap/BridgeGapV4.sol";

/// @title BridgeStateV4 -- the shared bridge's storage layout, events, errors and the helpers both the bridge and its
///        creator-role module (BridgeRoleV4, run by DELEGATECALL from the bridge's fallback) use. Size split only
///        (EIP-170); one storage, one owner (Ownable2Step's slots first, then these, in this order, in both).
abstract contract BridgeStateV4 is IBridgeForAdaptersV4, Ownable2Step {

    uint8 public constant KIND_EVM = 1;
    uint8 public constant KIND_SVM = 2;
    uint8 public constant KIND_MOVE = 3;
    uint256 internal constant LD_PER_SD = 1e3; // 9 local decimals, 6 shared
    uint256 internal constant BPS = 10_000;
    uint64 public constant FIRST_OPEN_WINDOW = 1 hours;
    uint256 internal constant COMPOSE_RESERVE_GAS = 30_000;
    /// @notice B1-M4: a stored compose may be retried by anyone; after this window anyone may hand the tokens to the
    ///         recipient without the call (never stranded).
    uint64 public constant COMPOSE_WINDOW = 1 days;
    /// @notice B3-L1: an open authorisation lives at most 7 days (capped at issue on home and at arrival here).
    uint64 public constant MAX_OPEN_AUTH = 7 days;
    /// @notice AB1-R1: the window after which a held arrival's refund opens beyond its recipient (reason 2: to the
    ///         original sender only; reason 1 of a coin still unopened here: to anyone). Counted from heldAt.
    uint64 internal constant HELD_REFUND_WINDOW = 1 days;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;

    struct RouteIn {
        uint8 tid;
        uint32 remoteDomain;
        bytes32 peer;
    }

    struct Coin {
        address token;
        uint32 homePcid;
        uint16 transportMask;
        uint8 nChains;
        uint32[8] chains;
        bytes32 rowsHash;
        uint64 openedAt;
        bytes32 creatorEvm;
        bytes32 creatorSvm;
        uint64 roleNonce;
        bool renounced;
        bytes32 adminPendingEvm;
        bytes32 adminPendingSvm;
        uint128 chainTids; // T17-FIX: the coin's per-chain tids fixed at its creation (normalised, never 0 once open)
    }

    struct OpenAuth {
        bytes32 opener;
        uint64 deadline;
        bytes32 creatorEvm;
        bytes32 creatorSvm;
        uint64 roleNonce;
        bool renounced;
        uint64 issuedAt; // B4-I1: the stored opener's issue time at home (a same-role authorisation replaces it only if newer)
        bytes32 uriHash; // META-OPENLATER (G-ROLL 18 M-2): keccak256 of the home coin's metadataURI at authorizeOpen
    }

    struct HeldArrival {
        uint32 srcPcid;
        uint8 reason; // 1 not open here, 2 below minCredited, 3 buy-mode arrival not delivered by a delivery key (B1-M3)
        uint64 heldAt; // first seen here (the delivery window of a buy-mode arrival counts from it)
        bytes message;
    }

    /// @notice B1-M4: a composed arrival whose call has not run yet; the credited tokens sit in the bridge.
    struct PendingCompose {
        bytes32 hash; // keccak256(abi.encode(msgId, coinId, srcPcid, composeFrom, to, creditedLD, composeMsg))
        uint64 releaseAfter; // from then anyone may hand the tokens to `to` without the call
    }

    struct SendArgs {
        bytes32 coinId;
        uint32 dstPcid;
        uint8 transportId;
        bytes32 recipient;
        uint256 amountLD;
        uint256 minCreditedLD;
        bytes extraOptions;
        bytes composeMsg;
        address refundTo;
    }

    /// @dev §11.2.6: the buy runs ONLY on the coin's official pool (B1-H3).
    struct BuyArgs {
        uint256 quoteIn;
        uint256 minTokensOut;
    }

    /// @notice The coin's official pool on this chain (its open pool), set once by the core at the open.
    struct OfficialPool {
        address quote;
        uint24 lpFee;
        int24 tickSpacing;
        address hook;
    }


    mapping(uint32 => uint8) public chainKind;
    mapping(uint32 => mapping(uint8 => Route)) internal _routes;
    mapping(uint8 => mapping(uint32 => uint32)) internal _pcidOfDomain;
    mapping(uint8 => address) public adapterOf;
    uint32[] internal _pcids;

    mapping(bytes32 => Coin) internal _coins;
    mapping(address => bytes32) public coinOfToken;
    /// @dev keccak256(coinId, srcPcid, tid) -> the open authorisation that arrived from that row (B1-H1: only the
    ///      home chain's, over a transport of the coin's mask, is ever used).
    mapping(bytes32 => OpenAuth) internal _openAuth;
    mapping(bytes32 => bool) public consumed;
    mapping(bytes32 => OfficialPool) internal _officialPool;
    mapping(bytes32 => HeldArrival) internal _held;
    mapping(bytes32 => mapping(address => bool)) public acceptedBelowMin;
    mapping(bytes32 => bool) public sendPaused; // keccak256(scope, key)

    address public bridgeFeeTo;
    mapping(bytes32 => PendingCompose) public pendingCompose;
    /// @dev E4-R5: pause-only keys (the supply watcher's): may pause sends, never unpause (BridgeRoleV4).
    mapping(address => bool) internal _pauser;
    /// @dev B4-I3: how many pause-only keys are on (VerifyBridgeV4: exactly the supply watcher). Appended last.
    uint256 internal _pauserCount;
    /// @dev gate-cheap-erc20 H-1: this release's CheapestComposerV4 (PangeaBridgeV4.setComposer; 0 = none). A send it makes
    ///      carries the USER (a.refundTo) as the message's sender, not the composer. Appended last.
    address internal _composer;

    event ChainAdded(uint32 indexed pcid, uint8 kind);
    event RouteSet(uint32 indexed pcid, uint8 indexed tid, uint32 remoteDomain, bytes32 peer);
    event TransportSet(uint8 indexed tid, address adapter);
    event SendPausedSet(uint8 scope, bytes32 key, bool paused);
    event PauserSet(address indexed pauser, bool on);
    event BridgeFeeToSet(address to);
    event ComposerSet(address composer);
    event CoinRegistered(bytes32 indexed coinId, address indexed token, uint32 homePcid, uint32[] chains, uint16 transportMask, bytes32 rowsHash);
    event ChainOpened(bytes32 indexed coinId, uint32 pcid, address token, address opener);
    event Sent(
        bytes32 indexed msgId,
        bytes32 indexed coinId,
        address indexed from,
        uint32 dstPcid,
        uint8 transportId,
        uint8 mode,
        uint256 amountLD,
        uint64 amountSD,
        bytes32 recipient,
        uint8 priceSource,
        uint128 psUsdE18,
        uint128 p2E18,
        uint256 bridgeFeeLD,
        uint256 nativeFee
    );
    event GapPriceUsed(bytes32 indexed msgId, uint8 keyId, uint64 observedAt, bytes32 srcPool, bytes32 dstPool, uint64 srcBlock, uint64 dstBlock);
    /// @notice A-D8: a send toward a keys-only (dstPcid, tid) paid our delivery (oracle.deliveryCharge) to `to`.
    event DeliveryPaid(bytes32 indexed msgId, uint32 indexed dstPcid, uint8 indexed tid, address to, uint256 costWei);
    event GapBuy(bytes32 indexed msgId, address indexed from, uint32 indexed dstPcid, uint256 quotePaid, uint256 tokensOut, uint256 pexecE18, uint256 psE18, uint256 panchorE18);
    event Received(
        bytes32 indexed msgId,
        bytes32 indexed coinId,
        address indexed to,
        uint32 srcPcid,
        uint8 transportId,
        uint8 mode,
        uint64 amountSD,
        uint256 creditedLD,
        uint256 withheldLD,
        uint8 priceSource
    );
    event Held(bytes32 indexed msgId, bytes32 indexed coinId, uint8 reason);
    event HeldReleased(bytes32 indexed msgId);
    event HeldRefunded(bytes32 indexed msgId, bytes32 refundMsgId);
    event ComposeFailed(bytes32 indexed msgId, address to, bytes reason);
    event ComposeStored(bytes32 indexed msgId, bytes32 indexed coinId, address indexed to, uint32 srcPcid, bytes32 composeFrom, uint256 creditedLD, bytes composeMsg);
    event ComposeDone(bytes32 indexed msgId, bool called);
    event AcceptedBelowMin(bytes32 indexed msgId, address indexed to);
    event CreatorChanged(bytes32 indexed coinId, bytes32 evm, bytes32 svm, uint64 roleNonce, uint8 by);
    event CreatorRenounced(bytes32 indexed coinId, uint64 roleNonce);
    event AdminProposedCreator(bytes32 indexed coinId, bytes32 evm, bytes32 svm);
    event OpenAuthorized(bytes32 indexed coinId, uint32 dstPcid, bytes32 opener, uint64 deadline);
    event OpenAuthReceived(bytes32 indexed coinId, bytes32 opener, uint64 deadline);
    event RoleMirrorStale(bytes32 indexed coinId, uint64 roleNonce);

    error CoinNotOpenHere(bytes32 coinId);
    error CoinAlreadyOpen(bytes32 coinId);
    error ChainNotListed(uint32 pcid);
    error TransportNotListed(uint8 tid);
    error RouteMissing(uint32 pcid, uint8 tid);
    error RowExists(uint32 pcid, uint8 tid);
    error PeerNotCanonical(uint32 pcid, uint8 tid);
    error RowsMismatch();
    error BadKind();
    error AdapterExists(uint8 tid);
    error AdapterMismatch();
    error NotAdapter();
    error WrongPeer();
    error WrongChain();
    error AlreadyConsumed(bytes32 msgId);
    error SendPaused();
    error CreditBelowMin(uint256 credited, uint256 minCredited);
    error GapPriceInvalid(uint8 why);
    error GapPriceExpired(uint64 validUntil);
    error NotHeld();
    error HeldNotReleasable();
    error NotCreator();
    error Renounced();
    error NotHome();
    error NotPendingCreator();
    error OpenNotAuthorized();
    error NotCore();
    error BadAmount();
    error BadRecipient();
    error BuySlippage(uint256 out, uint256 minOut);
    error BuyValue();
    error BuyNeedsPrice();
    error ZeroAddress();
    error ComposerSend();
    error TokenMismatch();
    error DeliveryWindow(uint64 openAt);
    error RefundWindow(uint64 openAt);
    error NotRefundable();
    error ComposeUnknown();
    error ComposeTooEarly(uint64 releaseAfter);
    error NotSelf();
    error NotPauser();
    error OpenAuthTooLong(uint64 deadline);
    /// @notice META-OPENLATER (G-ROLL 18 M-2): an authorised (open-later) leg must carry the home coin's metadataURI as it
    ///         was at authorizeOpen (keccak256 equal to the authorisation's uriHash); only the creator's own direct open in
    ///         FIRST_OPEN_WINDOW chooses freely.
    error OpenURINotHome(bytes32 got, bytes32 authorised);
    /// @notice A-D8: the send's native value is below the keys-only delivery charge it must carry.
    error DeliveryFeeUnpaid(uint256 value, uint256 costWei);
    /// @notice A-D8: the oracle's delivery charge could not be read / names no recipient (never a keys-only send unpaid).
    error DeliveryUnreadable(uint32 dstPcid, uint8 tid);
    error DeliveryPayFailed(address to);
    error RenounceDisabled();
    /// @notice gapPreviewBuy's answer (§11.2.6 figures; psUsdE18 = the credit price Ps, panchorE18 = the anchor).
    error GapPreviewBuy(
        uint256 tokensOut,
        uint256 quotePaid,
        uint256 pexecUsdE18,
        uint256 psUsdE18,
        uint8 priceSource,
        uint256 panchorE18,
        uint128 p2E18,
        uint32 coverSrcMicroUsd,
        uint64 amountSD,
        uint32 bridgeFeePpm
    );

    function _local() internal view virtual returns (uint32);

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

    function _listed(Coin storage c, uint32 pcid) internal view returns (bool) {
        for (uint256 i = 0; i < c.nChains; i++) {
            if (c.chains[i] == pcid) return true;
        }
        return false;
    }

    /// @dev T17-FIX (AUD-T17 M-1/L-1): reverts unless `pcid` is another listed chain of `c` and `tid` is in BOTH this
    ///      chain's and `pcid`'s creation set (chainTids): a row or transport added later never extends an open coin.
    function _checkPair(Coin storage c, uint32 pcid, uint8 tid) internal view {
        uint32 me = _local();
        uint256 ct = c.chainTids;
        uint256 a;
        uint256 b;
        for (uint256 i = 0; i < c.nChains; i++) {
            uint32 x = c.chains[i];
            if (x == me) a = uint16(ct >> (16 * i));
            if (x == pcid) b = uint16(ct >> (16 * i));
        }
        if (pcid == me || b == 0) revert ChainNotListed(pcid);
        if ((a & b) >> tid & 1 == 0) revert TransportNotListed(tid);
    }

    function _role(Coin storage c) internal view returns (Codec.Role memory) {
        return Codec.Role(c.creatorEvm, c.creatorSvm, c.roleNonce, c.renounced);
    }

    function _applyRole(Coin storage c, bytes32 coinId, Codec.Role memory r, uint8 by) internal {
        if (by == 2 && r.roleNonce <= c.roleNonce) {
            emit RoleMirrorStale(coinId, r.roleNonce);
            return;
        }
        (c.creatorEvm, c.creatorSvm, c.roleNonce, c.renounced) = (r.creatorEvm, r.creatorSvm, r.roleNonce, r.renounced);
        if (r.renounced) emit CreatorRenounced(coinId, r.roleNonce);
        else emit CreatorChanged(coinId, r.creatorEvm, r.creatorSvm, r.roleNonce, by);
    }

    function _home(bytes32 coinId) internal view returns (Coin storage c) {
        c = _coins[coinId];
        if (c.token == address(0)) revert CoinNotOpenHere(coinId);
        if (c.homePcid != _local()) revert NotHome();
    }

    // ------------------------------------------------------------ send helpers (bridge + quoteSend in the module)

    function _isSendPaused(bytes32 coinId, uint32 dstPcid, uint8 tid) internal view returns (bool) {
        return sendPaused[keccak256(abi.encode(uint8(0), bytes32(0)))] || sendPaused[keccak256(abi.encode(uint8(1), bytes32(uint256(tid))))]
            || sendPaused[keccak256(abi.encode(uint8(2), coinId))]
            || sendPaused[keccak256(abi.encode(uint8(3), keccak256(abi.encode(coinId, dstPcid))))];
    }

    function _route(SendArgs calldata a) internal view returns (Coin storage c, ITransportAdapterV4 adapter) {
        c = _coins[a.coinId];
        if (c.token == address(0)) revert CoinNotOpenHere(a.coinId);
        _checkPair(c, a.dstPcid, a.transportId);
        adapter = ITransportAdapterV4(adapterOf[a.transportId]);
        if (address(adapter) == address(0) || _routes[a.dstPcid][a.transportId].peer == bytes32(0)) {
            revert RouteMissing(a.dstPcid, a.transportId);
        }
        if (_isSendPaused(a.coinId, a.dstPcid, a.transportId)) revert SendPaused();
        if (a.recipient == bytes32(0)) revert BadRecipient();
        if (chainKind[a.dstPcid] == KIND_EVM && uint256(a.recipient) >> 160 != 0) revert BadRecipient();
    }

    function _amounts(uint256 amountLD, uint16 bps) internal pure returns (uint256 burnLD, uint256 fee, uint64 sd) {
        if (amountLD == 0) revert BadAmount();
        fee = amountLD * bps / BPS;
        uint256 s = (amountLD - fee) / LD_PER_SD;
        if (s == 0 || s > type(uint64).max) revert BadAmount();
        sd = uint64(s);
        burnLD = fee + s * LD_PER_SD;
    }

    function _header(SendArgs calldata a, uint64 sd, uint16 bps, uint8 mode) internal view returns (Codec.Header memory h) {
        h.mode = mode;
        h.transportId = a.transportId;
        h.srcPcid = _local();
        h.dstPcid = a.dstPcid;
        h.coinId = a.coinId;
        h.recipient = a.recipient;
        h.sender = bytes32(uint256(uint160(msg.sender)));
        h.amountSD = sd;
        h.bridgeFeePpm = uint32(bps) * 100;
        uint256 m = a.minCreditedLD / LD_PER_SD;
        h.minCreditedSD = m > type(uint64).max ? type(uint64).max : uint64(m);
    }

    /// @dev A-D8 (§11.2.6 step 7, keys-only delivery as v4): what a user send toward (dst, tid) owes our delivery
    ///      ((0, 0) = an ordinary route). A failed / malformed read, or a cost with no recipient, refuses the send.
    function _deliveryCharge(IGapOracleV4 o, uint32 dst, uint8 tid) internal view returns (uint256 costWei, address to) {
        (bool ok, bytes memory ret) = address(o).staticcall(abi.encodeCall(IGapOracleV4.deliveryCharge, (dst, tid)));
        if (!ok || ret.length != 64) revert DeliveryUnreadable(dst, tid);
        (costWei, to) = abi.decode(ret, (uint256, address));
        if (costWei != 0 && to == address(0)) revert DeliveryUnreadable(dst, tid);
    }

}

src/v4/bridge/CoinPreimageV4.sol

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

/// @title CoinPreimageV4 -- coinId = keccak256(canonical preimage bytes), V4-INTERFACES §11.2.2 (identical on Solana)
///   "PANGEA-COIN-V4" | u8 1 | nameHash | symbolHash | creatorEvm | creatorSvm | u32 homePcid | u64 createdAt | salt |
///   u8 nChains | nChains x u32 pcid (strictly ascending, includes home) | u16 transportMask | rowsHash
library CoinPreimageV4 {
    uint8 internal constant PREIMAGE_VERSION = 1;
    uint256 internal constant MAX_CHAINS = 8;

    struct Preimage {
        bytes32 nameHash;
        bytes32 symbolHash;
        bytes32 creatorEvm;
        bytes32 creatorSvm;
        uint32 homePcid;
        uint64 createdAt;
        bytes32 salt;
        uint32[] chains;
        uint16 transportMask;
        bytes32 rowsHash;
        /// @dev T17-FIX (AUD-T17 M-1/M-2): the tids each listed chain uses, bits [16i, 16i+16) for chains[i]; 0 = the
        ///      mask on every chain. NOT in the coinId bytes: bound by rowsHash (BridgeRoleV4.rowsHash appends it).
        uint128 chainTids;
    }

    error ListsInvalid(uint8 why);

    function encode(Preimage memory p) internal pure returns (bytes memory b) {
        b = abi.encodePacked(
            "PANGEA-COIN-V4", PREIMAGE_VERSION, p.nameHash, p.symbolHash, p.creatorEvm, p.creatorSvm, p.homePcid, p.createdAt, p.salt
        );
        b = abi.encodePacked(b, uint8(p.chains.length));
        for (uint256 i = 0; i < p.chains.length; i++) {
            b = abi.encodePacked(b, p.chains[i]);
        }
        b = abi.encodePacked(b, p.transportMask, p.rowsHash);
    }

    function coinId(Preimage memory p) internal pure returns (bytes32) {
        return keccak256(encode(p));
    }

    /// @notice why: 1 chain count, 2 not ascending, 3 home not listed, 4 empty mask / bit 0 set.
    function check(Preimage memory p) internal pure {
        uint256 n = p.chains.length;
        if (n == 0 || n > MAX_CHAINS) revert ListsInvalid(1);
        bool home;
        for (uint256 i = 0; i < n; i++) {
            if (i > 0 && p.chains[i] <= p.chains[i - 1]) revert ListsInvalid(2);
            if (p.chains[i] == p.homePcid) home = true;
        }
        if (!home) revert ListsInvalid(3);
        if (p.transportMask == 0 || p.transportMask & 1 != 0) revert ListsInvalid(4);
    }

    function listed(Preimage memory p, uint32 pcid) internal pure returns (bool) {
        for (uint256 i = 0; i < p.chains.length; i++) {
            if (p.chains[i] == pcid) return true;
        }
        return false;
    }
}

src/v4/bridge/ITransportV4.sol

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

/// @title ITransportAdapterV4 -- a transport adapter of the shared bridge (V4-INTERFACES §11.2.14)
interface ITransportAdapterV4 {
    function transportId() external view returns (uint8);
    function bridge() external view returns (address);
    function quote(uint32 dstPcid, bytes calldata message, bytes calldata extraOptions) external view returns (uint256);
    /// @notice Bridge only. Returns the transport's own message id (LZ guid / Hyperlane message id).
    function send(uint32 dstPcid, bytes calldata message, bytes calldata extraOptions, address refundTo)
        external
        payable
        returns (bytes32 transportMsgId);
}

/// @notice What the adapters read from / call on the bridge.
interface IBridgeForAdaptersV4 {
    struct Route {
        uint32 remoteDomain;
        bytes32 peer;
    }

    function owner() external view returns (address);
    function routeOf(uint32 pcid, uint8 tid) external view returns (Route memory);
    function pcidOf(uint8 tid, uint32 remoteDomain) external view returns (uint32);
    function receiveFromTransport(uint32 srcPcid, bytes32 srcPeer, bytes calldata message, bytes32 transportMsgId, address executor)
        external;
}

src/v4/bridge/PangeaCoinV4.sol

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {GapRecorderV4} from "../gap/GapRecorderV4.sol";
import {GapMathV4} from "../gap/GapMathV4.sol";
import {GapBlockV4} from "../gap/GapBlockV4.sol";
import {PangeaOFTV4Storage as S} from "../gap/PangeaOFTV4Storage.sol";

/// @notice What the coin reads from CoinDeployerV4 while it is constructed (bridge + the opening mint's recipient),
///         keeping both out of the init code: one CREATE2 address per coin on every EVM chain.
interface ITokenOpenV4 {
    function bridge() external view returns (address);
    function poolManager() external view returns (address);
    function pendingMintTo() external view returns (address);
    /// @notice META-EVM (owner Q1 1150): the coin's first metadataURI (the open's OpenArgs.metadataURI; may be empty),
    ///         read like pendingMintTo so it stays out of the init code (the token address does not depend on it).
    function pendingMetadataURI() external view returns (string memory);
    /// @notice SUPPLY MIRROR: the address that may report this coin's global minted supply (SupplyReporter).
    function supplyReporter() external view returns (address);
}

interface ICreatorOfV4 {
    function creatorOf(bytes32 coinId) external view returns (address);
    function core() external view returns (address);
    function coinInfo(bytes32 coinId)
        external
        view
        returns (address token, uint32 homePcid, uint16 transportMask, uint8 nChains, uint32[] memory chains);
}

/// @title PangeaCoinV4 -- a v4 coin on one chain (V4-INTERFACES §11.2.8)
/// @notice Plain ERC-20 + EIP-2612 permit, 9 decimals, no owner. Exactly OPEN_SUPPLY (1B) is minted ONCE, in the
///         constructor, when this chain opens (CoinDeployerV4, CREATE2 salt = coinId). Afterwards only the immutable
///         bridge mints (verified arrivals, never more than burned at the source) and burns (only its own caller's
///         tokens, or tokens it just bought). No other issuance path exists.
///         Same-transaction sale lock (§11.2.8, B1-M1): after a buyAndSend the bridge calls lockSales(); for the rest of
///         that transaction a transfer of this coin TO the PoolManager reverts SameTxSellLocked (no buy-then-dump in
///         one transaction). B3-I2 (assessed, documented, not fixable here): a sale settled with
///         ERC-6909 claims of this coin already held in the PoolManager (deposited before the lock, even earlier in the
///         same transaction) moves no ERC-20 and is not seen by this lock; refusing it would need the pool's hook (the
///         live, unchanged V2 hook). The lock is defence in depth only: the buy's price is Ps = min(Pexec, Panchor x
///         (1 + k)) with Panchor read BEFORE the buy (B1-M1), so a same-transaction dump cannot raise what is credited.
///         Price recorder (§11.2.8, B1-M1): the audited old-scope GapRecorderV4 ring, unchanged, in this coin's
///         storage (PangeaOFTV4Storage's namespace): every non-zero move to / from the PoolManager records the official
///         pool's live price (the pool learned once from the bridge, GapRecorderV4.learn); `gapPrices()` gives the
///         fallback reads of §11.3.4 (Pref = min over L at the source, Pd_ref = pdTrusted at the destination), which
///         a same-block pump cannot raise / a same-block dump cannot lower.
contract PangeaCoinV4 is ERC20Permit {
    uint256 public constant OPEN_SUPPLY = 1_000_000_000 * 1e9;

    address public immutable bridge;
    bytes32 public immutable coinId;
    address public immutable creatorAtLaunch;
    address public immutable poolManager;
    bool internal transient _salesLocked;
    /// @notice Arbitrum-stack chain (Robinhood): the ring counts L2 blocks (GapBlockV4), probed once at construction.
    bool public immutable arbBlocks;
    uint256 internal constant LOOKBACK = GapMathV4.LOOKBACK_DEFAULT_SEC;
    /// @notice META-EVM (owner Q1 1150; live CH:89 BadTerms(9)): the most bytes a metadataURI may have.
    uint256 public constant MAX_METADATA_URI_BYTES = 128;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;

    /// @notice META-EVM (owner Q1 1150, live PangeaOFTV3:207 / PangeaOFTV3LogModule:53-65): logo, description and links.
    ///         Set at the open (may be empty), then by the metadata authority only (setMetadataURI).
    string public metadataURI;

    /// @notice SUPPLY MIRROR (owner 2026-11-12, ported from PangeaOFTV3): `totalSupply()` reports the coin's GLOBAL
    ///         minted supply (web/lib/v4/supply-minted-v4.mjs: the open chains' local supplies + in flight), written by
    ///         `supplyReporter` (follows it up or down), floored at this chain's own supply. `localSupply()` is what is
    ///         really on this chain; balances and transfers are the plain local ERC-20's. 0 = never reported.
    uint256 public reportedSupply;
    /// @notice The only address that may call reportSupply (the v4 SupplyReporter: one address on every chain). Read
    ///         from the coin deployer at construction (not in the init code: the coin's address does not depend on it).
    address public immutable supplyReporter;

    /// @notice `totalSupply()` now reports `newSupply` (was `oldSupply`). No balance moved.
    event SupplyReported(uint256 oldSupply, uint256 newSupply);

    /// @notice Live PangeaOFTV3 / PangeaOFTV3LogModule event, same signature.
    event MetadataURISet(string uri);

    error NotBridge();
    error NotSupplyReporter();
    /// @notice A report above the coin's listed chains x 1B (it can never have minted more).
    error SupplyAboveListed(uint256 supply, uint256 max);
    error ZeroMintTo();
    error ZeroBridge();
    error SameTxSellLocked();
    /// @notice Live PangeaOFTV3LogModule error: the caller is not the metadata authority.
    error NotMetadataAuthority();
    /// @notice META-EVM: a metadataURI above MAX_METADATA_URI_BYTES (live refused it at launch: CH:89 BadTerms(9)).
    error MetadataURITooLong(uint256 length);

    /// @notice v4-gap-A2 item 3 / TOKENOMICS-V4: the coin's creator NOW on this chain = its vault while the chain's
    ///         tokenomics switch is on (LaunchCoreV4.tokenomicsOf), else the bridge's creator role (0xdEaD after a
    ///         renounce). A TokenomicsVaultV24 binds only when this names it (ITokenomicsCoin.creator); the fee hook
    ///         never reads it.
    function creator() external view returns (address) {
        address core = ICreatorOfV4(bridge).core();
        (bool ok, bytes memory r) = core.staticcall(abi.encodeWithSignature("tokenomicsOf(bytes32)", coinId));
        if (ok && r.length == 32) {
            address v = abi.decode(r, (address));
            if (v != address(0)) return v;
        }
        return ICreatorOfV4(bridge).creatorOf(coinId);
    }

    constructor(string memory name_, string memory symbol_, bytes32 coinId_, address creatorAtLaunch_)
        ERC20(name_, symbol_)
        ERC20Permit(name_)
    {
        bridge = ITokenOpenV4(msg.sender).bridge();
        if (bridge == address(0)) revert ZeroBridge();
        coinId = coinId_;
        creatorAtLaunch = creatorAtLaunch_;
        poolManager = ITokenOpenV4(msg.sender).poolManager();
        supplyReporter = ITokenOpenV4(msg.sender).supplyReporter();
        arbBlocks = GapBlockV4.arbitrumStack();
        address to = ITokenOpenV4(msg.sender).pendingMintTo();
        if (to == address(0)) revert ZeroMintTo();
        _mint(to, OPEN_SUPPLY);
        string memory uri = ITokenOpenV4(msg.sender).pendingMetadataURI();
        if (bytes(uri).length > MAX_METADATA_URI_BYTES) revert MetadataURITooLong(bytes(uri).length);
        if (bytes(uri).length > 0) {
            metadataURI = uri;
            emit MetadataURISet(uri);
        }
    }

    /// @notice META-EVM (owner Q1 1150): who may set metadataURI = the coin's creator role on this chain as the bridge
    ///         holds it (BridgeRoleV4.creatorOf: the current creator after a handover / admin step-in, as mirrored
    ///         here). address(0) = nobody (after a renounce, or no EVM creator). Live's separate
    ///         propose/acceptMetadataAuthority is replaced by the bridge's creator handover (one role, not two).
    function metadataAuthority() public view returns (address a) {
        a = ICreatorOfV4(bridge).creatorOf(coinId);
        if (a == DEAD) a = address(0);
    }

    /// @notice Live PangeaOFTV3LogModule.setMetadataURI, plus the live launch bound (<= 128 bytes). Empty clears it.
    function setMetadataURI(string calldata uri) external {
        address a = metadataAuthority();
        if (a == address(0) || msg.sender != a) revert NotMetadataAuthority();
        if (bytes(uri).length > MAX_METADATA_URI_BYTES) revert MetadataURITooLong(bytes(uri).length);
        metadataURI = uri;
        emit MetadataURISet(uri);
    }

    function decimals() public pure override returns (uint8) {
        return 9;
    }

    // ------------------------------------------------------------------ supply mirror (PangeaOFTV3 port)

    /// @notice The global minted supply as last reported, never below this chain's own supply (before any report: the
    ///         local supply). Display only: nothing on chain reads it (every share, cap and bridge figure is local).
    function totalSupply() public view override returns (uint256) {
        uint256 l = super.totalSupply();
        uint256 r = reportedSupply;
        return r > l ? r : l;
    }

    /// @notice What is really on this chain (the ERC-20's own total).
    function localSupply() external view returns (uint256) {
        return super.totalSupply();
    }

    /// @notice The most a report may say: the coin's listed chains (the bridge's coin record) x OPEN_SUPPLY.
    function maxReportableSupply() public view returns (uint256) {
        (,,, uint8 n,) = ICreatorOfV4(bridge).coinInfo(coinId);
        return uint256(n) * OPEN_SUPPLY;
    }

    /// @notice The supply reporter writes the global minted supply (up or down). Above maxReportableSupply reverts; a
    ///         figure below the local supply is kept but totalSupply() floors it (an arrival can land before a report).
    function reportSupply(uint256 newSupply) external {
        if (supplyReporter == address(0) || msg.sender != supplyReporter) revert NotSupplyReporter();
        uint256 max = maxReportableSupply();
        if (newSupply > max) revert SupplyAboveListed(newSupply, max);
        uint256 old = reportedSupply;
        if (newSupply == old) return;
        reportedSupply = newSupply;
        emit SupplyReported(old, newSupply);
        emit Transfer(address(0), DEAD, 0);
    }

    function bridgeMint(address to, uint256 amount) external {
        if (msg.sender != bridge) revert NotBridge();
        _mint(to, amount);
    }

    /// @notice The bridge moves its own caller's bridge fee (B1-L4); called only with `from` = the bridge's caller.
    function bridgeTransfer(address from, address to, uint256 amount) external {
        if (msg.sender != bridge) revert NotBridge();
        _transfer(from, to, amount);
    }

    /// @notice The bridge, right after a buyAndSend's swap: no sale of this coin into the PoolManager for the rest of
    ///         the transaction.
    function lockSales() external {
        if (msg.sender != bridge) revert NotBridge();
        _salesLocked = true;
    }

    function _update(address from, address to, uint256 value) internal override {
        address pm = poolManager;
        if (_salesLocked && to == pm && value != 0) revert SameTxSellLocked();
        super._update(from, to, value);
        if (value != 0 && from != to && (from == pm || to == pm) && pm != address(0)) {
            GapRecorderV4.recordLive(S.layout(), pm, bridge, GapBlockV4.number(arbBlocks));
        }
    }

    /// @notice The recorded prices of the official pool, quote x 1e18 per whole coin (0 = none / pool not known):
    ///         Plast (newest earlier-block record), Pref (source: min(live, the ring within L)), Pd_ref (destination:
    ///         GapMathV4.pdTrusted, the max rule), live (rounded down).
    function gapPrices() external view returns (uint256 plast, uint256 pref, uint256 pdRef, uint256 live) {
        S.Layout storage l = S.layout();
        if (!l.known) return (0, 0, 0, 0);
        uint256 blk = GapBlockV4.number(arbBlocks);
        GapMathV4.Ring memory r = GapRecorderV4.load(l);
        live = GapRecorderV4.livePrice(l, poolManager, false);
        plast = GapMathV4.plast(r, blk);
        pref = GapMathV4.pref(r, live, block.timestamp, blk, LOOKBACK);
        pdRef = GapMathV4.pdTrusted(
            r, GapRecorderV4.livePrice(l, poolManager, true), block.timestamp, blk, LOOKBACK, GapRecorderV4.bucketWidth(l)
        );
    }

    function bridgeBurn(address from, uint256 amount) external {
        if (msg.sender != bridge) revert NotBridge();
        _burn(from, amount);
    }
}

src/v4/bridge/PangeaDeployerV4.sol

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

/// @notice What a v4 infra contract reads from its deployer in its constructor (the TokenDeployerV4 pattern, §11.2.1):
///         chain-specific values stay out of the init code, so the address is the same on every EVM chain.
interface IPendingConfigV4 {
    function pending() external view returns (bytes memory);
}

/// @title PangeaDeployerV4 -- CREATE2 deployer of the shared-bridge infra (bridge, adapters, coin deployer, core)
/// @notice Itself deployed through the canonical CREATE2 deployer with a fixed salt and `initializer` (the same deploy
///         key / multisig in every config), so it has one address on every EVM chain, and so does everything it deploys
///         with the same salt and init code. Only `initializer` deploys; the per-chain config is handed over through
///         `pending()` for the duration of the constructor only.
contract PangeaDeployerV4 is IPendingConfigV4 {
    address public immutable initializer;
    bytes internal _pending;

    event Deployed(bytes32 indexed salt, address indexed at);

    error NotInitializer();
    error DeployFailed();

    constructor(address initializer_) {
        initializer = initializer_;
    }

    function pending() external view returns (bytes memory) {
        return _pending;
    }

    function predict(bytes32 salt, bytes calldata initcode) external view returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(initcode))))));
    }

    function deploy(bytes32 salt, bytes calldata initcode, bytes calldata config) external returns (address a) {
        if (msg.sender != initializer) revert NotInitializer();
        _pending = config;
        bytes memory code = initcode;
        assembly ("memory-safe") {
            a := create2(0, add(code, 0x20), mload(code), salt)
        }
        delete _pending;
        if (a == address(0)) revert DeployFailed();
        emit Deployed(salt, a);
    }
}

src/v4/bridge/gap/BridgeGapV4.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IPendingConfigV4} from "../PangeaDeployerV4.sol";
import {BridgeCodecV4 as Codec} from "../BridgeCodecV4.sol";
import {IGapOracleV4} from "./IGapOracleV4.sol";
import {GapPriceSigV4 as Sig} from "./GapPriceSigV4.sol";
import {GapMathV4} from "../../gap/GapMathV4.sol";

/// @title BridgeGapV4 -- the shared bridge's gap pricing, a STATELESS view helper (size: §11.2.10's module split)
/// @notice Called (STATICCALL) by PangeaBridgeV4 only for prices and credits; holds no state and no power: every
///         number it returns is capped by the bridge's own rules (credited <= A, hard invariant (i)). Same address on
///         every EVM chain (PangeaDeployerV4; the oracle from `pending()`).
///         - verify(): §11.3.2 on a signed PAIR price, EIP-712 domain ("PangeaGapPrice", "1", chain id, the BRIDGE).
///         - source price: signed (verified, reverts on a bad signature) > fallback reader > none (§11.3.4-5).
///         - credit(): the §8 arrival rules with GapMathV4 (signed Pd from the message, else the destination reader).
///         - buy(): Ps = min(Pexec in USD, Panchor x (1 + k)), the source cover.
contract BridgeGapV4 {
    bytes32 internal constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 internal constant NAME_HASH = keccak256("PangeaGapPrice");
    bytes32 internal constant VERSION_HASH = keccak256("1");

    IGapOracleV4 public immutable oracle;
    /// @dev BridgeStateV4.chainKind(uint32) (KIND_EVM = 1), read from the calling bridge.
    bytes4 internal constant CHAIN_KIND = bytes4(keccak256("chainKind(uint32)"));

    error GapPriceInvalid(uint8 why);
    error GapPriceExpired(uint64 validUntil);

    constructor() {
        oracle = IGapOracleV4(abi.decode(IPendingConfigV4(msg.sender).pending(), (address)));
    }

    function domainSeparator(address bridge) public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, bridge));
    }

    function digest(Sig.GapPrice calldata p, address bridge) public view returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator(bridge), Sig.hash(p)));
    }

    /// @dev why: 1 coin, 2 src pcid, 3 dst pcid, 4 src token, 5 decimals, 6 key, 7 validity window, 8 clock skew,
    ///      9 zero price, 10 signature; 11 the signed quote price's chain / quote (A2-ASK-1; any quote, ANY PAIRS).
    function verify(Sig.SignedGapPrice calldata gp, bytes32 coinId, uint32 local, uint32 dst, address token, address bridge)
        public
        view
    {
        Sig.GapPrice calldata p = gp.p;
        if (p.coinId != coinId) revert GapPriceInvalid(1);
        if (p.src.pcid != local) revert GapPriceInvalid(2);
        if (p.dst.pcid != dst) revert GapPriceInvalid(3);
        if (p.src.token != bytes32(uint256(uint160(token)))) revert GapPriceInvalid(4);
        if (p.src.decimals != 9) revert GapPriceInvalid(5);
        address key = _signer(p.keyId, p.observedAt, p.validUntil);
        if (p.src.priceUsdE18 == 0 || p.dst.priceUsdE18 == 0) revert GapPriceInvalid(9);
        _checkSig(digest(p, bridge), gp.sig, key);
    }

    /// @dev §11.3.2 steps shared by both signed messages: the signer slot live, not expired, the validity window,
    ///      the clock skew. Returns the slot's key.
    function _signer(uint8 keyId, uint64 observedAt, uint64 validUntil) internal view returns (address) {
        if (keyId > 3) revert GapPriceInvalid(6);
        IGapOracleV4.PriceSigner memory s = oracle.priceSigner(keyId);
        if (s.key == address(0) || block.timestamp < s.validFrom || block.timestamp > s.validUntil) revert GapPriceInvalid(6);
        if (block.timestamp > validUntil) revert GapPriceExpired(validUntil);
        if (validUntil < observedAt || validUntil - observedAt > oracle.maxValiditySec()) revert GapPriceInvalid(7);
        if (observedAt > block.timestamp + 5) revert GapPriceInvalid(8);
        return s.key;
    }

    function _checkSig(bytes32 dg, bytes memory sig, address key) internal pure {
        (address got, ECDSA.RecoverError e,) = ECDSA.tryRecover(dg, sig);
        if (e != ECDSA.RecoverError.NoError || got != key) revert GapPriceInvalid(10);
    }

    /// @notice A2-ASK-1: the EIP-712 digest of a signed quote USD price (the gap price's domain: this chain, the bridge).
    function quoteDigest(Sig.QuoteUsdPrice memory q, address bridge) public view returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator(bridge), Sig.hashQuote(q)));
    }

    /// @notice A2-ASK-1 (signed price first): the quote's USD for Pexec_usd. `signedQuote` = abi.encode(QuoteUsdPrice,
    ///         bytes sig) (empty = none): when given it is VERIFIED (else the call reverts) and used for this chain
    ///         (pcid = oracle.localChain()) and THIS quote (the coin's). ANY PAIRS (owner 2026-11-08 23:15, F1): any
    ///         quote -- native, or ANY ERC-20, listed or not (no asset venue needed); the signer prices it. None ->
    ///         the oracle's asset reader (0 = unpriced: that buy then crosses plain and unpriced, credited in full;
    ///         OD-A-11, D1 RULE-CHECK 1300, was BuyNeedsPrice).
    function quoteUsd(address quote, bytes calldata signedQuote, address bridge) public view returns (uint256) {
        if (signedQuote.length == 0) return oracle.assetUsd(quote, false);
        (Sig.QuoteUsdPrice memory q, bytes memory sig) = abi.decode(signedQuote, (Sig.QuoteUsdPrice, bytes));
        if (q.pcid != oracle.localChain() || q.quote != quote) revert GapPriceInvalid(11);
        address key = _signer(q.keyId, q.observedAt, q.validUntil);
        if (q.priceUsdE18 == 0) revert GapPriceInvalid(9);
        _checkSig(quoteDigest(q, bridge), sig, key);
        return q.priceUsdE18;
    }

    /// @notice The send's price: (priceSource, psUsdE18, p2E18, source depth). AB1-R2 (§11.3.2 "k unchanged"): under a
    ///         signed price the source depth is still read ON CHAIN from the coin's source reader (before the buy), so
    ///         k follows the dynamic curve exactly as on the fallback path; depth 0 (unreadable) -> kMin as there.
    function sourcePrice(Sig.SignedGapPrice calldata gp, bytes32 coinId, uint32 local, uint32 dst, address token)
        external
        view
        returns (uint8 source, uint128 ps, uint128 p2, uint256 depth)
    {
        if (gp.sig.length != 0) {
            verify(gp, coinId, local, dst, token, msg.sender);
            (, depth) = oracle.coinPriceSrc(token);
            return (Codec.PS_SIGNED, gp.p.src.priceUsdE18, gp.p.dst.priceUsdE18, depth);
        }
        uint256 p;
        (p, depth) = oracle.coinPriceSrc(token);
        if (p != 0 && p <= type(uint128).max) return (Codec.PS_FALLBACK, uint128(p), 0, depth);
        // GAPFIX ANYPAIRS: the quote has no USD source -> its pool price in the QUOTE, p2 = the quote's family (EVM
        // destinations only; priceClass stays 0, so a Solana-style class message never reads as one). The destination
        // prices the gap as the ratio when its quote is of the same family, else credits in full (fee 0 by design).
        (bool ok, bytes memory k) = msg.sender.staticcall(abi.encodeWithSelector(CHAIN_KIND, dst));
        if (ok && k.length == 32 && abi.decode(k, (uint256)) == 1) {
            uint8 fam;
            (p, fam) = oracle.coinPriceClass(token, false);
            if (fam != 0) return (Codec.PS_FALLBACK, uint128(p), fam, 0);
        }
        return (Codec.PS_NONE, 0, 0, 0);
    }

    /// @notice The arrival credit (LD) of `h` on this chain for `token`, amount `a` (LD).
    function credit(Codec.Header calldata h, address token, uint256 a) external view returns (uint256) {
        IGapOracleV4.Params memory p = oracle.params(h.coinId);
        if (!p.gapOn || h.priceSource == Codec.PS_NONE || h.psUsdE18 == 0) return a;
        if (h.priceSource == Codec.PS_FALLBACK && h.priceClass == 0 && h.p2E18 != 0) {
            // GAPFIX ANYPAIRS class pair (sourcePrice): Ps and Pd in the same quote family, the pools' price ratio
            (uint256 pc, uint8 fam) = oracle.coinPriceClass(token, true);
            if (h.mode != Codec.MODE_PLAIN || fam == 0 || fam != h.p2E18) return a; // no common family: fee 0 by design
            return GapMathV4.creditPlain(a, h.psUsdE18, pc);
        }
        (uint256 pdR, uint256 depth, uint32 fD) = oracle.coinPriceDst(token);
        uint256 pd = h.priceSource == Codec.PS_SIGNED ? h.p2E18 : pdR;
        if (pd == 0 || pd > GapMathV4.PRICE_MAX) return a;
        if (h.mode == Codec.MODE_PLAIN) return GapMathV4.creditPlain(a, h.psUsdE18, pd);
        uint256 cover = GapMathV4.coverUsdE18(h.coverSrcMicroUsd, 0, p.coverCapUsdE18);
        uint256 c = GapMathV4.creditBuy(
            a, h.bridgeFeePpm, h.psUsdE18, _marginAt(p, depth), cover, pd, h.priceSource == Codec.PS_SIGNED ? 0 : fD, 9
        );
        return c > a ? a : c;
    }

    /// @notice buyAndSend's credit price and cover: Ps = min(Pexec_usd, Panchor x (1 + k)); 0 Ps = unpriced.
    ///         A2-ASK-1: `signedQuote` (see quoteUsd) prices the quote first; the cover's native USD is the signed
    ///         quote price when the quote is native, else the oracle's.
    function buy(
        bytes32 coinId,
        address quote,
        uint256 quotePaid,
        uint256 out,
        uint256 panchor,
        uint256 depth,
        uint256 transportFee,
        bytes calldata signedQuote
    ) external view returns (uint256 ps, uint256 pexecUsd, uint32 coverMicro) {
        IGapOracleV4.Params memory p = oracle.params(coinId);
        uint256 qUsd = quoteUsd(quote, signedQuote, msg.sender);
        pexecUsd = _pexecUsd(quote, quotePaid, out, qUsd);
        if (pexecUsd == 0 || panchor == 0) return (0, pexecUsd, 0);
        ps = GapMathV4.psBuy(pexecUsd, panchor, p.kOn, _k(p, depth));
        if (ps > type(uint128).max) ps = 0;
        coverMicro = _cover(p, transportFee, quote == address(0) && signedQuote.length != 0 ? qUsd : oracle.assetUsd(address(0), false));
    }

    /// @notice Plain-send credit known at the source (priceSource 1): min(A, A x Ps / Pd).
    function creditPlain(uint256 a, uint256 ps, uint256 pd) external pure returns (uint256) {
        return GapMathV4.creditPlain(a, ps, pd);
    }

    /// @notice AB1-R2: the buy path's k (ppm) for `coinId` at `token`'s source depth as the bridge reads it now (the
    ///         planner's mirror; signed and fallback alike): (depth USD E18, k ppm).
    function sourceK(bytes32 coinId, address token) external view returns (uint256 depth, uint256 kPpm) {
        (, depth) = oracle.coinPriceSrc(token);
        kPpm = _k(oracle.params(coinId), depth);
    }

    function _k(IGapOracleV4.Params memory p, uint256 depth) internal pure returns (uint256) {
        return depth == 0 ? _lo(p.kMinPpm, p.kMaxPpm) : GapMathV4.kPpm(p.kK, p.kMinPpm, p.kMaxPpm, depth, _marginAt(p, depth));
    }

    function _marginAt(IGapOracleV4.Params memory p, uint256 depth) internal pure returns (uint32) {
        if (depth == 0) return _lo(p.marginMinPpm, p.marginMaxPpm);
        return GapMathV4.margin(p.marginK, p.marginMinPpm, p.marginMaxPpm, depth);
    }

    function _lo(uint32 lo, uint32 hi) internal pure returns (uint32) {
        return lo > hi ? hi : lo;
    }

    function _pexecUsd(address quote, uint256 quotePaid, uint256 out, uint256 qUsd) internal view returns (uint256) {
        if (quotePaid == 0) return 0;
        uint8 dq = 18;
        if (quote != address(0)) {
            (bool s, bytes memory r) = quote.staticcall{gas: 30_000}(abi.encodeWithSignature("decimals()"));
            if (!s || r.length != 32 || abi.decode(r, (uint256)) > 36) return 0;
            dq = uint8(abi.decode(r, (uint256)));
        }
        uint256 pq = GapMathV4.pexec(quotePaid, out, 9, dq);
        return pq == 0 ? 0 : GapMathV4.mulDown(pq, qUsd);
    }

    function _cover(IGapOracleV4.Params memory p, uint256 transportFee, uint256 n) internal pure returns (uint32) {
        if (p.coverCapUsdE18 == 0 || transportFee == 0) return 0;
        uint256 usd = Math.mulDiv(transportFee, n, 1e18);
        if (usd > p.coverCapUsdE18) usd = p.coverCapUsdE18;
        uint256 micro = usd / GapMathV4.MICRO_USD_E18;
        return micro > type(uint32).max ? type(uint32).max : uint32(micro);
    }
}

src/v4/bridge/gap/GapPriceSigV4.sol

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

/// @title GapPriceSigV4 -- the signed gap price PAIR (V4-INTERFACES §11.3.1), EIP-712 struct hashing
library GapPriceSigV4 {
    struct GapPriceLeg {
        uint32 pcid;
        bytes32 token;
        bytes32 pool;
        uint128 priceUsdE18;
        uint8 decimals;
        uint64 blockOrSlot;
    }

    struct GapPrice {
        bytes32 coinId;
        GapPriceLeg src;
        GapPriceLeg dst;
        uint64 observedAt;
        uint64 validUntil;
        uint8 keyId;
    }

    /// @notice sig.length == 0 -> "no signed price" (fallback).
    struct SignedGapPrice {
        GapPrice p;
        bytes sig;
    }

    /// @notice RULING A2-ASK-1 (signed price first): the signed USD price of the coin's QUOTE on the chain of the buy
    ///         (native = address(0), or ANY ERC-20: ANY PAIRS, listed or not), for buyAndSend's Pexec_usd (and the cover when the quote is native) where no asset
    ///         reader prices it (Robinhood). Same EIP-712 domain and signer slots as GapPrice ("PangeaGapPrice", "1",
    ///         chain id, the BRIDGE). priceUsdE18 = USD x 1e18 per WHOLE quote unit (1 ETH, 1 USDC).
    struct QuoteUsdPrice {
        uint32 pcid;
        address quote;
        uint128 priceUsdE18;
        uint64 observedAt;
        uint64 validUntil;
        uint8 keyId;
    }

    bytes32 internal constant QUOTE_USD_TYPEHASH =
        keccak256("QuoteUsdPrice(uint32 pcid,address quote,uint128 priceUsdE18,uint64 observedAt,uint64 validUntil,uint8 keyId)");

    function hashQuote(QuoteUsdPrice memory q) internal pure returns (bytes32) {
        return keccak256(abi.encode(QUOTE_USD_TYPEHASH, q.pcid, q.quote, q.priceUsdE18, q.observedAt, q.validUntil, q.keyId));
    }

    bytes32 internal constant LEG_TYPEHASH =
        keccak256("GapPriceLeg(uint32 pcid,bytes32 token,bytes32 pool,uint128 priceUsdE18,uint8 decimals,uint64 blockOrSlot)");
    bytes32 internal constant PRICE_TYPEHASH = keccak256(
        "GapPrice(bytes32 coinId,GapPriceLeg src,GapPriceLeg dst,uint64 observedAt,uint64 validUntil,uint8 keyId)GapPriceLeg(uint32 pcid,bytes32 token,bytes32 pool,uint128 priceUsdE18,uint8 decimals,uint64 blockOrSlot)"
    );

    function hashLeg(GapPriceLeg calldata l) internal pure returns (bytes32) {
        return keccak256(abi.encode(LEG_TYPEHASH, l.pcid, l.token, l.pool, l.priceUsdE18, l.decimals, l.blockOrSlot));
    }

    function hash(GapPrice calldata p) internal pure returns (bytes32) {
        return keccak256(abi.encode(PRICE_TYPEHASH, p.coinId, hashLeg(p.src), hashLeg(p.dst), p.observedAt, p.validUntil, p.keyId));
    }
}

src/v4/bridge/gap/IGapOracleV4.sol

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

/// @title IGapOracleV4 -- the shared bridge's gap prices: our signed gap price (PRIMARY) and the upgradable fallback
///        reader registry. Owner 2026-11-06 20:45: signed price first; else the on-chain reader of the coin's pool;
///        else NO gap fee; never a user-supplied price.
interface IGapOracleV4 {
    /// @notice §11.3.3 signer slot (keyId 0..3): validFrom <= now <= validUntil; validUntil = now revokes at once.
    struct PriceSigner {
        address key;
        uint64 validFrom;
        uint64 validUntil;
    }

    /// @notice Per-chain gap parameters (coin override possible). Every value admin-set (LEAD UPDATE 2/3).
    struct Params {
        uint16 bridgeFeeBps; // < 10,000; default 20
        bool gapOn; // false = the coin's arrivals are credited in full (escape)
        bool kOn; // the buy backstop Ps = min(Pexec, Psrc x (1 + k))
        uint64 marginK; // x 1e6 (GapMathV4.curve)
        uint32 marginMinPpm;
        uint32 marginMaxPpm;
        uint64 kK; // x 1e6
        uint32 kMinPpm;
        uint32 kMaxPpm;
        uint128 coverCapUsdE18; // 0 = no cover
    }

    function localChain() external view returns (uint32);
    function params(bytes32 coinId) external view returns (Params memory);

    function priceSigner(uint8 keyId) external view returns (PriceSigner memory);
    function maxValiditySec() external view returns (uint32);

    /// @notice B1-M3: our delivery keys (buy-mode arrivals at once) and the window after which anyone may deliver.
    function isDeliveryKey(address key) external view returns (bool);
    function exclusiveWindowSec() external view returns (uint32);
    /// @notice A-D8: what a send toward (dstPcid, tid) owes our keys-only delivery and to whom ((0, 0) = none).
    function deliveryCharge(uint32 dstPcid, uint8 tid) external view returns (uint256 costWei, address to);

    /// @notice FALLBACK source price: the coin's pool reader on this chain, rounded down (0s = unreadable).
    function coinPriceSrc(address token) external view returns (uint256 priceUsdE18, uint256 depthUsdE18);

    /// @notice FALLBACK destination price: the reader of `token`'s pool on this chain, rounded UP; 0s when unreadable.
    function coinPriceDst(address token) external view returns (uint256 priceUsdE18, uint256 depthUsdE18, uint32 feePpm);

    /// @notice USD x 1e18 per whole `asset` (quote / native = address(0)) on this chain, by its reader (0 = unreadable).
    function assetUsd(address asset, bool roundUp) external view returns (uint256);

    /// @notice GAPFIX ANYPAIRS: `token`'s rule price in its pool's quote and that quote's family ((0, 0) = none).
    function coinPriceClass(address token, bool roundUp) external view returns (uint256 pQuoteE18, uint8 family);

    /// @notice A2-ASK-1: the venue id `asset` is LISTED under (0 = not listed).
    function assetVenueId(address asset) external view returns (uint16);
}

/// @title IGapReaderV4 -- a venue reader in the fallback registry (Uniswap v2/v3/v4, Aerodrome, Pancake, ...).
interface IGapReaderV4 {
    /// @notice USD x 1e18 per whole `token` at the pool `poolRef` (venue-specific encoding), rounded as asked; its
    ///         quote-side depth in USD x 1e18 and the pool's total fee (ppm). 0s = unreadable.
    function read(address token, bytes calldata poolRef, bool roundUp)
        external
        view
        returns (uint256 priceUsdE18, uint256 depthUsdE18, uint32 feePpm);
}

/// @title IGapQuoteReaderV4 -- GAPFIX ANYPAIRS (optional for a reader; one without it = no class price): the price in
///        the pool's quote (x 1e18 per whole token) and the quote.
interface IGapQuoteReaderV4 {
    function readQuote(address token, bytes calldata poolRef, bool roundUp) external view returns (uint256 pQuoteE18, address quote);
}

src/v4/gap/GapBlockV4.sol

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

/// @title GapBlockV4 -- the block number the v4 gap rules count in ("an earlier block", the ring's blocks)
/// @notice Audit r4 R4-1 (lead ruling): "earlier block" means the chain's OWN block. On Arbitrum-stack chains
///         (Robinhood, Arbitrum) `block.number` is the parent chain's (L1) number (~12 s, many L2 blocks with
///         different timestamps), so there the rules read ArbSys(0x64).arbBlockNumber(), the L2 block. Which one is
///         an IMMUTABLE of the token (PangeaOFTV4.gapArbBlockNumber), fixed at its construction from its deployer
///         (ITokenParamsV4.pendingArbBlockNumber); nothing can change it later.
library GapBlockV4 {
    /// @dev Arbitrum's ArbSys precompile.
    address internal constant ARB_SYS = address(0x64);
    /// @dev The read's gas cap (ArbSys answers in a few hundred gas; an INVALID-coded account must not eat the rest).
    uint256 internal constant READ_GAS = 20_000;

    /// @dev ArbSys did not answer (never on an Arbitrum-stack chain): fail closed rather than mix block numbers.
    error GapBlockUnreadable();

    /// @notice The current block in the rules' numbering: arbBlockNumber() when `arb`, else block.number.
    function number(bool arb) internal view returns (uint256 n) {
        if (!arb) return block.number;
        (bool ok, bytes memory r) = ARB_SYS.staticcall{gas: READ_GAS}(abi.encodeWithSignature("arbBlockNumber()"));
        if (!ok || r.length != 32) revert GapBlockUnreadable();
        n = abi.decode(r, (uint256));
    }

    /// @notice Whether this chain answers ArbSys.arbBlockNumber() (an Arbitrum-stack chain). On any other chain
    ///         the answer is not 32 bytes -> false: no code at 0x64 (the call succeeds with no return data), or another
    ///         precompile there (BSC's refuses this input, from memory of bsc-geth; the probe then burns READ_GAS once).
    function arbitrumStack() internal view returns (bool) {
        (bool ok, bytes memory r) = ARB_SYS.staticcall{gas: READ_GAS}(abi.encodeWithSignature("arbBlockNumber()"));
        return ok && r.length == 32;
    }
}

src/v4/gap/GapMathV4.sol

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

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

/// @title GapMathV4 -- the Gap v4 arithmetic and the codec v4 (spec §2-§11, V4-INTERFACES §2, §3)
/// @notice CANONICAL. The Rust port (solana/oft-v4 math_v4.rs) and the JS port (web/lib/v4/gap-math-v4.mjs)
///         implement the same functions and must pass test/v4/vectors/gap-math-v4.json, which
///         test/v4/vectors/GapMathV4Vectors.t.sol checks against this library. A change here is a change to
///         all three.
/// @dev All pure. Units: ppm = 1e6 base; every price is "pricing unit x 1e18 per WHOLE token" (uint128, 0 =
///      unknown); amounts are raw local units. Every product goes through 512-bit mulDiv. Rounding is always
///      AGAINST THE CREDIT: Ps, Pexec, Pref, the cover and m round DOWN; Pd, fD, the depth round UP; the credit
///      rounds DOWN (so the withheld part A - credited rounds up).
library GapMathV4 {
    // ================================================================ units

    uint256 internal constant PPM = 1_000_000;
    uint256 internal constant E18 = 1e18;
    uint256 internal constant PRICE_MAX = type(uint128).max;
    /// @dev USD 1e18 per micro-dollar (the codec's cover unit).
    uint256 internal constant MICRO_USD_E18 = 1e12;
    /// @dev OFT shared decimals.
    uint8 internal constant SHARED_DECIMALS = 6;

    // ================================================================ codec v4 (spec §7, frozen)

    uint8 internal constant VER = 0x04;
    uint8 internal constant MODE_PLAIN = 0;
    uint8 internal constant MODE_BUY = 1;
    uint8 internal constant MODE_REFUND = 0xFF;
    uint8 internal constant REFUND_CLASS = 255;

    uint256 internal constant OFF_SEND_TO = 0; // bytes32
    uint256 internal constant OFF_AMOUNT_SD = 32; // uint64 BE
    uint256 internal constant OFF_VER = 40; // uint8
    uint256 internal constant OFF_MODE = 41; // uint8
    uint256 internal constant OFF_CLASS = 42; // uint8
    uint256 internal constant OFF_PS_CLASS = 43; // uint128 BE
    uint256 internal constant OFF_PS_USD = 59; // uint128 BE
    uint256 internal constant OFF_BRIDGE_FEE = 75; // uint32 BE
    uint256 internal constant OFF_COVER_SRC = 79; // uint32 BE, micro-USD
    uint256 internal constant OFF_MIN_CREDITED = 83; // uint64 BE
    uint256 internal constant OFF_RESERVED = 91; // 5 bytes, 0
    uint256 internal constant HEADER_LEN = 96;

    /// @notice decode status: a valid v4 message (mode 0 or 1).
    uint8 internal constant DEC_OK = 0;
    /// @notice decode status: exactly the refund marker (mode 0xFF, class 255, both prices 0, not composed).
    uint8 internal constant DEC_REFUND = 1;
    /// @notice decode status: not a valid codec v4 message: refused (never credited at fee 0).
    uint8 internal constant DEC_BAD = 2;

    error GapMsgTooShort(uint256 length);

    struct Header {
        bytes32 sendTo;
        uint64 amountSD;
        uint8 mode;
        uint8 priceClass;
        uint128 psClassE18;
        uint128 psUsdE18;
        uint32 bridgeFeePpm;
        uint32 coverSrcMicroUsd;
        uint64 minCreditedSD;
        bool composed;
    }

    /// @notice The v4 message: the 96-byte header, then composeFrom | composeMsg iff composeMsg is not empty.
    ///         The sender's own message only; the refund marker is built by `encodeRefund`.
    function encode(Header memory h, bytes32 composeFrom, bytes memory composeMsg) internal pure returns (bytes memory m) {
        m = abi.encodePacked(
            h.sendTo,
            h.amountSD,
            VER,
            h.mode,
            h.priceClass,
            h.psClassE18,
            h.psUsdE18,
            h.bridgeFeePpm,
            h.coverSrcMicroUsd,
            h.minCreditedSD,
            bytes5(0)
        );
        if (composeMsg.length != 0) m = abi.encodePacked(m, composeFrom, composeMsg);
    }

    /// @notice The refund marker (v3 AMENDMENT 2 shape, v4 codec): only an expired-compose return builds it.
    function encodeRefund(bytes32 sendTo, uint64 amountSD) internal pure returns (bytes memory) {
        Header memory h;
        (h.sendTo, h.amountSD, h.mode, h.priceClass) = (sendTo, amountSD, MODE_REFUND, REFUND_CLASS);
        return encode(h, bytes32(0), "");
    }

    /// @notice Decodes and VALIDATES a message. Reverts only below 40 bytes (no sendTo / amountSD).
    ///         DEC_BAD when: shorter than 96 bytes; ver != 4; reserved bytes != 0; mode not 0, 1 or 0xFF;
    ///         mode 0xFF or class 255 that is not exactly the refund marker; class 0 with psClass != 0, or class
    ///         != 0 with psClass == 0; bridgeFeePpm >= 1e6 (arithmetic: G divides by 1e6 - b); mode 0 with coverSrc != 0 or with
    ///         no price at all; mode 1 with psUsd == 0.
    function decode(bytes calldata m) internal pure returns (Header memory h, uint8 status) {
        if (m.length < OFF_VER) revert GapMsgTooShort(m.length);
        h.sendTo = bytes32(m[OFF_SEND_TO:OFF_AMOUNT_SD]);
        h.amountSD = uint64(bytes8(m[OFF_AMOUNT_SD:OFF_VER]));
        if (m.length < HEADER_LEN || uint8(m[OFF_VER]) != VER) return (h, DEC_BAD);
        h.mode = uint8(m[OFF_MODE]);
        h.priceClass = uint8(m[OFF_CLASS]);
        h.psClassE18 = uint128(bytes16(m[OFF_PS_CLASS:OFF_PS_USD]));
        h.psUsdE18 = uint128(bytes16(m[OFF_PS_USD:OFF_BRIDGE_FEE]));
        h.bridgeFeePpm = uint32(bytes4(m[OFF_BRIDGE_FEE:OFF_COVER_SRC]));
        h.coverSrcMicroUsd = uint32(bytes4(m[OFF_COVER_SRC:OFF_MIN_CREDITED]));
        h.minCreditedSD = uint64(bytes8(m[OFF_MIN_CREDITED:OFF_RESERVED]));
        h.composed = m.length > HEADER_LEN;
        status = validate(h, bytes5(m[OFF_RESERVED:HEADER_LEN]));
    }

    /// @notice The rules of `decode` on decoded fields (shared with the vectors' memory decode).
    function validate(Header memory h, bytes5 reserved) internal pure returns (uint8) {
        if (reserved != bytes5(0)) return DEC_BAD;
        if (h.mode == MODE_REFUND || h.priceClass == REFUND_CLASS) {
            bool exact = h.mode == MODE_REFUND && h.priceClass == REFUND_CLASS && h.psClassE18 == 0 && h.psUsdE18 == 0
                && !h.composed;
            return exact ? DEC_REFUND : DEC_BAD;
        }
        if (h.mode != MODE_PLAIN && h.mode != MODE_BUY) return DEC_BAD;
        if ((h.priceClass == 0) != (h.psClassE18 == 0)) return DEC_BAD;
        if (h.bridgeFeePpm >= PPM) return DEC_BAD;
        if (h.mode == MODE_PLAIN) {
            if (h.coverSrcMicroUsd != 0) return DEC_BAD;
            if (h.psClassE18 == 0 && h.psUsdE18 == 0) return DEC_BAD;
        } else if (h.psUsdE18 == 0) {
            return DEC_BAD;
        }
        return DEC_OK;
    }

    /// @notice `composeFrom | composeMsg` of a composed message (LayerZero OFTComposeMsgCodec's last argument).
    function composeTail(bytes calldata m) internal pure returns (bytes calldata) {
        return m[HEADER_LEN:];
    }

    // ================================================================ defaults (LEAD UPDATE 2: NO compiled bounds)
    //
    // Every v4 parameter is an admin setting (per chain + per-coin override, GapRegistryV4.paramsOf). These are
    // the documented defaults only; the code keeps arithmetic safety (no overflow, no division by zero) and
    // resolves a nonsensical pair deterministically: min > max -> max wins.

    uint64 internal constant MARGIN_K_DEFAULT = 1_000_000; // K = 1, x 1e6
    uint32 internal constant MARGIN_MIN_DEFAULT_PPM = 1_000;
    uint32 internal constant MARGIN_MAX_DEFAULT_PPM = 100_000;
    uint64 internal constant EXEC_CAP_K_DEFAULT = 2_000_000; // Kk = 2, x 1e6
    uint32 internal constant EXEC_CAP_MIN_DEFAULT_PPM = 15_000;
    uint32 internal constant EXEC_CAP_MAX_DEFAULT_PPM = 200_000;
    uint32 internal constant LOOKBACK_DEFAULT_SEC = 30;
    uint32 internal constant FEE_CAP_DEFAULT_PPM = 10_000;
    uint16 internal constant BRIDGE_FEE_DEFAULT_BPS = 20;
    /// @dev The largest bridge fee a token charges: 9,999 bps (999,900 ppm < 1e6, which the codec accepts on EVM
    ///      and Solana). >= 10,000 bps would carry b >= 1e6, a message no destination can decode (invariant iii).
    uint16 internal constant BRIDGE_FEE_MAX_BPS = 9_999;

    // ================================================================ receive outcomes (events, previews)

    uint8 internal constant R_CREDITED = 0; // the formula ran (withheld may be 0)
    uint8 internal constant R_BAD_VERSION = 1; // DEC_BAD: refused
    uint8 internal constant R_REFUND = 2; // the refund marker: full
    uint8 internal constant R_ESCAPED = 3; // the per-coin escape: full
    uint8 internal constant R_SEED_NO_POOL = 4; // no pool here, a listed seeder: full
    uint8 internal constant R_NO_POOL = 5; // no pool here: hold
    uint8 internal constant R_UNREADABLE = 6; // Pd, fD, m (depth) or the cover unreadable: hold
    uint8 internal constant R_BELOW_MIN = 7; // credited < minCredited: hold (acceptBelowMin lands it)
    uint8 internal constant R_UNTRUSTED = 8; // not a trusted executor: refused
    uint8 internal constant R_BURN_OFF = 9; // burn off (LEAD UPDATE 3 §9.1): credited in full

    // ================================================================ settings

    /// @notice The bridge fee a token charges (LEAD UPDATE 3 §9.4): the resolved registry bps when readable and at
    ///         most 9,999; unreadable or >= 10,000 (which the registry refuses, and whose b >= 1e6 the codec refuses)
    ///         counts as unreadable: the default 20. Every send therefore carries b < 1e6.
    function bridgeFeeBpsOrDefault(bool ok, uint256 bps) internal pure returns (uint16) {
        if (!ok || bps > BRIDGE_FEE_MAX_BPS) return BRIDGE_FEE_DEFAULT_BPS;
        return uint16(bps);
    }

    /// @notice A curve clamp(lo, hi, floor(K x 1e9 / sqrtUp(depthUsdE18))) (LEAD UPDATE 2: K stored x 1e6, so
    ///         the result is ppm): lo > hi -> hi wins (lo := hi); K 0 -> lo; depth 0 -> hi (an UNREADABLE depth is
    ///         the caller's hold, never this).
    function curve(uint64 k, uint32 lo, uint32 hi, uint256 depthUsd) internal pure returns (uint32) {
        if (lo > hi) lo = hi;
        if (k == 0) return lo;
        if (depthUsd == 0) return hi;
        uint256 d = uint256(k) * 1e9 / sqrtUp(depthUsd);
        if (d < lo) return lo;
        if (d > hi) return hi;
        return uint32(d);
    }

    // ================================================================ prices (spec §3, §5)

    /// @notice ceil(a * b / 1e18); 0 if either factor is 0 or above PRICE_MAX, or the product above PRICE_MAX.
    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 if either factor is 0 or above PRICE_MAX, the product 0 or above PRICE_MAX.
    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) return 0;
    }

    /// @notice The part of the official pool's HOOK fee above feeCapPpm is removed from what the buyer paid
    ///         (spec §5): quotePaid - ceil(quotePaid * (hookFeePpm - feeCapPpm) / 1e6) when the hook fee is above
    ///         the cap, else quotePaid. (A fee taken in tokens is capped the same way: the removal is in value.)
    function capQuotePaid(uint256 quotePaid, uint256 hookFeePpm, uint256 feeCapPpm) internal pure returns (uint256) {
        if (hookFeePpm <= feeCapPpm) return quotePaid;
        uint256 ex = hookFeePpm - feeCapPpm;
        if (ex >= PPM) return 0;
        return quotePaid - Math.mulDiv(quotePaid, ex, PPM, Math.Rounding.Ceil);
    }

    /// @notice Pexec = floor(quotePaid * 10^decTok * 1e18 / (tokensOut * 10^decQuote)): quote units x 1e18 per
    ///         whole token. 0 (unpriced: the buy reverts) when tokensOut is 0, the decimals are out of range
    ///         (|18 + decTok - decQuote| > 36) or the result is 0 or above PRICE_MAX.
    function pexec(uint256 quotePaid, uint256 tokensOut, uint8 decTok, uint8 decQuote) internal pure returns (uint256 p) {
        if (tokensOut == 0) return 0;
        int256 e = 18 + int256(uint256(decTok)) - int256(uint256(decQuote));
        if (e > 36 || e < -36) return 0;
        if (e >= 0) {
            // quotePaid / tokensOut above PRICE_MAX stays above it scaled up; below it the product fits.
            if (quotePaid / tokensOut > PRICE_MAX) return 0;
            p = Math.mulDiv(quotePaid, 10 ** uint256(e), tokensOut);
        } else {
            p = quotePaid / tokensOut / 10 ** uint256(-e);
        }
        if (p > PRICE_MAX) return 0;
    }

    /// @notice floor(Plast * (1e6 + k) / 1e6), at most PRICE_MAX.
    function execCap(uint256 plastE18, uint256 k) internal pure returns (uint256 c) {
        c = Math.mulDiv(plastE18, PPM + k, PPM);
        if (c > PRICE_MAX) c = PRICE_MAX;
    }

    /// @notice The backstop k (LEAD UPDATE 2): max(mSrc, curve(Kk, kMin, kMax, srcDepthUsd)), mSrc the margin curve
    ///         at the same source depth (so k >= m always).
    function kPpm(uint64 kk, uint32 kMin, uint32 kMax, uint256 srcDepthUsd, uint32 mSrcPpm) internal pure returns (uint32) {
        uint32 k = curve(kk, kMin, kMax, srcDepthUsd);
        return k > mSrcPpm ? k : mSrcPpm;
    }

    /// @notice The buy path's credit price (D2): Ps = min(Pexec, floor(Plast * (1 + k))) when the backstop is on,
    ///         Pexec when it is off. 0 when Pexec is 0, or (on) Plast is 0 (no record from an earlier block: the buy
    ///         reverts GapNeedRecord).
    function psBuy(uint256 pexecE18, uint256 plastE18, bool on, uint256 k) internal pure returns (uint256) {
        if (pexecE18 == 0) return 0;
        if (!on) return pexecE18;
        if (plastE18 == 0) return 0;
        uint256 c = execCap(plastE18, k);
        return pexecE18 < c ? pexecE18 : c;
    }

    /// @notice The destination's class pair or USD pair (v3 pickPair, unchanged): the class pair when the
    ///         message's class is non-zero, equal to the destination quote's class and both class prices are
    ///         known; else the USD pair when both are known; else nothing (hold).
    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 recorder (spec §4a, §4d, §4e)
    //
    // Three buckets in a ring, each `width` seconds wide (width = L/2, the token's cached look-back; an L change
    // reaches the buckets at the next send or receive and takes full effect within one L). A bucket keeps
    // {start, lastTs, lastBlock, min, max, lastPrice}; a NEW bucket's min and max start at the price in force when
    // it opens (the previous record's lastPrice: the "open price"), so the oldest bucket still in the ring always
    // carries the price in force before its first record. The ring also keeps the last price of the newest block
    // before the head bucket's lastBlock (prevBlock, prevPrice), so "the newest record from an earlier block" is
    // known even after records of the current block.

    struct Slot {
        uint40 start; // bucket start, unix seconds (a multiple of the width at write time)
        uint40 lastTs; // timestamp of its latest record
        uint48 lastBlock; // block of its latest record; 0 = empty slot
        uint128 min; // min of its records and its open price
        uint128 max; // max of its records and its open price
        uint128 lastPrice; // its latest record
    }

    struct Ring {
        Slot[3] s;
        uint8 head; // the newest slot
        uint48 prevBlock; // the block before head.lastBlock that has a record (0 = none)
        uint128 prevPrice; // its last record
        uint40 prevTs; // its timestamp (audit r2: the destination's age bound)
    }

    /// @notice One record (the official pool's price `p`, quote x 1e18 per whole token, rounded DOWN) at
    ///         (`ts`, `blk`), into buckets of `width` seconds. A zero price or width writes nothing.
    function ringWrite(Ring memory r, uint256 p, uint256 ts, uint256 blk, uint256 width) internal pure returns (Ring memory) {
        if (p == 0 || width == 0) return r;
        if (p > PRICE_MAX) p = PRICE_MAX;
        uint128 price = uint128(p);
        Slot memory h = r.s[r.head];
        uint40 start = uint40(ts - ts % width);
        if (h.lastBlock == 0) {
            // the first record ever: its own open price
            r.s[r.head] = Slot(start, uint40(ts), uint48(blk), price, price, price);
            return r;
        }
        if (blk != h.lastBlock) (r.prevBlock, r.prevPrice, r.prevTs) = (h.lastBlock, h.lastPrice, h.lastTs);
        if (start <= h.start) {
            // the same bucket (or an older start after a width change: the head keeps it)
            if (price < h.min) h.min = price;
            if (price > h.max) h.max = price;
            (h.lastTs, h.lastBlock, h.lastPrice) = (uint40(ts), uint48(blk), price);
            r.s[r.head] = h;
            return r;
        }
        uint128 open = h.lastPrice;
        uint8 n = uint8((uint256(r.head) + 1) % 3);
        r.s[n] = Slot(start, uint40(ts), uint48(blk), open < price ? open : price, open > price ? open : price, price);
        r.head = n;
        return r;
    }

    /// @notice Plast: the lastPrice of the newest record from a block BEFORE `blk` (0 = none).
    function plast(Ring memory r, uint256 blk) internal pure returns (uint256 p) {
        (p,) = plastRec(r, blk);
    }

    /// @notice The newest record from a block BEFORE `blk`: its price and timestamp ((0, 0) = none).
    function plastRec(Ring memory r, uint256 blk) internal pure returns (uint256 p, uint256 t) {
        Slot memory h = r.s[r.head];
        if (h.lastBlock == 0) return (0, 0);
        if (h.lastBlock < blk) return (h.lastPrice, h.lastTs);
        if (r.prevBlock != 0 && r.prevBlock < blk) return (r.prevPrice, r.prevTs);
        return (0, 0);
    }

    /// @notice Pref_src (spec §4e) = min(live, every bucket with a record at or after now - L (its min, which
    ///         includes its open price), the lastPrice of the newest bucket whose last record is before now - L
    ///         (the price in force at the window start)). Records of the current block can only LOWER it (a
    ///         minimum), never raise it. 0 (the send reverts GapNeedRecord) when there is no record from an
    ///         earlier block or `live` is 0.
    function pref(Ring memory r, uint256 live, uint256 ts, uint256 blk, uint256 lookback) internal pure returns (uint256 v) {
        if (live == 0 || plast(r, blk) == 0) return 0;
        v = live;
        uint256 from = ts > lookback ? ts - lookback : 0;
        uint256 preTs;
        uint256 prePrice;
        for (uint256 i; i < 3; i++) {
            Slot memory s = r.s[i];
            if (s.lastBlock == 0) continue;
            if (s.lastTs >= from) {
                if (s.min < v) v = s.min;
            } else if (s.lastTs >= preTs) {
                (preTs, prePrice) = (s.lastTs, s.lastPrice);
            }
        }
        if (prePrice != 0 && prePrice < v) v = prePrice;
    }

    /// @notice Pd for a TRUSTED delivery (audit r3 F1 / F2 rulings, r4 R4-1 + lead ruling R4-1-2; r2 G2-02). With
    ///         R = the newest earlier-block record and B = the max of EVERY ring bucket whose last record is at or after
    ///         R (R's own bucket carries the price in force when it opened, so a netted fake LOW close cannot hide the
    ///         honest price before it; later buckets hold only current-block records, which can only raise Pd), and
    ///         H = horizonMax (every bucket max within L + 3 widths and the previous block's close, as pdSelf):
    ///           - R within the look-back (ts >= now - L): Pd = max(live, R + 1, B + 1, H);
    ///           - R stale but the pool already has a record from the CURRENT block (it was traded before the delivery
    ///             in this block, e.g. a same-block dump): the same -- the price in force at the start of the block,
    ///             so a same-block dump never lowers it;
    ///           - otherwise (a quiet pool, no current-block trade): Pd = live (a stale planted close cannot pin Pd).
    ///         H (lead ruling after r4, r5 G5-M1): the honest price stays counted until its bucket ages out of H or
    ///         leaves the ring. NOT a closure of the netted-fake attack: A-SETTERS.md "Pd" has the measured residual
    ///         (a trusted delivery has no L gate, so two fakes still work once a same-block dump waits out L + 3w).
    ///         Accepted cost: honest trusted arrivals within L + 3w of a real spike, or on the first record after a
    ///         quiet stretch that ended one, are priced at it (a lower credit, a larger burn).
    ///         R4-1: when R counts but its bucket is no longer in the ring (three newer buckets opened in the current
    ///         block), 0: the caller HOLDS (retriable next block), never the bare R.
    ///         Accepted residual (grief only): a stale HIGH (planted, or an honest old spike in R's bucket: R4-4) plus
    ///         any trade in the delivery's block before it counts again (a lower credit). 0 when live is 0.
    function pdTrusted(Ring memory r, uint256 liveUp, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
        internal
        pure
        returns (uint256)
    {
        if (liveUp == 0) return 0;
        (uint256 p, uint256 t, uint256 bmax, bool inRing) = plastRecBucket(r, blk);
        if (p == 0) return liveUp;
        bool within = t + lookback >= ts;
        bool currentBlockTraded = r.s[r.head].lastBlock == blk;
        if (!within && !currentBlockTraded) return liveUp;
        if (!inRing) return 0;
        uint256 rec = (bmax > p ? bmax : p) + 1;
        (uint256 hz,) = horizonMax(r, ts, blk, lookback, width);
        if (hz > rec) rec = hz;
        return liveUp > rec ? liveUp : rec;
    }

    /// @notice The max + 1 of every non-empty bucket still in force within L + 3 bucket widths (r4 R4-2: 2.5 L at width
    ///         L/2) and of the previous block's close when as recent (0 = none). A bucket's close stays in force until
    ///         the next newer bucket opens, however late, so a bucket counts while its last record OR the next newer
    ///         bucket's start is within that horizon (r5 G5-M1, option 1). `ok`: a record from an earlier block
    ///         within L exists (a bucket counts only when its last record is from an earlier block, F6).
    function horizonMax(Ring memory r, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
        internal
        pure
        returns (uint256 m, bool ok)
    {
        uint256 from = ts > lookback ? ts - lookback : 0;
        uint256 horizon = lookback + 3 * width;
        uint256 fromMax = ts > horizon ? ts - horizon : 0;
        for (uint256 i; i < 3; i++) {
            Slot memory s = r.s[i];
            if (s.lastBlock == 0) continue;
            // the slot after a non-head slot is the next newer bucket (ringWrite's order)
            if (s.lastTs < fromMax && (i == r.head || r.s[(i + 1) % 3].start < fromMax)) continue;
            if (uint256(s.max) + 1 > m) m = uint256(s.max) + 1;
            if (s.lastTs >= from && s.lastBlock < blk) ok = true;
        }
        if (r.prevBlock != 0 && r.prevBlock < blk && r.prevTs >= fromMax) {
            if (uint256(r.prevPrice) + 1 > m) m = uint256(r.prevPrice) + 1;
            if (r.prevTs >= from) ok = true;
        }
    }

    /// @notice The newest earlier-block record R (price, ts), the max over R and every non-empty bucket whose last
    ///         record is at or after R's ts, and whether R's own bucket (a bucket with start <= R.ts <= lastTs) is
    ///         still in the ring. (0, 0, 0, false) = no earlier-block record.
    function plastRecBucket(Ring memory r, uint256 blk)
        internal
        pure
        returns (uint256 p, uint256 t, uint256 bmax, bool inRing)
    {
        (p, t) = plastRec(r, blk);
        if (p == 0) return (0, 0, 0, false);
        bmax = p;
        for (uint256 i; i < 3; i++) {
            Slot memory s = r.s[i];
            if (s.lastBlock == 0 || s.lastTs < t) continue;
            if (s.max > bmax) bmax = s.max;
            if (s.start <= t) inRing = true;
        }
    }

    /// @notice Pd for a SELF-delivered arrival (the executor is the recipient, not a trusted executor or a delivery
    ///         key; audit r2 G2-01, r3 F4 / F6, r4 R4-2, r5 G5-M1): max(live, horizonMax), so two netted fake low closes
    ///         at any spacing do not hide the honest open price from the recipient's own delivery (the L gate below
    ///         keeps the second bucket's start inside the horizon). Three fakes still do: A-SETTERS.md "Pd" has the
    ///         measured residual. An old spike burns only the first record after a quiet stretch, for L + 3w (F4,
    ///         narrowed by G5-M1). Needs at least one record from an earlier block within L (ts >= now - L; a
    ///         non-head bucket only when its last record is from an earlier block, F6): otherwise ok = false (the
    ///         arrival holds, retriable). Never below pdTrusted at the same moment.
    function pdSelf(Ring memory r, uint256 liveUp, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
        internal
        pure
        returns (bool ok, uint256 pd)
    {
        if (liveUp == 0) return (false, 0);
        uint256 m;
        (m, ok) = horizonMax(r, ts, blk, lookback, width);
        if (!ok) return (false, 0);
        pd = liveUp > m ? liveUp : m;
    }

    // ================================================================ the dynamic margin (LEAD, V4-INTERFACES §3)

    /// @notice ceil(sqrt(x)).
    function sqrtUp(uint256 x) internal pure returns (uint256 s) {
        s = Math.sqrt(x);
        if (s * s != x) s += 1;
    }

    /// @notice The destination pool's QUOTE-side virtual reserve, raw quote units, rounded UP, at the pool price
    ///         `priceE18` (quote x 1e18 per whole token): liquidity x sqrt(raw price), the same on both currency
    ///         orders (token currency0: L x sqrtP of currency1; token currency1: L / sqrtP' of currency0, sqrtP' =
    ///         sqrt(1 / raw price)). 0 (unreadable) when 18 + decQuote - decTok < 0 or decQuote > 36.
    ///         G-EVMB-2 L-1: e = 18 + decQuote - decTok above 38 (quotes of 30..36 decimals at the coin's 9) is split:
    ///         j = ceil((e - 38) / 2), sqrt(priceE18 x 10^e) is taken as sqrtUp(priceE18 x 10^(e - 2j)) x 10^j (still
    ///         rounded up; e <= 54, so j <= 8 and every product stays far below 2^256).
    function depthQuoteRaw(uint256 liquidity, uint256 priceE18, uint8 decTok, uint8 decQuote) internal pure returns (uint256) {
        if (liquidity == 0 || priceE18 == 0 || priceE18 > PRICE_MAX || decQuote > 36) return 0;
        int256 e = 18 + int256(uint256(decQuote)) - int256(uint256(decTok));
        if (e < 0) return 0;
        uint256 j = e > 38 ? (uint256(e) - 37) / 2 : 0;
        // x = raw price x 1e36 / 10^(2j) = priceE18 x 10^(e - 2j), e - 2j <= 38; x < 2^128 x 10^38 < 2^255
        uint256 x = priceE18 * 10 ** (uint256(e) - 2 * j);
        return Math.mulDiv(liquidity, sqrtUp(x) * 10 ** j, E18, Math.Rounding.Ceil);
    }

    /// @notice USD x 1e18 of `rawQuote` quote units at `usdPerQuoteUpE18` (rounded up): ceil(raw x usd / 10^dec).
    function depthUsdE18(uint256 rawQuote, uint256 usdPerQuoteUpE18, uint8 decQuote) internal pure returns (uint256) {
        if (rawQuote == 0 || usdPerQuoteUpE18 == 0 || decQuote > 36) return 0;
        return Math.mulDiv(rawQuote, usdPerQuoteUpE18, 10 ** uint256(decQuote), Math.Rounding.Ceil);
    }

    /// @notice m (ppm) at a locked-LP quote depth (LEAD UPDATE 2): curve(marginK, marginMinPpm, marginMaxPpm, depth).
    ///         A fixed per-coin m is marginK 0 with min = max = m.
    function margin(uint64 marginK, uint32 mMin, uint32 mMax, uint256 depthUsd) internal pure returns (uint32) {
        return curve(marginK, mMin, mMax, depthUsd);
    }

    // ================================================================ the cost cover (spec §9)

    /// @notice The counted basefee: clamp(basefee, floor, cap); cap 0 -> 0 (no gas cover); floor > cap -> the cap.
    function effBaseFee(uint256 basefee, IGapRegistryV4.CoverV4 memory c) internal pure returns (uint256) {
        uint256 cap = c.baseFeeCapWei;
        if (cap == 0) return 0;
        uint256 fl = c.baseFeeFloorWei > cap ? cap : c.baseFeeFloorWei;
        if (basefee < fl) return fl;
        return basefee > cap ? cap : basefee;
    }

    /// @notice The native price the cover counts: the read clamped to the band [min, max]; 0 (no cover) when the
    ///         read is 0 or max is 0; min > max -> max.
    function nativeUsd(uint256 read, IGapRegistryV4.CoverV4 memory c) internal pure returns (uint256) {
        uint256 hi = c.nativeUsdMaxE18;
        if (read == 0 || hi == 0) return 0;
        uint256 lo = c.nativeUsdMinE18 > hi ? hi : c.nativeUsdMinE18;
        if (read < lo) return lo;
        return read > hi ? hi : read;
    }

    /// @notice The source cover carried in the message, micro-USD, rounded down (spec §9 SOURCE):
    ///         min(cap, floor((lzFeeWei + buyAndSendUnits x (effBaseFee + tip)) x nativeUsd / 1e18)) / 1e12, with
    ///         the gas term 0 when the basefee cap is 0; at most type(uint32).max micro-USD (the codec field).
    ///         0 when the native price is unreadable or the band max is 0.
    function coverSrcMicroUsd(uint256 lzFeeWei, IGapRegistryV4.CoverV4 memory c, uint256 basefee, uint256 nativeRead)
        internal
        pure
        returns (uint32)
    {
        uint256 n = nativeUsd(nativeRead, c);
        if (n == 0 || c.coverCapUsdE18 == 0) return 0;
        uint256 b = effBaseFee(basefee, c);
        uint256 gasWei = b == 0 ? 0 : uint256(c.buyAndSendUnits) * (b + c.tipAllowanceWei);
        uint256 cap = c.coverCapUsdE18;
        if (lzFeeWei > PRICE_MAX) lzFeeWei = PRICE_MAX; // gasWei < 2^97: the sum fits
        uint256 usd = Math.mulDiv(lzFeeWei + gasWei, n, E18);
        if (usd > cap) usd = cap;
        uint256 micro = usd / MICRO_USD_E18;
        return micro > type(uint32).max ? type(uint32).max : uint32(micro);
    }

    /// @notice The destination cover, USD x 1e18, rounded down (spec §9 DESTINATION):
    ///         min(cap, floor(swapUnits x (effBaseFee + tip) x nativeUsd / 1e18)); 0 when unreadable.
    function coverDstUsdE18(IGapRegistryV4.CoverV4 memory c, uint256 basefee, uint256 nativeRead) internal pure returns (uint256) {
        uint256 n = nativeUsd(nativeRead, c);
        uint256 b = effBaseFee(basefee, c);
        if (n == 0 || b == 0 || c.coverCapUsdE18 == 0) return 0;
        uint256 usd = Math.mulDiv(uint256(c.swapUnits) * (b + c.tipAllowanceWei), n, E18);
        return usd > c.coverCapUsdE18 ? c.coverCapUsdE18 : usd;
    }

    /// @notice Audit r4 R4-3: the destination sale allowance bounded by the arrival's value: min(coverDst,
    ///         floor(A x psUsd / 10^dec x maxPpm / 1e6)), USD x 1e18, with A the amount (local decimals `dec`) and
    ///         psUsd the source USD price the message carries (what was paid; not manipulable here). Splitting one
    ///         round into N arrivals then gains at most maxPpm of its value in destination cover. maxPpm 0 = no
    ///         destination cover.
    function coverDstBounded(uint256 coverDstUsd, uint256 amountLD, uint256 psUsdE18, uint256 maxPpm, uint8 dec)
        internal
        pure
        returns (uint256)
    {
        if (coverDstUsd == 0 || maxPpm == 0 || dec > 36) return 0;
        uint256 bound = Math.mulDiv(Math.mulDiv(amountLD, psUsdE18, 10 ** uint256(dec)), maxPpm, PPM);
        return coverDstUsd < bound ? coverDstUsd : bound;
    }

    /// @notice C_usd = min(destination cap, coverSrc + coverDst), USD x 1e18. (The source already capped its part
    ///         at its own cap, so the sum is at most min(both caps) + the destination's part, then capped again.)
    function coverUsdE18(uint32 coverSrcMicro, uint256 coverDstUsd, uint256 capDstUsd) internal pure returns (uint256 c) {
        c = uint256(coverSrcMicro) * MICRO_USD_E18 + coverDstUsd;
        if (c > capDstUsd) c = capDstUsd;
    }

    /// @notice C in the pricing unit: the USD amount itself for the USD pair; for a class pair
    ///         floor(C_usd x 1e18 / classUsdE18), 0 when the class's USD price is unreadable.
    function coverInUnit(uint256 coverUsd, bool isClass, uint256 classUsdE18) internal pure returns (uint256) {
        if (!isClass) return coverUsd;
        if (classUsdE18 == 0 || classUsdE18 > PRICE_MAX) return 0;
        return Math.mulDiv(coverUsd, E18, classUsdE18);
    }

    // ================================================================ the credit (spec §6, §9)

    /// @notice G = floor(A x 1e6 / (1e6 - b)), b < 1e6 (the codec refuses more).
    function gross(uint256 amountLD, uint256 bPpm) internal pure returns (uint256) {
        return Math.mulDiv(amountLD, PPM, PPM - bPpm);
    }

    /// @notice Plain (spec §6): credited = min(A, floor(A x Ps / Pd)). Pd 0 is the caller's hold (returns 0).
    function creditPlain(uint256 amountLD, uint256 ps, uint256 pd) internal pure returns (uint256) {
        if (pd == 0) return 0;
        if (ps >= pd) return amountLD;
        return Math.mulDiv(amountLD, ps, pd); // < A
    }

    /// @notice Buy-and-bridge (spec §9): with G = gross(A, b),
    ///             V = floor(G x Ps x (1e6 + m) / (1e6 x 10^decDst))       value of G in [unit x 1e18]
    ///             credited = min(A, floor((V + C) x 10^decDst x 1e6 / (Pd x (1e6 - fD))))
    ///         G is counted in the destination's raw units (it is derived from the shared-decimal amount, so it is
    ///         the same token amount as the source's G; the spec's /10^decSrc x 10^decDst is that conversion).
    ///         Pd 0 or fD >= 1e6 is the caller's hold (returns 0). Never overflows (the A check comes first).
    function creditBuy(
        uint256 amountLD,
        uint256 bPpm,
        uint256 ps,
        uint256 mPpm,
        uint256 coverUnitE18,
        uint256 pd,
        uint256 fDPpm,
        uint8 decDst
    ) internal pure returns (uint256) {
        if (pd == 0 || pd > PRICE_MAX || fDPpm >= PPM || decDst > 36) return 0;
        uint256 g = gross(amountLD, bPpm);
        uint256 scale = 10 ** uint256(decDst);
        uint256 v = Math.mulDiv(g, ps * (PPM + mPpm), PPM * scale) + coverUnitE18;
        uint256 den = pd * (PPM - fDPpm); // < 2^148
        uint256 num = scale * PPM; // <= 1e42 < 2^140
        // credited >= A  <=>  v x num >= A x den  <=>  v >= ceil(A x den / num)
        if (v >= Math.mulDiv(amountLD, den, num, Math.Rounding.Ceil)) return amountLD;
        return Math.mulDiv(v, num, den); // < A
    }

    function _min32(uint32 a, uint32 b) private pure returns (uint32) {
        return a < b ? a : b;
    }
}

src/v4/gap/GapRecorderV4.sol

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

import {GapMathV4} from "./GapMathV4.sol";
import {GapPriceLib} from "../../v3/gap/GapPriceLib.sol";
import {IGapRegistryV4} from "./IGapRegistryV4.sol";
import {PangeaOFTV4Storage as S} from "./PangeaOFTV4Storage.sol";

/// @title GapRecorderV4 -- the token's own price recorder (spec §4a, owner D1: no new hook)
/// @notice Shared by PangeaOFTV4 (its `_update` writes a record whenever a non-zero amount of the token moves to
///         or from the PoolManager, and every send / receive writes one) and PangeaOFTV4GapModule (reads Plast,
///         Pref, Pd_ref). The ring's arithmetic is GapMathV4.ringWrite / plast / pref; this library packs it into
///         the token's storage and writes only the words a record changes (one bucket and the meta word).
///         `record` here and GapMathV4.ringWrite are the same function (fuzzed against each other).
///
///         v4 settle ordering: a v4 swap moves the price in `swap`, BEFORE the ERC-20 moves in settle / take, so a
///         record always holds the price AFTER the swap that caused it, and a record of the current block can
///         already be pumped. GapMathV4.plast / pref therefore never let a current-block record raise anything.
/// @dev The official pool's state is read from the PoolManager by extsload (StateLibrary's layout): pools slot 6,
///      slot0 at the pool's base slot, liquidity at + 3.
library GapRecorderV4 {
    uint256 internal constant POOLS_SLOT = 6;
    uint256 internal constant LIQUIDITY_OFFSET = 3;
    uint256 internal constant POSITIONS_OFFSET = 6;
    bytes4 internal constant EXTSLOAD = 0x1e2eaeaf;
    /// @dev The bucket width before any send or receive has set it: L's default / 2.
    uint256 internal constant WIDTH_DEFAULT = GapMathV4.LOOKBACK_DEFAULT_SEC / 2;
    /// @dev Gas caps of the one-time pool read (registry) and of the quote's decimals().
    uint256 internal constant LEARN_GAS = 60_000;
    uint256 internal constant DECIMALS_GAS = 30_000;
    uint8 internal constant TOKEN_DECIMALS = 9;
    /// @dev v4's dynamic-fee flag (LPFeeLibrary.DYNAMIC_FEE_FLAG).
    uint24 internal constant DYNAMIC_FEE_FLAG = 0x800000;

    uint256 private constant M32 = (1 << 32) - 1;
    uint256 private constant M40 = (1 << 40) - 1;
    uint256 private constant M48 = (1 << 48) - 1;
    uint256 private constant M128 = (1 << 128) - 1;

    // ------------------------------------------------------------------ the official pool

    /// @notice Caches the official pool from the registry once (never again: set-once in the registry, no
    ///         re-point in v4). Refuses (returns false, caches nothing) a pool whose key does not hash to its
    ///         id, a dynamic or out-of-range LP fee, a currency order that cannot be, or an unreadable quote
    ///         decimals. Gas-capped (LEARN_GAS), any failure is "not known".
    ///         G-EVMB-2 L-3 (negative cache): a pool that is SET but can never be used is marked `unusable` and never
    ///         looked up again (no repeated registry read + decimals() on every swap). Only a definite answer is
    ///         cached: a failed or malformed registry read, an unset pool, or a decimals() call that did not get its
    ///         full DECIMALS_GAS (the caller's gas, 63/64 rule) caches nothing.
    function learn(S.Layout storage l, address reg) internal returns (bool) {
        if (l.known) return true;
        if (l.unusable) return false;
        (bool ok, bytes memory ret) = reg.staticcall{gas: LEARN_GAS}(abi.encodeCall(IGapRegistryV4.officialPool, (address(this))));
        if (!ok || ret.length != 256) return false;
        (bool set, IGapRegistryV4.OfficialPool memory o) = abi.decode(ret, (bool, IGapRegistryV4.OfficialPool));
        if (!set) return false;
        if (o.poolId == bytes32(0) || o.poolId != poolIdOf(o) || o.lpFee >= DYNAMIC_FEE_FLAG || o.lpFee > GapMathV4.PPM) {
            l.unusable = true;
            return false;
        }
        bool fullGas = gasleft() > DECIMALS_GAS + DECIMALS_GAS / 63 + 1_000;
        (bool okDec, uint8 dec) = quoteDecimalsOf(o.quote);
        if (!okDec) {
            if (fullGas) l.unusable = true;
            return false;
        }
        (l.known, l.tokenIs0, l.quoteDecimals, l.lpFee, l.tickSpacing) = (true, o.tokenIsCurrency0, dec, o.lpFee, o.tickSpacing);
        (l.poolQuote, l.poolHook, l.poolId, l.lockedPositionKey) = (o.quote, o.hook, o.poolId, o.lockedPositionKey);
        return true;
    }

    /// @notice keccak256(abi.encode(PoolKey)) of the key the pool names (this token and `quote` in currency
    ///         order, fee lpFee, its tick spacing and hook); 0 when the order is impossible.
    function poolIdOf(IGapRegistryV4.OfficialPool memory o) internal view returns (bytes32) {
        address t = address(this);
        if (o.tokenIsCurrency0 ? !(t < o.quote) : !(o.quote < t)) return bytes32(0);
        (address c0, address c1) = o.tokenIsCurrency0 ? (t, o.quote) : (o.quote, t);
        return keccak256(abi.encode(c0, c1, uint24(o.lpFee), int24(o.tickSpacing), o.hook));
    }

    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 > 36) return (false, 0);
        return (true, uint8(w));
    }

    // ------------------------------------------------------------------ PoolManager reads

    function _extsload(address pm, bytes32 slot) private view returns (bool ok, uint256 w) {
        bytes4 sel = EXTSLOAD;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), slot)
            ok := staticcall(gas(), pm, m, 36, 0, 32)
            ok := and(ok, eq(returndatasize(), 32))
            if ok { w := mload(0) }
        }
    }

    /// @notice slot0's sqrtPriceX96 of pool `id` (0 on failure).
    function liveSqrt(address pm, bytes32 id) internal view returns (uint160) {
        (, uint256 w) = _extsload(pm, keccak256(abi.encodePacked(id, POOLS_SLOT)));
        return uint160(w);
    }

    /// @notice The pool's in-range liquidity (0 on failure).
    function liquidity(address pm, bytes32 id) internal view returns (uint128) {
        (, uint256 w) = _extsload(pm, bytes32(uint256(keccak256(abi.encodePacked(id, POOLS_SLOT))) + LIQUIDITY_OFFSET));
        return uint128(w);
    }

    /// @notice The liquidity of position `key` in pool `id` (StateLibrary.getPositionLiquidity; 0 on failure).
    function positionLiquidity(address pm, bytes32 id, bytes32 key) internal view returns (uint128) {
        if (key == bytes32(0)) return 0;
        bytes32 base = bytes32(uint256(keccak256(abi.encodePacked(id, POOLS_SLOT))) + POSITIONS_OFFSET);
        (, uint256 w) = _extsload(pm, keccak256(abi.encodePacked(key, base)));
        return uint128(w);
    }

    /// @notice The official pool's live price, quote x 1e18 per whole token, rounded `up` or down; 0 unknown.
    function livePrice(S.Layout storage l, address pm, bool up) internal view returns (uint256) {
        if (!l.known) return 0;
        return GapPriceLib.fromSqrtX96(liveSqrt(pm, l.poolId), l.tokenIs0, TOKEN_DECIMALS, l.quoteDecimals, up);
    }

    // ------------------------------------------------------------------ the ring

    /// @notice A record of the official pool's live price (rounded down), now. Nothing when the pool is not
    ///         known (and cannot be learned) or the price is unknown.
    ///         `blk` is the block in the rules' numbering (GapBlockV4: the L2 block on Arbitrum-stack chains).
    function recordLive(S.Layout storage l, address pm, address reg, uint256 blk) internal {
        if (!l.known && !learn(l, reg)) return;
        uint256 p = livePrice(l, pm, false);
        if (p != 0) record(l, p, block.timestamp, blk);
    }

    /// @notice GapMathV4.ringWrite on the packed storage (same rules; fuzzed against it).
    function record(S.Layout storage l, uint256 p, uint256 ts, uint256 blk) internal {
        if (p == 0) return;
        if (p > GapMathV4.PRICE_MAX) p = GapMathV4.PRICE_MAX;
        uint256 meta = l.ringMeta;
        uint256 head = meta & 0xff;
        uint256 width = (meta >> 8) & M32;
        if (width == 0) width = WIDTH_DEFAULT;
        uint256 b = l.ring[2 * head + 1];
        uint256 lastBlock = (b >> 80) & M48;
        uint256 start = ts - ts % width;
        if (lastBlock == 0) {
            l.ring[2 * head] = p | (p << 128);
            l.ring[2 * head + 1] = _b(start, ts, blk, p);
            return;
        }
        uint256 lastPrice = b >> 128;
        uint256 newMeta = meta;
        // prev = the head's latest (block, price, ts) when this record opens a new block
        if (blk != lastBlock) {
            newMeta = (newMeta & ((1 << 40) - 1)) | (lastBlock << 40) | (lastPrice << 88) | (((b >> 40) & M40) << 216);
        }
        uint256 hStart = b & M40;
        if (start <= hStart) {
            uint256 a = l.ring[2 * head];
            uint256 mn = a & M128;
            uint256 mx = a >> 128;
            if (p < mn) mn = p;
            if (p > mx) mx = p;
            uint256 na = mn | (mx << 128);
            if (na != a) l.ring[2 * head] = na;
            l.ring[2 * head + 1] = _b(hStart, ts, blk, p);
        } else {
            uint256 n = (head + 1) % 3;
            (uint256 mn, uint256 mx) = lastPrice < p ? (lastPrice, p) : (p, lastPrice);
            l.ring[2 * n] = mn | (mx << 128);
            l.ring[2 * n + 1] = _b(start, ts, blk, p);
            newMeta = (newMeta & ~uint256(0xff)) | n;
        }
        if (newMeta != meta) l.ringMeta = newMeta;
    }

    /// @notice Sets the bucket width to max(1, L / 2) (a send or receive, which read L). An L change takes full
    ///         effect within one L (GapMathV4 ring notes).
    function setWidth(S.Layout storage l, uint256 lookback) internal {
        uint256 w = lookback / 2;
        if (w == 0) w = 1;
        uint256 meta = l.ringMeta;
        if ((meta >> 8) & M32 != w) l.ringMeta = (meta & ~(M32 << 8)) | (w << 8);
    }

    function _b(uint256 start, uint256 ts, uint256 blk, uint256 p) private pure returns (uint256) {
        return (start & M40) | ((ts & M40) << 40) | ((blk & M48) << 80) | (p << 128);
    }

    /// @notice The ring, unpacked (for GapMathV4.plast / pref and the views).
    function load(S.Layout storage l) internal view returns (GapMathV4.Ring memory r) {
        uint256 meta = l.ringMeta;
        r.head = uint8(meta);
        r.prevBlock = uint48(meta >> 40);
        r.prevPrice = uint128(meta >> 88);
        r.prevTs = uint40(meta >> 216);
        for (uint256 i; i < 3; i++) {
            uint256 a = l.ring[2 * i];
            uint256 b = l.ring[2 * i + 1];
            r.s[i] = GapMathV4.Slot(uint40(b), uint40(b >> 40), uint48(b >> 80), uint128(a), uint128(a >> 128), uint128(b >> 128));
        }
    }

    /// @notice The current bucket width (seconds).
    function bucketWidth(S.Layout storage l) internal view returns (uint256 w) {
        w = (l.ringMeta >> 8) & M32;
        if (w == 0) w = WIDTH_DEFAULT;
    }
}

src/v4/gap/IGapRegistryV4.sol

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

/// @title IGapRegistryV4 -- per-chain gap settings for PangeaOFTV4 tokens (Gap v4 spec §15, V4-INTERFACES §4, §8)
/// @notice Stream A owns this file; stream B implements it (src/v4/registry/GapRegistryV4.sol).
///         It is IPangeaGapRegistry (v3) MINUS the price log, its capacity and windows, the writer reward,
///         the co-sign, the oversized land and the cover window; PLUS the v4 settings. Readers, hop gas caps,
///         trusted executors and the two delivery keys are unchanged from v3.
///
///         ANYPAIRS (owner 2026-11-06, lead ruling in RESUME-2026-11-06.md): ANY pool on ANY chain. There is NO
///         listing of a pair token: no stables list, no admin quote classes, no registrar, no admin routes. The admin
///         keeps PARAMETERS only: the USD anchors (the tokens a path may end in, taken as exactly $1), the chain's
///         native class, and the venues (per reader: the DEX code whose pools it may read, by CREATE2). A coin's
///         quote USD path is passed IN ITS LAUNCH (setOfficialPool) and stored PER COIN; the registry checks only that
///         it READS (pools at a venue's CREATE2 address, listed readers, ends in an anchor, both roundings non-zero).
///         Anchor quotes and native-class quotes (native, wrapped native) need no path (the chain's native path, set
///         by anyone while none reads, prices the native coin). A stored path that stops reading may be replaced by
///         ANYONE with one that reads; one that still reads cannot be touched by anyone. Class is derived: an anchor
///         1, native / wrapped native the chain's `nativeClass`, any other quote 0 (priced through USD).
///         The token's ABI here is UNCHANGED: `quoteClass`, `usdPerQuoteE18`, `usdPerQuoteBothNativeE18` answer for
///         the CALLER's own path (msg.sender is the token, also through its module and views), so the module needs
///         no new code.
///
///         LEAD UPDATE 2 (owner 2026-11-05): NO COMPILED BOUNDS. Every v4 parameter is admin-set per chain PLUS a
///         per-coin override (B's storage and setters; every setter emits an event, no timelock; listed in
///         B-SETTERS.md). The TOKEN reads ONE resolved struct, `paramsOf(token)` (the chain values with the coin's
///         overrides applied), and keeps only arithmetic safety: a nonsensical pair resolves deterministically
///         (min > max: max wins), nothing overflows or divides by zero. HARD INVARIANTS stay in the token's code
///         whatever the registry says: credited <= A on every arrival (the rest is never minted); no admin path mints,
///         moves or seizes users' tokens or pool liquidity; a pause stops only NEW sends (arrivals always land or
///         hold retriably, the refund marker always lands); supply and balances are untouchable.
///
///         A token reads its official pool ONCE (the first send, receive or pool transfer after it is set) and
///         caches it for life: setOfficialPool is set-once per token and there is no re-point in v4.
///         FACTORY ORDER (stream B): setOfficialPool(token, pool) BEFORE the launch liquidity is added, so the
///         launch LP add (a token transfer into the PoolManager) writes the token's first price record; a
///         buy-and-bridge or plain send needs a record from an earlier block (GapNeedRecord otherwise).
interface IGapRegistryV4 {
    // ------------------------------------------------------------------ types

    /// @notice One conversion step (v3 unchanged): 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 ANYPAIRS: what a listed reader may read, an admin PARAMETER (venue code, never a token choice).
    ///         `kind` 1: a Uniswap-v3-style pool, address = CREATE2(deployer, keccak256(abi.encode(token0, token1,
    ///         fee)), initCodeHash) with fee = pool.fee(); 2: a Uniswap-v2-style pair, salt keccak256(abi.encodePacked
    ///         (token0, token1)); 0: none (the reader prices no path). `deployer` is the address that CREATE2s the pools
    ///         (the factory for Uniswap; PancakeSwap v3's PoolDeployer). `gasCap`: the hop gas cap every stored hop of
    ///         this reader gets (the caller's is ignored), in [1, 100,000].
    struct Venue {
        address deployer;
        bytes32 initCodeHash;
        uint8 kind;
        uint32 gasCap;
    }

    /// @notice A token's official launch pool (Uniswap v4). Set once, by a listed factory. v4 adds `tickSpacing`
    ///         (the token rebuilds the exact PoolKey -- currency order from the token and `quote`, fee = `lpFee`,
    ///         hooks = `hook` -- and checks keccak256(PoolKey) == `poolId` before it ever swaps on it) and
    ///         `lockedPositionKey`: the v4 position key (Position.calculatePositionKey(owner, tickLower, tickUpper,
    ///         salt)) of the PERMANENTLY LOCKED launch liquidity, whose liquidity the margin and the k curve read
    ///         (LEAD UPDATE 2: depth = locked-LP quote depth). It may hold no liquidity yet when set (the factory
    ///         names the pool before seeding it); a depth of 0 holds a receive and refuses a buy.
    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 (the dynamic-fee flag 0x800000 is refused by the token)
        bool tokenIsCurrency0;
        int24 tickSpacing;
        bytes32 lockedPositionKey;
    }

    /// @notice How the official pool's hook fee is read (v3 unchanged). NONE: unreadable (the token
    ///         refuses the pool's price: send reverts, receive holds).
    enum HookKind {
        NONE,
        V1, // PangeaFeeHook: configs(id).feeBps
        V2 // PangeaFeeHookV2: feeOf(id), live
    }

    /// @notice The cost cover figures (spec §9). No compiled bounds; the token's arithmetic rules:
    ///         baseFeeCapWei 0 = no gas cover; baseFeeFloorWei > baseFeeCapWei -> the cap wins;
    ///         nativeUsdMaxE18 0 = no cover at all; nativeUsdMinE18 > nativeUsdMaxE18 -> the max wins;
    ///         coverCapUsdE18 0 = no cover. Units are the MEASURED MINIMUM receipt gasUsed. The source uses
    ///         buyAndSendUnits, the destination swapUnits; one message's cover is at most the destination's cap
    ///         (the source already capped its own part at its cap).
    struct CoverV4 {
        uint32 buyAndSendUnits;
        uint32 swapUnits;
        uint64 baseFeeFloorWei;
        uint64 baseFeeCapWei;
        uint64 tipAllowanceWei;
        uint128 nativeUsdMinE18;
        uint128 nativeUsdMaxE18;
        uint128 coverCapUsdE18;
        /// @dev Audit r4 R4-3: the destination sale allowance is at most this share (ppm) of the arrival's value at the
        ///      source USD price (A x psUsd). Per chain (setCover), per coin with O_COVER. 0 = no destination cover.
        uint32 coverDstMaxValuePpm;
    }

    /// @notice What a token reads on its send / receive path, in ONE call: the chain values with `token`'s
    ///         overrides already applied (LEAD UPDATE 2). Defaults in brackets.
    ///         margin (destination): m = clamp(marginMinPpm, marginMaxPpm, floor(marginK x 1e9 / isqrtUp(depthUsdE18)))
    ///           with depth the destination's locked-LP quote depth at Pd_ref; marginK = K x 1e6 [K 1 -> 1e6];
    ///           marginK 0 -> marginMinPpm; [1,000 / 100,000]. A fixed per-coin m is marginK 0 and min = max = m.
    ///         k (source backstop): when execCapOn [true], k = max(m_src, clamp(execCapMinPpm, execCapMaxPpm,
    ///           floor(execCapK x 1e9 / isqrtUp(srcDepthUsdE18)))), srcDepth the source's locked-LP quote depth at
    ///           Plast, m_src this chain's margin curve at srcDepth; Ps = min(Pexec, Plast x (1 + k)). Off: Ps = Pexec.
    ///           [Kk 2 -> 2e6; 15,000 / 200,000]. A fixed per-coin k is execCapK 0 and min = max = k.
    ///         lookbackSec L [30]; feeCapPpm [10,000] caps the counted hook fee (Pexec) and fD; minLiquidity [0]
    ///           the least in-range liquidity of a pool whose price is read; bridgeFeeBps [20] (> 10,000 refused by
    ///           the token's arithmetic); lockOn [true] the same-transaction sell lock after a buyAndSend;
    ///           burnOn [true]: the gap rule withholds (and so burns) the part above the formula; false (LEAD UPDATE 3
    ///           §9.1) credits every arrival IN FULL (credited = A), like an escape. There is no withheld sink.
    struct ParamsV4 {
        uint64 marginK;
        uint32 marginMinPpm;
        uint32 marginMaxPpm;
        bool execCapOn;
        uint64 execCapK;
        uint32 execCapMinPpm;
        uint32 execCapMaxPpm;
        uint32 lookbackSec;
        uint32 feeCapPpm;
        uint128 minLiquidity;
        uint16 bridgeFeeBps;
        bool lockOn;
        bool burnOn;
        CoverV4 cover;
    }

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

    event ReaderSet(address indexed reader, bool allowed);
    event GapEscapeSet(address indexed token, bool on);
    event V2RecordMaxAgeSet(uint32 seconds_);
    event HookKindSet(address indexed hook, HookKind kind);
    event FactorySet(address indexed factory, bool listed);
    // ---- ANYPAIRS
    event UsdAnchorSet(address indexed token, bool anchor);
    event NativeClassSet(uint8 class_);
    event VenueSet(address indexed reader, Venue venue);
    /// @notice The chain's native path was set (`by`: whoever sent it; first, or replacing one that no longer read).
    ///         The hops as stored: `nativePath()` (not in the event: the registry's EIP-170 room).
    event NativePathSet(address indexed by);
    /// @notice `token`'s quote path was stored: at its launch (`by` = its factory) or as a replacement of a path that
    ///         no longer read (`by` = anyone). The hops as stored: `coinPath(token)`.
    event CoinPathSet(address indexed token, address indexed by);
    event OfficialPoolSet(address indexed token, address indexed factory, OfficialPool pool);
    event GapExecutorSet(address indexed executor, bool trusted);
    event DeliveryKeySet(uint8 indexed slot, address indexed key);
    event BridgeFeeSet(uint16 bps);
    // ---- v4: B defines the setter events (one per setter, B-SETTERS.md)
    event SendPausedSet(address indexed token, uint32 indexed dstEid, bool paused);

    // ------------------------------------------------------------------ errors (setters)

    error NotOwner();
    error NotListedFactory();
    error PoolAlreadySet(address token);
    error HookNotListed(address hook);
    /// @notice The quote path does not read (a launch leg is refused; a replacement is refused).
    error QuoteNotPricable(address quote);
    /// @notice Native, the 0xEeee placeholder and the wrapped native are never USD anchors.
    error NotAnAnchor(address token);
    /// @notice nativeClass 1 (USD) and 255 (the refund marker) are refused.
    error BadNativeClass(uint8 class_);
    /// @notice A venue with kind > 2, a zero deployer / hash for kind != 0, or a gas cap outside [1, 100,000].
    error BadVenue(address reader);
    /// @notice A path refused: 1 shape (0 or more than 2 hops, not starting at the quote, hops not chained),
    ///         2 does not end in a USD anchor, 3 a hop's reader is unlisted or has no venue, 4 a hop's pool is not
    ///         its venue's CREATE2 pool of exactly the hop's two tokens, 5 a path given for a quote that needs none.
    error BadPath(uint8 why);
    /// @notice A replacement of a path that still reads (nobody may touch a path that reads).
    error PathStillReads();
    /// @notice The quote's decimals are unreadable or above 36 (the math bound).
    error BadQuoteDecimals(address quote);
    error BadV2RecordMaxAge(uint32 seconds_);
    error BridgeFeeTooHigh(uint16 bps);
    error LzExecutorHelperRefused(address helper);
    /// @notice A reader's gas cap cannot be met (v3 rule): gasleft() >= gasCap * 64 / 63 + 5,000 before
    ///         each hop. The token passes it on (retriable), never prices on a starved read.
    error GapGasTooLow(uint256 needed, uint256 left);

    // ------------------------------------------------------------------ owner setters

    function owner() external view returns (address);
    /// @notice A listed reader is the owner's statement that it is FLASH-PROOF (v3: UniV3Reader at the previous
    ///         block's close, V2PairReader only for a pair untouched this block). No v4-pool hop readers (D1).
    function setReader(address reader, bool allowed) external;
    /// @notice ANYPAIRS parameters (owner): the USD anchors, the native class, each reader's venue.
    function setUsdAnchor(address token, bool anchor) external;
    function setNativeClass(uint8 class_) external;
    function setVenue(address reader, Venue calldata venue) external;
    function setGapEscape(address token, bool on) external;
    function setV2RecordMaxAge(uint32 seconds_) external;
    function setHookKind(address hook, HookKind kind) external;
    function setFactory(address factory, bool listed) external;
    function setGapExecutor(address executor, bool trusted) external;
    function setDeliveryKey(uint8 slot, address key) external;
    /// @notice The v4 settings' setters are B's (chain values and per-coin overrides of every ParamsV4 field,
    ///         the chain-wide and per-coin send pause, events, no timelock): see B-SETTERS.md. Only the views the
    ///         token reads are part of this interface.

    // ------------------------------------------------------------------ paths (ANYPAIRS: anyone)

    /// @notice The chain's native USD path (1 or 2 hops from address(0) to an anchor). Anyone, while no native
    ///         path is stored or the stored one does not read; it must read.
    function setNativePath(Hop[] calldata hops) external;
    /// @notice Replace `token`'s stored quote path with `hops`. Anyone, only while the stored one does NOT read;
    ///         the new one must read (the checks of setOfficialPool).
    function replaceCoinPath(address token, Hop[] calldata hops) external;

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

    /// @notice Once per token, from a listed factory, BEFORE the launch liquidity is added (see above).
    ///         Refused unless the hook is listed (hookKind != NONE), the quote's decimals read and are <= 36,
    ///         lpFee is static (< 0x800000), lockedPositionKey != 0 and poolId == keccak256(abi.encode(PoolKey))
    ///         for the key built from (token, quote, lpFee, tickSpacing, hook). ANYPAIRS: `path` is the quote's USD
    ///         path, stored for this token: empty for an anchor or native-class quote (BadPath(5) otherwise),
    ///         else it must READ (QuoteNotPricable: that leg is refused).
    function setOfficialPool(address token, OfficialPool calldata pool, Hop[] calldata path) external;

    // ------------------------------------------------------------------ views read by the token

    function poolManager() external view returns (address);
    function wrappedNative() external view returns (address);
    function isReader(address reader) external view returns (bool);
    function isUsdAnchor(address token) external view returns (bool);
    function nativeClass() external view returns (uint8);
    function isFactory(address factory) external view returns (bool);
    /// @notice Derived (ANYPAIRS): an anchor 1; native or the wrapped native `nativeClass`; else 0.
    function quoteClass(address quote) external view returns (uint8);
    function gapEscape(address token) external view returns (bool);
    function v2RecordMaxAge() external view returns (uint32);
    function hookKind(address hook) external view returns (HookKind);
    function venueOf(address reader) external view returns (Venue memory);
    function nativePath() external view returns (Hop[] memory);
    function coinPath(address token) external view returns (Hop[] memory);
    /// @notice Whether `quote` needs a path (it is not an anchor and not native-class).
    function needsPath(address quote) external view returns (bool);
    /// @notice `set == false`: no official pool on this chain yet.
    function officialPool(address token) external view returns (bool set, OfficialPool memory pool);
    function hasOfficialPool(address token) external view returns (bool);
    /// @notice The official pool's live fee, ppm: hook fee (V1 configs(id).feeBps x 100, V2 feeOf(id)) + the
    ///         static lpFee. ok false on no pool, HookKind NONE or a failed hook read. The token caps it at
    ///         feeCapPpm.
    function poolFeePpm(address token) external view returns (bool ok, uint32 ppm);
    /// @notice USD per whole `quote`, 1e18 (an anchor is 1e18), through the CALLER's stored path (the native path for
    ///         address(0) and the wrapped native); the path chained rounding UP when `roundUp`, DOWN otherwise; 0 on any
    ///         failure (a caller with no path for `quote` reads 0). Reverts only with GapGasTooLow.
    function usdPerQuoteE18(address quote, bool roundUp) external view returns (uint256);
    /// @notice Both roundings from one read of each hop (the caller's path, as above; v3's usdPerQuoteBothE18 is gone:
    ///         no v4 token reads it, and off chain `coinUsdE18` answers per coin) and, when the same reads give it, the native path rounded down
    ///         (else 0: the token reads usdPerQuoteE18(address(0), false) itself).
    function usdPerQuoteBothNativeE18(address quote) external view returns (uint256 down, uint256 up, uint256 nativeDown);
    /// @notice For anyone (web, arb): `token`'s quote in USD through its stored path, both roundings (0, 0 = unreadable).
    function coinUsdE18(address token) external view returns (uint256 down, uint256 up);
    /// @notice For anyone (the launch form): 0 when `hops` would be stored for `quote` and reads now; else the
    ///         BadPath reason (1..5), 6 when it validates but does not read.
    function checkPath(address quote, Hop[] calldata hops) external view returns (uint8 why);
    /// @notice Whether `executor` (the caller of EndpointV2.lzReceive) may land a v4 receive: a listed LayerZero
    ///         executor (setGapExecutor) or one of the two delivery keys. address(0) never. v4: EVERY receive
    ///         but the refund marker requires it (spec §8 rule 3).
    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 isDeliveryKey(address key) external view returns (bool);
    function deliveryKeysSet() external view returns (bool);
    function isLzExecutorHelper(address a) external pure returns (bool);
    /// @notice The chain's bridge fee bps (default 20). LEAD UPDATE 3 §9.4: the token charges the RESOLVED
    ///         paramsOf(token).bridgeFeeBps (coin override applied); the registry refuses >= 10,000.
    function bridgeFeeBps() external view returns (uint16);
    /// @notice Sends of `token` toward `dstEid` refused (GapSendPaused) while the chain-wide or the coin's pause is
    ///         on (B resolves both); arrivals always land.
    function sendPaused(address token, uint32 dstEid) external view returns (bool);
    /// @notice The resolved settings of `token` (see ParamsV4). This is what the token calls.
    function paramsOf(address token) external view returns (ParamsV4 memory);

    // ------------------------------------------------------------------ keys-only delivery and the Solana prepay (v3 unchanged)

    /// @notice v3 IGapDelivery: our delivery cost toward a keys-only destination, this chain's native wei (0 = LayerZero delivers).
    function deliveryCost(uint32 dstEid) external view returns (uint256);
    /// @notice v3 IGapDelivery: (cost, recipient); a non-zero cost needs a recipient.
    function deliveryCharge(uint32 dstEid) external view returns (uint256 costWei, address to);
    /// @notice v3 IGapPrepay: the L4 prepay of a composed send into Solana.
    function prepayCharge(uint32 dstEid, uint256 composeLen) external view returns (uint256 lamports, uint256 costWei, address to);
}

src/v4/gap/PangeaOFTV4Storage.sol

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

/// @title PangeaOFTV4Storage -- the state PangeaOFTV4 shares with its gap module
/// @notice One ERC-7201 namespace, read and written by the token (its price recorder in `_update`, the metadata
///         it sets in its constructor) and by PangeaOFTV4GapModule, which runs in the token's context by
///         DELEGATECALL (buyAndSend's swap, the send's message, the receive, the 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.
///         v4: the v3 price records, price log, writer rewards, cover windows, co-sign nonces and epochs are
///         gone; the official pool is cached once for life (no re-point); the recorder is a 3-bucket ring
///         (GapMathV4.Ring, packed by GapRecorderV4).
library PangeaOFTV4Storage {
    /// @custom:storage-location erc7201:pangea.oft.v4
    struct Layout {
        // ---- the official pool, cached from the registry on first use (GapRecorderV4.learn), never changed
        bool known; // the pool below is cached
        bool tokenIs0; // this token is the pool's currency0
        uint8 quoteDecimals; // the quote's decimals (native: 18)
        uint24 lpFee; // the static LP fee (ppm)
        int24 tickSpacing;
        address poolQuote; // address(0) = native
        /// @dev G-EVMB-2 L-3: the pool the bridge / registry names can never be used (its key does not hash to its id,
        ///      a dynamic or out-of-range fee, or a quote whose decimals() is unreadable with its full gas cap), so it is
        ///      never looked up again. Packed into the first word after poolQuote (bits 232..239): no field moves.
        bool unusable;
        address poolHook;
        bytes32 poolId;
        bytes32 lockedPositionKey; // the permanently locked launch position (the margin's and k's depth)
        // ---- the recorder ring (GapRecorderV4): slot i is words 2i (min | max << 128) and 2i + 1
        //      (start | lastTs << 40 | lastBlock << 80 | lastPrice << 128); `ringMeta` is
        //      head | width << 8 (32 bits) | prevBlock << 40 | prevPrice << 88 | prevTs << 216.
        uint256[6] ring;
        uint256 ringMeta;
        // ---- the receive
        uint256 gapBurnedLD;
        mapping(bytes32 guid => uint256 withheldLD) gapWithheld;
        /// @dev acceptBelowMin: the recipient's consent to land `guid` below its minCredited.
        mapping(bytes32 guid => mapping(address to => bool)) acceptedBelowMin;
        // ---- the metadata (v3 unchanged)
        string metadataURI;
        address metadataAuthority;
        address pendingMetadataAuthority;
        // ---- audit r3 F5: the block in which `sendTo`'s destination sale allowance (coverDst) was last counted
        mapping(address sendTo => uint256 blockNumber) coverDstBlock;
    }

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

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.