Skip to content
Verified contractPartialMIT

Vault

Address0x40b06ea3de1c00498a6a27d6aa5201807ec25285
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,500,604
Creation transaction
0x66e8b43dd5…dcb97cef1f

src/Vault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {IVault} from "./interfaces/IVault.sol";
import {IDealer} from "./interfaces/IDealer.sol";
import {IGm, ISanctions, Quote} from "./interfaces/IGm.sol";
import {GmConstants} from "./GmConstants.sol";

/// @notice USDC (FiatTokenV2_2) EIP-3009 entry point with a packed or ERC-1271 signature.
/// @dev why: lets a client pay a deposit with one signature (no prior approve), pulled by the vault itself.
interface IUsdc3009 {
    function receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes memory signature
    ) external;
}

/// @notice Chainlink USDC/USD aggregator (8 decimals).
/// @dev why: the only price oracle the vault reads on chain; it values USDC received in a rebalance (see _usdcPx).
interface IChainlinkFeed {
    function decimals() external view returns (uint8);
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

/// @title NobuQuant nobuQQQ vault (v2)
/// @notice Shares are the nobuQQQ ERC-20 token (name "NobuQuant nobuQQQ Core", symbol "nobuQQQ").
///         Immutable unit-based vault over four slots: 0 QQQon, 1 TQQQon, 2 SGOVon (18 dec), 3 USDC (6 dec, 1 USD).
///         Holders own shares; each share is a pro-rata claim on the four slot balances.
/// @dev Frozen design: docs/C0_SPEC_FREEZE.md (NOB-317). ABI: IVault.
///
///      TRUST MODEL (plain English)
///
///      Who can do what
///      - Anyone: redeemInKind (burn your own shares for your pro-rata slice of the vault; needs no key, dealer or
///        price); executeAllowlistOff once its timelock is ready; every view.
///      - Holder: a deposit, a cash redeem and a register declaration each need the holder's own signature, so the
///        relayer cannot create or cash out a holder's shares without it. The exception is a forced exit (below).
///      - Safe (immutable address): setDealer (instant), lowerAllowance (instant), queue/cancel/execute an allowance
///        raise (7-day timelock), queue/cancel the allowlist-off (14-day timelock), disableSanctionsCheck (one-way),
///        announceWindDown / cancelWindDown and pushOut (see "Announced wind-down" below).
///        It is also the genesis depositor and the fee recipient. On the Dealer the Safe sets keys, limits and
///        forced-exit permissions and can withdraw the Dealer's own funds. The Safe can move vault assets out only through pushOut after an announced
///        wind-down is effective, and then only to the holder, in kind and pro rata; it has no other function that moves them.
///      - Dealer (contract, replaceable by the Safe): the only caller of deposit, redeem, rebalance, forceRedeem,
///        register and unregister. The vault checks every outcome by changes in its own balances, so what a dealer
///        can take is limited by the rules in this file, not by trust in the dealer. In a cash redeem or a forced exit
///        the dealer pays this vault: the vault measures its own USDC increase, checks it against the signed minimum
///        or the full owed amount, and forwards it to the holder. A holder's wallet balance is never the measure, so
///        USDC that reaches a holder from anywhere else never counts as payment (audit M-1). Honest limit: any token
///        that reaches the vault during a dealer callback counts as dealer delivery, whatever its source. The vault
///        grants no approvals, has no ERC-1271 signature and holds no claim, order or vesting, so only the dealer or
///        a voluntary sender can add to it.
///      - Relayer and operator: keys held in the Dealer, unknown to this contract. The relayer submits client-signed
///        deposits and redeems, register/unregister and forced exits the Safe has allowed. The operator submits
///        rebalances. Both act only through the Dealer, so they are bound by the limits below and the Dealer's limits.
///      - Ondo attestation signer: signs the price quotes behind rebalance legs and forced exits. A quote counts only if
///        its signer holds the signer role at Ondo's manager, it matches this chain, the fund's Ondo user id, the
///        asset, the side, the quantity and its expiry, and Ondo executed it in the same call. The vault trusts those
///        signed prices.
///      - Sanctions oracle: if it flags a wallet, that wallet cannot deposit, redeem, be force-redeemed or use
///        redeemInKind, and it cannot send or receive shares (allowlist on or off). It fails open: an oracle that
///        errors, returns junk or flags this vault itself blocks nobody. Shares of a flagged wallet are frozen, not
///        destroyed.
///      - Chainlink USDC/USD feed: values USDC received in a rebalance at min(1 USD, feed). A stale feed makes a
///        rebalance that receives USDC revert. Deposits and exits never read it.
///
///      What nobody can do
///      - Upgrade this contract (no proxy, no owner-set code), change the fee, the slot assets or the Ondo, USDC, feed
///        and sanctions addresses (constants and immutables), or pause anything (no pause function exists).
///      - Take vault assets out other than by (a) a holder redeeming shares, (b) a rebalance inside the allowance below,
///        (c) a forced exit, where the holder must be paid in full at Ondo's signed sell price, or (d) pushOut after an
///        announced wind-down, which sends a holder only their own pro-rata slice, to that holder. Fee shares are
///        minted to the Safe and dilute holders at the fixed rate below.
///      - Block redeemInKind (I3, exit liveness). redeemInKind succeeds for any holder not flagged by the vault
///        sanctions check, unless a token being delivered (a slot token with a non-zero slice, or a named token the
///        holder listed) itself refuses the transfer or balance read (an Ondo pause, blocklist or compliance hook, or
///        a Circle blacklist). Nothing NBQ, the Safe, the dealer, the operator or the oracle can do blocks it. The
///        exit is all or nothing; nothing is skipped, held or forfeited.
///
///      Announced wind-down (#673)
///      - The Safe announces (one active announcement; announcing again after a cancel restarts the 14 days); 14 days later it is effective (no execute step; the Safe can cancel only before
///        that). From the announcement deposits revert; from the effective time rebalances revert and the fee stops.
///      - pushOut(holder), by the Safe or the holder only, burns the holder's shares and sends the holder their
///        floor-rounded pro-rata of the free balance, in kind. A slice a token refuses is not lost: it stays in the
///        vault as that holder's exact claim (held), is excluded from every other pro-rata (free balance = balance
///        minus the sum of held), and a later pushOut delivers it. redeemInKind itself stays all or nothing.
///      - Limits: held amounts are fixed token units (a seizure, burn or rebase of the token is not shared), and a
///        held claim is tied to its holder address.
///
///      Bounds (with their numbers)
///      - Rebalance allowance: default 1% per day (100 bps), maximum 5% (500 bps = MAX_ALLOWANCE_BPS). Raising it
///        needs a Safe transaction, a 7-day wait and execution within the next 7 days. Lowering is instant and also
///        cancels a pending raise.
///      - Every rebalance is charged cap/4 (REBALANCE_CHARGE_DIV) plus its value shortfall against a bucket of `cap`
///        that refills over 24 hours. The shortfall is measured at the executed Ondo quote prices, so it counts only
///        the dealer delivering less than the quoted value: at most about 0.75% of NAV per day (1.5% in a worst
///        24-hour window) at the default allowance, and 3.75% (7.5%) at the 5% maximum. It does not count Ondo's
///        bid/ask spread or a quote priced away from the market (stale, or chosen among several). That loss goes to
///        Ondo, not the operator, and it is bounded by count, not value: at most 4 rebalances per day at a constant
///        allowance (8 in a worst 24-hour window), each up to the whole NAV and each paying the spread on both legs.
///        lowerAllowance(0), setDealer(0) or new Dealer keys stop it at once (audit L-1).
///      - Fee: 2% per year (FEE_BPS = 200), fixed, paid by minting shares to the Safe.
///      - 1,000 dead shares are minted to the dead address at genesis, so supply never returns to zero.
///      - Allowlist: starts on. Turning it off needs a 14-day timelock and cannot be undone.
///      - Sanctions check: starts on. The Safe can turn it off; it cannot be turned back on.
///      - Supply is capped below 2^128 (MAX_SUPPLY).
// Design-inherent lint notes (reviewed, C1): every state-changing entry point holds one transient lock, so the
// dealer/USDC callbacks cannot re-enter (reentrancy-*); timestamps drive deadlines, timelocks, fee and budget
// (block-timestamp); loops are bounded by 3-4 slots or a holder-chosen named list (calls-loop, require-revert-in-loop).
// uint64 timestamps cannot truncate before year 584e9 (unsafe-typecast).
// forge-lint: disable-start(reentrancy-events, reentrancy-no-eth, block-timestamp, calls-loop, require-revert-in-loop)
contract Vault is IVault, ERC20, EIP712 {
    // ---------------- Config ----------------
    /// @notice Constructor inputs; all are fixed at deployment except `dealer`, which the Safe can replace.
    struct Config {
        address safe; // admin Safe: timelocked and emergency controls, fee recipient
        address gm; // Ondo GM manager that verifies and executes quotes
        bytes32 nbqUserId; // the fund's Ondo user id; a quote must carry it
        address[3] gmSlots; // GM tokens for slots 0-2
        address usdc; // slot 3
        address usdcFeed; // Chainlink USDC/USD
        address sanctions; // sanctions oracle
        address dealer; // initial dealer; may be zero until the Safe sets one
    }

    // ---------------- Constants ----------------
    /// @notice Hard ceiling of the rebalance allowance: 5% per day. why: bounds what a raise can ever allow.
    uint16 public constant MAX_ALLOWANCE_BPS = 500;
    /// @notice Annual management fee, 2% in bps, fixed. why: an investor-facing constant that no key can change.
    uint16 public constant FEE_BPS = 200;
    /// @notice USD (1e18) a forced-exit quote quantity may differ from the slice. why: absorbs fee-accrual drift,
    ///         slices under the 0.98 USD Ondo minimum and donated dust between quote time and execution.
    uint256 public constant FORCE_SLACK_USD = 2e18;
    /// @notice Holder of the dead shares. why: a well-known burn address, so those shares are never redeemed.
    address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
    /// @notice Hard supply ceiling (C0 section 4: S < 2^128), checked after every deposit mint.
    ///         why: bounds the share supply so the fee and slice arithmetic stays far from uint256 limits.
    uint256 public constant MAX_SUPPLY = type(uint128).max;

    /// @dev Number of slots (3 GM tokens + USDC); loops run over this fixed size.
    uint256 private constant SLOTS = 4;
    /// @dev 1e18 fixed-point unit for prices and fractions.
    uint256 private constant WAD = 1e18;
    /// @dev Seconds in the allowance bucket's refill window (a full bucket refills in one day).
    uint256 private constant DAY = 86_400;
    /// @dev Seconds in the year used by the fee rate.
    uint256 private constant YEAR = 365 days;
    /// @dev Longest gap one fee accrual covers (5 years). why: keeps the fee arithmetic bounded for any gap.
    uint256 private constant MAX_FEE_DT = 5 * YEAR;
    /// @dev Shares minted to DEAD at genesis. why: supply never falls to zero, which blocks near-empty-vault rounding
    ///      games and keeps pro-rata slices well defined.
    uint256 private constant DEAD_SHARES = 1000;
    /// @dev Scales 6-decimal USDC to the 18-decimal USD unit used for values.
    uint256 private constant USDC_TO_WAD = 1e12;
    /// @dev Wait before a queued allowance raise can be executed (7 days).
    uint64 private constant ALLOWANCE_DELAY = 7 days;
    /// @dev Wait before the allowlist can be turned off (14 days).
    uint64 private constant ALLOWLIST_DELAY = 14 days;
    /// @dev Notice between the Safe's wind-down announcement and the day pushOut works (14 days).
    uint64 private constant WIND_DOWN_DELAY = 14 days;
    /// @dev How long a ready timelock stays executable (7 days). why: a stale queued change cannot be sprung later.
    uint64 private constant EXEC_WINDOW = 7 days;
    /// @notice Gas forwarded to the sanctions oracle. why: caps what a slow or hostile oracle can burn.
    uint256 public constant SANCTIONS_GAS = 50_000;
    /// @notice Oldest Chainlink USDC/USD answer accepted, in seconds (30 hours). why: a stale price must not value USDC.
    uint256 public constant USDC_FEED_MAX_AGE = 108_000;
    /// @notice Each rebalance is charged cap divided by this (cap/4). why: limits the number of rebalances per day even
    ///         when each one loses nothing, which bounds spread churn.
    uint256 public constant REBALANCE_CHARGE_DIV = 4;
    /// @dev Ondo quote side code for a buy (mint).
    uint8 private constant BUY = 0;
    /// @dev Ondo quote side code for a sell (redeem).
    uint8 private constant SELL = 1;

    /// @dev EIP-712 type hashes for the three client-signed tickets.
    bytes32 private constant DECLARATION_TYPEHASH =
        keccak256("Declaration(address wallet,bytes32 termsHash,uint256 epoch)");
    bytes32 private constant DEPOSIT_TYPEHASH =
        keccak256("Deposit(address client,uint256 usdc,uint256 minShares,uint256 deadline,bytes32 salt)");
    bytes32 private constant REDEEM_TYPEHASH =
        keccak256("Redeem(address owner,uint256 shares,uint256 minUsdc,uint256 deadline,bytes32 nonce)");

    // ---------------- Immutables ----------------
    /// @notice Admin Safe. why: fixed at deployment so there is no owner to transfer or hijack.
    address public immutable SAFE;
    /// @notice Ondo GM manager that checks and executes quotes. why: fixed so the quote domain cannot be swapped.
    address public immutable GM;
    /// @notice The fund's Ondo user id; every quote must carry it, so another user's quote cannot be used here.
    bytes32 public immutable NBQ_USER_ID;
    /// @notice Sanctions oracle queried for compliance. why: fixed so it cannot be pointed at another contract.
    address public immutable SANCTIONS;
    /// @notice USDC token (slot 3). why: fixed so the cash leg cannot be swapped.
    address public immutable USDC;
    /// @notice Chainlink USDC/USD feed. why: fixed so the depeg price source cannot be swapped.
    address public immutable USDC_FEED;
    /// @dev GM slot tokens 0-2 (read through SLOT(i)). why: fixed so the asset set cannot change.
    address private immutable SLOT0;
    address private immutable SLOT1;
    address private immutable SLOT2;

    // ---------------- Storage (frozen order, C0 section 3; slots 7-13 after ERC20 + EIP712) ----------------
    /// @notice Current dealer; zero disables every dealer-only path (the emergency stop). slot 7
    address public dealer;
    /// @dev Rebalance allowance in bps of NAV per day. slot 7
    uint16 internal allowanceBps;
    /// @dev Allowance queued by queueAllowanceRaise; zero when none. slot 7
    uint16 internal pendingAllowanceBps;
    /// @notice True while only approved wallets may hold or move shares; one-way off. slot 7
    bool public allowlistOn;
    /// @notice True while the on-chain sanctions check applies; one-way off. slot 7
    bool public sanctionsOn;
    /// @dev Time budgetUsed was last settled (start of the current refill). slot 8
    uint64 internal budgetAt;
    /// @dev Time a queued allowance raise becomes executable; zero when none. slot 8
    uint64 internal allowanceEta;
    /// @notice Time the queued allowlist-off becomes executable; zero when none. slot 8
    uint64 public allowlistOffEta;
    /// @notice Time the fee was last accrued. slot 8
    uint64 public feeAt;
    /// @dev Leaky-bucket fill, as a WAD fraction of NAV, before the refill since budgetAt. slot 9
    uint256 internal budgetUsed;
    /// @notice Number of rebalances so far (the counter in the Rebalanced event). slot 10
    uint256 public rebalanceCount;
    /// @notice Wallets that may deposit and (while the allowlist is on) hold or move shares. slot 11
    mapping(address => bool) public approved;
    /// @notice Per-wallet declaration epoch; unregistering bumps it so old signed declarations stop working. slot 12
    mapping(address => uint256) public epoch;
    /// @notice Redeem tickets already used, per owner. why: a signed redeem can be executed only once. slot 13
    mapping(address => mapping(bytes32 => bool)) public usedRedeem;
    /// @notice Time the announced wind-down becomes effective (announce + 14 days); zero when none. slot 14
    uint64 public windDownAt;
    /// @notice Per holder and slot: token units a refused pushOut kept for that holder (retry with pushOut). slot 15
    mapping(address => uint256[4]) public held;
    /// @dev Per slot: sum of every holder's held amount, excluded from every pro-rata base. slots 16-19 (internal: size)
    uint256[4] internal heldTotal;

    /// @dev Reentrancy lock, in transient storage so it costs no persistent slot and resets every transaction.
    bool private transient _locked;

    // ---------------- Modifiers ----------------
    /// @dev Blocks re-entry into any locked entry point, so dealer or token callbacks cannot call back in mid-flow.
    ///      The `_` placeholder stays in the modifier, so an early `return` in a body still reaches `_exit()`.
    modifier lock() {
        _enter();
        _;
        _exit();
    }

    /// @dev Dealer-only paths: client flows run through the dealer, which trades with Ondo.
    modifier onlyDealer() {
        _checkDealer();
        _;
    }

    /// @dev Safe-only controls.
    modifier onlySafe() {
        _checkSafe();
        _;
    }

    /// @dev For views: reverts inside a vault call, when balances are mid-flight and a read would be misleading.
    modifier notLocked() {
        _checkNotLocked();
        _;
    }

    /// @dev Why a function: the modifier bodies are emitted once instead of at every use (bytecode size).
    function _enter() private {
        if (_locked) revert Locked();
        _locked = true;
    }

    /// @dev Releases the transient lock.
    function _exit() private {
        _locked = false;
    }

    /// @dev Reverts NotDealer unless the caller is the current dealer.
    function _checkDealer() private view {
        if (msg.sender != dealer) revert NotDealer();
    }

    /// @dev Reverts NotSafe unless the caller is the Safe.
    function _checkSafe() private view {
        if (msg.sender != SAFE) revert NotSafe();
    }

    /// @dev Reverts Locked while a vault call holds the lock.
    function _checkNotLocked() private view {
        if (_locked) revert Locked();
    }

    // ---------------- Constructor ----------------
    /// @param c Deployment config. Reverts BadConfig on a wrong chain, zero address (dealer may be zero),
    ///          zero user id, wrong decimals, an address without code, a duplicate slot token (including USDC),
    ///          or a USDC/USD feed without code or with decimals() != 8.
    /// @notice Fix the deployment config and start with allowance 1%/day, allowlist on, sanctions on, Safe approved.
    /// @dev why: every address that matters is validated once here, since none of them can be changed afterwards.
    constructor(Config memory c) ERC20("NobuQuant nobuQQQ Core", "nobuQQQ") EIP712("nobuQQQ", "2") {
        // why: the Ondo and USDC addresses are mainnet-only; refuse to deploy anywhere else.
        if (block.chainid != 1) revert BadConfig();
        // why: a zero admin, Ondo manager, USDC or sanctions oracle would leave the vault unusable or unguarded.
        if (c.safe == address(0) || c.gm == address(0) || c.usdc == address(0) || c.sanctions == address(0)) {
            revert BadConfig();
        }
        // why: a zero user id would make quotes for no one acceptable.
        if (c.nbqUserId == bytes32(0)) revert BadConfig();
        // why: the Ondo manager must be a contract, or every quote check would fail.
        if (c.gm.code.length == 0) revert BadConfig();
        for (uint256 k; k < 3; ++k) {
            address s = c.gmSlots[k];
            if (s == address(0) || s.code.length == 0) revert BadConfig();
            // why: slot maths assumes 18-decimal GM tokens.
            if (_decimals(s) != 18) revert BadConfig();
        }
        if (c.usdc.code.length == 0) revert BadConfig();
        // why: slot maths and USDC_TO_WAD assume 6-decimal USDC.
        if (_decimals(c.usdc) != 6) revert BadConfig();
        // why: one token in two slots would double-count its balance in every slice.
        address[4] memory toks = [c.gmSlots[0], c.gmSlots[1], c.gmSlots[2], c.usdc];
        for (uint256 i; i < SLOTS; ++i) {
            for (uint256 j = i + 1; j < SLOTS; ++j) {
                if (toks[i] == toks[j]) revert BadConfig();
            }
        }
        // why: the feed must be a contract, and _usdcPx scales its answer assuming 8 decimals.
        if (c.usdcFeed == address(0) || c.usdcFeed.code.length == 0) revert BadConfig();
        if (_feedDecimals(c.usdcFeed) != 8) revert BadConfig();

        SAFE = c.safe;
        GM = c.gm;
        NBQ_USER_ID = c.nbqUserId;
        SANCTIONS = c.sanctions;
        USDC = c.usdc;
        USDC_FEED = c.usdcFeed;
        SLOT0 = c.gmSlots[0];
        SLOT1 = c.gmSlots[1];
        SLOT2 = c.gmSlots[2];

        dealer = c.dealer;
        // why: 100 bps = 1% per day is the default rebalance allowance.
        allowanceBps = 100;
        allowlistOn = true;
        sanctionsOn = true;
        // forge-lint: disable-next-line(unsafe-typecast)
        budgetAt = uint64(block.timestamp);
        // forge-lint: disable-next-line(unsafe-typecast)
        feeAt = uint64(block.timestamp);
        // why: the Safe must be able to make the genesis deposit and hold its fee shares while the allowlist is on.
        approved[c.safe] = true;
    }

    // =====================================================================
    // Dealer-only
    // =====================================================================

    /// @notice Mint `shares` to `d.client` against the client's EIP-3009 USDC payment (payee: this vault). Dealer only.
    /// @dev The vault keeps the USDC slice, forwards the rest to the dealer, and checks every GM slice by balance delta.
    ///      Genesis (totalSupply == 0): only the Safe, amounts = `genesis`, plus 1000 dead shares.
    ///      Why: the dealer buys the GM slices at Ondo with the client's USDC; the vault accepts only if its balances
    ///      rose by the exact pro-rata slices (rounded up).
    /// @param d Client-signed deposit ticket; its EIP-712 digest is the EIP-3009 nonce.
    /// @param usdcAuth Client signature over USDC ReceiveWithAuthorization.
    /// @param shares Shares to mint (>= d.minShares).
    /// @param genesis Genesis amounts per slot; must be all zero outside genesis.
    /// @param data Opaque dealer data.
    function deposit(
        Deposit calldata d,
        bytes calldata usdcAuth,
        uint256 shares,
        uint256[4] calldata genesis,
        bytes calldata data
    ) external lock onlyDealer {
        // why: from the announcement on no one may join; the vault is being wound down (cancel reopens it).
        if (windDownAt != 0) revert WindingDown();
        // FiatTokenV2_2 requires now < validBefore, so a deposit at now == deadline can never settle.
        if (block.timestamp >= d.deadline) revert DeadlinePassed();
        // why: only approved wallets may deposit (required even if the allowlist is off).
        if (!approved[d.client]) revert NotApproved(d.client);
        // why: compliance; a flagged wallet cannot enter.
        if (_sanctioned(d.client)) revert Sanctioned(d.client);
        // why: a zero mint would take USDC for nothing.
        if (shares == 0) revert ZeroShares();
        // why: enforces the client's signed minimum.
        if (shares < d.minShares) revert SharesBelowMin(shares, d.minShares);

        bytes32 h = _depositDigest(d);
        // why: the fee is settled first so the new depositor's slice is priced after the fee dilution.
        _accrueFee();
        uint256 S = totalSupply();
        if (S == 0) {
            // The Safe's signature fully determines genesis: shares are bound to the signed minShares and the
            // signed salt commits to the genesis mix, so the relayer chooses nothing (M-C1).
            if (shares != d.minShares) revert GenesisSharesMismatch(shares, d.minShares);
            if (d.salt != keccak256(abi.encode(genesis))) revert GenesisMixMismatch();
        }
        // Early cap (before any external call): an oversized mint reverts SupplyAboveMax, never a Panic in _mint.
        if (shares > MAX_SUPPLY) revert SupplyAboveMax(shares);
        if (S == 0 && shares + DEAD_SHARES > MAX_SUPPLY) revert SupplyAboveMax(shares + DEAD_SHARES);
        uint256[4] memory a = _depositAmounts(d.client, S, shares, genesis);
        // why: the client's payment must at least cover the USDC part of the slice the vault keeps.
        if (d.usdc < a[3]) revert UsdcBelowSlice(d.usdc, a[3]);

        uint256 u0 = _pullUsdc(d, h, usdcAuth);
        _fillDeposit(h, d.usdc - a[3], a, u0, data);

        // why: the dead shares are minted once, at genesis (see DEAD_SHARES).
        if (S == 0) _mint(DEAD, DEAD_SHARES);
        _mint(d.client, shares);
        // why: final supply check, including the fee shares minted above.
        if (totalSupply() > MAX_SUPPLY) revert SupplyAboveMax(totalSupply());
        emit Deposited(d.client, h, d.usdc, shares, a);
    }

    /// @notice Cash exit: burn the owner's shares, send the GM slice to the dealer, then pay the owner the USDC slice
    ///         plus what the dealer paid this vault, at least `r.minUsdc` in total. Dealer only.
    /// @dev Why: lets the dealer sell the GM slice at Ondo; the dealer pays this vault, the vault measures its own USDC
    ///      increase and forwards it, so the owner's signed minimum cannot be met with USDC from anywhere else (M-1).
    /// @param r Owner-signed redeem ticket.
    /// @param ownerSig Owner signature (EOA or ERC-1271) over the Redeem digest.
    /// @param data Opaque dealer data.
    function redeem(Redeem calldata r, bytes calldata ownerSig, bytes calldata data) external lock onlyDealer {
        // why: a signed redeem expires; unlike deposit there is no EIP-3009 window, so the deadline itself is valid.
        if (block.timestamp > r.deadline) revert DeadlinePassed();
        if (r.shares == 0) revert ZeroShares();
        // why: compliance; a flagged owner cannot cash out.
        if (_sanctioned(r.owner)) revert Sanctioned(r.owner);
        // why: replay protection; each signed ticket works once.
        if (usedRedeem[r.owner][r.nonce]) revert RedeemNonceUsed();
        // why: only the owner (EOA or ERC-1271 wallet) can authorise burning its shares.
        if (!SignatureChecker.isValidSignatureNow(r.owner, _redeemDigest(r), ownerSig)) revert BadOwnerSig();
        // why: marked used before any external call.
        usedRedeem[r.owner][r.nonce] = true;

        // why: the fee is settled first so the owner's slice is priced after the fee dilution.
        _accrueFee();
        // why: the slice rounds down, so rounding never favours the leaver.
        uint256[4] memory a = _slices(r.shares, totalSupply(), Math.Rounding.Floor);
        _burn(r.owner, r.shares);

        address dealer_ = dealer;
        uint256[3] memory gmIn = _sendGmToDealer(a, dealer_);
        // why: the dealer pays this vault; only the vault's own balance counts as payment (M-1).
        uint256 v0 = _bal(USDC);

        IDealer(dealer_).onRedeem(r.owner, gmIn, r.minUsdc, data);

        // why: the owner gets the USDC slice plus all the dealer paid in; that total must meet the signed minimum.
        uint256 paid = a[3] + _usdcIn(v0);
        if (paid < r.minUsdc) revert UsdcBelowMin(paid, r.minUsdc);
        if (paid > 0) _rawTransfer(USDC, r.owner, paid);
        emit Redeemed(r.owner, r.nonce, r.shares, paid, a);
    }

    /// @notice Swap vault slots with the dealer at Ondo-signed, Ondo-executed prices, within the daily allowance.
    ///         Dealer only (reached through the dealer's operator key).
    /// @dev Why: the only way the fund's mix changes. The allowance charges a fixed cap/4 per rebalance plus the value
    ///      shortfall measured at the executed Ondo quote prices (the dealer delivering less than the quoted value, and
    ///      rounding). Ondo's bid/ask spread and a stale or shopped quote are not measured; they are bounded only by
    ///      the number of rebalances (header Bounds).
    ///      Legs are disjoint per slot. GM legs (slots 0-2) need a verified quote of exactly that quantity whose
    ///      attestation is unused before and consumed after the callback. USDC out is valued at 1 USD,
    ///      USDC in at min(1 USD, Chainlink USDC/USD). Reverts RebalancesOff when the allowance is zero.
    /// @param outAmts Amounts the vault sends to the dealer, per slot.
    /// @param inAmts Amounts the dealer must push to the vault, per slot.
    /// @param q Ondo quotes for GM slots 0-2 (ignored for untraded slots).
    /// @param sig Ondo signatures for `q`.
    /// @param data Opaque dealer data.
    function rebalance(
        uint256[4] calldata outAmts,
        uint256[4] calldata inAmts,
        Quote[3] calldata q,
        bytes[3] calldata sig,
        bytes calldata data
    ) external lock onlyDealer {
        // why: once the wind-down is effective the mix is frozen; the notice period still allows rebalancing.
        if (_effective()) revert WindingDown();
        // why: lowerAllowance(0) switches rebalancing off.
        if (allowanceBps == 0) revert RebalancesOff();
        uint256 sumOut = 0;
        for (uint256 i; i < SLOTS; ++i) {
            // why: a slot is either sold or bought, never both, so values cannot be netted against each other.
            if (outAmts[i] != 0 && inAmts[i] != 0) revert LegsNotDisjoint();
            sumOut += outAmts[i];
        }
        // why: a swap must send something out.
        if (sumOut == 0) revert NothingOut();

        // why: every traded GM leg is checked against a signed, unused Ondo quote before anything moves.
        (uint256[3] memory p, uint256[3] memory ids) = _verifyLegs(outAmts, inAmts, q, sig, false);

        _accrueFee();
        address dealer_ = dealer;
        for (uint256 i; i < SLOTS; ++i) {
            if (outAmts[i] > 0) _rawTransfer(_token(i), dealer_, outAmts[i]);
        }
        uint256[4] memory b1;
        for (uint256 i; i < SLOTS; ++i) {
            if (inAmts[i] > 0) b1[i] = _bal(_token(i));
        }

        IDealer(dealer_).onRebalance(outAmts, inAmts, data);

        // why: the dealer must have delivered every promised inflow, measured by balance, not by its word.
        for (uint256 i; i < SLOTS; ++i) {
            if (inAmts[i] > 0) _requireDelta(_token(i), b1[i], inAmts[i]);
        }
        // why: each quote must really have been executed at Ondo, so the valuation price is a real fill.
        for (uint256 i; i < 3; ++i) {
            if (outAmts[i] + inAmts[i] > 0 && !_ondoUsed(ids[i])) revert QuoteNotExecuted(ids[i]);
        }

        (uint256 vOut, uint256 vIn) = _values(outAmts, inAmts, p);
        // why: charges the allowance bucket; reverts AllowanceExceeded when the charge is too large.
        _spendBudget(vOut, vIn);
        uint256 count = ++rebalanceCount;
        emit Rebalanced(count, outAmts, inAmts, p, ids, vOut, vIn, budgetUsed, _cap());
    }

    /// @notice Forced cash exit of an ineligible holder at Ondo's signed SELL price, paid in full in USDC. Dealer only.
    /// @dev Why: lets the fund remove a holder who must not stay, without that holder losing money: the dealer must pay
    ///      this vault at least the owed amount, measured on the vault's own balance (M-1), and the vault pays the
    ///      holder exactly that. The Dealer only calls this for holders the Safe has allowed.
    ///      Unapproves the holder and bumps its epoch. With zero shares it only emits Unregistered.
    ///      The quote quantity may differ from the slice by at most FORCE_SLACK_USD + 1 bp of value.
    /// @param holder Holder to cash out (never the Safe, the dead address or a sanctioned holder).
    /// @param q Ondo SELL quotes for GM slots 0-2 (ignored for zero slices).
    /// @param sig Ondo signatures for `q`.
    /// @param data Opaque dealer data.
    function forceRedeem(address holder, Quote[3] calldata q, bytes[3] calldata sig, bytes calldata data)
        external
        lock
        onlyDealer
    {
        // why: the Safe holds the fee shares and DEAD holds the dead shares; neither may be sold out.
        if (holder == SAFE || holder == DEAD) revert Protected(holder);
        // why: compliance; a flagged holder is frozen, not paid out.
        if (_sanctioned(holder)) revert Sanctioned(holder);
        // why: the holder loses approval and old declarations die (epoch + 1), so it must declare again to return.
        approved[holder] = false;
        uint256 ep = ++epoch[holder];
        _accrueFee();
        uint256 sh = balanceOf(holder);
        // why: nothing to pay out; the unapproval above is the whole effect.
        if (sh == 0) {
            emit Unregistered(holder, ep);
            return;
        }

        // why: the slice rounds down, so rounding never favours the leaver.
        uint256[4] memory a = _slices(sh, totalSupply(), Math.Rounding.Floor);
        (uint256 owedEx, uint256[3] memory ids) = _verifyForceLegs(a, q, sig);

        _burn(holder, sh);
        uint256 v0;
        {
            // (scoped: keeps the stack small enough to compile)
            address dealer_ = dealer;
            uint256[3] memory gmIn = _sendGmToDealer(a, dealer_);
            // why: the dealer pays this vault; only the vault's own balance counts as payment (M-1).
            v0 = _bal(USDC);
            IDealer(dealer_).onForceRedeem(holder, gmIn, owedEx, data);
        }

        // why: each sold slice must correspond to a quote Ondo really executed.
        for (uint256 k; k < 3; ++k) {
            if (a[k] > 0 && !_ondoUsed(ids[k])) revert QuoteNotExecuted(ids[k]);
        }
        uint256 owed = owedEx + a[3];
        uint256 paid = a[3] + _usdcIn(v0);
        // why: a forced exit pays the holder in full (there is no signed minimum): the dealer must pay this vault at
        // least owedEx, measured on the vault's own balance (M-1). The holder gets exactly what is owed; any surplus
        // stays with all holders.
        if (paid < owed) revert UsdcBelowMin(paid, owed);
        if (owed > 0) _rawTransfer(USDC, holder, owed);
        emit ForceRedeemed(holder, sh, owed, a, ids);
    }

    /// @notice Approve a wallet from its signed self-declaration for the current epoch. Dealer only.
    /// @dev Why: the declaration is the wallet's own signed statement of the terms it accepts (termsHash); the epoch
    ///      makes a declaration void after an unregister or forced exit.
    /// @param d Declaration (wallet, terms hash, epoch).
    /// @param sig Wallet signature (EOA or ERC-1271) over the Declaration digest.
    function register(Declaration calldata d, bytes calldata sig) external lock onlyDealer {
        // why: a declaration signed before an unregister must not work again.
        if (d.epoch != epoch[d.wallet]) revert BadDeclaration();
        // why: only the wallet itself (EOA or ERC-1271) can declare for itself.
        if (!SignatureChecker.isValidSignatureNow(d.wallet, _declarationDigest(d), sig)) revert BadDeclaration();
        approved[d.wallet] = true;
        emit Registered(d.wallet, d.termsHash, d.epoch);
    }

    /// @notice Remove a wallet's approval and invalidate its declarations (epoch + 1). Dealer only.
    /// @dev Why: lets the fund stop a wallet from depositing or (allowlist on) sending and receiving shares without
    ///      touching its shares; the wallet can still exit with redeemInKind, which needs no approval.
    /// @param wallet Wallet to unregister.
    function unregister(address wallet) external lock onlyDealer {
        // why: the Safe holds the fee shares and DEAD the dead shares; neither may be unregistered.
        if (wallet == SAFE || wallet == DEAD) revert Protected(wallet);
        approved[wallet] = false;
        uint256 ep = ++epoch[wallet];
        emit Unregistered(wallet, ep);
    }

    // =====================================================================
    // Anyone
    // =====================================================================

    /// @notice Burn `shares` and receive their pro-rata slice of all four slots and of each named token. Anyone.
    /// @dev Why: the guaranteed exit, with no dealer, price, pause or allowlist; of the vault's own checks only the sanctions flag (P3) can block it.
    ///      All or nothing: if a token being delivered (a slot token with a non-zero slice, or a named token) refuses the
    ///      transfer or the balance read (an Ondo pause, blocklist or compliance hook, or a Circle blacklist), the whole
    ///      call reverts (TransferFailed(token) for a refused transfer) and nothing changes; the holder can call again
    ///      once the token works. Nothing is skipped, held or forfeited. A slot whose slice is 0 is not called.
    ///      Mix risk: the slice is computed from the balances at inclusion. A rebalance that lands before this call
    ///      changes only the mix, not the share of value; its value loss is capped by the rebalance allowance and the
    ///      leaver bears the same as every remaining holder. The holder sends the call, so no minOut or deadline is used.
    ///      An unlisted airdrop slice stays with the remaining holders (it is not a promised token).
    /// @param shares Shares to burn.
    /// @param named Extra tokens held by the vault, strictly increasing, none a slot token or this vault.
    function redeemInKind(uint256 shares, address[] calldata named) external lock {
        if (shares == 0) revert ZeroShares();
        // why: compliance requirement; a flagged wallet cannot exit until the flag is lifted.
        if (_sanctioned(msg.sender)) revert Sanctioned(msg.sender);
        // why: named tokens must be unique extras (see _checkNamed), so none is paid twice or doubles a slot.
        _checkNamed(named);

        // why: fee shares are minted first so the pro-rata base includes them.
        _accrueFee();
        uint256 S0 = totalSupply();
        uint256[4] memory pre;
        uint256[4] memory amounts;
        bool any = false;
        for (uint256 k; k < SLOTS; ++k) {
            pre[k] = _bal(_token(k));
            // why: pre stays the raw balance (for _checkNotTampered); the slice is of the free balance (not held).
            amounts[k] = Math.mulDiv(_free(k, pre[k]), shares, S0);
            if (amounts[k] > 0) any = true;
        }
        uint256[] memory namedAmounts = new uint256[](named.length);
        for (uint256 j; j < named.length; ++j) {
            namedAmounts[j] = Math.mulDiv(_bal(named[j]), shares, S0);
            if (namedAmounts[j] > 0) any = true;
        }
        // why: burning shares for nothing is a mistake (every slice rounded to zero); refuse it.
        if (!any) revert NothingToRedeem();

        // why: burn before paying out, so the transfers below cannot be used against an unburned balance.
        _burn(msg.sender, shares);
        uint256 supplyAfter = S0 - shares;

        for (uint256 k; k < SLOTS; ++k) {
            if (amounts[k] > 0) _rawTransfer(_token(k), msg.sender, amounts[k]);
        }
        for (uint256 j; j < named.length; ++j) {
            if (namedAmounts[j] == 0) continue;
            _rawTransfer(named[j], msg.sender, namedAmounts[j]);
            // why: a named token is arbitrary code; it must not have moved slot balances or supply behind the vault's back.
            _checkNotTampered(named[j], pre, amounts, supplyAfter);
        }

        emit RedeemedInKind(msg.sender, shares, amounts, named, namedAmounts);
    }

    /// @notice After the wind-down is effective, send `holder` their whole pro-rata share in kind and burn their
    ///         shares. Callable by the Safe or by the holder only. A slice the token refuses is kept for the holder
    ///         (`held`) and delivered by the next pushOut. Skips the dead address and a sanctioned holder (no effect).
    /// @dev Why: lets the Safe close the fund without any holder's action, and never lets it take value: the
    ///      recipient is always the holder and the amount always their own floor-rounded slice of the free balance.
    ///      Why only Safe or holder: a stranger could otherwise force holds by starving gas or push an Ondo-blocked
    ///      holder out of their cash exit. Why `held` is a token amount, not shares: a share claims all four slots, so
    ///      a residual share would pay an already delivered slot twice. Held amounts leave every pro-rata base
    ///      (`heldTotal`), and the claim is cleared before its transfer, so a reentering token only meets the lock.
    /// @param holder Wallet to push out.
    function pushOut(address holder) external lock {
        // why: caller rule above; reuses NotSafe for a stranger.
        if (msg.sender != SAFE && msg.sender != holder) revert NotSafe();
        // why: nothing happens before the announced time (also when nothing was announced).
        if (!_effective()) revert TimelockNotReady();
        // why: skip instead of revert, so one MultiSend can push many holders; DEAD's shares and a flagged wallet's
        // shares stay in the vault (compliance), as for every other exit.
        if (holder == DEAD || _sanctioned(holder)) return;
        // why: the fee is settled first so the holder's slice is priced after the fee dilution.
        _accrueFee();
        uint256 sh = balanceOf(holder);
        uint256[4] memory a;
        if (sh > 0) {
            a = _slices(sh, totalSupply(), Math.Rounding.Floor);
            _burn(holder, sh);
        }
        uint256[4] memory sent;
        uint256[4] memory kept;
        for (uint256 k; k < SLOTS; ++k) {
            uint256 h0 = held[holder][k];
            uint256 x = h0 + a[k];
            if (x == 0) continue;
            // why: the old claim is cleared before the call; a refusal below re-records the full amount.
            if (h0 != 0) {
                held[holder][k] = 0;
                heldTotal[k] -= h0;
            }
            if (_tryTransfer(_token(k), holder, x)) {
                sent[k] = x;
            } else {
                held[holder][k] = x;
                heldTotal[k] += x;
                kept[k] = x;
            }
        }
        emit PushedOut(holder, sh, sent, kept);
    }

    /// @notice Turn the share allowlist off (one-way) once the Safe's 14-day timelock is ready, within 7 days. Anyone.
    /// @dev Why: open to anyone so the change needs no further Safe action once the public wait is over; the Safe can
    ///      still cancel it before it executes.
    function executeAllowlistOff() external {
        // why: it is one-way and already done.
        if (!allowlistOn) revert AlreadyOff();
        uint64 eta = allowlistOffEta;
        // why: nothing was queued.
        if (eta == 0) revert NoPendingAllowlistOff();
        // why: the 14-day public notice must pass first, and a queued change goes stale after 7 days.
        _requireWindow(eta);
        allowlistOn = false;
        allowlistOffEta = 0;
        emit AllowlistOff();
    }

    // =====================================================================
    // Safe-only
    // =====================================================================

    /// @notice Set the dealer (instant; zero disables dealer paths). Safe only.
    /// @dev Why instant: setDealer(0) is the emergency stop. Client protections live in this vault (allowance, signed
    ///      minimums, full payout on a forced exit, the in-kind exit), so a replacement dealer drops only the
    ///      Dealer's own gates (forced-exit permission and daily limits), not the vault's.
    /// @param newDealer New dealer address.
    // forge-lint: disable-next-line(missing-zero-check)
    function setDealer(address newDealer) external onlySafe {
        address old = dealer;
        dealer = newDealer;
        emit DealerSet(old, newDealer);
    }

    /// @notice Lower the rebalance allowance instantly; also clears any pending raise. Safe only.
    /// @dev Why instant: it only tightens, and it is the stop for a suspected bad operator key. The used part of the
    ///      bucket is rescaled to the new cap (rounded up) so lowering never frees headroom.
    /// @param bps New allowance in bps (strictly lower).
    function lowerAllowance(uint16 bps) external onlySafe {
        uint16 old = allowanceBps;
        // why: this function may only tighten; raises go through the timelock.
        if (bps >= old) revert AllowanceNotLower();
        // why: settle the refill at the old rate before rescaling.
        _decay();
        budgetUsed = Math.mulDiv(budgetUsed, bps, old, Math.Rounding.Ceil);
        allowanceBps = bps;
        pendingAllowanceBps = 0;
        allowanceEta = 0;
        emit AllowanceLowered(old, bps);
    }

    /// @notice Queue an allowance raise, executable 7 days later for 7 days, up to MAX_ALLOWANCE_BPS. Safe only.
    /// @dev Why: loosening the cap needs 7 days of public notice. A new queue replaces a pending one.
    /// @param bps New allowance in bps (strictly higher, at most MAX_ALLOWANCE_BPS).
    function queueAllowanceRaise(uint16 bps) external onlySafe {
        // why: this function may only raise; lowering is lowerAllowance.
        if (bps <= allowanceBps) revert AllowanceNotHigher();
        // why: the 5% ceiling can never be exceeded, whatever the Safe signs.
        if (bps > MAX_ALLOWANCE_BPS) revert AllowanceAboveMax();
        // forge-lint: disable-next-line(unsafe-typecast)
        uint64 eta = uint64(block.timestamp) + ALLOWANCE_DELAY;
        pendingAllowanceBps = bps;
        allowanceEta = eta;
        emit AllowanceRaiseQueued(bps, eta);
    }

    /// @notice Cancel the pending allowance raise. Safe only.
    /// @dev Why: lets the Safe withdraw a raise it no longer wants during the notice period.
    function cancelAllowanceRaise() external onlySafe {
        // why: nothing queued.
        if (allowanceEta == 0) revert NoPendingRaise();
        pendingAllowanceBps = 0;
        allowanceEta = 0;
        emit AllowanceRaiseCancelled();
    }

    /// @notice Apply the pending allowance raise inside its execution window. Safe only.
    /// @dev Why: the second step of the timelocked raise.
    function executeAllowanceRaise() external onlySafe {
        uint64 eta = allowanceEta;
        // why: nothing queued.
        if (eta == 0) revert NoPendingRaise();
        // why: the 7-day public notice must pass first, and a queued raise goes stale after 7 days.
        _requireWindow(eta);
        // why: settle the refill at the old rate before the cap changes.
        _decay();
        uint16 old = allowanceBps;
        uint16 nu = pendingAllowanceBps;
        allowanceBps = nu;
        pendingAllowanceBps = 0;
        allowanceEta = 0;
        emit AllowanceRaised(old, nu);
    }

    /// @notice Queue turning the share allowlist off (14-day timelock; anyone executes). Safe only.
    /// @dev Why: the allowlist is a compliance control the fund may later retire; the long wait gives holders notice.
    function queueAllowlistOff() external onlySafe {
        // why: it is one-way and already off.
        if (!allowlistOn) revert AlreadyOff();
        // forge-lint: disable-next-line(unsafe-typecast)
        uint64 eta = uint64(block.timestamp) + ALLOWLIST_DELAY;
        allowlistOffEta = eta;
        emit AllowlistOffQueued(eta);
    }

    /// @notice Cancel the pending allowlist-off. Safe only.
    /// @dev Why: lets the Safe withdraw the change before it executes.
    function cancelAllowlistOff() external onlySafe {
        // why: nothing queued.
        if (allowlistOffEta == 0) revert NoPendingAllowlistOff();
        allowlistOffEta = 0;
        emit AllowlistOffCancelled();
    }

    /// @notice Announce the wind-down: deposits stop now and pushOut works 14 days later. One active announcement at a time. Safe only.
    /// @dev Why: the public notice period lets every holder exit on their own before the Safe pushes anyone out.
    function announceWindDown() external onlySafe {
        // why: one announcement; its date never moves later or earlier.
        if (windDownAt != 0) revert WindingDown();
        // forge-lint: disable-next-line(unsafe-typecast)
        uint64 eta = uint64(block.timestamp) + WIND_DOWN_DELAY;
        windDownAt = eta;
        emit WindDownAnnounced(eta);
    }

    /// @notice Withdraw the announcement while the notice runs; impossible once it is effective. Safe only.
    /// @dev Why: gives the Safe an exit from a mistaken announcement, but never after holders may have been pushed out.
    function cancelWindDown() external onlySafe {
        uint64 w = windDownAt;
        // why: nothing announced.
        if (w == 0) revert NoWindDown();
        // why: after the effective time the wind-down is irreversible (held amounts and pushed-out holders exist).
        if (block.timestamp >= w) revert WindingDown();
        windDownAt = 0;
        emit WindDownCancelled();
    }

    /// @notice Turn the on-chain sanctions check off (one-way). Safe only.
    /// @dev Why: an escape if the oracle's list ever blocks exits wrongly; it cannot be turned back on.
    function disableSanctionsCheck() external onlySafe {
        // why: it is one-way and already off.
        if (!sanctionsOn) revert AlreadyOff();
        sanctionsOn = false;
        emit SanctionsCheckOff();
    }

    // =====================================================================
    // ERC-20 (locked transfers; approved-only via _update)
    // =====================================================================

    /// @notice ERC-20 transfer; both sides must be approved while the allowlist is on, and neither may be sanctioned.
    /// @dev Why locked: a transfer cannot run inside a dealer callback.
    function transfer(address to, uint256 value) public override lock returns (bool) {
        return super.transfer(to, value);
    }

    /// @notice ERC-20 transferFrom; both sides must be approved while the allowlist is on, and neither may be sanctioned.
    ///         A third-party spender is also screened, after the allowance and approved checks.
    /// @dev Why locked: a transfer cannot run inside a dealer callback.
    function transferFrom(address from, address to, uint256 value) public override lock returns (bool) {
        bool ok = super.transferFrom(from, to, value);
        // why: a sanctioned spender must not move an approved holder's shares (same fail-open/canary/off semantics).
        if (msg.sender != from && _sanctioned(msg.sender)) revert Sanctioned(msg.sender);
        return ok;
    }

    /// @dev Mints and burns are never checked: fee and genesis mints and every exit must always work.
    ///      Why the approved check: while the allowlist is on only approved wallets move shares.
    ///      Why the sanctions check runs in both modes: an approved wallet that is later flagged must not pass its
    ///      shares to another approved wallet that then exits (F-N1); `_sanctioned` still fails open on a broken
    ///      oracle, so a bad oracle never blocks a transfer, and exits (burns) never reach this check.
    ///      The spender of a transferFrom is screened in transferFrom itself, not here.
    function _update(address from, address to, uint256 value) internal override {
        if (from != address(0) && to != address(0)) {
            if (allowlistOn) {
                if (!approved[from]) revert NotApproved(from);
                if (!approved[to]) revert NotApproved(to);
            }
            if (_sanctioned(from)) revert Sanctioned(from);
            if (_sanctioned(to)) revert Sanctioned(to);
        }
        super._update(from, to, value);
    }

    // =====================================================================
    // Views
    // =====================================================================

    /// @notice Slot amounts per 1e18 shares, including the pending fee (rounded down). Reverts Locked inside a vault call.
    /// @dev Why: the public price signal for integrators; the lock guard stops a dealer reading it mid-flow.
    function assetsPerShare() external view notLocked returns (uint256[4] memory) {
        return _previewSlices(WAD, Math.Rounding.Floor);
    }

    /// @notice Slot amounts for `shares`, including the pending fee. Reverts Locked inside a vault call.
    /// @dev Why: lets the backend and clients size a deposit (round up) or an exit (round down) like the contract does.
    /// @param shares Share amount.
    /// @param roundUp Round up (deposit side) or down (redeem side).
    function previewSlice(uint256 shares, bool roundUp) external view notLocked returns (uint256[4] memory) {
        return _previewSlices(shares, roundUp ? Math.Rounding.Ceil : Math.Rounding.Floor);
    }

    /// @notice Fee shares that the next accrual would mint to the Safe.
    /// @dev Why: lets anyone see the accrued, not yet minted fee.
    function pendingFeeShares() external view returns (uint256) {
        return _pendingFee();
    }

    /// @notice Allowance state with the budget decayed to now (no write).
    /// @dev Why: lets the operator and anyone see the remaining rebalance headroom and a pending raise.
    function allowanceState()
        external
        view
        returns (uint16 allowanceBps_, uint256 budgetUsedNow, uint256 cap, uint16 pendingBps, uint64 eta)
    {
        cap = _cap();
        budgetUsedNow = _decayedUsed(cap);
        return (allowanceBps, budgetUsedNow, cap, pendingAllowanceBps, allowanceEta);
    }

    /// @notice EIP-712 digest of a Deposit (also the EIP-3009 nonce).
    /// @dev Why: wallets and the backend sign and verify the exact hash the contract uses.
    function depositDigest(Deposit calldata d) external view returns (bytes32) {
        return _depositDigest(d);
    }

    /// @notice EIP-712 digest of a Redeem.
    /// @dev Why: wallets and the backend sign and verify the exact hash the contract uses.
    function redeemDigest(Redeem calldata r) external view returns (bytes32) {
        return _redeemDigest(r);
    }

    /// @notice EIP-712 digest of a Declaration.
    /// @dev Why: wallets and the backend sign and verify the exact hash the contract uses.
    function declarationDigest(Declaration calldata d) external view returns (bytes32) {
        return _declarationDigest(d);
    }

    /// @notice Ondo EIP-712 digest of a quote under the live GM domain separator.
    /// @dev Why: lets tests and the backend check a quote signature the way the vault will.
    function ondoQuoteDigest(Quote calldata q) external view returns (bytes32) {
        return _ondoDigest(q);
    }

    /// @notice Slot token: i < 3 GM slots, i == 3 USDC. Reverts for i > 3 (array bounds).
    /// @dev Why: exposes the private slot immutables as one indexed getter (part of the frozen ABI).
    function SLOT(uint256 i) external view returns (address) {
        address[4] memory s = [SLOT0, SLOT1, SLOT2, USDC];
        return s[i];
    }

    /// @dev Reverts unless now is inside a queued timelock's execution window [eta, eta + EXEC_WINDOW].
    ///      Why: one check for both timelocks (allowance raise, allowlist off); TimelockNotReady before, TimelockExpired after.
    function _requireWindow(uint64 eta) private view {
        if (block.timestamp < eta) revert TimelockNotReady();
        if (block.timestamp > uint256(eta) + EXEC_WINDOW) revert TimelockExpired();
    }

    // =====================================================================
    // Internal: flows
    // =====================================================================

    /// @dev Slot amounts a deposit must add: the signed genesis mix at genesis, else the pro-rata slice rounded up.
    ///      Why: the first deposit sets the mix and only the Safe may make it; later deposits cannot change the mix.
    function _depositAmounts(address client, uint256 S, uint256 shares, uint256[4] calldata genesis)
        internal
        view
        returns (uint256[4] memory a)
    {
        if (S == 0) {
            uint256 sum = 0;
            for (uint256 k; k < SLOTS; ++k) {
                sum += genesis[k];
            }
            // why: only the Safe may seed the vault, and with something.
            if (client != SAFE || sum == 0) revert GenesisOnly();
            for (uint256 k; k < SLOTS; ++k) {
                a[k] = genesis[k];
            }
        } else {
            for (uint256 k; k < SLOTS; ++k) {
                // why: the genesis mix is meaningful only at genesis; a non-zero value later would be ignored silently.
                if (genesis[k] != 0) revert GenesisMustBeZero();
            }
            // why: rounded up, so the depositor never pays less than the exact pro-rata slice.
            a = _slices(shares, S, Math.Rounding.Ceil);
        }
    }

    /// @dev Pulls the client's exact signed USDC via EIP-3009 (nonce = deposit digest). Returns the pre-pull balance.
    function _pullUsdc(Deposit calldata d, bytes32 h, bytes calldata usdcAuth) internal returns (uint256 u0) {
        u0 = _bal(USDC);
        IUsdc3009(USDC).receiveWithAuthorization(d.client, address(this), d.usdc, 0, d.deadline, h, usdcAuth);
        uint256 b = _bal(USDC);
        uint256 got = b > u0 ? b - u0 : 0;
        // why: the vault must really have received the signed amount (a short pull is refused).
        if (got != d.usdc) revert UsdcMismatch(got, d.usdc);
    }

    /// @dev Forwards `fwd` USDC to the dealer, calls onDeposit, then checks every slice by balance delta.
    function _fillDeposit(bytes32 h, uint256 fwd, uint256[4] memory a, uint256 u0, bytes calldata data) internal {
        address dealer_ = dealer;
        if (fwd > 0) _rawTransfer(USDC, dealer_, fwd);

        uint256[3] memory b0;
        uint256[3] memory gmOut;
        for (uint256 k; k < 3; ++k) {
            b0[k] = _bal(_token(k));
            gmOut[k] = a[k];
        }
        IDealer(dealer_).onDeposit(h, fwd, gmOut, data);
        for (uint256 k; k < 3; ++k) {
            _requireDelta(_token(k), b0[k], a[k]);
        }
        _requireDelta(USDC, u0, a[3]);
    }

    /// @dev sliceUp = ceil(bal * shares / S) (mint), sliceDown = floor(bal * shares / S) (burn).
    ///      Why: rounding goes in the vault's favour on both sides, so it never costs the other holders.
    function _slices(uint256 shares, uint256 S, Math.Rounding rnd) internal view returns (uint256[4] memory a) {
        for (uint256 k; k < SLOTS; ++k) {
            a[k] = Math.mulDiv(_free(k, _bal(_token(k))), shares, S, rnd);
        }
    }

    /// @dev The part of slot k's balance `b` that belongs to the pro-rata base: the balance less amounts kept for
    ///      holders by a refused pushOut. Why: a held amount is a fixed claim of its holder, not shared with the others.
    function _free(uint256 k, uint256 b) internal view returns (uint256) {
        uint256 h = heldTotal[k];
        return h < b ? b - h : 0;
    }

    /// @dev True once an announced wind-down has reached its effective time.
    function _effective() internal view returns (bool) {
        uint64 w = windDownAt;
        return w != 0 && block.timestamp >= w;
    }

    /// @dev Read-only slice over the supply including the fee that the next accrual would mint; zeros when empty.
    function _previewSlices(uint256 shares, Math.Rounding rnd) internal view returns (uint256[4] memory a) {
        uint256 S = totalSupply() + _pendingFee();
        if (S != 0) a = _slices(shares, S, rnd);
    }

    /// @dev Sends the GM part of a slice to the dealer; the dealer sells it at Ondo.
    function _sendGmToDealer(uint256[4] memory a, address dealer_) internal returns (uint256[3] memory gm) {
        for (uint256 k; k < 3; ++k) {
            gm[k] = a[k];
            if (a[k] > 0) _rawTransfer(_token(k), dealer_, a[k]);
        }
    }

    /// @dev Checks every traded GM leg against its Ondo quote (quantity, side by direction, unused, distinct) and
    ///      returns each leg's price and attestation id (zero for an untraded slot). A leg sells when `outAmts[i] > 0`,
    ///      else buys; its quantity is `outAmts[i] + inAmts[i]`. `slack` selects the forced-exit quantity bound.
    ///      Why: one verifier for rebalance and forceRedeem; a leg is only valid if Ondo signed this exact trade for this
    ///      fund and has not yet executed it.
    function _verifyLegs(
        uint256[4] memory outAmts,
        uint256[4] memory inAmts,
        Quote[3] calldata q,
        bytes[3] calldata sig,
        bool slack
    ) internal view returns (uint256[3] memory p, uint256[3] memory ids) {
        for (uint256 i; i < 3; ++i) {
            uint256 qty = outAmts[i] + inAmts[i];
            // why: an untraded slot needs no quote.
            if (qty == 0) continue;
            p[i] = _verifyQuote(q[i], sig[i], _token(i), outAmts[i] > 0 ? SELL : BUY, qty, slack);
            ids[i] = q[i].attestationId;
            // why: an already executed quote proves nothing about this call; it must be fresh.
            if (_ondoUsed(ids[i])) revert QuoteAlreadyUsed(ids[i]);
            for (uint256 j; j < i; ++j) {
                // why: one quote cannot cover two legs.
                if (outAmts[j] + inAmts[j] > 0 && ids[j] == ids[i]) revert DuplicateAttestation(ids[i]);
            }
        }
    }

    /// @dev Checks the SELL quote of each non-zero GM slice of a forced exit and sums the USDC owed for them.
    ///      Why: the holder is owed the Ondo-signed sell value of its slice; owedEx is in 6-decimal USDC, rounded down.
    function _verifyForceLegs(uint256[4] memory a, Quote[3] calldata q, bytes[3] calldata sig)
        internal
        view
        returns (uint256 owedEx, uint256[3] memory ids)
    {
        uint256[4] memory none;
        uint256[3] memory p;
        (p, ids) = _verifyLegs(a, none, q, sig, true);
        uint256 sum = 0;
        for (uint256 k; k < 3; ++k) {
            sum += a[k] * p[k];
        }
        // why: price (1e18) x quantity (1e18) / 1e30 = USDC with 6 decimals, rounded down.
        owedEx = sum / 1e30;
    }

    /// @dev Values a rebalance in WAD USD: the sold side at quote prices rounded up (USDC out at 1 USD), the bought side
    ///      at quote prices rounded down (USDC in at the feed-guarded price).
    function _values(uint256[4] calldata outAmts, uint256[4] calldata inAmts, uint256[3] memory p)
        internal
        view
        returns (uint256 vOut, uint256 vIn)
    {
        uint256 so = 0;
        uint256 si = 0;
        for (uint256 i; i < 3; ++i) {
            so += outAmts[i] * p[i];
            si += inAmts[i] * p[i];
        }
        // why: out rounds up and in rounds down, so rounding can only overstate the shortfall.
        vOut = Math.ceilDiv(so, WAD) + outAmts[3] * USDC_TO_WAD;
        // why: the feed is read only when USDC actually comes in, so a stale feed cannot block other rebalances.
        uint256 px = inAmts[3] > 0 ? _usdcPx() : 0;
        vIn = si / WAD + inAmts[3] * USDC_TO_WAD * px / WAD;
    }

    /// @dev USDC-in price in WAD: min(1 USD, Chainlink answer * 1e10). Reverts StaleUsdcFeed on a non-positive
    ///      answer, a zero or future updatedAt, or an answer older than USDC_FEED_MAX_AGE. USDC-out stays at par.
    function _usdcPx() internal view returns (uint256) {
        // forge-lint: disable-next-line(unused-return)
        (, int256 answer,, uint256 updatedAt,) = IChainlinkFeed(USDC_FEED).latestRoundData();
        // why: a non-positive answer, or a timestamp that is zero or in the future, cannot be a valid price.
        if (answer <= 0 || updatedAt == 0 || updatedAt > block.timestamp) revert StaleUsdcFeed();
        // why: an old answer must not value USDC.
        if (block.timestamp - updatedAt > USDC_FEED_MAX_AGE) revert StaleUsdcFeed();
        // why: scale 8 decimals to 18; capped at 1 USD so a feed above par never overvalues USDC.
        // forge-lint: disable-next-line(unsafe-typecast)
        return Math.min(WAD, uint256(answer) * 1e10);
    }

    /// @dev Validates the extra token list of redeemInKind.
    ///      Why: strictly increasing order means no duplicates; excluding the slot tokens and this vault keeps each slot's
    ///      payout on the main path and keeps the share token out of the list.
    function _checkNamed(address[] calldata named) internal view {
        for (uint256 j; j < named.length; ++j) {
            address t = named[j];
            // why: strictly increasing order proves the list has no duplicates.
            if (j > 0 && t <= named[j - 1]) revert BadNamedList();
            // why: slot tokens are paid by the main path and the vault's own token is the share being burned.
            if (t == address(this) || t == SLOT0 || t == SLOT1 || t == SLOT2 || t == USDC) revert BadNamedList();
        }
    }

    /// @dev After a named-token transfer, confirms all four slot balances and the supply are exactly as expected.
    ///      Why: a named token is arbitrary code and could try to move vault assets or change the supply during its transfer.
    function _checkNotTampered(
        address token,
        uint256[4] memory pre,
        uint256[4] memory amounts,
        uint256 supplyAfter
    ) internal view {
        for (uint256 k; k < SLOTS; ++k) {
            if (_bal(_token(k)) != pre[k] - amounts[k]) revert NamedTokenTampered(token);
        }
        if (totalSupply() != supplyAfter) revert NamedTokenTampered(token);
    }

    // =====================================================================
    // Internal: quotes (spec B4 steps 1-9; live GM domain and signer role)
    // =====================================================================

    /// @dev Checks one Ondo quote and returns its price. `slack` replaces step 5 (exact quantity) with the forceRedeem
    ///      bound: the quantity difference may be worth at most FORCE_SLACK_USD + 1 bp of the slice value at the quote
    ///      price. Why: a forced exit's slice can move between quote and execution (fees, deposits, dust), so it needs a
    ///      small tolerance; rebalances do not.
    function _verifyQuote(Quote calldata q, bytes calldata sig, address asset, uint8 side, uint256 qty, bool slack)
        internal
        view
        returns (uint256)
    {
        // why: a quote signed for another chain, user, asset or side must not be used here.
        if (q.chainId != block.chainid) revert QuoteWrongChain();
        if (q.userId != NBQ_USER_ID) revert QuoteWrongUser();
        if (q.asset != asset) revert QuoteWrongAsset();
        if (q.side != side) revert QuoteWrongSide();
        if (slack) {
            uint256 diff = q.quantity > qty ? q.quantity - qty : qty - q.quantity;
            if (diff * q.price / 1e18 > FORCE_SLACK_USD + qty * q.price / 1e18 / 10_000) revert QuoteQtyMismatch();
        } else if (q.quantity != qty) {
            revert QuoteQtyMismatch();
        }
        // why: an expired quote must not be accepted.
        if (block.timestamp > q.expiration) revert QuoteExpired();
        // why: a zero price would value a leg at nothing.
        if (q.price == 0) revert QuotePriceZero();
        (address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(_ondoDigest(q), sig);
        // why: only a signature by an account holding Ondo's attestation-signer role makes a quote valid.
        if (err != ECDSA.RecoverError.NoError || !IGm(GM).hasRole(GmConstants.ATTESTATION_SIGNER_ROLE, signer)) {
            revert QuoteBadSigner();
        }
        return q.price;
    }

    /// @dev Ondo's EIP-712 digest of a quote, built under the live domain separator read from the GM manager.
    function _ondoDigest(Quote calldata q) internal view returns (bytes32) {
        bytes32 structHash = keccak256(
            abi.encode(
                GmConstants.QUOTE_TYPEHASH,
                q.chainId,
                q.attestationId,
                q.userId,
                q.asset,
                q.price,
                q.quantity,
                q.expiration,
                q.side,
                q.additionalData
            )
        );
        return keccak256(abi.encodePacked(hex"1901", IGm(GM).getDomainSeparator(), structHash));
    }

    /// @dev True once Ondo has executed this attestation id. Why: proof that the quote was really filled.
    function _ondoUsed(uint256 attestationId) internal view returns (bool) {
        return IGm(GM).executedAttestationIds(attestationId);
    }

    // =====================================================================
    // Internal: allowance (leaky bucket, C0 section 6)
    // =====================================================================

    /// @dev Bucket size as a WAD fraction of NAV (1 bps = 1e14).
    function _cap() internal view returns (uint256) {
        return uint256(allowanceBps) * 1e14;
    }

    /// @dev Bucket fill after the linear refill since budgetAt (a full cap per DAY), floored at zero.
    function _decayedUsed(uint256 cap) internal view returns (uint256) {
        uint256 refill = cap * (block.timestamp - budgetAt) / DAY;
        uint256 used = budgetUsed;
        return used > refill ? used - refill : 0;
    }

    /// @dev Writes the refilled fill level and restarts the refill clock.
    function _decay() internal {
        budgetUsed = _decayedUsed(_cap());
        // forge-lint: disable-next-line(unsafe-typecast)
        budgetAt = uint64(block.timestamp);
    }

    /// @dev Every rebalance costs cap / REBALANCE_CHARGE_DIV plus its value shortfall; the cap is always checked (H5).
    function _spendBudget(uint256 vOut, uint256 vIn) internal {
        _decay();
        uint256 cap = _cap();
        uint256 used = budgetUsed + cap / REBALANCE_CHARGE_DIV;
        // why: any value lost (less received than sent) is charged as a fraction of the value sent out.
        if (vIn < vOut) used += Math.mulDiv(vOut - vIn, WAD, vOut, Math.Rounding.Ceil);
        budgetUsed = used;
        // why: the daily allowance is a hard limit; exceeding it undoes the rebalance.
        if (used > cap) revert AllowanceExceeded(used, cap);
    }

    // =====================================================================
    // Internal: fee (I4; never reverts, never moves tokens)
    // =====================================================================

    /// @dev Fee shares owed since feeAt. why: minting f = S*r/(1-r) new shares leaves the Safe with exactly the fraction
    ///      r = (FEE_BPS/10000) * dt/YEAR of the new supply, i.e. a flat 2% per year.
    function _pendingFee() internal view returns (uint256) {
        uint256 S = totalSupply();
        uint256 at = feeAt;
        // why: the fee stops at the wind-down's effective time (decision D1); nothing accrues after it.
        uint256 t = block.timestamp;
        uint256 w = windDownAt;
        if (w != 0 && w < t) t = w;
        // why: no supply or no elapsed time means no fee.
        if (S == 0 || at >= t) return 0;
        uint256 dt = Math.min(t - at, MAX_FEE_DT);
        uint256 den = YEAR * 10_000 - dt * FEE_BPS;
        uint256 f = Math.mulDiv(S, dt * FEE_BPS, den);
        // Unreachable below MAX_SUPPLY (fee <= S/9); the clamp makes "cannot revert for any state" literally true.
        uint256 room = type(uint256).max - S;
        return f > room ? room : f;
    }

    /// @dev Mints the pending fee shares to the Safe and restarts the clock. Called before every flow that depends on
    ///      the supply. Never reverts and never moves tokens.
    function _accrueFee() internal {
        uint256 fee = _pendingFee();
        // forge-lint: disable-next-line(unsafe-typecast)
        feeAt = uint64(block.timestamp);
        if (fee > 0) {
            _mint(SAFE, fee);
            emit FeeAccrued(fee);
        }
    }

    // =====================================================================
    // Internal: sanctions (50k-gas staticcall, fails open, flag-everyone canary)
    // =====================================================================

    /// @dev True if the check is on, the oracle flags `a`, and the oracle does not also flag this vault.
    ///      Why: the canary (is the vault itself "flagged"?) detects an oracle that flags everyone, which must not freeze
    ///      all exits.
    function _sanctioned(address a) internal view returns (bool) {
        if (!sanctionsOn) return false;
        if (!_flagged(a)) return false;
        return !_flagged(address(this));
    }

    /// @dev True only for a successful call returning at least 32 bytes whose first word is exactly 1.
    ///      Copies at most 32 bytes of return data, so a gas-burning or junk oracle cannot block an exit.
    ///      A failed or short call with gasleft() <= SANCTIONS_GAS / 63 afterwards reverts InsufficientGas, so a
    ///      caller cannot starve the call to force the fail-open path.
    function _flagged(address a) internal view returns (bool flagged) {
        address oracle = SANCTIONS;
        bytes4 sel = ISanctions.isSanctioned.selector;
        bool good = false;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, sel)
            mstore(add(ptr, 0x04), and(a, 0xffffffffffffffffffffffffffffffffffffffff))
            let ok := staticcall(SANCTIONS_GAS, oracle, ptr, 0x24, ptr, 0x20)
            good := and(ok, iszero(lt(returndatasize(), 0x20)))
            flagged := and(good, eq(mload(ptr), 1))
        }
        if (!good && gasleft() <= SANCTIONS_GAS / 63) revert InsufficientGas();
    }

