Skip to content
Verified contractExactUNLICENSED

PythProStore

Address0xbd86a61569bd01ec11bdf3e2441210d50c64a5ee
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,443,251
Creation transaction
0xbe056626f1…e1d20df9fd
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

src/propamm/PythProStore.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IPinGovernor} from "src/propamm/PythLane.sol";
import {IFrontLead} from "src/propamm/PythProBase.sol";
import {PythProReader} from "src/propamm/PythProReader.sol";
import {PythProCheck} from "src/propamm/libraries/PythProCheck.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
import {EquityRecord} from "src/propamm/libraries/EquityRecord.sol";

/// @notice The shared Pyth Pro price store of a builder-build chain (Ethereum, BNB Chain): one per chain, holding the
///         kept print of every feed its pairs price, each feed once for all the pairs that name it. Anyone posts a
///         Pyth Pro EVM update of any number of feeds (`post`); anyone lists a feed (`list`); a pair reads its two
///         feeds through its own reader (`PythProReader`, a price source anyone registers at the front), and the
///         store answers readers alone.
/// @dev The rules of the store:
///      - A feed key names one record, by everything a print is admitted under: [0-31] the feed's Pyth id | [32-39]
///        its quorum | [40-55] its jump threshold, bp (zero: no equity feed) | [56-76] its gap, ms (an equity feed's
///        alone: zero exactly where the threshold is zero) | [77-78] zero | [79] its 24/7 mark (an equity feed's
///        alone) | [80-87] its Pyth channel. A key's record lives at the
///        key itself (a map at storage slot 1: key `x`'s at keccak256(abi.encode(x, 1))), so its place is the same on
///        every chain and depends on no other listing.
///      - The list is anyone's (`list`), at once, and only grows: a key's record starts with no print, and no listing
///        changes another key's record, its parameters or its place. So no one lists a feed for another under a
///        weaker quorum or another threshold: each parameter set is its own key, two listers of one key share its
///        record and its posts, and listing a key again changes nothing. There is no count and no ceiling to exhaust.
///      - A post: an update carries any number of feeds, and `keys` names, for each, the keys it fills (its quorum,
///        threshold and gap; the feed's id and the update's channel complete the key). Each named key is stored only
///        where it is listed and the feed passes a landing's full admission under that key (properties 0, 3, 4, 5 and
///        12 present, a positive price, exponent -8, publishers at the key's quorum), its own update time is newer
///        than the stored one and at most the lead ahead of the front's clock in the post's block, so no post makes a
///        feed older, or stamps it further ahead of any fill's clock in that block than the fill admits.
///      - Refusals: a structurally bad update (envelope, signer, an unknown or repeated property, a wrong length, a
///        presence byte other than 0 or 1) or a `keys` of another length than its counts give reverts; a feed that
///        fails a key's admission, a key that is not listed, and a feed with no key named keep what is stored; a post
///        that stores nothing is a no-op.
///      - A kept cross is per leg: each feed key's record is written by its own posts, so a pair's two legs may come
///        from different updates, as on `PythLane`, each within its source's window but not of one instant. A pair of
///        two correlated volatile feeds (whose cross moves less than either leg) binds a short source window or a
///        `PrintLaneSource`, whose print carries both legs in one update.
///      - Confidence: each stored print keeps its leg's confidence over its price, as printed, in 1 bp units rounded up
///        (bits 244-255, at most 4,095), and the check answers the pair's, both legs summed, in ppm; where either leg's
///        field is saturated it answers `CONF_SATURATED`, past every listing's ceiling, so the front refuses the print.
///      - Records: `IPriceLane`'s (bits 0-179 the record an asset module reads): a crypto feed's session unknown, its
///        quality bit set, no session start or jump tag; the key's quorum at bits 180-187, its threshold at 188-203,
///        its 24/7 mark at 204 and its Pyth id at 212-243, written when the key is listed and never moved, the last
///        nonzero for every listed key; a 24/7 key's feed's own session as last recorded at 205-207 (`OWN`).
///      - Equity feeds: a key with a jump threshold takes exponent -5 as well (Pyth's equity feeds), scaled here to -8,
///        admits a print only with its market session (property 9) and a payload time at most the lead ahead of the
///        front's clock, and folds each update into its record by `EquityRecord`: the session and its start by the
///        payload's own time, from any update carrying the session; the jump tag, a print measured over the key's gap
///        of feed time after a gap from the price before it, the price before each of the last four jumps kept; and a
///        reopen past `EquityRecord.REOPEN_MS`.
///      - The 24/7 class: an equity key with its 24/7 mark (key bit 79) folds its sessions as `PythLane` folds a
///        marked feed's (`EquityRecord.always`): its record's session is the regular one where the feed's own is, and
///        `EquityRecord.ALWAYS` under every other, the feed's own kept at bits 205-207, so a listing on a store
///        reader fills a 24/7 index through its weekend under the module's 24/7 rules. An unmarked key keeps Pyth's
///        own labels (`EquityRecord.pythSession`), each held by the module to that session's longest. The mark is
///        part of the key: a marked and an unmarked key of one feed are two records, and a reader names one of them.
///        Readers are unchanged: they carry the whole 88-bit key.
///      - The signer: a post passes on the pinned signer while the pin is live, else on any signer Pyth's verifier
///        accepts. Anyone refreshes the pin against the verifier for another `PIN_TTL_SEC` (`refreshPin`) and re-pins
///        once the verifier drops it (`repin`); the front's protocol guardian or the protocol owner cuts it at once
///        (`cutPin`), and the protocol owner alone lifts that cut (`liftPinCut`). The store keeps one record a key,
///        whatever signer passed its post, and a kept read ignores the listing's lease: a pinned key Pyth has revoked
///        is honoured until the pin's end, at most `PIN_TTL_SEC` after its last refresh, unless it is cut. A listing's
///        operator who wants prints the verifier confirmed alone binds a source that keeps them apart
///        (`PrintLaneSource`), as the listing's source or as its backup (`darkenSource`).
///      - Reads: the price check (`check`), an asset-module pair's record (`assetRecord`), each answered only to a
///        reader, by the keys the call's last word names (a reader appends its own): the caller's code must be the
///        reader's (`PythProReader`) with this store's front, this store and those keys as its immutables, which the
///        store checks against the caller's code hash, rebuilding that code from the keys and the reader's code it
///        learnt at construction (`readerHash`), with no storage read; and the keys must be a pair `listReader`
///        takes. A reader's code answers the front alone and appends its own keys, so only the front's own calls
///        reach a read and a reader reads its own pair alone. `readerCode` answers the creation code a registrant
///        passes to `registerSource` for a pair's two keys, `readerOf` a contract's keys where its code is a reader's.
///      - The reader's code: the store's constructor makes two readers of its front and itself with keys no reader
///        is answered for, each key byte different between the two, and keeps the first's code but at the places
///        where the two differ, each one a 32-byte word holding the keys in both, and nowhere else: so the places
///        are the reader's keys word wherever solc put it, and the code the store rebuilds for any keys is the code
///        solc emits for a reader of them. Any other layout refuses the store's construction (`BadReaderCode`).
///      - A carried print (a check with an update) is checked as `PythProSource` checks it, by the reader's two keys:
///        the pinned signer passes without the verifier only under the listing's lease (flags bit 0) and while the
///        pin is live, any other signer by the verifier. An equity reader takes none: only the kept record knows the
///        session's start and the jump tag.
///      - The clock: the store holds the front's clock mode and pull lead (`syncClock`, anyone, reads them from the
///        front), a builder build's alone: the seal time (mode 0) or BNB Chain's millisecond precompile (mode 3). A
///        front upgrade that changes either is followed by a `syncClock`; until it, posts hold stored times to the
///        former clock.
contract PythProStore {
    /// @notice A structurally bad update or `keys`, a key or a reader's pair outside its bounds, a kept read with no
    ///         print at its quorum or under the wrong asset flag, or a front whose clock is no builder build's.
    error BadUpdate();
    /// @notice A post's or a carried print's signer is neither the live pin nor one Pyth's verifier accepts, or
    ///         `repin` or `refreshPin` names a signer the verifier refuses.
    error BadPullSigner();
    /// @notice A read by a caller whose code is not a reader's of the keys the call names, or of keys no reader is
    ///         answered for.
    error NotReader();
    /// @notice At construction: the reader's code holds its keys in a way the store cannot rebuild.
    error BadReaderCode();
    /// @notice `repin` while Pyth's verifier still accepts the current pin.
    error NotStale();
    /// @notice `cutPin` from neither the front's protocol guardian nor the protocol owner.
    error NotGuardian();
    /// @notice `liftPinCut` from any caller but the protocol owner.
    error NotOwner();
    /// @notice A cut stands (`pinCut`): the pin takes no refresh and no re-pin until the protocol owner lifts it.
    error PinIsCut();
    /// @notice A carried print on an equity reader.
    error KeptOnly();

    /// @dev Bytes before an update's payload: magic 4 | r 32 | s 32 | v - 27 1 | payload length 2.
    uint256 internal constant ENVELOPE = 71;
    uint256 internal constant M32 = 0xffffffff;
    uint256 internal constant M48 = 0xffffffffffff;
    uint256 internal constant M64 = 0xffffffffffffffff;
    /// @dev A feed key's 88 bits.
    uint256 internal constant M88 = (1 << 88) - 1;
    /// @dev A record's bits an asset module reads, 0-179.
    uint256 internal constant M180 = (1 << 180) - 1;
    /// @dev A record's leg confidence, bits 244-255: 1 bp units, rounded up, at most 4,095.
    uint256 internal constant CONF = uint256(0xfff) << 244;
    /// @dev The pair confidence the check answers where either leg's field is saturated (4,095 bp, which stands for
    ///      any wider confidence): the whole price, ppm, past the most a listing's ceiling may be (655,350 ppm).
    uint256 internal constant CONF_SATURATED = 1e6;
    /// @dev The lead's ceiling: the fronts' own on their pull lead.
    uint256 internal constant MAX_PULL_LEAD_MS = 4_000;
    /// @dev The pin's cut, bit 208 of slot 0.
    uint256 internal constant CUT = uint256(1) << 208;
    /// @dev A key's bits 40-79: its jump threshold, gap and 24/7 mark, zero for a crypto key.
    uint256 internal constant M40 = (1 << 40) - 1;
    /// @dev A key's gap, bits 56-76 (`EquityRecord.REOPEN_MS` at most, under 2^21).
    uint256 internal constant GAP_MASK = (1 << 21) - 1;
    /// @dev A key's 24/7 mark, bit 79, and a record's, bit 204, beside the feed's own session at 205-207, as
    ///      `PythLane` keeps them (`EquityRecord.always`).
    uint256 internal constant ALWAYS_KEY = 79;
    uint256 internal constant ALWAYS_BIT = 204;
    uint256 internal constant OWN = 205;
    /// @dev The most 32-byte words the reader's code may take (`R0`-`R6`): solc 0.8.35 emits 204 bytes.
    uint256 internal constant READER_WORDS = 7;
    /// @dev The keys of the two reference readers the constructor makes, each of 22 key bytes nonzero and every one
    ///      different between the two; each names one feed against itself on both legs, a pair no reader is answered
    ///      for.
    uint256 internal constant REF_A = 0xa5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5;
    uint256 internal constant REF_B = 0x5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a;

    /// @notice The front whose fills the store serves, whose clock and pull lead it holds stored times to, and whose
    ///         protocol guardian or protocol owner may cut the pin.
    address public immutable FRONT;
    /// @notice Pyth's Pro verifier, which admits a signer past the pin.
    address public immutable VERIFIER;
    /// @dev The reader's code, as a reader of this store and its front holds it, keys aside: its bytes in 32-byte
    ///      words, the keys' places zero, and the bytes past its end zero.
    bytes32 internal immutable R0;
    bytes32 internal immutable R1;
    bytes32 internal immutable R2;
    bytes32 internal immutable R3;
    bytes32 internal immutable R4;
    bytes32 internal immutable R5;
    bytes32 internal immutable R6;
    /// @dev The reader's code's length, bytes.
    uint256 internal immutable READER_LEN;
    /// @dev Where the reader's code holds its keys word: each place plus one, 16 bits each from bit 0, the first zero
    ///      ending the list.
    uint256 internal immutable KEYS_AT;

    /// @dev Slot 0: [0-159] the pinned signer, honoured without asking the verifier until the pin's end | [160-207]
    ///      the pin's end, unix seconds, zero for a pin never confirmed or one cut | [208] the pin's cut (`CUT`), set
    ///      by `cutPin` and cleared only by `liftPinCut` | [209-215] zero | [216-223] the front's clock mode |
    ///      [224-239] the front's pull lead, ms | [240-255] zero. A post reads it once.
    uint256 internal _pin;
    /// @dev Per feed key: its record. A map at storage slot 1.
    mapping(uint256 => uint256) internal _records;
    /// @dev Per equity key: the price before each of its last four jumps, the jump tagged t at bit 64 x (t mod 4). A
    ///      map at storage slot 2.
    mapping(uint256 => uint256) internal _jumps;
    /// @dev Per equity key: its open window (`EquityRecord.print`: the price fresh prints are measured from, 0-63, and
    ///      the window's end, feed ms, 64-111), zero for none. A map at storage slot 3.
    mapping(uint256 => uint256) internal _wins;

    /// @notice A post stored `stored` records, none where it was a no-op.
    event Posted(uint256 stored);
    /// @notice `repin` made `signer` the pin.
    event Repinned(address signer);
    /// @notice `refreshPin` honoured `signer` until `validUntil`, unix seconds.
    event PinRefreshed(address signer, uint48 validUntil);
    /// @notice `by` ended the pin's window (`cutPin`).
    event PinCut(address by);
    /// @notice The protocol owner lifted the pin's cut (`liftPinCut`).
    event PinCutLifted(address by);
    /// @notice Feed key `key` listed.
    event FeedListed(uint256 indexed key);
    /// @notice The store took the front's clock mode and pull lead, ms.
    event ClockSynced(uint256 mode, uint256 leadMs);
    /// @notice An equity key's print tagged a jump: the tag and the prices before and after it.
    event Jumped(uint256 indexed key, uint256 tag, uint256 before, uint256 price);

    /// @param front The front, never zero, on a builder build's clock (mode 0 or 3).
    /// @param verifier Pyth's Pro verifier.
    /// @param signer_ The pinned signer, honoured only once the verifier has confirmed it; zero for none.
    constructor(address front, address verifier, address signer_) {
        if (front == address(0)) revert BadUpdate();
        FRONT = front;
        VERIFIER = verifier;
        // the reader's code, as every reader of this store and this front holds it, keys aside
        (bytes32[READER_WORDS] memory r, uint256 len, uint256 at) = _learnReader(front);
        R0 = r[0];
        R1 = r[1];
        R2 = r[2];
        R3 = r[3];
        R4 = r[4];
        R5 = r[5];
        R6 = r[6];
        READER_LEN = len;
        KEYS_AT = at;
        uint256 w = uint160(signer_);
        // the pin is honoured without the verifier only once the verifier has confirmed it
        if (signer_ != address(0) && PythProCheck.signerOk(signer_, address(0), verifier)) {
            w |= ((block.timestamp + PythProCheck.PIN_TTL_SEC) & M48) << 160;
        }
        _pin = w | _frontClock(front);
    }

    /// @dev The reader's code for `front` and this store, learnt from two readers made here with the reference keys
    ///      `REF_A` and `REF_B`: the first's code in words, each place where it holds `REF_A` zeroed, with those places
    ///      (each plus one, 16 bits each) and its length. Refused (`BadReaderCode`) unless the two codes are of one
    ///      length of at most `READER_WORDS` words, the second holds `REF_B` at each place the first holds `REF_A` and
    ///      nowhere else differs from it, and there is a place at all. As every key byte differs between the two, the
    ///      bytes the keys move are those places' and no other: no place is a byte of code that merely equals `REF_A`.
    function _learnReader(address front) internal returns (bytes32[READER_WORDS] memory r, uint256 len, uint256 at) {
        // the store has no code yet: neither reader lists its keys
        bytes memory a = address(new PythProReader(front, address(this), REF_A & M88, REF_A >> 88)).code;
        bytes memory b = address(new PythProReader(front, address(this), REF_B & M88, REF_B >> 88)).code;
        len = a.length;
        if (len != b.length || len > READER_WORDS * 32) revert BadReaderCode();
        uint256 n;
        uint256 i;
        while (i + 32 <= len) {
            uint256 wa;
            uint256 wb;
            assembly ("memory-safe") {
                wa := mload(add(add(a, 0x20), i))
                wb := mload(add(add(b, 0x20), i))
            }
            if (wa != REF_A) {
                ++i;
                continue;
            }
            if (wb != REF_B || n == 16) revert BadReaderCode();
            at |= (i + 1) << (16 * n++);
            assembly ("memory-safe") {
                mstore(add(add(a, 0x20), i), 0)
                mstore(add(add(b, 0x20), i), 0)
            }
            // `REF_A` overlaps no shifted copy of itself (ten zero bytes, then none): the next place is past this one
            i += 32;
        }
        if (n == 0 || keccak256(a) != keccak256(b)) revert BadReaderCode();
        for (uint256 k; k < READER_WORDS; ++k) {
            uint256 w;
            if (k * 32 < len) {
                assembly ("memory-safe") {
                    w := mload(add(add(a, 0x20), mul(k, 0x20)))
                }
                // the bytes past the code's end, zero
                if (len < (k + 1) * 32) w &= ~(type(uint256).max >> ((len - k * 32) * 8));
            }
            r[k] = bytes32(w);
        }
    }

    // ================================================================ views
    /// @notice The pinned signer, honoured without asking the verifier until `pinValidUntil`; any signer Pyth's
    ///         verifier accepts is accepted too.
    function signer() external view returns (address) {
        return address(uint160(_pin));
    }

    /// @notice The pin's end, unix seconds; zero for a pin never confirmed or one cut (`cutPin`).
    function pinValidUntil() external view returns (uint48) {
        return uint48(_pin >> 160);
    }

    /// @notice The pin's cut, set by `cutPin` and cleared only by `liftPinCut`: while it stands `refreshPin` and
    ///         `repin` refuse, the pin stays dark and Pyth's verifier decides every signer.
    function pinCut() external view returns (bool) {
        return _pin & CUT != 0;
    }

    /// @notice The front's clock mode the store holds stored times to (`PropAMMClock`: 0 the seal time, 3 BNB Chain's
    ///         millisecond precompile).
    function clockMode() external view returns (uint256) {
        return (_pin >> 216) & 0xff;
    }

    /// @notice How far a stored feed time may run ahead of the front's clock in the post's block, ms: the front's
    ///         pull lead, as last synced.
    function MAX_LEAD_MS() external view returns (uint256) {
        return (_pin >> 224) & 0xffff;
    }

    /// @notice Whether feed key `key` is listed.
    function isListed(uint256 key) external view returns (bool) {
        return _records[key] != 0;
    }

    /// @notice Whether `who` is a reader the store answers, and its base and quote keys, read from its code: where its
    ///         code is a reader's of this store and its front, the keys it holds, and whether `listReader` takes
    ///         them (a contract made with the reader's code by other means than its constructor may hold any keys);
    ///         elsewhere false and zeros.
    function readerOf(address who) external view returns (bool reader, uint256 baseKey, uint256 quoteKey) {
        if (who.code.length != READER_LEN) return (false, 0, 0);
        uint256 o = (KEYS_AT & 0xffff) - 1;
        uint256 keys;
        assembly ("memory-safe") {
            extcodecopy(who, 0, o, 0x20)
            keys := mload(0)
        }
        if (_hashOf(keys) != who.codehash) return (false, 0, 0);
        baseKey = keys & M88;
        quoteKey = (keys >> 88) & M88;
        reader = _pairOk(keys) && _keyOk(baseKey) && _keyOk(quoteKey);
    }

    /// @notice The code hash of a reader of this store and its front holding `baseKey` and `quoteKey`: an operator's
    ///         check of a source. Reverts `BadUpdate` unless `listReader` takes the two keys (`_pairOk`, and each
    ///         key's bounds, `_keyOk`), so it never answers a hash for a reader the store does not serve.
    function readerHash(uint256 baseKey, uint256 quoteKey) external view returns (bytes32) {
        uint256 keys = baseKey | (quoteKey << 88);
        if (!_keyOk(baseKey) || !_keyOk(quoteKey) || !_pairOk(keys)) revert BadUpdate();
        return _hashOf(keys);
    }

    /// @notice The creation code of a reader of this store holding `baseKey` and `quoteKey`, as a registrant passes it
    ///         to the front's `registerSource`: the reader's own code with this store's front, this store and the two
    ///         keys as its constructor's arguments, so a reader made from it has the code the store answers.
    function readerCode(uint256 baseKey, uint256 quoteKey) external view returns (bytes memory) {
        return abi.encodePacked(type(PythProReader).creationCode, abi.encode(FRONT, address(this), baseKey, quoteKey));
    }

    /// @notice `IPriceCheck.cacheValid`, the lease's renewal test: the pin is live and one Pyth's verifier accepts
    ///         now; a store with no pin caches no trust, so a renewal finds it valid. The lease binds carried prints
    ///         alone here.
    function cacheValid() external view returns (bool) {
        uint256 w = _pin;
        address s = address(uint160(w));
        return s == address(0)
            || (block.timestamp <= (w >> 160) & M48 && PythProCheck.signerOk(s, address(0), VERIFIER));
    }

    /// @dev The caller's two keys, a reader's alone: the call's last word (a reader appends its own keys), keys of a
    ///      pair `listReader` takes (`_pairOk`; each key's own bounds hold wherever its record is read, as a record is
    ///      nonzero only for a listed key, and a carried print checks them), and the caller's code the reader's
    ///      holding them. No storage read.
    function _reader() internal view returns (uint256 keys) {
        assembly ("memory-safe") {
            keys := calldataload(sub(calldatasize(), 0x20))
        }
        if (!_pairOk(keys) || _hashOf(keys) != msg.sender.codehash) revert NotReader();
    }

    /// @dev The code hash of the reader holding keys word `keys`: the reader's code rebuilt in memory, `keys` written at
    ///      each of its places, hashed over its length.
    function _hashOf(uint256 keys) internal view returns (bytes32 h) {
        uint256 m;
        assembly ("memory-safe") {
            m := mload(0x40)
            mstore(0x40, add(m, 0xe0))
        }
        _put(m, R0);
        _put(m + 0x20, R1);
        _put(m + 0x40, R2);
        _put(m + 0x60, R3);
        _put(m + 0x80, R4);
        _put(m + 0xa0, R5);
        _put(m + 0xc0, R6);
        uint256 at = KEYS_AT;
        uint256 len = READER_LEN;
        assembly ("memory-safe") {
            for {} at { at := shr(16, at) } { mstore(add(m, sub(and(at, 0xffff), 1)), keys) }
            h := keccak256(m, len)
        }
    }

    function _put(uint256 p, bytes32 w) private pure {
        assembly ("memory-safe") {
            mstore(p, w)
        }
    }

    /// @dev Whether keys word `w` names a pair `listReader` takes, its keys' own bounds aside (`_keyOk`): the keys in
    ///      bits 0-175 alone, two feeds, a quote that is no equity key, one channel.
    function _pairOk(uint256 w) internal pure returns (bool) {
        uint256 kq = w >> 88;
        return w >> 176 == 0 && (w ^ kq) & M32 != 0 && (kq >> 40) & M40 == 0 && (w >> 80) & 0xff == kq >> 80;
    }

    /// @dev Whether `key` is within a key's bounds (`list`).
    function _keyOk(uint256 key) internal pure returns (bool) {
        uint256 jump = (key >> 40) & 0xffff;
        uint256 gap = (key >> 56) & GAP_MASK;
        return key >> 88 == 0 && key >> 80 != 0 && key & M32 != 0 && (key >> 32) & 0xff != 0 && (key >> 77) & 3 == 0
            && jump <= EquityRecord.MAX_JUMP_BPS && gap <= EquityRecord.REOPEN_MS && (jump == 0) == (gap == 0)
            && (jump != 0 || (key >> ALWAYS_KEY) & 1 == 0);
    }

    /// @notice `IPriceCheck.check` for the calling reader's pair. Every refusal reverts, as a price check's does.
    /// @dev With an empty update the pair's kept print: each key's record must carry a print at its quorum (bit 115).
    ///      The fourth word is the pair's confidence: both legs' (bits 244-255, 1 bp units) summed, in ppm, or
    ///      `CONF_SATURATED` where either leg's field is saturated. With an update, the carried print's own check
    ///      (`PythProCheck`, by the two keys' ids, quorums and channel) and the signer rule: the live pin under the
    ///      lease, else Pyth's verifier. Flags bit 1 must be set exactly for a reader whose base key is an equity key:
    ///      a fifth word then follows, the base's record's bits 0-179, so the answer is exactly five words then and
    ///      four otherwise, and such a reader takes no carried print.
    /// @param update Empty for the kept print, else a two-feed update of the pair's base then quote feed.
    /// @param flags [0] the listing's lease, which a carried print's signer rule reads and a kept read ignores | [1]
    ///        the base's record wanted, an asset-module pair's | [2-255] ignored.
    /// @param k The pair's cross scale, at most 58.
    /// @return ta The base leg's feed time, µs.
    /// @return tb The quote leg's feed time, µs.
    /// @return px The cross P = pa x 10^k / pb, rounded down; a kept print's nonzero and under 2^96.
    /// @return conf The pair's confidence, ppm: `CONF_SATURATED` where either kept leg's field is saturated.
    function check(bytes calldata update, uint256 flags, uint256 k)
        external
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf)
    {
        uint256 keys = _reader();
        uint256 kb = keys & M88;
        uint256 kq = keys >> 88;
        bool equity = (kb >> 40) & 0xffff != 0;
        if (((flags >> 1) & 1 != 0) != equity || k > 58) revert BadUpdate();
        if (update.length != 0) {
            if (equity) revert KeptOnly();
            // no record is read here to vouch for the keys' own bounds
            if (!_keyOk(kb) || !_keyOk(kq)) revert NotReader();
            address s;
            // `PythProCheck`'s word: the two ids, the two quorums, the keys' channel and the scale
            (,, ta, tb, px, s,, conf) = PythProCheck.check(
                update,
                (kb & M32) | ((kq & M32) << 32) | (((kb >> 32) & 0xff) << 64) | (((kq >> 32) & 0xff) << 80)
                    | ((kb >> 80) << 96) | (k << 104)
            );
            address pin;
            if (flags & 1 != 0) {
                uint256 w = _pin;
                pin = PythProCheck.livePin(address(uint160(w)), (w >> 160) & M48);
            }
            if (!PythProCheck.signerOk(s, pin, VERIFIER)) revert BadPullSigner();
            return (ta, tb, px, conf);
        }
        uint256 ra = _records[kb];
        uint256 rb = _records[kq];
        uint256 pa = ra & M64;
        uint256 pb = rb & M64;
        if (pa == 0 || pb == 0 || ((ra & rb) >> 115) & 1 == 0) revert BadUpdate();
        unchecked {
            // pa under 2^63 (every stored price is) and 10^k at most 10^58, under 2^193, so pa x 10^k stays under
            // 2^256; each time is under 2^48 ms; pb is nonzero, and the division still checks it
            px = pa * 10 ** k / pb;
            if (px == 0 || px >> 96 != 0) revert BadUpdate();
            ta = ((ra >> 64) & M48) * 1000;
            tb = ((rb >> 64) & M48) * 1000;
            // each leg's 12 bits, 1 bp units: the sum at most 819,000 ppm; a saturated leg may stand for any wider
            // confidence, so it answers one past every listing's ceiling
            conf = ra >> 244 == 0xfff || rb >> 244 == 0xfff ? CONF_SATURATED : ((ra >> 244) + (rb >> 244)) * 100;
        }
        if (equity) {
            assembly ("memory-safe") {
                let m := mload(0x40)
                mstore(m, ta)
                mstore(add(m, 0x20), tb)
                mstore(add(m, 0x40), px)
                mstore(add(m, 0x60), conf)
                mstore(add(m, 0x80), and(ra, M180))
                return(m, 0xa0)
            }
        }
    }

    /// @notice `IAssetSource.assetRecord` for the calling reader, an equity reader alone: its base's record (bits
    ///         0-179, the one its check answers as the fifth word) and the price before each of its last four jumps.
    ///         The store keeps one record whatever the lease, so the flag is moot here.
    function assetRecord(bool) external view returns (uint256 record, uint256 prices) {
        uint256 kb = _reader() & M88;
        if ((kb >> 40) & 0xffff == 0) revert BadUpdate();
        return (_records[kb] & M180, _jumps[kb]);
    }

    // ================================================================ the list
    /// @notice Anyone: lists feed key `key`, at once. Its record starts with no print and no session, and posts that
    ///         name the key fill it from then on. A key already listed is left as it is, so a second lister never
    ///         reverts and changes nothing.
    /// @param key [0-31] the feed's Pyth id, nonzero | [32-39] its quorum, nonzero | [40-55] its jump threshold, bp,
    ///        at most `EquityRecord.MAX_JUMP_BPS`, zero for no equity feed | [56-76] its gap, ms, at most
    ///        `EquityRecord.REOPEN_MS`, nonzero exactly with a threshold | [77-78] zero | [79] the 24/7 mark, only
    ///        beside a threshold | [80-87] its Pyth channel, nonzero | [88-255] zero.
    function list(uint256 key) public {
        if (!_keyOk(key)) revert BadUpdate();
        if (_records[key] != 0) return;
        // the key's own parameters and its feed's id, which no post moves: nonzero for every listed key
        _records[key] = (((key >> 32) & 0xff) << 180) | (((key >> 40) & 0xffff) << 188)
            | (((key >> ALWAYS_KEY) & 1) << ALWAYS_BIT) | ((key & M32) << 212);
        emit FeedListed(key);
    }

    /// @notice Anyone, and every reader's constructor: lists a reader's two keys where they are not yet (`list`).
    ///         Refused for another front than the store's, one feed against itself (it prices at a constant 10^k), an
    ///         equity quote key, or keys on two channels: the pairs the store answers no reader for. Nothing is
    ///         bound: a reader's keys are in its own code.
    function listReader(address front, uint256 baseKey, uint256 quoteKey) external {
        list(baseKey);
        list(quoteKey);
        if (front != FRONT || !_pairOk(baseKey | (quoteKey << 88))) revert BadUpdate();
    }

    // ================================================================ the clock
    /// @notice Anyone: takes the front's clock mode and pull lead again, after a front upgrade changed either.
    function syncClock() external {
        uint256 c = _frontClock(FRONT);
        _pin = (_pin & ~(uint256(0xffffff) << 216)) | c;
        emit ClockSynced((c >> 216) & 0xff, (c >> 224) & 0xffff);
    }

    /// @dev `front`'s clock mode (at bit 216) and pull lead (at bit 224), a builder build's alone: mode 0 or 3, which
    ///      count from no anchor, and a lead at most `MAX_PULL_LEAD_MS`.
    function _frontClock(address front) internal view returns (uint256) {
        PropAMMClock.Timing memory c = IFrontLead(front).clock();
        if (
            (c.clockMode != PropAMMClock.SEAL && c.clockMode != PropAMMClock.PRECOMPILE_MS)
                || c.pullLeadMs > MAX_PULL_LEAD_MS
        ) revert BadUpdate();
        return (c.clockMode << 216) | (c.pullLeadMs << 224);
    }

    // ================================================================ posts
    /// @notice Posts a Pyth Pro EVM update `u`: envelope magic 0x2a22999a | r | s | v - 27 | payload length (u16) |
    ///         payload, the payload 0x93c7d375 | timestamp µs (u64) | channel | feed count | feeds. `keys` holds, for
    ///         each feed in the update's order, a count byte and that many 6-byte entries, each a key of that feed to
    ///         fill, its bits 32-79 big-endian: its gap, ms (3 bytes) | its jump threshold, bp (2) | its quorum (1);
    ///         the feed's id and the update's channel complete the key. A count of 0 skips the feed. A key that is
    ///         not listed is skipped, so a wrong entry costs only itself; a `keys` that does not end exactly after the
    ///         last feed's entries reverts.
    function post(bytes calldata u, bytes calldata keys) external {
        uint256 w = _pin;
        uint256 plen = _envelope(u, w);
        uint256 p;
        uint256 head;
        uint256 a;
        assembly ("memory-safe") {
            p := add(u.offset, ENVELOPE)
            head := calldataload(p)
            a := keys.offset
        }
        if (head >> 224 != 0x93c7d375) revert BadUpdate();
        // the newest a stored time may be, above bit 64 (the front's clock in this block, read once, plus the lead),
        // and the payload's own time below it, ms
        uint256 times = ((PropAMMClock.nowMs((w >> 216) & 0xff, 0, 0) + ((w >> 224) & 0xffff)) << 64)
            | (((head >> 160) & M64) / 1000);
        uint256 count = (head >> 144) & 0xff;
        // the update's channel, where a key holds it
        uint256 ch = ((head >> 152) & 0xff) << 80;
        uint256 end = a + keys.length;
        uint256 pos = p + 14;
        uint256 stored;
        for (uint256 f; f < count; ++f) {
            (pos, a, stored) = _feed(pos, a, ch, times, stored);
        }
        if (pos != p + plen || a != end) revert BadUpdate();
        emit Posted(stored);
    }

    /// @notice Anyone: re-pins the signer to that of a validly signed update, only while the current pin is one Pyth's
    ///         verifier does not accept and no cut stands (`pinCut`).
    function repin(bytes calldata u) external {
        uint256 w = _pin;
        if (w & CUT != 0) revert PinIsCut();
        if (PythProCheck.signerOk(address(uint160(w)), address(0), VERIFIER)) revert NotStale();
        address s = _recover(u);
        if (!PythProCheck.signerOk(s, address(0), VERIFIER)) revert BadPullSigner();
        _pin = ((w >> 208) << 208) | uint160(s) | (((block.timestamp + PythProCheck.PIN_TTL_SEC) & M48) << 160);
        emit Repinned(s);
    }

    /// @notice Anyone: honours the pin for another `PIN_TTL_SEC`, confirming with Pyth's verifier each time that it
    ///         still accepts the pin, unless a cut stands (`pinCut`).
    function refreshPin() external {
        uint256 w = _pin;
        if (w & CUT != 0) revert PinIsCut();
        address s = address(uint160(w));
        if (!PythProCheck.signerOk(s, address(0), VERIFIER)) revert BadPullSigner();
        uint256 until = (block.timestamp + PythProCheck.PIN_TTL_SEC) & M48;
        _pin = (w & ~(M48 << 160)) | (until << 160);
        emit PinRefreshed(s, uint48(until));
    }

    /// @notice The front's protocol guardian or the protocol owner ends the pin's window at once (a key Pyth dropped,
    ///         or one that leaked), and the cut stands until the protocol owner lifts it (`liftPinCut`): until then
    ///         Pyth's verifier decides every signer, whatever it still accepts, and `refreshPin` and `repin` refuse.
    ///         Stop-only: it opens nothing.
    function cutPin() external {
        IPinGovernor g = IPinGovernor(FRONT);
        if (msg.sender != g.protocolGuardian() && msg.sender != g.instantOwner()) revert NotGuardian();
        _pin = (_pin & ~(M48 << 160)) | CUT;
        emit PinCut(msg.sender);
    }

    /// @notice The protocol owner (`instantOwner`, as the front's `liftLeaseCut`; not the front's owner, its timelock)
    ///         lifts the cut. The lift honours nothing itself: the pin stays dark until a `refreshPin`, which only a
    ///         key the verifier accepts passes, or a `repin` once it drops that key. Anyone may refresh a leaked key
    ///         the verifier still accepts the moment the cut lifts, so the protocol owner lifts only once Pyth has
    ///         dropped it.
    function liftPinCut() external {
        if (msg.sender != IPinGovernor(FRONT).instantOwner()) revert NotOwner();
        _pin &= ~CUT;
        emit PinCutLifted(msg.sender);
    }

    /// @dev The envelope: the magic, an update that ends exactly at its declared payload length, v of 0 or 1, and a
    ///      signer that is the live pin of slot 0's word `w` or one Pyth's verifier accepts. Returns the payload
    ///      length.
    function _envelope(bytes calldata u, uint256 w) internal view returns (uint256 plen) {
        address s = _recover(u);
        if (!PythProCheck.signerOk(s, PythProCheck.livePin(address(uint160(w)), (w >> 160) & M48), VERIFIER)) {
            revert BadPullSigner();
        }
        plen = u.length - ENVELOPE;
    }

    /// @dev The signer `u` recovers to, nonzero, past the envelope's own checks: the magic, an update that ends exactly
    ///      at its declared payload length, and v of 0 or 1.
    function _recover(bytes calldata u) internal view returns (address s) {
        if (u.length < ENVELOPE + 14) revert BadUpdate();
        uint256 hw;
        assembly ("memory-safe") {
            hw := calldataload(add(u.offset, 39))
        }
        uint256 plen = hw & 0xffff;
        uint256 v = (hw >> 16) & 0xff;
        if (bytes4(u[0:4]) != 0x2a22999a || u.length != ENVELOPE + plen || v > 1) revert BadUpdate();
        bytes32 h = keccak256(u[ENVELOPE:]);
        s = ecrecover(h, uint8(v + 27), bytes32(u[4:36]), bytes32(u[36:68]));
        if (s == address(0)) revert BadUpdate();
    }

    /// @dev One feed at `pos`, its keys named from `a` in the post's `keys`: id (4) | property count (1) | (property id
    ///      (1), value)... Properties by id, never by offset; an unknown or repeated id reverts. Property 12 is a
    ///      presence byte, then the u64 time only when present (2 or 10 bytes); a presence other than 0 or 1 reverts.
    ///      Then each named key (`ch` the update's channel, at the key's bits): only a listed key is read further (its
    ///      record holds the feed's id): a crypto key whose feed passes admission, is newer and at most the lead ahead
    ///      of the front's clock (`times` above bit 64, the clock plus the lead) is stored, its quality bit set and its
    ///      leg confidence (bits 244-255) its own; an equity key's update folds into its record (`_equity`), its
    ///      session by the payload's time (`times` below bit 64), a print or none. A feed with no confidence (property
    ///      5) carries no print: its price reads zero, which neither admission takes.
    function _feed(uint256 pos, uint256 a, uint256 ch, uint256 times, uint256 stored)
        internal
        returns (uint256 next, uint256 aNext, uint256 storedOut)
    {
        // unchecked: the cursor runs at most 255 feeds of at most 78 bytes each past the update's offset (a refused or
        // repeated property id reverts), pid x 8 is at most 2,040, a feed names at most 255 keys of 6 bytes and the
        // count stored is at most 255 x 255; calls stay checked
        unchecked {
            uint256 w;
            assembly ("memory-safe") {
                w := calldataload(pos)
            }
            uint256 id = w >> 224;
            uint256 n = (w >> 216) & 0xff;
            pos += 5;
            uint256 seen;
            uint256 price;
            uint256 pubs;
            uint256 expo;
            uint256 time;
            uint256 present;
            uint256 conf;
            for (uint256 i; i < n; ++i) {
                uint256 x;
                assembly ("memory-safe") {
                    x := calldataload(pos)
                }
                uint256 pid = x >> 248;
                // bytes per id, id byte included: 0-2: 9 | 3-4: 3 | 5: 9 | 6-8: refused | 9: 3 | 10-11: 9 | 12: 10
                uint256 step = (0x0a090903000000090303090909 >> (pid * 8)) & 0xff;
                if (pid > 12 || step == 0 || (seen >> pid) & 1 != 0) revert BadUpdate();
                seen |= 1 << pid;
                if (pid == 0) price = (x >> 184) & M64;
                else if (pid == 3) pubs = (x >> 232) & 0xffff;
                else if (pid == 4) expo = (x >> 232) & 0xffff;
                else if (pid == 5) conf = (x >> 184) & M64;
                else if (pid == 9) seen |= ((x >> 232) & 0xffff) << 16; // the session, above the ids seen
                else if (pid == 12) {
                    present = (x >> 240) & 0xff;
                    if (present > 1) revert BadUpdate();
                    if (present == 0) step = 2;
                    else time = (x >> 176) & M64;
                }
                pos += step;
            }
            next = pos;
            storedOut = stored;
            // the feed's count of keys, one byte, then 6 bytes a key; the post checks `keys` ends where the last ends
            assembly ("memory-safe") {
                n := shr(248, calldataload(a))
            }
            aNext = a + 1 + n * 6;
            // a listed key's id is nonzero
            if (n == 0 || id == 0) return (next, aNext, storedOut);
            if ((seen >> 5) & 1 == 0) price = 0;
            // the leg's confidence over its price, both at the print's own exponent: ceil(conf x 10^6 / price) ppm,
            // then 1 bp units rounded up, at most 4,095 (a u64 confidence x 10^6 stays under 2^84)
            if (price != 0) {
                conf = ((conf * 1e6 + price - 1) / price + 99) / 100;
                if (conf > 0xfff) conf = 0xfff;
            }
            for (a += 1; a < aNext; a += 6) {
                uint256 key;
                // the entry's 6 bytes are the key's bits 32-79; the feed's id and the channel complete it
                assembly ("memory-safe") {
                    key := or(or(id, ch), shl(32, shr(208, calldataload(a))))
                }
                uint256 rec = _records[key];
                // a listed key's record holds its feed's id
                if ((rec >> 212) & M32 != id) continue;
                if ((rec >> 188) & 0xffff != 0) {
                    if (_equity(key, rec, seen | (conf << 32), price, pubs, expo, time, present, times)) ++storedOut;
                    continue;
                }
                // admission: price > 0 (and < 2^63), exponent -8, feed time present, quorum
                if (
                    seen & 0x1019 != 0x1019 || price == 0 || price >= 1 << 63 || expo != 0xfff8 || present != 1
                        || pubs < (rec >> 180) & 0xff
                ) continue;
                uint256 tMs = time / 1000;
                // no time ahead of the front's clock (plus the lead), none at or above 2^48 ms: the old record stays
                if (tMs > times >> 64 || tMs >> 48 != 0) continue;
                if (tMs > ((rec >> 64) & M48)) {
                    // the print at its quorum (bit 115), the session unknown, the key's own bits kept, its own leg
                    // confidence, all of bits 244-255 rewritten
                    _records[key] = price | (tMs << 64) | (1 << 115) | (((rec >> 180) << 180) & ~CONF) | (conf << 244);
                    ++storedOut;
                }
            }
        }
    }

    /// @dev An equity key's update, its session (property 9) and its payload's time required, neither the payload's
    ///      time nor its print's more than the lead ahead of the front's clock: the session folds in by the payload's
    ///      time (`EquityRecord.session`, or on a 24/7 key `EquityRecord.always`, from any update that carries it, as
    ///      Pyth updates the session where no new aggregate formed), then a print admitted as any feed's (exponent -5
    ///      scaled to -8 first) and newer than the stored one folds in by `EquityRecord.print`, tagging a jump where
    ///      it is one, at the threshold and quorum the stored record `rec0` carries and the gap the key carries, with
    ///      its own leg confidence (`seen` bits 32-43 to bits 244-255); an update that moves only the session keeps the
    ///      kept print's. Whether the record changed.
    function _equity(
        uint256 key,
        uint256 rec0,
        uint256 seen,
        uint256 price,
        uint256 pubs,
        uint256 expo,
        uint256 time,
        uint256 present,
        uint256 times
    ) internal returns (bool) {
        uint256 bound = times >> 64;
        uint256 tpMs = times & M64;
        if (tpMs > bound || (seen >> 9) & 1 == 0) return false;
        uint256 rec = EquityRecord.pythSession((seen >> 16) & 0xffff);
        // a 24/7 key folds its feed's own session as `PythLane` folds a marked feed's
        rec = (rec0 >> ALWAYS_BIT) & 1 != 0
            ? EquityRecord.always(rec0, rec, OWN, tpMs)
            : EquityRecord.session(rec0, rec, tpMs);
        if (expo == 0xfffb) (price, expo) = (price * 1000, 0xfff8);
        uint256 fMs = time / 1000;
        if (
            seen & 0x1019 == 0x1019 && price != 0 && price < 1 << 63 && expo == 0xfff8 && present == 1
                && pubs >= (rec0 >> 180) & 0xff && fMs <= bound && fMs > (rec >> 64) & M48
        ) {
            // the pre-jump prices read only where the print tags a jump: `j` then holds the one slot it writes
            (uint256 r, uint256 win, uint256 j) = EquityRecord.print(
                rec, _wins[key], 0, price, fMs, tpMs, ((rec0 >> 188) & 0xffff) | (((key >> 56) & GAP_MASK) << 16)
            );
            uint256 tag = (r >> 164) & 0xffff;
            if (tag != (rec >> 164) & 0xffff) {
                uint256 sh = 64 * (tag & 3);
                _jumps[key] = (_jumps[key] & ~(M64 << sh)) | j;
                emit Jumped(key, tag, j >> sh, price);
            }
            _wins[key] = win;
            rec = r;
        }
        // a print folded in moved the time: the update's own leg confidence, all of bits 244-255 rewritten
        if ((rec ^ rec0) & (M48 << 64) != 0) rec = (rec & ~CONF) | (((seen >> 32) & 0xfff) << 244);
        if (rec == rec0) return false;
        _records[key] = rec;
        return true;
    }
}

