Skip to content
Verified contractExactUNLICENSED

PrintLaneSource

Address0xf166e802fb1994929b522f1ca5410a5f5bd1a366
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.35

 

Same code

3 more contracts

 

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,480,614
Creation transaction
0x52dcf0f252…a2f4a12830
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0x95b3…48ef2csrc/core/flamm/FLAMMLane.sol:FLAMMLane0x5d81…90de37src/core/flamm/FLAMMRoute.sol:FLAMMRoute0xb1ff…7fb0fesrc/periphery/FLAMMMaxima.sol:FLAMMMaxima0x6854…90a91bsrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0xf55c…49cf45src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0be7…5ecc47src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xa5db…72803esrc/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2795…4cfb77src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0x3a05…434368src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x70ca…60bee4src/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x60e4…314010src/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0x0b10…1ce950src/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x634d…298fcdsrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x5dc3…aa7e91src/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0x9dbb…798f1asrc/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x6b2b…518935src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0x99de…929869src/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0xe4be…cfac2esrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0x93ab…262861src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x6abb…60ea7esrc/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0x3858…f91f06src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0x4551…33b301src/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xb852…b71005src/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x6a6a…798659src/hooks/everlong/LeverageLib.sol:LeverageLib0x8039…16d055src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0xaa54…b56417src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x3bc5…2055ddsrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xf6d5…9dfeef

src/propamm/PrintLaneSource.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 {PythProBase} from "src/propamm/PythProBase.sol";