    // =====================================================================
    // Internal: tokens
    // =====================================================================

    /// @dev Slot index to token address.
    function _token(uint256 i) internal view returns (address) {
        if (i == 0) return SLOT0;
        if (i == 1) return SLOT1;
        if (i == 2) return SLOT2;
        return USDC;
    }

    /// @dev This vault's balance of `token`.
    function _bal(address token) internal view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
    }

    /// @dev Increase of this vault's USDC balance above `before`, floored at zero.
    ///      Why: exit payments are measured on the vault's own balance, never a holder's wallet (M-1).
    function _usdcIn(uint256 before) internal view returns (uint256) {
        uint256 nowBal = _bal(USDC);
        return nowBal > before ? nowBal - before : 0;
    }

    /// @dev Reverts SliceShort unless this vault's balance of `token` rose by at least `need` since `before`.
    ///      Why: the vault trusts balances, not the dealer's report.
    function _requireDelta(address token, uint256 before, uint256 need) internal view {
        uint256 b = _bal(token);
        uint256 got = b > before ? b - before : 0;
        if (got < need) revert SliceShort(token, need, got);
    }

    /// @dev Raw low-level transfer that never reverts on a refusal: returns true only for success with an empty or
    ///      exactly `true` return. Copies at most 32 bytes of return data.
    ///      Why: pushOut keeps a slice a token refuses instead of reverting the whole call.
    function _tryTransfer(address token, address to, uint256 amount) internal returns (bool ok) {
        bytes4 sel = IERC20.transfer.selector;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, sel)
            mstore(add(ptr, 0x04), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(ptr, 0x24), amount)
            ok := call(gas(), token, 0, ptr, 0x44, ptr, 0x20)
            let rds := returndatasize()
            ok := and(ok, or(iszero(rds), and(iszero(lt(rds, 0x20)), eq(mload(ptr), 1))))
        }
    }

    /// @dev Raw low-level transfer: success and (empty or exactly `true`) return required, else TransferFailed(token).
    function _rawTransfer(address token, address to, uint256 amount) internal {
        if (!_tryTransfer(token, to, amount)) revert TransferFailed(token);
    }

    /// @dev decimals() of a token, mapping any failure to BadConfig. Why: constructor-time validation only.
    function _decimals(address token) private view returns (uint8 d) {
        try IERC20Metadata(token).decimals() returns (uint8 v) {
            d = v;
        } catch {
            revert BadConfig();
        }
    }

    /// @dev decimals() of the price feed, mapping any failure to BadConfig. Why: constructor-time validation only.
    function _feedDecimals(address feed) private view returns (uint8 d) {
        try IChainlinkFeed(feed).decimals() returns (uint8 v) {
            d = v;
        } catch {
            revert BadConfig();
        }
    }

    // =====================================================================
    // Internal: EIP-712 digests (domain {nobuQQQ, 2, chainId, this})
    // =====================================================================

    /// @dev EIP-712 hash of a Deposit ticket; doubles as the EIP-3009 nonce, so the USDC pull is bound to this ticket.
    function _depositDigest(Deposit calldata d) internal view returns (bytes32) {
        return _hashTypedDataV4(
            keccak256(abi.encode(DEPOSIT_TYPEHASH, d.client, d.usdc, d.minShares, d.deadline, d.salt))
        );
    }

    /// @dev EIP-712 hash of a Redeem ticket.
    function _redeemDigest(Redeem calldata r) internal view returns (bytes32) {
        return _hashTypedDataV4(
            keccak256(abi.encode(REDEEM_TYPEHASH, r.owner, r.shares, r.minUsdc, r.deadline, r.nonce))
        );
    }

    /// @dev EIP-712 hash of a Declaration.
    function _declarationDigest(Declaration calldata d) internal view returns (bytes32) {
        return _hashTypedDataV4(keccak256(abi.encode(DECLARATION_TYPEHASH, d.wallet, d.termsHash, d.epoch)));
    }
}
// forge-lint: disable-end(reentrancy-events, reentrancy-no-eth, block-timestamp, calls-loop, require-revert-in-loop)

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

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

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

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

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

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

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

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

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

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

        emit Transfer(from, to, value);
    }

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        if (signer.code.length == 0) {
            (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
            return err == ECDSA.RecoverError.NoError && recovered == signer;
        } else {
            return isValidERC1271SignatureNow(signer, hash, signature);
        }
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC-1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

src/GmConstants.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// Pinned Ondo Global Markets constants, Ethereum mainnet (chainId 1). Verified in G1 (NOB-316) 2026-11-04.
/// Why: one source of fixed addresses and values, so other code and checks refer to the same pinned set.
library GmConstants {
    // Core: Ondo GM contracts and the cash tokens, as pinned addresses (see the trailing comment on each).
    address internal constant GM_MANAGER = 0x2c158BC456e027b2AfFCCadF1BDBD9f5fC4c5C8c; // GMTokenManager, immutable code (not a proxy)
    address internal constant USDON = 0xAcE8E719899F6E91831B18AE746C9A965c2119F1; // 18 dec, proxy
    address internal constant USDON_CONVERTER = 0x54F5eb3E9a3b1BB71F1A7a89C445FBA55B1FC813; // manager.usdonManager(); USDC<->USDon 1:1
    address internal constant USDON_CONVERTER_WALLET = 0x3312cc371Fe0Dd5171878630A1E5cf69778E8fa5; // holds USDC liquidity for redemptions
    address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // 6 dec
    address internal constant USDC_CHAINLINK = 0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6; // 8 dec, floor 0.98
    address internal constant ID_REGISTRY = 0xcf6958D69d535FD03BD6Df3F4fe6CDcd127D97df; // TransparentUpgradeableProxy
    address internal constant GM_IDENTIFIER = 0x428ECB70E90d1527A5f5e177789f51747b883F34; // rwaToken key in the registry
    address internal constant RATE_LIMITER = 0x98Db502215Da1ad9F626D4a0090A8A2f4971003c;
    address internal constant SANITY_ORACLE = 0x914D5Cb27cb30E80BdE8215ff577eD63Eb986B79;
    address internal constant ISSUANCE_HOURS = 0x5C8AD93f75805FB504FAc767378A170420671c32; // always open
    address internal constant SANCTIONS_ORACLE = 0x40C57923924B5c5c5455c48D93317139ADDaC8fb; // Chainalysis
    address internal constant BLOCKLIST = 0xd8c8174691d936E2C80114EC449037b13421B0a8;
    address internal constant TOKEN_COMPLIANCE = 0x54a8757c2FEF8649830b158a8C19D3a670e80318; // OndoComplianceGMView
    address internal constant ONDO_COMPLIANCE = 0x156F73fc73197555e950743Cb2B23F411c751002;
    address internal constant TOKEN_PAUSE_MANAGER = 0xfD48112E448417CA79305a518c4186dF4b0A200a;
    address internal constant GM_BEACON = 0x985462C9aA4D6c3Ad59Ae6e1e9c0C11347ED1598;
    address internal constant GM_TOKEN_IMPL = 0xebBcb2cEE51c2FeE4062c9C1270dcb98B0b22250;

    // GM tokens (18 dec): the Ondo GM token addresses.
    address internal constant QQQON = 0x0e397938C1Aa0680954093495B70A9F5e2249aBa;
    address internal constant TQQQON = 0xa45cd7ac9865b9539166ebaf2aBc362Df4736580;
    address internal constant SGOVON = 0x8De5D49725550f7b318b2FA0f1B1F118E98E8D0F;

    // Roles / admins: addresses holding roles or admin rights at the pin date, kept for reference checks.
    address internal constant ATTESTATION_SIGNER = 0xff2D04f6002C10eba702aDafE2f43CAc5996C477; // sole signer EOA at pin time
    address internal constant GM_ADMIN_TIMELOCK = 0x3715B2154d2FF4C5B027C7a1f734B53F27bc34f1; // DEFAULT_ADMIN, minDelay 7200 s; beacon + USDon ProxyAdmin owner
    address internal constant CONFIGURER_SAFE = 0x71A4d411b5f7941Dee020417fca30413712f1646; // threshold 4; also UNPAUSER, ADMIN_MINT
    address internal constant CONFIGURER_2 = 0xD2746617c58b72254785BDb483e04f311c858d5f;
    address internal constant PAUSER = 0x2e55b738F5969Eea10fB67e326BEE5e2fA15A2CC;
    address internal constant REGISTRY_PROXY_ADMIN = 0x988D740A4365d9D8106FC71aA691dDd2527C07fF;
    address internal constant REGISTRY_ADMIN_SAFE = 0x5AE21c99FC5f1584D8Cb09a298CFFd92B5d178eF; // threshold 3, no timelock; MASTER_CONFIGURER + proxy admin owner
    address internal constant TREASURY_SAFE = 0x5132395FEdaA811825A1Fbb1d01CdB1609Ee75F8; // fund admin Safe (NOT yet registered at pin time)

    // EIP-712: domain and quote type values used to verify a quote signature.
    string internal constant DOMAIN_NAME = "OndoGMTokenManager";
    string internal constant DOMAIN_VERSION = "1";
    bytes32 internal constant DOMAIN_SEPARATOR = 0xe366cab15d2bf3f9f295fa4d4f299170e44e971d8e7f1808dfef3c453692222c;
    bytes32 internal constant QUOTE_TYPEHASH = 0xaa6d9093095fdf69cb4e18b3e4053e238ec6e2d5a083964634b640da3b8f44a4;
    string internal constant QUOTE_TYPE =
        "Quote(uint256 chainId,uint256 attestationId,bytes32 userId,address asset,uint256 price,uint256 quantity,uint256 expiration,uint8 side,bytes32 additionalData)";
    bytes32 internal constant ATTESTATION_SIGNER_ROLE = 0x023d9737d781c665e5048e4dfd034f07fec540e8ecb2336b3d85a375b90a3a35;

    // Parameters: numeric limits and decimals pinned at the same time; USD amounts are 1e18-scaled.
    uint256 internal constant MINIMUM_DEPOSIT_USD = 0.98e18;
    uint256 internal constant MINIMUM_REDEMPTION_USD = 0.98e18;
    uint256 internal constant RATE_LIMIT_USD = 65_000_000e18; // per token, global and per-user default, sub and redeem, 86400 s window
    uint256 internal constant RATE_LIMIT_WINDOW = 86_400;
    uint256 internal constant ORACLE_DEVIATION_BPS = 1000;
    uint256 internal constant ORACLE_MAX_AGE = 172_800;
    uint256 internal constant TIMELOCK_MIN_DELAY = 7200;
    uint8 internal constant GM_DECIMALS = 18;
    uint8 internal constant USDC_DECIMALS = 6;
}

src/interfaces/IDealer.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// Callbacks the vault makes on the dealer. Why: the vault hands the trade work to the dealer, then checks the result itself. The dealer trades with Ondo and PUSHES the deliverables.
/// `data` is opaque to the vault. The vault verifies every outcome by balance deltas only.
interface IDealer {
    /// @notice Deposit callback: the dealer trades the legs and pushes GM to the vault.
    /// @dev ticketHash identifies the ticket; usdcIn = USDC the vault forwarded (client payment minus the USDC slice the vault kept).
    /// Dealer must push gmOut[k] of GM slot k (k < 3) to the vault.
    function onDeposit(bytes32 ticketHash, uint256 usdcIn, uint256[3] calldata gmOut, bytes calldata data) external;

    /// @notice Redeem callback: the dealer sells the GM it was sent and pays the vault (msg.sender) in USDC.
    /// @dev minUsdc is the minimum the owner signed in the Redeem request; the vault enforces it after this call returns (UsdcBelowMin). The Dealer ignores it.
    ///      The vault already sent gmIn[k] of GM slot k to the dealer. It keeps the USDC slice, measures its own USDC
    ///      increase and forwards slice plus payment to `owner` (`owner` is informational; M-1).
    /// Dealer sells and pays the vault in USDC.
    function onRedeem(address owner, uint256[3] calldata gmIn, uint256 minUsdc, bytes calldata data) external;

    /// @notice Rebalance callback: the dealer trades and pushes the new amounts back to the vault.
    /// @dev The vault already sent outAmts (3 GM slots + USDC) to the dealer.
    /// Dealer trades and pushes inAmts (3 GM slots + USDC) to the vault.
    function onRebalance(uint256[4] calldata outAmts, uint256[4] calldata inAmts, bytes calldata data) external;

    /// @notice Forced-exit callback: like onRedeem, for a holder exiting through forceRedeem.
    /// @dev As onRedeem for a forced exit (the vault forwards slice plus payment to `holder`, informational; M-1).
    /// owedUsdc = vault-computed USDC owed excluding the slice; the dealer must pay at least this to the vault.
    function onForceRedeem(address holder, uint256[3] calldata gmIn, uint256 owedUsdc, bytes calldata data) external;
}

src/interfaces/IGm.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// Why: the signed price/size terms of one Ondo trade; a Leg carries one together with its signature.
/// Ondo GMTokenManager quote struct (EIP-712 signed by the attestation signer). Verified in G1 (NOB-316).
struct Quote {
    // chain the quote is valid on
    uint256 chainId;
    // unique id of this attestation
    uint256 attestationId;
    // Ondo user id the quote is issued to
    bytes32 userId;
    // GM token being bought or sold
    address asset;
    uint256 price; // USD, 1e18
    uint256 quantity; // GM token units, 1e18
    // quote expiry timestamp
    uint256 expiration;
    uint8 side; // 0 BUY (mint), 1 SELL (redeem)
    // extra data field of the quote
    bytes32 additionalData;
}

/// Ondo GMTokenManager surface used by the vault and the dealer.
/// Why: only the functions this system calls or reads are declared.
interface IGm {
    /// EIP-712 domain separator of the manager (used to check quote signatures).
    function getDomainSeparator() external view returns (bytes32);
    /// Whether `account` holds `role` at the manager (e.g. the attestation signer role).
    function hasRole(bytes32 role, address account) external view returns (bool);
    /// Whether attestation `id` was already used.
    function executedAttestationIds(uint256 id) external view returns (bool);
    /// Buy GM: spend `depositAmount` of `depositToken` against the signed quote `q`.
    function mintWithAttestation(Quote calldata q, bytes calldata sig, address depositToken, uint256 depositAmount)
        external
        returns (uint256);
    /// Sell GM against the signed quote `q`; receive at least `minReceive` of `receiveToken`.
    function redeemWithAttestation(Quote calldata q, bytes calldata sig, address receiveToken, uint256 minReceive)
        external
        returns (uint256);
}

/// Sanctions oracle view used to screen addresses.
interface ISanctions {
    /// Whether `a` is on the sanctions list.
    function isSanctioned(address a) external view returns (bool);
}

src/interfaces/IVault.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Quote} from "./IGm.sol";