src/propamm/PythLane.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IPythLane} from "src/propamm/interfaces/IPythLane.sol";
import {IPriceLane} from "src/propamm/interfaces/IPriceSource.sol";
import {PythProCheck} from "src/propamm/libraries/PythProCheck.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";
import {EquityRecord} from "src/propamm/libraries/EquityRecord.sol";

/// @notice What the price lane reads of its front: who may cut the pin (its protocol guardian or the protocol owner),
///         who alone lifts that cut (the protocol owner, `instantOwner`, as the front's `liftLeaseCut`) and who appends
///         feeds (its owner, the timelock).
interface IPinGovernor {
    /// @notice The front's protocol guardian.
    function protocolGuardian() external view returns (address);
    /// @notice The protocol owner, who acts on the front without the timelock.
    function instantOwner() external view returns (address);
    /// @notice The front's owner, its timelock.
    function owner() external view returns (address);
}

/// @notice The shared Pyth price lane of a storage-build chain: one per chain, holding every feed the fronts price, in
///         a list that only grows, with an immutable quorum per feed and one channel. Anyone
///         posts a Pyth Pro EVM update with each feed's slot in the list (`post`).
/// @dev The rules of a post, the records and the list:
///      - A post: each feed it carries is stored only when that slot holds the feed's own record and it passes a
///        landing's full admission (properties 0, 3, 4, 5 and 12 present, a positive price, exponent -8, publishers
///        at the quorum), its own update time is newer than the stored one and at most `MAX_LEAD_MS` ahead of the
///        fronts' clock in the post's block (`PropAMMClock`, with the fronts' mode and origin), so no post can make a
///        feed older, or stamp it further ahead of any fill's clock in that block than the fill admits (a front's
///        `registerSource` takes only a price lane whose lead is at most its own pull lead) and darken fills.
///      - Refusals: a structurally bad update (envelope, signer, channel, an unknown or repeated property, a wrong
///        length, a presence byte other than 0 or 1, a slot's two bytes per feed missing or extra) reverts; a feed
///        that fails admission, or is skipped, keeps its old record; a post that stores nothing is a no-op.
///      - Confidence: each stored print keeps its leg's confidence over its price, as printed, in 1 bp units rounded up
///        (bits 244-255, at most 4,095), and the check answers the pair's, both legs summed, in ppm; where either leg's
///        field is saturated it answers `CONF_SATURATED`, past every listing's ceiling, so the front refuses the print.
///      - Records: `IPriceLane`'s, source-neutral (bits 0-179 the record an asset module reads): a crypto feed's
///        session unknown, its quality bit set, no session start or jump tag. Each record carries its feed's Pyth id
///        (bits 212-243, set when the feed is listed and never moved), which binds a post's slot to its feed; the
///        front sees it only inside the base leg's record, which `check` answers as a fifth word under flags bit 1,
///        and folds it into the fill's tag source there. A listed slot's feed never changes, so a source entry's two
///        slots (`registerSource`) name the same two feeds for good.
///      - Equity feeds: one listed with a jump threshold takes exponent -5 as well (Pyth's equity feeds), scaled here
///        to -8, admits a print only with its market session (property 9) and a payload time at most `MAX_LEAD_MS`
///        ahead of the fronts' clock, and folds each update into its record by `EquityRecord`: the session and its
///        start by the payload's own time, from any update carrying the session, so a change is recorded even where
///        the price is carried forward; the jump tag, a print measured over `GAP_MS` of feed time after a gap from the
///        price before it, the price before each of the last four jumps kept (`jumpsOf`); and a reopen past
///        `EquityRecord.REOPEN_MS`.
///      - 24/7 feeds: an equity feed listed as one (an index priced around the clock; `FeedConfig`) records the
///        regular session where the feed reports it and one session, `EquityRecord.ALWAYS`, under every other, so a
///        listing that allows both fills through nights, weekends and holidays while the feed is posted, its regular
///        hours under the regular session's rules. Its record keeps the feed's own session among the price lane's
///        bits, and a change of it starts the record's session again (`EquityRecord.always`). The mark is fixed with
///        the feed's listing, as its threshold is.
///      - The list only grows. The constructor lists the first feeds, from slot 1, and the front's owner (its
///        timelock: 10 days, which the protocol guardian may cancel) appends more (`extendFeeds`), each at the next
///        slot under the constructor's refusals, up to `MAX_FEEDS`. Slot 0 names no feed. A listed feed's slot, id,
///        quorum and jump threshold never change and no feed is removed, so an append moves no source: it names none
///        (a source entry names a price lane's slots, `registerSource`) and writes only the new feed's record, which
///        posts that carry the feed fill from then on. It cannot change the channel, the verifier, the clock,
///        `GAP_MS` or the readers: those come only with a successor price lane.
///      - Reads: a front reads a listing's kept print as it reads every vendor's, by the price check (`check`, an
///        empty update), which the source entry's two slots name; the records themselves (`records`) remain for a
///        lens. Both are served only to the registered readers (the fronts and the lens), not to any contract.
///      - Held prints: a post picks which of a vendor's valid updates a feed keeps, so a fill priced off the kept
///        print alone would be priced by whoever posted last, its own taker included. Each feed therefore holds, for
///        `HOLD_MS` of the fronts' clock after a post replaces a print, the lowest and the highest price it kept
///        during that clock time and the one before (`_held`, `_heldBefore`): the print standing when the first
///        post of that time arrived, and every print stored in it. A check asked for a side (flags bit 2) answers
///        the pair's price from the held prints that are worse for that side's taker, so a print prices such a fill
///        alone only once it has stood for `HOLD_MS` with no post after it: a post can move that price against the
///        taker of its own block and the next, never for one. The fronts ask it for every fill's print, on both doors
///        (a jump's print stands against a stale quote however a later post bounces back); a check not asked for a
///        side reads the kept print.
contract PythLane is IPythLane {
    /// @notice A structurally bad update, a kept read of one slot twice or one that fails its quorum, or a
    ///         construction or append outside its bounds.
    error BadUpdate();
    /// @notice A post's signer is neither the live pin nor one Pyth's verifier accepts, or `repin` or `refreshPin`
    ///         names a signer the verifier refuses.
    error BadPullSigner();
    /// @notice A read of records by an account that is no registered reader.
    error NotReader();
    /// @notice `repin` while Pyth's verifier still accepts the current pin.
    error NotStale();
    /// @notice `cutPin` from neither the front's protocol guardian nor the protocol owner.
    error NotGuardian();
    /// @notice `extendFeeds` from any caller but the front's owner.
    error NotOwner();
    /// @notice A cut stands (`pinCut`): the pin takes no refresh and no re-pin until the protocol owner lifts it.
    error PinIsCut();

    /// @dev Bytes before an update's payload: magic 4 | r 32 | s 32 | v - 27 1 | payload length 2.
    uint256 internal constant ENVELOPE = 71;
    /// @dev The list's ceiling: a slot fits a source entry's 16 bits and a post's two bytes, whose 0 names none.
    uint256 internal constant MAX_FEEDS = 65_535;
    uint256 internal constant M32 = 0xffffffff;
    uint256 internal constant M48 = 0xffffffffffff;
    uint256 internal constant M64 = 0xffffffffffffffff;
    /// @dev A record's 24/7 mark, bit 204, and the bits a marked feed's own session is kept in, 205-207
    ///      (`EquityRecord.always`).
    uint256 internal constant ALWAYS_BIT = 204;
    uint256 internal constant OWN = 205;
    /// @dev A record's leg confidence, bits 244-255: 1 bp units, rounded up, at most 4,095.
    uint256 internal constant CONF = uint256(0xfff) << 244;
    /// @dev The pair confidence the check answers where either leg's field is saturated (4,095 bp, which stands for
    ///      any wider confidence): the whole price, ppm, past the most a listing's ceiling may be (655,350 ppm).
    uint256 internal constant CONF_SATURATED = 1e6;
    /// @dev `MAX_LEAD_MS`'s ceiling: the fronts' own on their pull lead.
    uint256 internal constant MAX_PULL_LEAD_MS = 4_000;
    /// @notice How far a stored feed time may run ahead of the fronts' clock in the post's block, in ms: the fronts'
    ///         pull lead (`PULL_LEAD_MS`), at most which a front's `registerSource` takes a price lane, so no record is
    ///         further ahead of any fill's clock in that block than the fill admits.
    uint256 public immutable MAX_LEAD_MS;
    /// @notice How long a replaced print is held on the fronts' clock, ms: two of that clock's steps, 400 ms where it
    ///         counts Base's blocks or reads their milliseconds (a block is 200 ms), 2 s where it is the seal time. A
    ///         check asked for a side reads every print held, so a print prices that side alone only once this long
    ///         has passed since the last post. The two words a feed holds cover two clock times, all that fall inside
    ///         the span where the clock moves in steps of half of it. The 400 ms assumes Base's 200 ms blocks
    ///         (`PropAMMClock.BLOCK_MS`), two clock steps a hold, fixed at construction: if Base's block interval
    ///         changes, the lane is redeployed (a successor lane) for the new one.
    uint256 public immutable HOLD_MS;

    /// @notice Pyth's Pro verifier, which admits a signer past the pin.
    address public immutable VERIFIER;
    /// @notice The Pyth channel every post must carry, 1 to 3.
    uint8 public immutable override channel;
    /// @dev The registered readers, set at construction; zero past the last one named.
    address internal immutable READER0;
    address internal immutable READER1;
    address internal immutable READER2;
    /// @notice The front whose protocol guardian or the protocol owner may cut the pin at once (a stop-only power).
    address public immutable GOVERNOR;
    /// @dev The fronts' clock (`PropAMMClock`): its mode, and the block and milliseconds mode 2 counts from.
    uint256 internal immutable CLOCK_MODE;
    uint256 internal immutable CLOCK_BLOCK;
    uint256 internal immutable CLOCK_MS;
    /// @dev The feed time an equity feed's fresh print may move past the stored one's before it counts as the first
    ///      print after a gap, ms (`EquityRecord.print`), at most `EquityRecord.REOPEN_MS`.
    uint256 internal immutable GAP_MS;

    /// @notice The pinned signer, honoured without asking the verifier until `pinValidUntil` (`PythProCheck.livePin`);
    ///         any signer Pyth's verifier accepts is accepted too. Both at slot 0 (bits 0-159 and 160-207).
    address public signer;
    /// @notice The pin's end, unix seconds; zero for a pin never confirmed or one cut (`cutPin`).
    uint48 public pinValidUntil;
    /// @notice The pin's cut, set by `cutPin` and cleared only by `liftPinCut`: while it stands `refreshPin` and
    ///         `repin` refuse, so nothing writes `pinValidUntil`, which `cutPin` zeroed, the pin stays dark and Pyth's
    ///         verifier decides every signer. Slot 0, bit 208.
    bool public pinCut;
    /// @dev The number of feeds listed, which is the last slot taken (slots run from 1); storage slot 1. A feed's
    ///      id, quorum, jump threshold and 24/7 mark live in its record alone (bits 212-243, 180-187, 188-203 and
    ///      204), which no post moves.
    uint256 internal _count;
    /// @dev Per feed id: its slot, zero for an id the price lane does not list (`indexOf`, a poster's slot); a map at
    ///      storage slot 2, id `x`'s at keccak256(abi.encode(x, 2)).
    mapping(uint32 => uint256) internal _indexOf;
    /// @dev Per feed, by slot: its record (`IPriceLane`), the price lane's own bits holding its quorum (180-187) and
    ///      jump threshold (188-203), so a post reads one storage slot for each feed it stores, a 24/7 feed's mark
    ///      (204, `ALWAYS_BIT`) and its feed's own session as last recorded (205-207, `OWN`; 208-211 reserved, zero),
    ///      and the print's leg confidence at 244-255. Slot s's at storage slot 3 + s; slot 0, which no feed takes,
    ///      reads zero.
    uint256[65536] internal _records;
    /// @dev Per equity feed: the price before each of its last four jumps, the jump tagged t at bit 64 x (t mod 4).
    ///      Slot s's at storage slot 65,539 + s.
    uint256[65536] internal _jumps;
    /// @dev Per equity feed: its open window (`EquityRecord.print`: the price fresh prints are measured from, 0-63, and
    ///      the window's end, feed ms, 64-111), zero for none. Slot s's at storage slot 131,075 + s.
    uint256[65536] internal _wins;
    /// @dev Per feed: the prices it kept during the latest clock time a post stored a print of it (`_hold`): [0-63]
    ///      the lowest | [64-127] the highest, each exponent -8 | [128-175] that clock time, ms | [176-255] 0. Among
    ///      them is the print that stood when that time's first post arrived. Zero before the feed's first print. Slot
    ///      s's at storage slot 196,611 + s.
    uint256[65536] internal _held;
    /// @dev Per feed: `_held` as it stood for the clock time before, written only where that time lies under
    ///      `HOLD_MS` before the next post's; a reader tells an older word by its own time. Slot s's at storage slot
    ///      262,147 + s.
    uint256[65536] internal _heldBefore;

    /// @notice A post stored `stored` feeds' records, none where it was a no-op.
    event Posted(uint256 stored);
    /// @notice `repin` made `signer` the pin.
    event Repinned(address signer);
    /// @notice `refreshPin` honoured `signer` until `validUntil`, unix seconds.
    event PinRefreshed(address signer, uint48 validUntil);
    /// @notice `by` ended the pin's window (`cutPin`).
    event PinCut(address by);
    /// @notice The protocol owner lifted the pin's cut (`liftPinCut`).
    event PinCutLifted(address by);
    /// @notice A feed listed at `slot`, by the constructor or an append; `jumpBps` as `FeedConfig` holds it, a 24/7
    ///         feed's mark included.
    event FeedListed(uint256 indexed slot, uint32 pythId, uint8 quorum, uint16 jumpBps);
    /// @notice An equity feed's print at `slot` tagged a jump: the tag and the prices before and after it.
    event Jumped(uint256 indexed slot, uint256 tag, uint256 before, uint256 price);

    /// @notice A feed as the constructor and `extendFeeds` list it.
    struct FeedConfig {
        uint32 pythId; // the feed's Pyth id, nonzero
        uint8 quorum; // the publishers a print must reach, nonzero
        // the jump threshold, bp, at most `EquityRecord.MAX_JUMP_BPS`; zero: not an equity feed. Bit 15 beside a
        // threshold marks a 24/7 feed, whose prints outside its regular session read `EquityRecord.ALWAYS`
        uint16 jumpBps;
    }

    /// @param verifier Pyth's Pro verifier.
    /// @param signer_ The pinned signer, honoured only once the verifier has confirmed it; zero for none.
    /// @param channel_ The Pyth channel every post must carry, 1 to 3.
    /// @param clockMode The fronts' clock mode (`PropAMMClock`), with `clockBlock` and `clockMs` its origin in mode 2.
    /// @param gapMs `GAP_MS`, 1 to `EquityRecord.REOPEN_MS`.
    /// @param leadMs `MAX_LEAD_MS`, at most 4,000: the fronts' `PULL_LEAD_MS` on this chain.
    /// @param feeds The first feeds, at slots 1 up: one to `MAX_FEEDS`.
    /// @param readers At most three (the front, its lens), as no reader is added after construction.
    /// @param governor The front (its predicted address before it exists), whose protocol guardian or the protocol
    ///        owner may cut the pin.
    constructor(
        address verifier,
        address signer_,
        uint8 channel_,
        uint256 clockMode,
        uint256 clockBlock,
        uint256 clockMs,
        uint256 gapMs,
        uint256 leadMs,
        FeedConfig[] memory feeds,
        address[] memory readers,
        address governor
    ) {
        if (feeds.length == 0 || feeds.length > MAX_FEEDS || readers.length == 0 || readers.length > 3) {
            revert BadUpdate();
        }
        if (
            channel_ == 0 || channel_ > 3 || governor == address(0) || clockMode > PropAMMClock.BLOCKS || gapMs == 0
                || gapMs > EquityRecord.REOPEN_MS || leadMs > MAX_PULL_LEAD_MS
        ) revert BadUpdate();
        VERIFIER = verifier;
        GOVERNOR = governor;
        CLOCK_MODE = clockMode;
        CLOCK_BLOCK = clockBlock;
        CLOCK_MS = clockMs;
        GAP_MS = gapMs;
        MAX_LEAD_MS = leadMs;
        HOLD_MS = clockMode == PropAMMClock.SEAL ? 2000 : 2 * PropAMMClock.BLOCK_MS;
        signer = signer_;
        // the pin is honoured without the verifier only once the verifier has confirmed it
        if (signer_ != address(0) && PythProCheck.signerOk(signer_, address(0), verifier)) {
            pinValidUntil = uint48(block.timestamp + PythProCheck.PIN_TTL_SEC);
        }
        channel = channel_;
        READER0 = readers[0];
        READER1 = readers.length > 1 ? readers[1] : address(0);
        READER2 = readers.length > 2 ? readers[2] : address(0);
        for (uint256 i; i < feeds.length; ++i) {
            _list(feeds[i], i + 1);
        }
    }

    // ================================================================ reads
    /// @inheritdoc IPriceLane
    function records(uint256 i, uint256 j) external view returns (uint256 ri, uint256 rj) {
        if (msg.sender != READER0 && msg.sender != READER1 && msg.sender != READER2) revert NotReader();
        // a slot past 65,535 holds no record, as no feed is listed there
        if (i < 65_536) ri = _records[i];
        if (j < 65_536) rj = _records[j];
    }

    /// @inheritdoc IPriceLane
    function clockConfig() external view returns (uint256 mode, uint256 block0, uint256 ms0) {
        return (CLOCK_MODE, CLOCK_BLOCK, CLOCK_MS);
    }

    /// @inheritdoc IPriceLane
    function jumpsOf(uint256 i) external view returns (uint256 jumpBps, uint256 prices) {
        if (msg.sender != READER0 && msg.sender != READER1 && msg.sender != READER2) revert NotReader();
        return ((_listed(i) >> 188) & 0xffff, _jumps[i]);
    }

    /// @inheritdoc IPythLane
    function feedCount() external view returns (uint256) {
        return _count;
    }

    /// @inheritdoc IPythLane
    function feedId(uint256 i) external view returns (uint32) {
        return uint32(_listed(i) >> 212);
    }

    /// @inheritdoc IPythLane
    function quorumOf(uint256 i) external view returns (uint8) {
        return uint8(_listed(i) >> 180);
    }

    /// @dev Slot `i`'s record, which its id makes nonzero for every listed feed (slots 1 to `_count`): any other slot,
    ///      0 among them, reverts as an index past the end of a list does (Panic 0x32).
    function _listed(uint256 i) internal view returns (uint256 r) {
        r = _records[i];
        if (r == 0) {
            assembly ("memory-safe") {
                mstore(0, shl(224, 0x4e487b71))
                mstore(4, 0x32)
                revert(0, 0x24)
            }
        }
    }

    /// @inheritdoc IPythLane
    function indexOf(uint32 pythId) external view returns (uint256) {
        return _indexOf[pythId];
    }

    /// @inheritdoc IPriceLane
    function isReader(address who) external view returns (bool) {
        return who != address(0) && (who == READER0 || who == READER1 || who == READER2);
    }

    /// @notice `IPriceCheck.check` on a pair's kept print, the empty update alone, served to the registered readers.
    ///         Every refusal reverts, as a price check's does.
    /// @dev The two slots must differ (one feed against itself prices at a constant 10^k), and each record must carry
    ///      a print at its quorum (bit 115); no vendor id is compared, as a listed slot's feed never changes. The
    ///      fourth word is the pair's confidence: both legs' (bits 244-255, 1 bp units) summed, in ppm, or
    ///      `CONF_SATURATED` where either leg's field is saturated. Where flag bit 1 asks, a fifth word follows, the
    ///      base's record as stored (bits 0-179 the record an asset module reads, 180-255 the price lane's own), so the
    ///      answer is exactly five words then and four otherwise.
    ///      Asked for a side (flags bit 2), the cross is that side's taker's worst over the held prints
    ///      (`_heldPrice`): for a taker selling the base, the lowest base price over the highest quote price, rounded
    ///      down; for one buying it (bit 3), the highest over the lowest, rounded up. The times, the confidence and
    ///      the record stay the kept print's, and the confidence carries bit 255, by which the front tells a price
    ///      lane that holds prints from one that ignores the flag, and at bits 128-223 the kept cross itself
    ///      (pa x 10^k / pb on the kept prints, rounded down), which the front books the fill's fee at.
    /// @param update Empty: the check reads the kept print alone.
    /// @param flags [0] the front's lease, which the price lane ignores (it keeps no trust a read could honour) | [1]
    ///        the base's record wanted, an asset-module pair's | [2] a side's price wanted, over the held prints | [3]
    ///        that side: set where the taker buys the base | [4-7] reserved, ignored | [8-23] the base feed's slot |
    ///        [24-39] the quote feed's, as the source entry holds them | [40-255] reserved, ignored.
    /// @param k The pair's cross scale.
    /// @return ta The base leg's feed time, µs.
    /// @return tb The quote leg's feed time, µs.
    /// @return px The cross P = pa x 10^k / pb, rounded down (up for a buying taker's side), nonzero and under 2^96.
    /// @return conf The pair's confidence, ppm: `CONF_SATURATED` where either leg's field is saturated; where a side
    ///         was asked, bit 255 set and the kept cross at bits 128-223 (under 2^96, or zero where it is not).
    function check(bytes calldata update, uint256 flags, uint256 k)
        external
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf)
    {
        if (msg.sender != READER0 && msg.sender != READER1 && msg.sender != READER2) revert NotReader();
        uint256 sb = (flags >> 8) & 0xffff;
        uint256 sq = (flags >> 24) & 0xffff;
        uint256 ra = _records[sb];
        uint256 rb = _records[sq];
        uint256 pa = ra & M64;
        uint256 pb = rb & M64;
        if (update.length != 0 || pa == 0 || pb == 0 || k > 58 || sb == sq || ((ra & rb) >> 115) & 1 == 0) {
            revert BadUpdate();
        }
        unchecked {
            // a side's price: each leg's held print that is worse for that side's taker, the quote leg's the other way
            uint256 up;
            if ((flags >> 2) & 1 != 0) {
                // the kept cross, as an unsided check answers it, before the held prints move either leg
                uint256 kp = pa * 10 ** k / pb;
                conf = (1 << 255) | (kp >> 96 == 0 ? kp << 128 : 0);
                up = (flags >> 3) & 1;
                pa = _heldPrice(sb, pa, up != 0);
                pb = _heldPrice(sq, pb, up == 0);
            }
            // pa under 2^63 (every stored price is) and 10^k at most 10^58, under 2^193, so pa x 10^k stays under
            // 2^256; each time is under 2^48 ms; pb is nonzero, and the division still checks it
            px = (pa * 10 ** k + up * (pb - 1)) / pb;
            if (px == 0 || px >> 96 != 0) revert BadUpdate();
            ta = ((ra >> 64) & M48) * 1000;
            tb = ((rb >> 64) & M48) * 1000;
            // each leg's 12 bits, 1 bp units: the sum at most 819,000 ppm; a saturated leg may stand for any wider
            // confidence, so it answers one past every listing's ceiling
            conf |= ra >> 244 == 0xfff || rb >> 244 == 0xfff ? CONF_SATURATED : ((ra >> 244) + (rb >> 244)) * 100;
        }
        if ((flags >> 1) & 1 != 0) {
            assembly ("memory-safe") {
                let m := mload(0x40)
                mstore(m, ta)
                mstore(add(m, 0x20), tb)
                mstore(add(m, 0x40), px)
                mstore(add(m, 0x60), conf)
                mstore(add(m, 0x80), ra)
                return(m, 0xa0)
            }
        }
    }

    /// @dev Feed `i`'s held print that is worse for a taker than its kept price `p`: the highest (`high`) or the
    ///      lowest of `p` and the prices `_held` and `_heldBefore` name, each read while the fronts' clock is under
    ///      `HOLD_MS` past its own time (a time ahead of the clock counts as held). `_heldBefore` is older than
    ///      `_held`, so it is read only while that one is held.
    function _heldPrice(uint256 i, uint256 p, bool high) internal view returns (uint256) {
        // times are 48 bits and `HOLD_MS` at most 2,000: no sum overflows
        unchecked {
            uint256 nowMs = PropAMMClock.nowMs(CLOCK_MODE, CLOCK_BLOCK, CLOCK_MS);
            uint256 h = _held[i];
            for (uint256 n; n < 2 && h != 0 && ((h >> 128) & M48) + HOLD_MS > nowMs; ++n) {
                uint256 q = high ? (h >> 64) & M64 : h & M64;
                if (high ? q > p : q < p) p = q;
                h = _heldBefore[i];
            }
            return p;
        }
    }

    /// @dev A stored print's hold: feed `i` kept `p0` (zero before its first print) and now keeps `p1`, at clock time
    ///      `nowMs`. A second post of one clock time widens that time's lowest and highest; the first post of a later
    ///      one starts them at `p0` and `p1`, the earlier word moved to `_heldBefore` while it is still held.
    function _hold(uint256 i, uint256 p0, uint256 p1, uint256 nowMs) internal {
        unchecked {
            uint256 h = _held[i];
            uint256 t = (h >> 128) & M48;
            uint256 lo = h & M64;
            uint256 hi = (h >> 64) & M64;
            if (h == 0 || t != nowMs) {
                if (h != 0 && t + HOLD_MS > nowMs) _heldBefore[i] = h;
                lo = p0 == 0 ? p1 : p0;
                hi = lo;
            }
            if (p1 < lo) lo = p1;
            if (p1 > hi) hi = p1;
            _held[i] = lo | (hi << 64) | (nowMs << 128);
        }
    }

    /// @notice True: no trust is cached here, and no storage build calls it (`IPriceLane.check`).
    function cacheValid() external pure returns (bool) {
        return true;
    }

    // ================================================================ the list
    /// @notice The front's owner (its timelock: 10 days, which the protocol guardian may cancel) appends `f` at the
    ///         next slot, under the constructor's refusals, up to `MAX_FEEDS`. It changes no listed feed and names no
    ///         source.
    function extendFeeds(FeedConfig calldata f) external {
        if (msg.sender != IPinGovernor(GOVERNOR).owner()) revert NotOwner();
        uint256 n = _count;
        if (n >= MAX_FEEDS) revert BadUpdate();
        _list(f, n + 1);
    }

    /// @dev Lists `f` at slot `s`, one past the list's last: a nonzero id not yet listed, a nonzero quorum and a jump
    ///      threshold at most `EquityRecord.MAX_JUMP_BPS`, a 24/7 feed's mark (`jumpBps` bit 15) only beside a
    ///      threshold; its record starts with no print and no session, its quorum, jump threshold and mark in the
    ///      price lane's own bits and the feed's own id, so a post proves which feed a slot holds.
    function _list(FeedConfig memory f, uint256 s) internal {
        uint256 bps = f.jumpBps & 0x7fff;
        uint256 always = f.jumpBps >> 15;
        if (
            f.pythId == 0 || f.quorum == 0 || bps > EquityRecord.MAX_JUMP_BPS || (always != 0 && bps == 0)
                || _indexOf[f.pythId] != 0
        ) revert BadUpdate();
        _count = s;
        _indexOf[f.pythId] = s;
        _records[s] = (uint256(f.quorum) << 180) | (bps << 188) | (always << ALWAYS_BIT) | (uint256(f.pythId) << 212);
        emit FeedListed(s, f.pythId, f.quorum, f.jumpBps);
    }

    // ================================================================ posts
    /// @notice Posts a Pyth Pro EVM update `u`: envelope magic 0x2a22999a | r | s | v - 27 | payload length (u16) |
    ///         payload, the payload 0x93c7d375 | timestamp µs (u64) | channel | feed count | feeds. `at` holds two
    ///         bytes per feed, big-endian, in the update's order: the feed's slot in the list (`indexOf(id)`), or 0 to
    ///         skip it. A feed whose slot holds another feed's record, or none, is skipped as a 0 is, so a wrong slot
    ///         costs only that feed; an `at` of another length than twice the feed count reverts.
    function post(bytes calldata u, bytes calldata at) external {
        uint256 plen = _envelope(u);
        uint256 p;
        uint256 head;
        assembly ("memory-safe") {
            p := add(u.offset, ENVELOPE)
            head := calldataload(p)
        }
        if (head >> 224 != 0x93c7d375 || (head >> 152) & 0xff != channel) revert BadUpdate();
        // the newest a stored time may be, above bit 64 (the fronts' clock in this block, read once, plus the lead),
        // and the payload's own time below it, ms
        uint256 times = ((PropAMMClock.nowMs(CLOCK_MODE, CLOCK_BLOCK, CLOCK_MS) + MAX_LEAD_MS) << 64)
            | (((head >> 160) & M64) / 1000);
        uint256 count = (head >> 144) & 0xff;
        if (at.length != count << 1) revert BadUpdate();
        uint256 pos = p + 14;
        uint256 stored;
        for (uint256 f; f < count; ++f) {
            uint256 ix;
            // feed f's slot, the two bytes at 2f, inside `at` by the length check
            assembly ("memory-safe") {
                ix := shr(240, calldataload(add(at.offset, shl(1, f))))
            }
            (pos, stored) = _feed(pos, ix, times, stored);
        }
        if (pos != p + plen) revert BadUpdate();
        emit Posted(stored);
    }

    /// @notice Anyone: re-pins the signer to that of a validly signed update, only while the current pin is one Pyth's
    ///         verifier does not accept and no cut stands (`pinCut`).
    function repin(bytes calldata u) external {
        if (pinCut) revert PinIsCut();
        if (PythProCheck.signerOk(signer, address(0), VERIFIER)) revert NotStale();
        address s = _recover(u);
        if (!PythProCheck.signerOk(s, address(0), VERIFIER)) revert BadPullSigner();
        signer = s;
        pinValidUntil = uint48(block.timestamp + PythProCheck.PIN_TTL_SEC);
        emit Repinned(s);
    }

    /// @notice Anyone: honours the pin for another `PIN_TTL_SEC`, confirming with Pyth's verifier each time that it
    ///         still accepts the pin, unless a cut stands (`pinCut`).
    function refreshPin() external {
        if (pinCut) revert PinIsCut();
        address s = signer;
        if (!PythProCheck.signerOk(s, address(0), VERIFIER)) revert BadPullSigner();
        uint48 until = uint48(block.timestamp + PythProCheck.PIN_TTL_SEC);
        pinValidUntil = until;
        emit PinRefreshed(s, until);
    }

    /// @notice The front's protocol guardian or the protocol owner ends the pin's window at once (a key Pyth dropped,
    ///         or one that leaked), and the cut stands until the protocol owner lifts it (`liftPinCut`): until then
    ///         Pyth's verifier decides every signer, whatever it still accepts, and `refreshPin` and `repin` refuse.
    ///         Stop-only: it opens nothing.
    function cutPin() external {
        IPinGovernor g = IPinGovernor(GOVERNOR);
        if (msg.sender != g.protocolGuardian() && msg.sender != g.instantOwner()) revert NotGuardian();
        pinValidUntil = 0;
        pinCut = true;
        emit PinCut(msg.sender);
    }

    /// @notice The protocol owner (`instantOwner`, as the front's `liftLeaseCut`; not the front's owner, its timelock)
    ///         lifts the cut. The lift honours nothing itself: the pin stays dark until a `refreshPin`, which only a
    ///         key the verifier accepts passes, or a `repin` once it drops that key. Anyone may refresh a leaked key
    ///         the verifier still accepts the moment the cut lifts, so the protocol owner lifts only once Pyth has
    ///         dropped it.
    function liftPinCut() external {
        if (msg.sender != IPinGovernor(GOVERNOR).instantOwner()) revert NotOwner();
        pinCut = false;
        emit PinCutLifted(msg.sender);
    }

    /// @dev The envelope: the magic, an update that ends exactly at its declared payload length, v of 0 or 1, and a
    ///      signer that is the pin or one Pyth's verifier accepts. Returns the payload length.
    function _envelope(bytes calldata u) internal view returns (uint256 plen) {
        address s = _recover(u);
        if (!PythProCheck.signerOk(s, PythProCheck.livePin(signer, pinValidUntil), VERIFIER)) revert BadPullSigner();
        plen = u.length - ENVELOPE;
    }

    /// @dev The signer `u` recovers to, nonzero, past the envelope's own checks: the magic, an update that ends exactly
    ///      at its declared payload length, and v of 0 or 1.
    function _recover(bytes calldata u) internal view returns (address s) {
        if (u.length < ENVELOPE + 14) revert BadUpdate();
        uint256 hw;
        assembly ("memory-safe") {
            hw := calldataload(add(u.offset, 39))
        }
        uint256 plen = hw & 0xffff;
        uint256 v = (hw >> 16) & 0xff;
        if (bytes4(u[0:4]) != 0x2a22999a || u.length != ENVELOPE + plen || v > 1) revert BadUpdate();
        bytes32 h = keccak256(u[ENVELOPE:]);
        s = ecrecover(h, uint8(v + 27), bytes32(u[4:36]), bytes32(u[36:68]));
        if (s == address(0)) revert BadUpdate();
    }

    /// @dev One feed at `pos`, named slot `ix` by the post: id (4) | property count (1) | (property id (1), value)...
    ///      Properties by id, never by offset; an unknown or repeated id reverts. Property 12 is a presence byte, then
    ///      the u64 time only when present (2 or 10 bytes); a presence other than 0 or 1 reverts. Slot 0 is skipped
    ///      before any storage read. Only a feed whose slot holds its own record is read further (its quorum and jump
    ///      threshold from it): a crypto feed that passes admission, is newer and at most `MAX_LEAD_MS` ahead of the
    ///      fronts' clock (`times` above bit 64, the clock plus the lead) is stored, its quality bit set and its leg
    ///      confidence (bits 244-255) its own; an equity feed's update folds into its record (`_equity`), its session
    ///      by the payload's time (`times` below bit 64), a print or none. A feed with no confidence (property 5)
    ///      carries no print: its price reads zero, which neither admission takes.
    function _feed(uint256 pos, uint256 ix, uint256 times, uint256 stored)
        internal
        returns (uint256 next, uint256 storedOut)
    {
        // unchecked: the cursor runs at most 255 feeds of at most 78 bytes each past the update's offset (a refused or
        // repeated property id reverts), pid x 8 is at most 2,040 and the count stored at most 255; calls stay checked
        unchecked {
            uint256 w;
            assembly ("memory-safe") {
                w := calldataload(pos)
            }
            uint256 id = w >> 224;
            uint256 n = (w >> 216) & 0xff;
            pos += 5;
            uint256 seen;
            uint256 price;
            uint256 pubs;
            uint256 expo;
            uint256 time;
            uint256 present;
            uint256 conf;
            for (uint256 i; i < n; ++i) {
                uint256 x;
                assembly ("memory-safe") {
                    x := calldataload(pos)
                }
                uint256 pid = x >> 248;
                // bytes per id, id byte included: 0-2: 9 | 3-4: 3 | 5: 9 | 6-8: refused | 9: 3 | 10-11: 9 | 12: 10
                uint256 step = (0x0a090903000000090303090909 >> (pid * 8)) & 0xff;
                if (pid > 12 || step == 0 || (seen >> pid) & 1 != 0) revert BadUpdate();
                seen |= 1 << pid;
                if (pid == 0) price = (x >> 184) & M64;
                else if (pid == 3) pubs = (x >> 232) & 0xffff;
                else if (pid == 4) expo = (x >> 232) & 0xffff;
                else if (pid == 5) conf = (x >> 184) & M64;
                else if (pid == 9) seen |= ((x >> 232) & 0xffff) << 16; // the session, above the ids seen
                else if (pid == 12) {
                    present = (x >> 240) & 0xff;
                    if (present > 1) revert BadUpdate();
                    if (present == 0) step = 2;
                    else time = (x >> 176) & M64;
                }
                pos += step;
            }
            next = pos;
            storedOut = stored;
            if (ix == 0) return (next, storedOut);
            uint256 rec = _records[ix];
            // the slot binds to the feed's own record: a listed feed's id is nonzero
            if (id == 0 || (rec >> 212) & M32 != id) return (next, storedOut);
            if ((seen >> 5) & 1 == 0) price = 0;
            // the leg's confidence over its price, both at the print's own exponent: ceil(conf x 10^6 / price) ppm,
            // then 1 bp units rounded up, at most 4,095 (a u64 confidence x 10^6 stays under 2^84)
            if (price != 0) {
                conf = ((conf * 1e6 + price - 1) / price + 99) / 100;
                if (conf > 0xfff) conf = 0xfff;
            }
            if ((rec >> 188) & 0xffff != 0) {
                if (_equity(ix, rec, seen | (conf << 32), price, pubs, expo, time, present, times)) {
                    storedOut = stored + 1;
                }
                return (next, storedOut);
            }
            // admission: price > 0 (and < 2^63), exponent -8, feed time present, quorum
            if (
                seen & 0x1019 != 0x1019 || price == 0 || price >= 1 << 63 || expo != 0xfff8 || present != 1
                    || pubs < (rec >> 180) & 0xff
            ) return (next, storedOut);
            uint256 tMs = time / 1000;
            // no time ahead of the fronts' clock (plus the lead), none at or above 2^48 ms: the old record stays
            if (tMs > times >> 64 || tMs >> 48 != 0) return (next, storedOut);
            if (tMs > ((rec >> 64) & M48)) {
                // the print at its quorum (bit 115), the session unknown, the price lane's own bits kept, its own
                // leg confidence, all of bits 244-255 rewritten
                _records[ix] = price | (tMs << 64) | (1 << 115) | (((rec >> 180) << 180) & ~CONF) | (conf << 244);
                // the print it replaces is held (`times` above bit 64 is the clock plus the lead)
                _hold(ix, rec & M64, price, (times >> 64) - MAX_LEAD_MS);
                storedOut = stored + 1;
            }
        }
    }

    /// @dev An equity feed's update, its session (property 9) and its payload's time required, neither the payload's
    ///      time nor its print's more than `MAX_LEAD_MS` ahead of the fronts' clock: the session folds in by the
    ///      payload's time (`EquityRecord.session`, or on a 24/7 feed `EquityRecord.always`, from any update that
    ///      carries it, as Pyth updates the session where no new aggregate formed), then a print admitted as any
    ///      feed's (exponent -5 scaled to -8 first) and newer than the stored one folds in by `EquityRecord.print`,
    ///      tagging a jump where it is one, at the threshold and quorum the stored record `rec0` carries, with its own
    ///      leg confidence (`seen` bits 32-43 to bits 244-255); an update that moves only the session keeps the kept
    ///      print's. Whether the record changed.
    function _equity(
        uint256 i,
        uint256 rec0,
        uint256 seen,
        uint256 price,
        uint256 pubs,
        uint256 expo,
        uint256 time,
        uint256 present,
        uint256 times
    ) internal returns (bool) {
        uint256 bound = times >> 64;
        uint256 tpMs = times & M64;
        if (tpMs > bound || (seen >> 9) & 1 == 0) return false;
        uint256 rec = EquityRecord.pythSession((seen >> 16) & 0xffff);
        rec = (rec0 >> ALWAYS_BIT) & 1 != 0
            ? EquityRecord.always(rec0, rec, OWN, tpMs)
            : EquityRecord.session(rec0, rec, tpMs);
        if (expo == 0xfffb) (price, expo) = (price * 1000, 0xfff8);
        uint256 fMs = time / 1000;
        if (
            seen & 0x1019 == 0x1019 && price != 0 && price < 1 << 63 && expo == 0xfff8 && present == 1
                && pubs >= (rec0 >> 180) & 0xff && fMs <= bound && fMs > (rec >> 64) & M48
        ) {
            // the pre-jump prices read only where the print tags a jump: `j` then holds the one slot it writes
            (uint256 r, uint256 win, uint256 j) =
                EquityRecord.print(rec, _wins[i], 0, price, fMs, tpMs, ((rec0 >> 188) & 0xffff) | (GAP_MS << 16));
            uint256 tag = (r >> 164) & 0xffff;
            if (tag != (rec >> 164) & 0xffff) {
                uint256 sh = 64 * (tag & 3);
                _jumps[i] = (_jumps[i] & ~(M64 << sh)) | j;
                emit Jumped(i, tag, j >> sh, price);
            }
            _wins[i] = win;
            rec = r;
            // the print it replaces is held (`bound` is the clock plus the lead)
            _hold(i, rec0 & M64, price, bound - MAX_LEAD_MS);
        }
        // a print folded in moved the time: the update's own leg confidence, all of bits 244-255 rewritten
        if ((rec ^ rec0) & (M48 << 64) != 0) rec = (rec & ~CONF) | (((seen >> 32) & 0xfff) << 244);
        if (rec == rec0) return false;
        _records[i] = rec;
        return true;
    }
}