/// @notice A pair's Pyth Pro price source that a fill may read without carrying a print: the kept print. Anyone posts a
///         signed two-feed update (`post`), which Pyth verifies in that call and this source then checks exactly as
///         `PythProSource` checks a carried one.
/// @dev The rules of the kept print:
///      - One record keeps it: the newest print Pyth verified at its post, written when neither leg is older than the
///        kept print's and one is newer. Every post goes through Pyth's `verifyUpdate` before any byte of it is read,
///        whoever signed it and whatever the poster asks, so no print is ever kept that Pyth did not verify, and a key
///        Pyth drops is refused from its next post on.
///      - Value: `post` is payable and passes all the value it is sent to Pyth with the verification. The value must
///        be exactly Pyth's `verification_fee()` (zero today; Pyth's owner sets it): Pyth refuses a lower one, and a
///        higher one, which Pyth would keep, is refused here against the fee read from Pyth
///        (`PythProCheck.BadFee`). Nothing is refunded to the poster on any path and no ETH is ever left here.
///      - A post that replaces nothing (the same print again, or an older one) still verifies, pays the fee, writes
///        nothing and returns: a second poster of a print never reverts for being second.
///      - A post fails whole or not at all: a verifier that reverts, is paused, answers another shape or asks a fee
///        the post did not carry reverts the post (Pyth's own revert, or `PythProCheck.BadVerifier`) before anything
///        is read or written, and the kept print stands until it ages out.
///      - The front's check reads the kept print where the taker carries none, and checks a carried print as
///        `PythProSource` does where the taker carries one (by STATICCALL with no value, so only while Pyth's fee is
///        zero). The listing's lease (flags bit 0) is ignored.
///      - The front's window still bounds the kept print's age at the fill: once the kept print is older than the
///        source's window or the listing's `maxAgeMs`, a fenced fill that carries none refuses (`StalePull` at the
///        front), so it fails closed, never at an older price.
///      - `SourceDark` at the front is for a source that gives no print: none kept, or a dark source.
///      - Every read answers the kept print's pair confidence, stored in 0.1 bp units rounded up (saturating at
///        65,535), so it reads back under 10 ppm wider than the print's own.
///      - Registered by anyone as any source (`registerSource`, by CREATE3 from the front at its id), so it needs no
///        front change; it takes no pull lead of its own but reads the front's (`clock().pullLeadMs`) at its
///        construction, so no post can stamp a leg the front's fills would refuse as future. A front upgrade that
///        changes the lead comes with new kept-print sources.
///      - Its configuration reads through `config()` (`PythProBase`), and it answers its front alone.
contract PrintLaneSource is PythProBase {
    /// @notice A post stamps a leg past this block's time plus the front's pull lead.
    error FuturePull();
    /// @notice A read of the kept print with no print kept.
    error NoPrint();

    uint256 internal constant M16 = (1 << 16) - 1;
    uint256 internal constant M48 = (1 << 48) - 1;
    uint256 internal constant M63 = (1 << 63) - 1;

    /// @dev The kept print, the newest Pyth verified at its post: [0-47] base leg time, ms | [64-111] quote leg time,
    ///      ms | [112-127] the pair's confidence, 0.1 bp units (ppm / 10 rounded up, at most 65,535) | [128-190] base
    ///      price | [191-253] quote price | [254-255] zero. Storage slot 0.
    uint256 internal kept;

    /// @param front The front this source serves, never zero: the only caller its check answers, so no other contract
    ///        reads the vendor's price through it.
    /// @param verifier Pyth's Pro verifier.
    /// @param word as `PythProSource`'s: [0-31] base feed id | [32-63] quote feed id | [64-71] base quorum | [72-79]
    ///        quote quorum | [80-87] channel.
    constructor(address front, address verifier, uint256 word) PythProBase(front, verifier, word, 0) {
        if (front == address(0)) revert();
    }

    /// @notice Anyone: verifies `u` through Pyth, then keeps it if it passes the pair's checks, no leg is stamped
    ///         after this block's time plus the front's pull lead, and it may replace the kept print: none kept, or no
    ///         leg older and one leg later. A post that replaces nothing writes nothing and returns, so a second poster
    ///         of a print does not revert. Its legs' times are kept in ms, compared in ms, and its pair confidence
    ///         beside them.
    /// @dev Value: exactly Pyth's `verification_fee()`, passed whole to Pyth; a lower or a higher value reverts, and
    ///      nothing is refunded. The second argument is ignored: it once asked for Pyth's verifier, which every post
    ///      now goes through, and it stays so that the entry keeps its selector and argument layout,
    ///      `post(bytes,bool)`, which a desk contract's code calls.
    function post(bytes calldata u, bool) external payable {
        (uint256 pa, uint256 pb, uint256 ta, uint256 tb,,, uint256 conf) =
            PythProCheck.check(PythProCheck.verify(VERIFIER, u, msg.value), CFG);
        // a leg past the front's lead would make every fill of the block that reads the kept print refuse as future,
        // and being newer it could not be replaced within the block
        if ((ta > tb ? ta : tb) > block.timestamp * 1e6 + LEAD_MS * 1000) revert FuturePull();
        // the legs' times in ms from here on, under 2^48 by the check above; the confidence in 0.1 bp, rounded up
        (ta, tb) = (ta / 1000, tb / 1000);
        uint256 r = kept;
        // none kept, or no leg older and one leg later: a feed whose time stands still holds the record back by
        // neither leg, and no leg moves back
        if (r != 0) {
            uint256 ra = r & M48;
            uint256 rb = (r >> 64) & M48;
            if (ta < ra || tb < rb || (ta == ra && tb == rb)) return;
        }
        conf = (conf + 9) / 10;
        kept = ta | (tb << 64) | ((conf > M16 ? M16 : conf) << 112) | (pa << 128) | (pb << 191);
    }

    /// @dev `IPriceCheck.check`'s answer, as `PythProSource`'s for a carried print; an empty one reads the kept print,
    ///      refused where none is kept: its legs' times (ms, answered in µs), the cross and its pair confidence (0.1 bp
    ///      units, answered in ppm). The front's flags are not read.
    function _answer(bytes calldata u, uint256, uint256 k)
        internal
        view
        override
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf, uint256, uint256 size)
    {
        size = 0x80;
        if (u.length != 0) {
            (ta, tb, px, conf) = _carried(u, k);
        } else {
            uint256 r = kept;
            if (r == 0) revert NoPrint();
            ta = (r & M48) * 1000;
            tb = ((r >> 64) & M48) * 1000;
            conf = ((r >> 112) & M16) * 10;
            px = ((r >> 128) & M63) * 10 ** (k & 0xff) / ((r >> 191) & M63);
        }
    }
}

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, Pyth's verifier, the
///         feeds' check word, the front's pull lead read at construction), 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.
/// @dev Every update a source reads goes through Pyth's own `verifyUpdate` first (`PythProCheck`), once an update: a
///      posted one by a call that pays Pyth's fee, a carried one by STATICCALL with no value. No signer is kept and
///      no signature is checked here, and the listing's lease (the front's flags bit 0) is read by no source. A source
///      takes no ETH but a post's value, which goes whole to Pyth in the same call: it has no receive and its fallback
///      refuses value, so none is ever left in it.
abstract contract PythProBase {
    /// @dev The front this source answers, or zero for any caller.
    address internal immutable FRONT;
    /// @dev Pyth's Pro verifier, whose `verifyUpdate` every update goes through.
    address internal immutable VERIFIER;
    /// @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: an address with code (`PythProCheck.BadVerifier` otherwise).
    /// @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, uint256 word, uint256 flags) {
        if (verifier.code.length == 0) revert PythProCheck.BadVerifier();
        FRONT = front;
        VERIFIER = verifier;
        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, and the front's pull lead it
    ///         holds posts to, ms.
    function config() external view returns (address front, address verifier, uint256 lead) {
        return (FRONT, VERIFIER, LEAD_MS);
    }

    /// @notice The lease's renewal test (`IPriceCheck.cacheValid`): a source caches no trust, as Pyth verifies every
    ///         update it reads, so a renewal always finds it valid and the lease binds nothing here.
    function cacheValid() external pure returns (bool) {
        return true;
    }

    /// @notice `IPriceCheck.check`, without an ABI decoder. It takes no value.
    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`: verified by Pyth (`PythProCheck.verifyView`: a STATICCALL with no value, which passes
    ///      only while Pyth's fee is zero and refuses the print on any failure of the verifier's), then the payload
    ///      Pyth answered checked by the pair's feeds: its legs' times (µs), the cross at scale `k` and the pair's
    ///      confidence, ppm.
    function _carried(bytes calldata u, uint256 k)
        internal
        view
        returns (uint256 ta, uint256 tb, uint256 px, uint256 conf)
    {
        (,, ta, tb, px,, conf) = PythProCheck.check(PythProCheck.verifyView(VERIFIER, u), CFG | ((k & 0xff) << 104));
    }

    /// @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/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 Pro verifier, a third-party contract this interface mirrors in part.
interface IPythProVerifier {
    /// @notice Verifies `update` (its format, its signature and its signer, by Pyth's own rules) and answers its
    ///         payload and the signer. It takes `verification_fee()` of the call's value and reverts on a value below
    ///         it; a value above it it offers back to the caller and, where the caller takes no ETH, keeps
    ///         (`RefundFailed`), without reverting.
    function verifyUpdate(bytes calldata update) external payable returns (bytes memory payload, address signer);

    /// @notice The fee one `verifyUpdate` takes, wei; Pyth's owner sets it.
    function verification_fee() external view returns (uint256);
}

/// @notice Pyth's verification of a Pyth Pro EVM update (`verify`, `verifyView`) and the pull-price check of a two-feed
///         payload Pyth answered (`check`), in one inline-assembly pass over it. Every refusal of the check reverts
///         `BadPull()`.
/// @dev Every update goes through Pyth's own `verifyUpdate`, once and before any read of it: nothing here recovers a
///      signature or asks about a signer, no signer is kept between updates, and only the payload Pyth answers is
///      parsed, never the update's own bytes. A verifier that reverts, is paused or answers another shape refuses the
///      update (Pyth's own revert, its first 0x100 bytes, or `BadVerifier`). An update must be exactly its 71-byte
///      envelope and the payload Pyth answered: bytes after it, which Pyth lets pass, refuse it (`BadPull`).
///
///      The check, of the payload `verify` answered:
///      1. (Pyth's, inside `verifyUpdate`: the update's format, its signature and its signer.)
///      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 exact-length check (the cursor against the payload's end after the second feed), which
///      is frozen with it: mload past the payload reads other memory and never reverts, the cursor only moves forward,
///      and every byte used lies below the cursor after its read, so an accepted payload 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, and so does an update longer
    ///         than its envelope and the payload Pyth answered.
    error BadPull();

    /// @notice Pyth's verifier answered a verification with something other than a payload and a signer (no code at
    ///         its address, or another shape), or failed with no reason of its own (out of gas among them).
    error BadVerifier();

    /// @notice The value sent with an update is above Pyth's verification fee.
    error BadFee();

    /// @notice The gas each call to Pyth's verifier is given: a verifier that misbehaves, looping or answering at
    ///         length, fails the verification without burning the caller's gas.
    uint256 internal constant VERIFIER_GAS = 100_000;

    /// @notice Verifies update `u` through Pyth's `verifyUpdate` on `verifier`, sending it `value` wei, and answers the
    ///         payload Pyth returned, in memory, for the caller to parse.
    /// @dev The value rule: `value` must be exactly Pyth's `verification_fee()`. A lower value Pyth refuses. A higher
    ///      one Pyth would keep (it offers the excess back to its caller, a contract of ours that takes no ETH, and
    ///      goes on where that fails), so it is refused here: a nonzero `value` is checked against the fee, read from
    ///      Pyth before the call (`BadFee` above it); a zero one needs no read, as it is never above the fee. A
    ///      caller therefore passes on the value it was sent (one update) or the fee it read (`fee`, several
    ///      updates), never keeps any, and never refunds. A revert of Pyth's is passed up unchanged.
    function verify(address verifier, bytes calldata u, uint256 value) internal returns (bytes memory payload) {
        if (value != 0) {
            if (value > fee(verifier)) revert BadFee();
        }
        (uint256 m, uint256 size) = _encode(u);
        bool ok;
        assembly ("memory-safe") {
            ok := call(VERIFIER_GAS, verifier, value, m, size, 0, 0)
        }
        return _decode(m, ok);
    }

    /// @notice As `verify`, by STATICCALL with no value, for a read that carries its update (a carried print): it
    ///         passes while Pyth's fee is zero, and reverts with Pyth's own refusal once a fee is charged, when only a
    ///         posted update, which pays it, is taken.
    function verifyView(address verifier, bytes calldata u) internal view returns (bytes memory payload) {
        (uint256 m, uint256 size) = _encode(u);
        bool ok;
        assembly ("memory-safe") {
            ok := staticcall(VERIFIER_GAS, verifier, m, size, 0, 0)
        }
        return _decode(m, ok);
    }

    /// @notice Pyth's fee for one verification on `verifier`, wei: what an entry that verifies several updates reads
    ///         once, to require its value be exactly their count times it.
    function fee(address verifier) internal view returns (uint256) {
        return IPythProVerifier(verifier).verification_fee{gas: VERIFIER_GAS}();
    }

    /// @dev `verifyUpdate(u)`'s call data, written at the free memory pointer and not allocated: where it starts and
    ///      its size.
    function _encode(bytes calldata u) private pure returns (uint256 m, uint256 size) {
        assembly ("memory-safe") {
            m := mload(0x40)
            mstore(m, shl(224, 0x197e1a5a)) // verifyUpdate(bytes)
            mstore(add(m, 4), 0x20)
            mstore(add(m, 0x24), u.length)
            calldatacopy(add(m, 0x44), u.offset, u.length)
            // the update's padding, zero
            mstore(add(add(m, 0x44), u.length), 0)
            size := add(0x44, and(add(u.length, 31), not(31)))
        }
    }

    /// @dev The verifier's answer to the call written at `m`: where the call failed (`ok` false), Pyth's revert passed
    ///      up (its first 0x100 bytes), or `BadVerifier` where it gave no reason; else the payload it returned, copied
    ///      to `m` and allocated. The answer is `abi.encode(bytes payload, address signer)`: [0x00] the payload's
    ///      offset, 0x40 | [0x20] the signer, Pyth's own business | [0x40] the payload's length | the payload. Any
    ///      other shape, an empty answer among them, reverts `BadVerifier`; a payload that is not the whole update
    ///      after its 71-byte envelope (magic, signature, the payload's length) reverts `BadPull`.
    function _decode(uint256 m, bool ok) private pure returns (bytes memory payload) {
        assembly ("memory-safe") {
            let n := returndatasize()
            // Pyth's own revert, where it gave one: its first 0x100 bytes, so the call's gas bounds the copy
            if and(iszero(ok), gt(n, 0)) {
                if gt(n, 0x100) { n := 0x100 }
                returndatacopy(m, 0, n)
                revert(m, n)
            }
            // the update's length, as `_encode` wrote it
            let ulen := mload(add(m, 0x24))
            let len
            if gt(n, 0x5f) {
                returndatacopy(m, 0, 0x60)
                len := mload(add(m, 0x40))
            }
            // a failure with no reason (out of gas among them), then the answer's shape; a payload's length is a u16
            // in the update
            if or(
                or(iszero(ok), lt(n, 0x60)),
                or(iszero(eq(mload(m), 0x40)), or(gt(len, 0xffff), gt(add(len, 0x60), n)))
            ) {
                mstore(0, shl(224, 0x09823c25)) // BadVerifier()
                revert(0, 4)
            }
            // the update is its 71-byte envelope and the payload Pyth answered, and nothing after it
            if iszero(eq(ulen, add(len, 71))) {
                mstore(0, shl(224, 0x6f0b2a9e)) // BadPull()
                revert(0, 4)
            }
            payload := m
            mstore(m, len)
            returndatacopy(add(m, 0x20), 0x60, len)
            // the word after the payload, zero
            mstore(add(add(m, 0x20), len), 0)
            mstore(0x40, and(add(add(m, 0x5f), len), not(31)))
        }
    }

    // Layout notes (offsets inside the 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 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 earlier memory 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 `payload` (as `verify` answered it) 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 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 memory payload, uint256 cfg)
        internal
        pure
        returns (uint256 pa, uint256 pb, uint256 ta, uint256 tb, uint256 px, 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 := mload(pos)
                if iszero(eq(shr(224, w), feedId)) { fail() }
                next := add(pos, 5)
                let seen := 0
                for { let n := byte(4, w) } n { n := sub(n, 1) } {
                    let x := mload(next)
                    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)
                    next := add(next, 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)
                    and(not(seen), or(0x1039, shl(9, equity))),
                    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() }
            }

            let p := add(payload, 0x20)
            let m := mload(0x40)
            // payload magic | timestamp (masked out) | channel | feed count == 2, in one compare
            if iszero(
                eq(
                    and(shr(144, mload(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, mload(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(p, mload(payload)))) { fail() }
            conf := add(conf, cb)
            px := div(mul(pa, exp(10, and(shr(104, cfg), 0xff))), pb)
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0x95b386d242c061ab2551a0d294c94dfe3948ef2c"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x5d81d4a7cfd40c3dfe9e009212545608be90de37"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0xb1ffeae12c53f876aa0e495e9c00c829f47fb0fe"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x68546ce65986354c5394e4bc2f28027ef490a91b"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0xf55c5807b6fbe5555443fd6ddbbd52079849cf45"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0be7fdb3d611b05df90a61778a644654735ecc47"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xa5db415d1af2158dd0a4a3c9c1eada277472803e"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x27957f4ddf818de39a1c9dba0bf273a5994cfb77"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0x3a05779218510235badcbddcdd78732a16434368"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x70cace9076ac8dd6a691ced2f9aa62a5c360bee4"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x60e4ab6b6ba72325c58924ee7753b14b37314010"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0x0b107b1f0c64f3716554ccc83b53e492e51ce950"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x634d5a14c42fb5bec82a7aea32bf636a8d298fcd"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x5dc3bb30c60390ce9522b7e3ca315dd334aa7e91"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0x9dbba0cbd9d7883f4eedd1c8e08780fac4798f1a"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x6b2b25ebba12e78afea697b9ac6d2167a6518935"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0x99de54a108c64ebe23ac7766901c199a91929869"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0xe4be161081d1c9aa91951ca347cc99da35cfac2e"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0x93ab647215a9f9f1050302a76506afcbc0262861"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x6abb06b1e9cba80888992d366913bb9b7760ea7e"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0x3858e2202cebcb6f12f36a596260dd2ed8f91f06"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0x4551cddb1de95f5452f6a0f836e047e01833b301"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xb852d9cbdda85cbed7da0885bca2714ba1b71005"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x6a6a3ff1e834dbbf07dee472e07d1ca977798659"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x80396f9f894cc3060dfaa7468c4f576e8b16d055"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0xaa5434e13eb54f37c577229efc981cceceb56417"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x3bc57bc05cc9dd1fe18106add8ffc060882055dd"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xf6d56f4ed6a7c441fd96c53a327026bac19dfeef"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.