/// FROZEN ABI (C0, NOB-317). Slots: 0 QQQon, 1 TQQQon, 2 SGOVon (18 dec), 3 USDC (6 dec, valued at 1 USD).
interface IVault {
    // ---------------- EIP-712 structs (domain {name "nobuQQQ", version "2", chainId, vault}) ----------------
    struct Declaration {
        address wallet;
        bytes32 termsHash;
        uint256 epoch;
    }

    struct Deposit {
        address client;
        uint256 usdc; // 6 dec; also the EIP-3009 value. digest(Deposit) is the EIP-3009 nonce.
        uint256 minShares;
        uint256 deadline;
        bytes32 salt;
    }

    struct Redeem {
        address owner;
        uint256 shares;
        uint256 minUsdc; // 6 dec; total USDC the owner must receive (slice + dealer payout)
        uint256 deadline;
        bytes32 nonce;
    }

    // ---------------- Events ----------------
    event Deposited(address indexed client, bytes32 indexed ticketHash, uint256 usdc, uint256 shares, uint256[4] amounts);
    event Redeemed(address indexed owner, bytes32 indexed nonce, uint256 shares, uint256 usdcPaid, uint256[4] amounts);
    event RedeemedInKind(
        address indexed holder, uint256 shares, uint256[4] amounts, address[] named, uint256[] namedAmounts
    );
    event Rebalanced(
        uint256 indexed count,
        uint256[4] outAmts,
        uint256[4] inAmts,
        uint256[3] prices,
        uint256[3] attestationIds,
        uint256 valueOut,
        uint256 valueIn,
        uint256 budgetUsed,
        uint256 budgetCap
    );
    event ForceRedeemed(address indexed holder, uint256 shares, uint256 usdcPaid, uint256[4] amounts, uint256[3] attestationIds);
    event Registered(address indexed wallet, bytes32 termsHash, uint256 epoch);
    event Unregistered(address indexed wallet, uint256 epoch);
    event FeeAccrued(uint256 shares);
    event DealerSet(address indexed old, address indexed current);
    event AllowanceLowered(uint16 old, uint16 current);
    event AllowanceRaiseQueued(uint16 bps, uint64 eta);
    event AllowanceRaiseCancelled();
    event AllowanceRaised(uint16 old, uint16 current);
    event AllowlistOffQueued(uint64 eta);
    event AllowlistOffCancelled();
    event AllowlistOff();
    event SanctionsCheckOff();
    event WindDownAnnounced(uint64 eta);
    event WindDownCancelled();
    event PushedOut(address indexed holder, uint256 shares, uint256[4] sent, uint256[4] kept);