src/propamm/PythProBase.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {PythProCheck} from "src/propamm/libraries/PythProCheck.sol";
import {PropAMMClock} from "src/propamm/libraries/PropAMMClock.sol";

/// @notice What a source reads of its front: the pull lead, how far after the clock a print's feed time may lie.
interface IFrontLead {
    /// @notice The front's maker-time windows and clock (`PropAMMFront.clock`); a source reads its pull lead, how
    ///         far after the clock a print's feed time may lie, ms.
    function clock() external view returns (PropAMMClock.Timing memory);
}

/// @notice A Pyth Pro price source's common part: its configuration (the front it answers, the vendor's verifier, the
///         pinned signer and its end, the feeds' check word, the front's pull lead read at construction), the signer
///         rule, the lease's renewal test and `IPriceCheck.check`, answered without an ABI decoder: the call as the
///         front writes it (the selector, the update's offset 0x60, the front's flags, k, the update), bounded by the
///         calldata's end, from the front alone where the source names one; any other call reverts empty. A source
///         answers it (`_answer`) in four words, the fourth the pair's confidence, or five where it serves an
///         asset-module pair's record.
abstract contract PythProBase {
    /// @notice The print's signer fails the signer rule, the pin named at construction is one the verifier refuses, or
    ///         `PrintLaneSource` holds no print for the read.
    error BadPullSigner();

    /// @dev The front this source answers, or zero for any caller.
    address internal immutable FRONT;
    /// @dev Pyth's Pro verifier, whose `isValidSigner` view backs the pin.
    address internal immutable VERIFIER;
    /// @dev The pinned signer, one the verifier accepted at deployment (zero for none), and its validity's end, unix s.
    address internal immutable PIN;
    uint256 internal immutable PIN_UNTIL;
    /// @dev `PythProCheck`'s configuration but for its scale.
    uint256 internal immutable CFG;
    /// @dev The front's pull lead at construction, ms (zero with no front): a posted leg may lie this far after the
    ///      block's time and no further.
    uint256 internal immutable LEAD_MS;

    /// @param front The front this source answers, or zero for any caller.
    /// @param verifier Pyth's Pro verifier.
    /// @param pin The pinned signer (zero for none).
    /// @param pinUntil The pin's end, unix seconds.
    /// @param word [0-31] base feed id | [32-63] quote feed id | [64-71] base quorum | [72-79] quote quorum | [80-87]
    ///        channel.
    /// @param flags More of `PythProCheck`'s configuration bits, above its scale's.
    constructor(address front, address verifier, address pin, uint256 pinUntil, uint256 word, uint256 flags) {
        FRONT = front;
        VERIFIER = verifier;
        PIN = pin;
        PIN_UNTIL = pinUntil;
        CFG = (word & 0xffffffffffffffff) | (((word >> 64) & 0xff) << 64) | (((word >> 72) & 0xff) << 80)
            | (((word >> 80) & 0xff) << 96) | flags;
        LEAD_MS = front == address(0) ? 0 : IFrontLead(front).clock().pullLeadMs;
    }

    /// @notice The source's configuration: its front (zero: any caller), Pyth's verifier, the pinned signer (zero:
    ///         none) and its end, and the front's pull lead it holds posts to, ms.
    function config() external view returns (address front, address verifier, address pin, uint256 pinUntil, uint256 lead) {
        return (FRONT, VERIFIER, PIN, PIN_UNTIL, LEAD_MS);
    }

    /// @notice The lease's renewal test: the pin is one Pyth's verifier accepts now, and up to its end; a source with
    ///         no pin caches no trust, so a renewal finds it valid.
    function cacheValid() external view returns (bool) {
        return PIN == address(0) || (block.timestamp <= PIN_UNTIL && PythProCheck.signerOk(PIN, address(0), VERIFIER));
    }

    /// @notice `IPriceCheck.check`, without an ABI decoder.
    fallback() external {
        bytes calldata u;
        uint256 k;
        uint256 flags;
        address front = FRONT;
        assembly ("memory-safe") {
            if iszero(and(eq(shr(224, calldataload(0)), 0x1c8026cb), eq(calldataload(4), 0x60))) { revert(0, 0) }
            if iszero(or(iszero(front), eq(caller(), front))) { revert(0, 0) }
            flags := calldataload(0x24)
            k := calldataload(0x44)
            u.length := calldataload(0x64)
            u.offset := 0x84
            if gt(add(0x84, u.length), calldatasize()) { revert(0, 0) }
        }
        (uint256 ta, uint256 tb, uint256 px, uint256 conf, uint256 rec, uint256 size) = _answer(u, flags, k);
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, ta)
            mstore(add(m, 0x20), tb)
            mstore(add(m, 0x40), px)
            mstore(add(m, 0x60), conf)
            mstore(add(m, 0x80), rec)
            return(m, size)
        }
    }

    /// @dev A carried print `u`, checked by the pair's feeds and the signer rule: its legs' times (µs), the cross at
    ///      scale `k` and the pair's confidence, ppm.
    function _carried(bytes calldata u, uint256 flags, uint256 k)
        internal
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf)
    {
        address s;
        (,, ta, tb, px, s,, conf) = PythProCheck.check(u, CFG | ((k & 0xff) << 104));
        if (!_signerOk(s, flags)) revert BadPullSigner();
    }

    /// @dev The signer rule: the pin while the front passes the listing's lease (flags bit 0) and the pin has not
    ///      ended, or a signer Pyth's verifier accepts.
    function _signerOk(address s, uint256 flags) internal view returns (bool) {
        return PythProCheck.signerOk(s, flags & 1 != 0 && block.timestamp <= PIN_UNTIL ? PIN : address(0), VERIFIER);
    }

    /// @dev The check's answer to update `u` under the front's `flags` at scale `k`: the legs' times (µs), the cross,
    ///      the pair's confidence (ppm, 0 for none), a fifth word, and the answer's size in bytes (0x80, or 0xa0 with
    ///      the fifth word).
    function _answer(bytes calldata u, uint256 flags, uint256 k)
        internal
        view
        virtual
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf, uint256 rec, uint256 size);
}

src/propamm/PythProReader.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice What a reader asks of its store at its construction.
interface IPythProList {
    /// @notice Lists a reader's two feed keys, refusing another front than the store's and a pair the store answers
    ///         no reader for.
    function listReader(address front, uint256 baseKey, uint256 quoteKey) external;
}

/// @notice A pair's Pyth Pro price source on a builder build that keeps nothing itself: it reads the chain's shared
///         price store (`PythProStore`), which holds every feed's kept print once for all the pairs that name it.
///         Anyone registers one for a pair (`registerSource`, by CREATE3 from the front at its id), so it needs no
///         front change.
/// @dev The rules of the reader:
///      - It answers its front alone, and only by passing the front's call to the store by STATICCALL with one word
///        appended, its two feed keys, and the store's answer or refusal back unchanged: `IPriceCheck.check` (the kept
///        print on an empty update, a carried print otherwise, a fifth word on an asset-module pair),
///        `IPriceCheck.cacheValid` and `IAssetSource.assetRecord`. Any other caller reverts empty.
///      - It holds no price and no storage. Its front, its store and its two keys are its immutables, so its code is
///        theirs alone: the store answers a caller only where the caller's code is a reader's of the store's front
///        and the store, holding the keys the call's last word names (`PythProStore.readerHash`), so no other contract
///        reads the store through one and no reader reads another pair's keys.
///      - Its constructor lists its keys at the store (`listReader`), which refuses another front and a pair the
///        store answers no reader for. A reader made while the store has no code lists nothing: the store's
///        constructor makes two such, with keys no reader is answered for, to learn the reader's code from them.
///      - It has no function of its own: the store answers its keys (`PythProStore.readerOf`), from its code.
contract PythProReader {
    /// @dev The front this reader answers.
    address internal immutable FRONT;
    /// @dev The price store it reads.
    address internal immutable STORE;
    /// @dev Its pair's two feed keys, the word it appends to every call it passes on: the base key at bits 0-87, the
    ///      quote key at 88-175.
    uint256 internal immutable KEYS;

    /// @param front The front this reader serves, the store's own (`listReader` refuses another).
    /// @param store The chain's price store.
    /// @param baseKey The base leg's feed key (`PythProStore`: the feed's Pyth id, its quorum, its jump threshold and
    ///        gap where it is an equity feed, its channel).
    /// @param quoteKey The quote leg's feed key, another feed on the same channel, no equity feed.
    constructor(address front, address store, uint256 baseKey, uint256 quoteKey) {
        FRONT = front;
        STORE = store;
        KEYS = baseKey | (quoteKey << 88);
        if (store.code.length != 0) IPythProList(store).listReader(front, baseKey, quoteKey);
    }

    /// @notice The front's call, passed to the store with the reader's keys appended; the store's answer, or its
    ///         refusal, passed back.
    fallback() external {
        address front = FRONT;
        address store = STORE;
        uint256 keys = KEYS;
        assembly ("memory-safe") {
            if iszero(eq(caller(), front)) { revert(0, 0) }
            let m := mload(0x40)
            let n := calldatasize()
            calldatacopy(m, 0, n)
            // the keys: the store reads them as the call's last word, whatever the front's call holds
            mstore(add(m, n), keys)
            // Yul evaluates arguments right to left: the call first, in its own statement
            let ok := staticcall(gas(), store, m, add(n, 0x20), 0, 0)
            returndatacopy(m, 0, returndatasize())
            if iszero(ok) { revert(m, returndatasize()) }
            return(m, returndatasize())
        }
    }
}