    // ---------------- Errors ----------------
    error NotDealer();
    error NotSafe();
    error Locked();
    error DeadlinePassed();
    error NotApproved(address wallet);
    error SharesBelowMin(uint256 got, uint256 min);
    error UsdcMismatch(uint256 got, uint256 expected);
    error UsdcBelowSlice(uint256 paid, uint256 slice);
    error SliceShort(address token, uint256 need, uint256 got);
    error UsdcBelowMin(uint256 paid, uint256 min);
    error RedeemNonceUsed();
    error BadOwnerSig();
    error BadDeclaration();
    error QuoteWrongChain();
    error QuoteWrongUser();
    error QuoteWrongAsset();
    error QuoteWrongSide();
    error QuoteQtyMismatch();
    error QuoteExpired();
    error QuotePriceZero();
    error QuoteBadSigner();
    error QuoteNotExecuted(uint256 attestationId);
    error QuoteAlreadyUsed(uint256 attestationId);
    error LegsNotDisjoint();
    error NothingOut();
    error AllowanceExceeded(uint256 used, uint256 cap);
    error AllowanceNotLower();
    error AllowanceNotHigher();
    error AllowanceAboveMax();
    error NoPendingRaise();
    error Protected(address holder);
    error Sanctioned(address holder);
    error BadNamedList();
    error NamedTokenTampered(address token);
    error NothingToRedeem();
    error ZeroShares();
    error GenesisOnly();
    error GenesisMustBeZero();
    error GenesisSharesMismatch(uint256 shares, uint256 minShares);
    error GenesisMixMismatch();
    error SupplyAboveMax(uint256 supply);
    error TimelockNotReady();
    error TimelockExpired();
    error AlreadyOff();
    error NoPendingAllowlistOff();
    error TransferFailed(address token);
    error StaleUsdcFeed();
    error RebalancesOff();
    error InsufficientGas();
    error DuplicateAttestation(uint256 id);
    error WindingDown();
    error NoWindDown();
    error BadConfig(); // constructor only: chain != 1, zero address, wrong decimals