src/propamm/interfaces/IPriceSource.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice The front's one seam to a price vendor. A source is a contract anyone registers under a global id
///         (`registerSource`; its entry written once, never edited); each listing binds one and, if it likes, a
///         backup, its operator's choice (`setSource`).
/// @dev How the front reads a source, and what a wrong price can do:
///      - The front reads no vendor format: a builder build's fill asks a pull check (for its kept print, or for the
///        print a ticket fill carries), which the front itself deploys from its registrant's code at its registration
///        (CREATE3 at salt `bytes32(id)`) so a fill derives its address; a storage build's fill asks a stored price
///        lane (`IPriceLane`) for its kept print by the same check.
///      - On a listing of a crypto pair a wrong price only tightens or stops that listing: the price fence clamps
///        toward the pool, so it either refuses the listing's fills or leaves its maker's signed levels unclamped, the
///        risk a pair with no price source already carries.
///      - The protocol's spread fee is measured against the same price and bounded by the fill from above only, so the
///        more prints a source admits for one fill (a wider window, or either of two vendors), the more a poster, or a
///        taker carrying a print, may pick the one that cuts it.
interface IPriceCheck {
    /// @notice Verifies a vendor's signed update for a pair's two legs, writing nothing: a fill calls it by STATICCALL
    ///         under a gas cap, and a ticket fill passes a carried print's refusal's revert data on.
    /// @dev The source's word (its feeds, quorums, channel) is its own, fixed at deployment. The front takes exactly
    ///      five words under `flags` bit 1 and exactly four without it, and reads any other answer as a failure. The
    ///      source's window (its entry's, copied into the listing's price word) bounds the earlier leg's age at the
    ///      fill.
    /// @param update The vendor's update: empty asks a source that keeps prints for its kept print.
    /// @param flags The front's flags:
    ///        - bit 0: the listing's lease, under which the source may honour its cached trust (a pinned key, say).
    ///        - bit 1: set on every check of an asset-module pair (pair word bit 15) and on no other: asks a fifth
    ///          word, the base's record (`IAssetModule`: bits 0-179 as there, the rest the source's own). Such a pair's
    ///          source on a builder build serves its module that record too (`IAssetSource`).
    ///        - bits 2-3, on every storage build's print, both doors: bit 2 asks the price that is worst for the
    ///          fill's taker among the prints the price lane holds, bit 3 names that taker's side (set where it buys
    ///          the base). A source that holds prints answers `conf` with bit 255 set, which the front takes off
    ///          before the band reads it; one that ignores the flags answers its kept print with the bit clear, which
    ///          a PRINT or SESSION listing takes as its print and a tied listing's named fill as no price.
    ///        - bits 4-7: reserved, zero.
    ///        - bits 8-39, on a storage build: the source entry's base slot (8-23) and quote slot (24-39), by which a
    ///          stored price lane serving many pairs reads the pair's two records.
    ///        - bits 40-87: reserved, zero.
    /// @param k The pair's cross scale.
    /// @return ta The first leg's feed time, microseconds.
    /// @return tb The second leg's feed time, microseconds.
    /// @return px P = pa x 10^k / pb, rounded down, both legs at one exponent.
    /// @return conf The pair's confidence, ppm of P, both legs' summed, in whatever measure the source keeps (a
    ///         vendor's confidence, a quote's spread, two vendors' disagreement); 0 where it has none. Uncapped: the
    ///         front reads it against the listing's ceiling. Under bit 1 a fifth word follows, the base's record.
    function check(bytes calldata update, uint256 flags, uint256 k)
        external
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf);

    /// @notice Whether the source's cached trust (a pinned key, say) still holds by its vendor's own verifier: a
    ///         listing's daily lease renews only on true (`refreshLease`, anyone). A source with no cache answers true
    ///         and ignores the lease. A trust revoked after a renewal stays honoured until the lease lapses, at most a
    ///         day, unless the listing's operator or its pool's guardian, the protocol guardian or the protocol owner
    ///         cuts the lease.
    function cacheValid() external view returns (bool);
}