    // ---------------- Dealer-only (msg.sender == dealer) ----------------
    function deposit(
        Deposit calldata d,
        bytes calldata usdcAuth,
        uint256 shares,
        uint256[4] calldata genesis,
        bytes calldata data
    ) external;
    function redeem(Redeem calldata r, bytes calldata ownerSig, bytes calldata data) external;
    function rebalance(
        uint256[4] calldata outAmts,
        uint256[4] calldata inAmts,
        Quote[3] calldata q,
        bytes[3] calldata sig,
        bytes calldata data
    ) external;
    function forceRedeem(address holder, Quote[3] calldata q, bytes[3] calldata sig, bytes calldata data) external;
    function register(Declaration calldata d, bytes calldata sig) external;
    function unregister(address wallet) external;

    // ---------------- Anyone ----------------
    /// No key, dealer, price, pause or approval involved. All or nothing: a token that refuses the transfer reverts the whole call (TransferFailed).
    function redeemInKind(uint256 shares, address[] calldata named) external;
    function executeAllowlistOff() external;
    /// After the announced wind-down time: the Safe or the holder sends the holder's whole pro-rata share in kind.
    function pushOut(address holder) external;

    // ---------------- Safe-only ----------------
    function setDealer(address newDealer) external;
    function lowerAllowance(uint16 bps) external;
    function queueAllowanceRaise(uint16 bps) external;
    function cancelAllowanceRaise() external;
    function executeAllowanceRaise() external;
    function queueAllowlistOff() external;
    function cancelAllowlistOff() external;
    function disableSanctionsCheck() external;
    function announceWindDown() external;
    function cancelWindDown() external;