/// @notice An asset-module pair's source on a builder build (`IPriceCheck` under flags bit 1) also serves the pair's
///         module the base's record outside a fill (`IAssetFront.assetFacts`: the module's bind, latch, re-arms and
///         large syncs), which the front probes when a listing of such a pair binds it, so a source that answers a
///         fill but not the module is never bound. A storage build's stored price lane serves the same through
///         `IPriceLane` (`records`, `jumpsOf`).
interface IAssetSource {
    /// @notice The base's record as the source keeps it (the one its check answers as the fifth word) and the price
    ///         before each of its last four jumps (8 decimals, 64 bits each, the jump tagged t at bit 64 x (t mod 4)),
    ///         to the front alone; `lease` the listing's lease flag. Exactly two words.
    function assetRecord(bool lease) external view returns (uint256 record, uint256 prices);
}

/// @notice A storage build's stored price lane: a vendor's posted prints, one record per feed, each at a fixed slot.
///         A fill reads a pair's two by the price lane's `check` under a gas cap, and an asset module's facts read
///         the base's (`records`, `jumpsOf`).
/// @dev A record is the source-neutral record an asset module reads, but for its bits 180-243, where that record names
///      the tag's source and the front writes the price lane's own address with the feed's key folded in
///      (`PropAMMAsset.record`): [0-63] price, exponent -8 (zero: none) | [64-111] its time, ms | [112-114] the market
///      session (0 unknown, 1 closed, 2 pre-market, 3 regular, 4 post-market, 5 overnight, 6 a 24/7 feed's outside its
///      regular one) | [115] the print met its source's quorum, which every record a fill reads must have | [116-163]
///      the session's start, ms | [164-179] the jump tag | [180-211] the price lane's own, which every reader masks (a
///      Pyth price lane's: [180-187] the feed's quorum, [188-203] its jump threshold, bp, [204] a 24/7 feed, [205-207]
///      that feed's own session, [208-211] reserved) | [212-243] the price lane's own per-slot identity, opaque to the
///      front and never changed | [244-255] the price lane's own (a Pyth price lane's: the print's leg confidence, 1
///      bp units). A price lane's written obligation: a slot's feed never changes. The front checks no feed key, so a
///      fill and the front's `assetFacts` read a listing's records by slot alone.
interface IPriceLane {
    /// @notice `IPriceCheck.check` as a storage build calls it, on every fill.
    /// @dev The front reads an answer of any other size than five words under `flags` bit 1 and four without it as a
    ///      failure. A price lane need not answer `IPriceCheck.cacheValid`, which no storage build calls.
    /// @param update Empty, asking the price lane's kept print: any other update is refused, a refusal a ticket fill
    ///        carrying a print passes on.
    /// @param flags Bit 0 the front's lease, which a price lane may ignore; bit 1 set exactly on an asset-module pair;
    ///        bit 2 set on every fill's print, with its taker's side at bit 3 (`IPriceCheck.check`); bits 8-23 the base
    ///        feed's slot and 24-39 the quote's (the listing's source entry, 1-65,535 each, never equal); bits 40-87
    ///        zero.
    /// @param k The pair's cross scale.
    /// @return ta The first leg's feed time, as `IPriceCheck.check` answers it.
    /// @return tb The second leg's feed time, as `IPriceCheck.check` answers it.
    /// @return px The price, as `IPriceCheck.check` answers it.
    /// @return conf The pair's confidence, ppm, as `IPriceCheck.check` answers it. Under bit 1 a fifth word follows,
    ///         the base's record as stored.
    function check(bytes calldata update, uint256 flags, uint256 k)
        external
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf);

    /// @notice Records `i` and `j`, served to the price lane's registered readers alone.
    function records(uint256 i, uint256 j) external view returns (uint256 ri, uint256 rj);

    /// @notice Whether `who` may read records.
    function isReader(address who) external view returns (bool);

    /// @notice The front whose protocol guardian or the protocol owner may cut the price lane's pin. The front does not
    ///         check it at `registerSource`: a third-party price lane names its own.
    function GOVERNOR() external view returns (address);

    /// @notice The fronts' clock the price lane holds stored times to (`PropAMMClock`): its mode, and the block and
    ///         milliseconds mode 2 counts from. A front registers only a price lane on its own clock whose lead
    ///         (`MAX_LEAD_MS`) is at most its own pull lead, so no stored time is further ahead of the clock a fill
    ///         reads in the same block than the fill admits.
    function clockConfig() external view returns (uint256 mode, uint256 block0, uint256 ms0);

    /// @notice How far a stored feed time may run ahead of the fronts' clock in the post's block, ms.
    function MAX_LEAD_MS() external view returns (uint256);

    /// @notice Feed `i`'s jump threshold, bp (nonzero exactly on an equity feed, which only a stock's base leg may
    ///         read), and its last four pre-jump prices (exponent -8, 64 bits each); served to the registered readers.
    function jumpsOf(uint256 i) external view returns (uint256 jumpBps, uint256 prices);
}

src/propamm/interfaces/IPythLane.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IPriceLane} from "src/propamm/interfaces/IPriceSource.sol";

/// @notice The shared Pyth price lane of a storage-build chain, a stored price lane (`IPriceLane`): every feed it
///         lists, in a list that only grows, each at a fixed index, posted by anyone under a landing's full admission.
///         Its records are `IPriceLane`'s: a crypto feed's session unknown (0), its quality bit set (the price lane
///         stores only a print at its feed's quorum), no session start or jump tag, the feed's quorum and jump
///         threshold at bits 180-203, its Pyth id at bits 212-243, set when it is listed and never moved, and at bits
///         244-255 the print's leg confidence, 1 bp units.
interface IPythLane is IPriceLane {
    /// @notice Posts the Pyth Pro EVM update `u` with `at`, two bytes per feed in the update's order: the feed's slot,
    ///         big-endian (`indexOf(id)`, 1-65,535), or 0 to skip it. A feed whose slot holds another feed's record is
    ///         skipped too; an `at` whose length is not twice the update's feed count reverts.
    function post(bytes calldata u, bytes calldata at) external;
    /// @notice The Pyth id of the feed at slot `i`, the one its record carries at bits 212-243, for a lens or a
    ///         script's read-back (the front never reads it); a slot the price lane does not list reverts (Panic 0x32).
    function feedId(uint256 i) external view returns (uint32);
    /// @notice The number of feeds listed, which is the last slot (slots run from 1).
    function feedCount() external view returns (uint256);
    /// @notice The publisher quorum the price lane admits feed `i` under.
    function quorumOf(uint256 i) external view returns (uint8);
    /// @notice A feed's slot, its position plus one; zero when the price lane does not carry it.
    function indexOf(uint32 pythId) external view returns (uint256);
    /// @notice The Pyth channel every post must carry.
    function channel() external view returns (uint8);
    /// @notice The Pyth verifier the price lane admits signers under.
    function VERIFIER() external view returns (address);
}

src/propamm/libraries/EquityRecord.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice The equity facts a price source keeps in an asset-module pair's base record (`IAssetModule`'s source-neutral
///         record, bits 0-179) for the module to judge, folded from each verified update.
/// @dev The facts:
///      - The session: another session, carried by an update stamped after both the stored session's start and the
///        stored print, starts at that update's own time, so a change is recorded even where the price is carried
///        forward, and an older update never moves it back.
///      - The jump tag, which counts the base's jumps: a gap (the session changed since the stored print, or the feed's
///        time moved more than the source's gap past it) opens a window of that gap of feed time in which every fresh
///        print is measured from the price before the gap, so a lagging first print cannot hide a split behind it. One
///        that moved more than the source's threshold grows the tag, keeps the price it moved from as that jump's
///        pre-jump price, and keeps the window open for the gap from itself, measured from its own price, so a flip
///        back and the jump's return are tagged again. The tag only counts up, wrapping at 2^16.
///      - A reopen: a fresh print more than `REOPEN_MS` past the stored one moves the session's start to its update's
///        time, under any label, so a reopen under the same label still opens a quiet window.
///
///      - A 24/7 feed (an index priced around the clock, weekends and holidays included): its source records the
///        regular session where the feed reports it, and one session, `ALWAYS`, under every other the feed reports
///        (pre-market, post-market, overnight, closed, unknown), and keeps the feed's own beside the record
///        (`always`). So the regular hours stand under the regular session's own rules, and the rest of the week
///        under the 24/7 session's. A change of the feed's own session starts the record's session again at that
///        update's time, whether its code changes (an exchange's open and close) or not (a weekend's end), as a
///        session change does on any other source: each opens a quiet window and a jump's window. A feed that reports
///        one session throughout never restarts there.
///
///      Only the jump needs the threshold and the gap at the source: a later print overwrites the facts a module would
///      need to judge it afterwards.
library EquityRecord {
    /// @dev The record's session code of a 24/7 feed's prints outside its regular session, past the five a market
    ///      session maps to (`pythSession`), and the regular session's own.
    uint256 internal constant ALWAYS = 6;
    uint256 internal constant REGULAR = 3;
    /// @dev The jump threshold's ceiling, bp. A 3:2 split moves the print 33.3 % only on a flat share: a rise r in the
    ///      same gap leaves a move of 1 - (1 + r) x 2/3, so at 25 % the split is still tagged on any rise below 12.5 %.
    uint256 internal constant MAX_JUMP_BPS = 2_500;
    /// @dev A fresh print this far past the stored one reopens its session (an overnight close, an exchange pause),
    ///      ms; a source's gap is at most this.
    uint256 internal constant REOPEN_MS = 1_800_000;
    uint256 internal constant M48 = (1 << 48) - 1;
    uint256 internal constant M64 = (1 << 64) - 1;

    /// @dev Pyth's market session (property 9: 0 regular, 1 pre-market, 2 post-market, 3 overnight, 4 closed) as the
    ///      record's code (0 unknown, 1 closed, 2 pre-market, 3 regular, 4 post-market, 5 overnight); any other value
    ///      reads unknown.
    function pythSession(uint256 label) internal pure returns (uint256) {
        return label > 4 ? 0 : (0x15423 >> (4 * label)) & 7;
    }

    /// @dev `rec` after an update stamped `tMs` (its own time, ms) that carried session `s`.
    function session(uint256 rec, uint256 s, uint256 tMs) internal pure returns (uint256) {
        if (s != (rec >> 112) & 7 && tMs > (rec >> 116) & M48 && tMs > (rec >> 64) & M48) {
            rec = (rec & ~((uint256(7) << 112) | (M48 << 116))) | (s << 112) | (tMs << 116);
        }
        return rec;
    }

    /// @dev `rec` after an update stamped `tMs` from a 24/7 feed's source that carried the feed's own session `s`
    ///      (`pythSession`'s code), which the source keeps in the three bits of `rec` from bit `own`, among its own
    ///      above the record's (0-179). The record's session is `REGULAR` where the feed's own is, and `ALWAYS`
    ///      under any other. Pyth's closed label and an unknown one (codes 1 and 0) fold into `ALWAYS` too, by design:
    ///      a 24/7 feed prints around the clock whatever its market's label, and a print it stops renewing ages out
    ///      at the front, not by its session. The first update, and any that carries another session of the feed
    ///      than the kept one, starts the record's at the update's own time where it is stamped after both the stored
    ///      start and the stored print, so an older update never moves it back.
    function always(uint256 rec, uint256 s, uint256 own, uint256 tMs) internal pure returns (uint256) {
        uint256 code = s == REGULAR ? REGULAR : ALWAYS;
        if (
            (s != (rec >> own) & 7 || (rec >> 112) & 7 != code) && tMs > (rec >> 116) & M48
                && tMs > (rec >> 64) & M48
        ) {
            rec = (rec & ~((uint256(7) << 112) | (M48 << 116) | (uint256(7) << own))) | (code << 112)
                | (tMs << 116) | (s << own);
        }
        return rec;
    }

    /// @dev `rec`, its window `win` ([0-63] the price fresh prints are measured from, [64-111] the window's end, feed
    ///      ms; zero: none open) and its pre-jump prices `jumps` (the jump tagged t at bit 64 x (t mod 4)) after a
    ///      fresh print `price` (8 decimals, at its source's quorum) at feed time `fMs`, newer than the stored one,
    ///      from an update stamped `tMs`. `facts`: the source's jump threshold, bp (0-15), and its gap, ms (16-63).
    function print(uint256 rec, uint256 win, uint256 jumps, uint256 price, uint256 fMs, uint256 tMs, uint256 facts)
        internal
        pure
        returns (uint256, uint256, uint256)
    {
        uint256 last = rec & M64;
        uint256 lastMs = (rec >> 64) & M48;
        if (last != 0) {
            uint256 gapMs = facts >> 16;
            bool gap = lastMs < (rec >> 116) & M48 || fMs > lastMs + gapMs;
            uint256 end = (win >> 64) & M48;
            // open while the stored print lies inside it, so the first print past its end is measured too
            bool open = win != 0 && lastMs <= end;
            if (!gap && !open) {
                win = 0;
            } else {
                uint256 ref = open ? win & M64 : last;
                if ((price > ref ? price - ref : ref - price) * 1e4 > (facts & 0xffff) * ref) {
                    uint256 tag = (((rec >> 164) & 0xffff) + 1) & 0xffff;
                    uint256 sh = 64 * (tag & 3);
                    jumps = (jumps & ~(M64 << sh)) | (ref << sh);
                    rec = (rec & ~(uint256(0xffff) << 164)) | (tag << 164);
                    win = price | ((fMs + gapMs) << 64);
                } else if (gap) {
                    // a gap inside an open window keeps that window's price; any other starts from the price before it
                    win = (open && fMs <= end ? ref : last) | ((fMs + gapMs) << 64);
                }
            }
        }
        if (fMs > lastMs + REOPEN_MS && tMs > (rec >> 116) & M48) rec = (rec & ~(M48 << 116)) | (tMs << 116);
        // the print, at its quorum (bit 115)
        return ((rec & ~(M64 | (M48 << 64))) | price | (fMs << 64) | (1 << 115), win, jumps);
    }
}