    // ---------------- Views ----------------
    /// Per 1e18 shares, including the pending fee. Reverts Locked inside a vault call.
    function assetsPerShare() external view returns (uint256[4] memory);
    function previewSlice(uint256 shares, bool roundUp) external view returns (uint256[4] memory);
    function pendingFeeShares() external view returns (uint256);
    function allowanceState()
        external
        view
        returns (uint16 allowanceBps, uint256 budgetUsedNow, uint256 cap, uint16 pendingBps, uint64 eta);
    function depositDigest(Deposit calldata d) external view returns (bytes32);
    function redeemDigest(Redeem calldata r) external view returns (bytes32);
    function declarationDigest(Declaration calldata d) external view returns (bytes32);
    function ondoQuoteDigest(Quote calldata q) external view returns (bytes32);

    // ---------------- State getters (frozen) ----------------
    function dealer() external view returns (address);
    function approved(address wallet) external view returns (bool);
    function epoch(address wallet) external view returns (uint256);
    function usedRedeem(address owner, bytes32 nonce) external view returns (bool);
    function allowlistOn() external view returns (bool);
    function sanctionsOn() external view returns (bool);
    function allowlistOffEta() external view returns (uint64);
    function feeAt() external view returns (uint64);
    function rebalanceCount() external view returns (uint256);
    function windDownAt() external view returns (uint64);
    function held(address holder, uint256 slot) external view returns (uint256);
    function SAFE() external view returns (address);
    function GM() external view returns (address);
    function NBQ_USER_ID() external view returns (bytes32);
    function SANCTIONS() external view returns (address);
    function USDC() external view returns (address);
    function SLOT(uint256 i) external view returns (address); // i < 3 GM slots, i == 3 USDC
    function MAX_ALLOWANCE_BPS() external view returns (uint16);
    function MAX_SUPPLY() external view returns (uint256);
    function FEE_BPS() external view returns (uint16);
    function FORCE_SLACK_USD() external view returns (uint256);
    function DEAD() external view returns (address);
    function USDC_FEED() external view returns (address);
    function USDC_FEED_MAX_AGE() external view returns (uint256);
    function REBALANCE_CHARGE_DIV() external view returns (uint256);
    function SANCTIONS_GAS() external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.