src/propamm/libraries/PropAMMClock.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice The chain's millisecond clock for words, ages and buckets, shared by the hot implementation and the landing
///         part so both measure time one way.
/// @dev The modes:
///      - Mode 0: the seal time, `block.timestamp` x 1000 (Ethereum; Base before its millisecond blocks; Arbitrum One,
///        Robinhood and HyperEVM, whose blocks share whole seconds).
///      - Mode 1: the BaseTime predeploy's `timestampMs()`.
///      - Mode 2: milliseconds from the block number (`ms0` at block `block0`, 200 ms a block) where they agree with
///        the block's seconds, BaseTime otherwise.
///      - Mode 3: the millisecond timestamp precompile at 0x70 (BNB Chain's BEP-706, from its Jenner upgrade), which
///        ignores its input and answers the block header's milliseconds. Before the precompile exists the call answers
///        nothing and the clock reads the seal time, so a mode-3 build turns exact at that upgrade with no change of
///        its own. Until then its first read in a transaction pays a cold account access; a precompile is warm.
///
///      A millisecond reading that disagrees with `block.timestamp`'s second, or that cannot be read, falls back to the
///      seal time, the start of the block's second: once blocks run faster than one a second, that reads up to a second
///      early, so ages read young, the unsafe side, which the age ceilings must absorb, and a print stamped later in
///      the second waits for the next.
///
///      The clock's anchor (`block0`, `ms0`) is one block's own: a block off reads 200 ms early in four blocks of five,
///      so ages read young, the unsafe side. On Base it is the first millisecond block. Base after its millisecond
///      blocks therefore runs mode 2 on an exact anchor, which the Base build checks at construction
///      (`PropAMMBaseFront`): modes 1 and 2 only where BaseTime answers, their anchor on its reading, and mode 0 only
///      where it does not. Ethereum's build takes mode 0 alone (0x70 holds nothing there), BNB Chain's mode 0 or
///      mode 3.
library PropAMMClock {
    /// @notice A build's maker-time windows and clock, as the hot implementation and the landing part answer them in
    ///         one call (`clock()`): seven words, in this order.
    struct Timing {
        uint256 maxLeadMs; // how far past the clock a maker time may lie, ms
        uint256 maxTtlMs; // the cap on a pool word's life, ms
        uint256 pullLeadMs; // how far after the clock a print's feed time may lie, ms
        uint256 ageSlackMs; // what the age clock adds to a seal reading, ms
        uint256 clockMode; // the clock's mode, below
        uint256 clockBlock; // the block mode 2 counts from
        uint256 clockMs; // that block's milliseconds
    }

    /// @dev The BaseTime predeploy, whose `timestampMs()` answers the block's milliseconds.
    address internal constant BASE_TIME = 0x4200000000000000000000000000000000000030;
    /// @dev BEP-706's millisecond timestamp precompile: any input, one word.
    address internal constant MS_PRECOMPILE = 0x0000000000000000000000000000000000000070;
    /// @dev Clock mode 0: the seal time.
    uint256 internal constant SEAL = 0;
    /// @dev Clock mode 1: BaseTime.
    uint256 internal constant BASE_TIME_MS = 1;
    /// @dev Clock mode 2: milliseconds from the block number.
    uint256 internal constant BLOCKS = 2;
    /// @dev Clock mode 3: the millisecond timestamp precompile.
    uint256 internal constant PRECOMPILE_MS = 3;
    /// @dev Milliseconds per block in mode 2.
    uint256 internal constant BLOCK_MS = 200;

    /// @dev The clock, ms ({read}).
    function nowMs(uint256 mode, uint256 block0, uint256 ms0) internal view returns (uint256 ms) {
        (ms,) = read(mode, block0, ms0);
    }

    /// @dev The clock, and whether it read the block's own milliseconds (`exact`) rather than the seal time, the start
    ///      of the block's second (mode 0, or another mode's fallback): where a build's blocks share whole seconds, a
    ///      seal reading lies up to a second before the block runs, which the build's age slack covers.
    function read(uint256 mode, uint256 block0, uint256 ms0) internal view returns (uint256 ms, bool exact) {
        if (mode != SEAL) {
            if (mode == BLOCKS && block.number >= block0) {
                ms = ms0 + (block.number - block0) * BLOCK_MS;
                if (ms / 1000 == block.timestamp) return (ms, true);
            }
            address source = mode == PRECOMPILE_MS ? MS_PRECOMPILE : BASE_TIME;
            bool ok;
            assembly ("memory-safe") {
                // timestampMs(), which the precompile ignores
                mstore(0, shl(224, 0x5745a677))
                // Yul evaluates arguments right to left: the call first, in its own statement
                let success := staticcall(gas(), source, 0, 4, 0, 0x20)
                ok := and(success, gt(returndatasize(), 31))
                ms := mload(0)
            }
            if (ok && ms / 1000 == block.timestamp) return (ms, true);
        }
        return (block.timestamp * 1000, false);
    }
}

src/propamm/libraries/PythProCheck.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

/// @notice Pyth's read-only signer view on its Pro verifier, a third-party contract this interface mirrors in part.
interface IPythProVerifier {
    /// @notice Whether `signer` is one of the verifier's current signers.
    function isValidSigner(address signer) external view returns (bool);
}

/// @notice The pull-price check of a two-feed Pyth Pro EVM update, in one inline-assembly pass over calldata. Every
///         refusal reverts `BadPull()`.
/// @dev The check:
///      1. It requires the envelope magic 0x2a22999a, an update that ends exactly at its declared payload length, a v
///         byte of 0 or 1, and a nonzero signer from ecrecover(keccak256(payload), v + 27, r, s), which it returns for
///         the caller's signer rule.
///      2. It requires the payload magic 0x93c7d375, the pair's channel and a feed count of exactly 2.
///      3. It parses each feed by property id, never by offset. Known ids and sizes: 0 price i64, 1 best bid i64,
///         2 best ask i64, 3 publisher count u16, 4 exponent i16, 5 confidence u64, 9 market session u16, 10 EMA price
///         i64, 11 EMA confidence u64, 12 feed update time (presence byte, then u64 µs). Any other id, and any id
///         repeated within a feed, refuses the update. The second feed must end the payload.
///      4. It requires feed 0 to be the base feed id and feed 1 the quote feed id, and on each property 0 with
///         0 < price < 2^63, property 3 at or above that leg's quorum, property 4 equal to -8, property 5 (the
///         confidence) present, and property 12 present (presence byte 1).
///      5. It returns both prices, both feed times (µs), P̂ = pa * 10^k / pb, rounded down, and the pair's
///         confidence `conf`, ppm: the sum of each leg's confidence over its price, ceil(confidence x 10^6 / price),
///         both as printed. No confidence refuses here: the front bands a listing's fence by it.
///
///      An equity base leg (`cfg` bit 112, a stock pair's source) may take exponent -5 as well, Pyth's for equities,
///      scaled here to -8 (x 10^3, so a print still under 2^63), and must carry property 9; `facts` then returns its
///      market session (property 9) below bit 16 and the payload's timestamp (µs) above it, zero otherwise.
///
///      Its safety rests on its two exact-length checks (the update's length against its declared payload length, and
///      the cursor against the update's end after the second feed), which are frozen with it: calldataload past the
///      update reads other calldata or zeros and never reverts, the cursor only moves forward, and every byte used lies
///      below the cursor after its read, so an accepted update was read entirely inside its own bytes.
///
///      `cfg`: [0..31] base feed id | [32..63] quote feed id | [64..79] base quorum | [80..95] quote quorum |
///      [96..103] channel | [104..111] k, with k <= 58 so that pa * 10^k cannot overflow | [112] an equity base leg |
///      [113..255] reserved, zero.
library PythProCheck {
    /// @notice {check} refuses the update: every refusal of the check reverts this.
    error BadPull();

    /// @notice How long a refresh lets the pinned signer be honoured without asking the verifier. A key Pyth revokes
    ///         therefore stays trusted at most this long after the last refresh (anyone refreshes, against the
    ///         verifier); between refreshes a lapsed pin only costs the verifier's call.
    uint256 internal constant PIN_TTL_SEC = 1 days;
    /// @notice The gas Pyth's verifier's signer view is given: a verifier that misbehaves, writing or looping, fails
    ///         the check without burning the caller's gas.
    uint256 internal constant VERIFIER_GAS = 100_000;

    // Layout notes (offsets inside the update `u`):
    //   0..3 magic | 4..35 r | 36..67 s | 68 v - 27 | 69..70 payload length | 71.. payload
    //   payload: 0..3 magic | 4..11 timestamp (an equity leg's `facts`) | 12 channel | 13 feed count | 14.. feeds
    // Property table: each property's 32-byte calldata word (id byte first) is parked at m + 32 * id (ids <= 12,
    // 13 words of scratch above the free memory pointer, never allocated), and the four required words are read
    // back after the feed. A required id is always written in the current feed (the `seen` mask), so a value left
    // from the other feed or from the signature step is never read. The confidence (id 5) is at the price's own
    // exponent, so a leg's confidence is taken over its price as printed, before an equity leg's scaling.
    // Step per id, one byte per id from id 0 upwards, id byte included: 0-2: 9 | 3-4: 3 | 5: 9 | 6-8: 0 (refused) |
    // 9: 3 | 10-11: 9 | 12: 10. Ids above 12 read 0 as well (the table is 13 bytes).
    /// @dev The check the library's header lists, of update `u` under the source's configuration word `cfg`.
    /// @return pa The base leg's price, 8 decimals (an equity leg's scaled to them).
    /// @return pb The quote leg's price, 8 decimals.
    /// @return ta The base leg's feed time, µs.
    /// @return tb The quote leg's feed time, µs.
    /// @return px The cross P̂ = pa * 10^k / pb, rounded down.
    /// @return signer The address the update's signature recovers to, for the caller's signer rule.
    /// @return facts On an equity base leg its market session below bit 16 and the payload's timestamp (µs) above it;
    ///         zero otherwise.
    /// @return conf The pair's confidence, ppm: each leg's ceil(confidence x 10^6 / price), as printed, summed.
    function check(bytes calldata u, uint256 cfg)
        internal
        view
        returns (
            uint256 pa,
            uint256 pb,
            uint256 ta,
            uint256 tb,
            uint256 px,
            address signer,
            uint256 facts,
            uint256 conf
        )
    {
        assembly ("memory-safe") {
            function fail() {
                mstore(0, shl(224, 0x6f0b2a9e)) // BadPull()
                revert(0, 4)
            }

            function leg(pos, m, feedId, quorum, equity) -> price, time, confLeg, next {
                let w := calldataload(pos)
                let id := shr(224, w)
                let n := byte(4, w)
                pos := add(pos, 5)
                let seen := 0
                for {} n { n := sub(n, 1) } {
                    let x := calldataload(pos)
                    let pid := shr(248, x)
                    let step := and(shr(shl(3, pid), 0x0a090903000000090303090909), 0xff)
                    let bit := shl(pid, 1)
                    if or(iszero(step), and(seen, bit)) { fail() }
                    seen := or(seen, bit)
                    mstore(add(m, shl(5, pid)), x)
                    pos := add(pos, step)
                }
                price := shr(192, shl(8, mload(m))) // id 0: bytes 1..8
                // id 5, bytes 1..8: ceil(confidence x 10^6 / price), ppm, on the price as printed (a zero price
                // divides to zero here and fails below); a u64 confidence x 10^6 stays under 2^84
                confLeg := div(add(mul(shr(192, shl(8, mload(add(m, 0xa0)))), 1000000), sub(price, 1)), price)
                let w12 := mload(add(m, 0x180)) // id 12: presence byte 1, time bytes 2..9
                time := shr(192, shl(16, w12))
                let expo := shr(232, mload(add(m, 0x80))) // id 4: 0x04fff8 is -8
                // an equity leg's exponent -5, scaled to -8 before the price's bound
                let five := and(equity, eq(expo, 0x04fffb))
                if five { price := mul(price, 1000) }
                if or(
                    // ids 0, 3, 4, 5, 12 (and 9)
                    or(and(not(seen), or(0x1039, shl(9, equity))), iszero(eq(id, feedId))),
                    or(
                        or(gt(sub(price, 1), 0x7ffffffffffffffe), lt(shr(240, shl(8, mload(add(m, 0x60)))), quorum)),
                        or(and(iszero(eq(expo, 0x04fff8)), iszero(five)), iszero(eq(byte(1, w12), 1)))
                    )
                ) { fail() }
                next := pos
            }

            let o := u.offset
            let hw := calldataload(add(o, 39)) // its last 3 bytes: v - 27 (68) | payload length (69..70)
            let plen := and(hw, 0xffff)
            let v := and(shr(16, hw), 0xff)
            if or(or(iszero(eq(shr(224, calldataload(o)), 0x2a22999a)), iszero(eq(u.length, add(plen, 71)))), gt(v, 1))
            { fail() }
            let p := add(o, 71)
            let m := mload(0x40)
            // signer = ecrecover(keccak256(payload), v + 27, r, s)
            calldatacopy(m, p, plen)
            mstore(m, keccak256(m, plen))
            mstore(add(m, 0x20), add(v, 27))
            calldatacopy(add(m, 0x40), add(o, 4), 0x40)
            mstore(0, 0)
            pop(staticcall(gas(), 1, m, 0x80, 0, 0x20))
            signer := mload(0)
            if iszero(signer) { fail() }
            // payload magic | timestamp (masked out) | channel | feed count == 2, in one compare
            if iszero(
                eq(
                    and(shr(144, calldataload(p)), 0xffffffff0000000000000000ffff),
                    or(0x93c7d37500000000000000000002, shl(8, and(shr(96, cfg), 0xff)))
                )
            ) { fail() }
            let q
            let equity := and(shr(112, cfg), 1)
            pa, ta, conf, q := leg(add(p, 14), m, and(cfg, 0xffffffff), and(shr(64, cfg), 0xffff), equity)
            // the base's session (id 9) and the payload's timestamp, read before the quote leg reuses the table
            if equity {
                let ts := and(shr(160, calldataload(p)), 0xffffffffffffffff)
                facts := or(shr(240, shl(8, mload(add(m, 0x120)))), shl(16, ts))
            }
            let cb
            pb, tb, cb, q := leg(q, m, and(shr(32, cfg), 0xffffffff), and(shr(80, cfg), 0xffff), 0)
            if iszero(eq(q, add(o, u.length))) { fail() }
            conf := add(conf, cb)
            px := div(mul(pa, exp(10, and(shr(104, cfg), 0xff))), pb)
        }
    }

    /// @notice The pin while it is valid (`validUntil` at or after now), else none.
    function livePin(address pin, uint256 validUntil) internal view returns (address) {
        return block.timestamp <= validUntil ? pin : address(0);
    }

    /// @notice The signer rule: the live pin (`livePin`), or else one Pyth's verifier accepts. The pin saves the
    ///         verifier's call, and it also keeps honouring a key Pyth has revoked until the pin's validity lapses
    ///         (at most `PIN_TTL_SEC` after its last refresh); a zero pin matches no signer.
    function signerOk(address signer, address pin, address verifier) internal view returns (bool ok) {
        if (signer == pin && pin != address(0)) return true;
        assembly ("memory-safe") {
            mstore(0, shl(224, 0xd5f50582)) // isValidSigner(address)
            mstore(4, signer)
            // a revert, a short answer or anything but true refuses
            // Yul evaluates arguments right to left: the call first, in its own statement
            let success := staticcall(VERIFIER_GAS, verifier, 0, 36, 0, 32)
            ok := and(and(success, gt(returndatasize(), 31)), eq(mload(0), 1))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.