Skip to content
Verified contractExactMIT

PeniwalletOrders

Address0x966bc8cb316248e46bd6de7c09bc9774c5f4e8be
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,485,043
Creation transaction
0x1d7a06778d…242971663b

contracts/orders/PeniwalletOrders.sol

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

import {
    Order,
    BatchLeg,
    BatchSwap,
    FillRequest,
    FillTerms,
    EIP712_DOMAIN_TYPEHASH,
    ORDER_TYPEHASH,
    FILL_PERMIT_TYPEHASH,
    BATCH_SWAP_TYPEHASH,
    BATCH_LEG_TYPEHASH,
    NotSigningAccount,
    OrderSignatureInvalid,
    OrderMalformed,
    OrderLifetimeInvalid,
    OrderDeadlinePassed,
    OrderIsCancelled,
    OrderEpochMismatch,
    FillAmountInvalid,
    OrderOverfilled,
    FillTooSmall,
    TakerNotAllowed,
    SelfSubmitNotOrigin,
    FillAuthorityUnset,
    FillPermitExpiryOutOfRange,
    FillNotPermitted,
    BatchSignatureInvalid,
    BatchMalformed,
    BatchDeadlinePassed,
    BatchDeadlineTooFar,
    BatchEpochMismatch,
    BatchTooFewLegs,
    BatchAlreadyUsed,
    NotLedgerOwner,
    NotPendingLedgerOwner,
    NotCancelAuthority,
    LedgerAddressInvalid,
    CancelListMalformed
} from "./OrderTypes.sol";
import {IPeniwalletOrders} from "../interfaces/IPeniwalletOrders.sol";

/**
 * @title PeniwalletOrders: the orders ledger (ADR-0008).
 * @notice Holds all order state and does all order checks for the core's
 *         `fillOrder` and `swapBatch`: the filled amount and cancelled flag of
 *         every order, each account's epoch, the used flag of every batch, the
 *         taker list, the fill authority and the cancel authority.
 *
 *         The ledger names no core. Its account functions are authenticated by
 *         `msg.sender`, which under EIP-7702 is code running at the user's own
 *         account, so a later core generation can adopt this same ledger and
 *         open orders survive that rotation.
 *
 * @dev Immutable, no proxy: this function set is final (ADR-0008 decision 1).
 *
 *      What a route can reach. Venue adapters run by delegatecall inside the
 *      account, so a call from an adapter to a route's pool has `msg.sender`
 *      equal to the account. The ledger narrows what a route that names it as
 *      a pool can do. It does not reduce it to nothing:
 *        - no `fallback`, no `receive`, no payable function;
 *        - none of the views an adapter probes on a pool or a token;
 *        - `recordFill`, `recordBatch` and `cancel` need more calldata words
 *          than a venue template can produce;
 *        - `cancelAll()` is the one account-authenticated write with short
 *          calldata, so a template could produce it;
 *        - the owner and authority functions (`setFillAuthority`,
 *          `setCancelAuthority`, `setTaker`, `transferOwnership`,
 *          `acceptOwnership`, and `cancelOrders` with short arrays) also fit a
 *          template. They are safe only while the ledger owner, the pending
 *          owner and the cancel authority are never accounts that delegate to
 *          the core.
 *      Nothing in this contract enforces the last two points. Tooling does:
 *      the ledger's selectors are pinned out of every venue template, and the
 *      owner, the pending owner and the cancel authority are checked for a
 *      delegation designator (ADR-0008 decision 1; decision 12, input check 4).
 *      Those checks must not be relaxed on the strength of this comment.
 *
 *      Arithmetic. All arithmetic is checked Solidity 0.8 arithmetic: there is
 *      no `unchecked` block and no assembly anywhere in this contract. No check
 *      ends in an arithmetic panic: every amount of an order is bounded below
 *      2^127 before it is multiplied, every subtraction is of a value already
 *      shown to be the smaller, and a `uint64` time is widened to 256 bits
 *      before anything is added to it.
 *
 *      Storage layout. FIXED (ADR-0008 section 3.1). The eight state variables
 *      are declared in exactly this order, each in a slot of its own; simulations
 *      override slot 4 (`fillAuthority`). Nothing else is kept in storage: the
 *      cached domain separator and its chain id are immutables.
 */
contract PeniwalletOrders is IPeniwalletOrders {
    // ─── storage (slots 0 to 7, never reordered) ───────────────────────────

    /// @dev Slot 0. One word per order, keyed by account then by order digest:
    ///      the amount of `tokenIn` filled so far in the low 255 bits and the
    ///      cancelled flag in the top bit.
    mapping(address account => mapping(bytes32 orderHash => uint256)) internal orderSlot;

    /// @notice Slot 1. An order or a batch is valid only when it signs the
    ///         account's current epoch; `cancelAll()` raises it.
    mapping(address account => uint64) public epoch;

    /// @notice Slot 2. A batch digest is recorded once.
    mapping(address account => mapping(bytes32 batchHash => bool)) public batchUsed;

    /// @notice Slot 3. The accounts that may be named as the taker of a fill.
    mapping(address => bool) public isTaker;

    /// @notice Slot 4. The signer of every `FillPermit`. Zero switches relayed fills off.
    address public fillAuthority;

    /// @notice Slot 5. May mark orders cancelled and nothing else. Zero switches it off.
    address public cancelAuthority;

    /// @notice Slot 6. The ledger owner: it sets the takers and both authorities.
    address public owner;

    /// @notice Slot 7. The address that may call `acceptOwnership()`, or zero.
    address public pendingOwner;

    // ─── EIP-712 domain ────────────────────────────────────────────────────

    /// @dev keccak256("PeniwalletOrders") = 0xbd2ba93d…b59a and keccak256("1") = 0xc89efdaa…8bc6.
    bytes32 private constant _NAME_HASH = keccak256("PeniwalletOrders");
    bytes32 private constant _VERSION_HASH = keccak256("1");

    /// @dev secp256k1n / 2, the EIP-2 low-s bound.
    uint256 private constant _HALF_N = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    // ─── the ledger's limits (private: the external surface is final) ──────

    /// @dev The top bit of an order's slot: the cancelled flag. The low 255
    ///      bits are the amount filled, which never reaches 2^127.
    uint256 private constant _CANCELLED = 1 << 255;
    /// @dev Every amount of an order is below this, so no product of two of
    ///      them, and no product of one with a basis-point value, can overflow.
    uint256 private constant _AMOUNT_BOUND = 1 << 127;
    uint256 private constant _BPS = 10_000;
    /// @dev An order's deadline is at most this long after its `createdAt`.
    uint256 private constant _MAX_LIFETIME = 365 days;
    /// @dev An order's `createdAt` is at most this far ahead of the block that fills it.
    uint256 private constant _MAX_CREATED_AHEAD = 900;
    /// @dev A fill permit is usable only in this many seconds before its expiry.
    uint256 private constant _PERMIT_WINDOW = 600;
    /// @dev A batch is recordable only in this long before its deadline.
    uint256 private constant _BATCH_WINDOW = 1 hours;
    /// @dev A batch has at least this many legs and at most `_MAX_LEGS`.
    uint256 private constant _MIN_LEGS = 2;
    uint256 private constant _MAX_LEGS = 16;
    /// @dev The native-coin sentinel. The ledger treats it as an ordinary
    ///      address everywhere except the balance read of `orderState`.
    address private constant _NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    /// @dev The most gas the `balanceOf` read of `orderState` hands to
    ///      `tokenIn`. It bounds the size of the answer a token can afford to
    ///      return, and with it the cost of copying that answer here, which is
    ///      what keeps `orderState` from running out of gas on a hostile token.
    ///      A token whose `balanceOf` needs more than this reads as 0.
    uint256 private constant _BALANCE_READ_GAS = 200_000;

    /// @dev The domain separator of the construction chain, and that chain's id.
    ///      Immutables, so they take no storage slot. `DOMAIN_SEPARATOR()`
    ///      re-derives whenever `block.chainid` differs.
    uint256 private immutable _CACHED_CHAIN_ID;
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;

    /// @param _owner The first ledger owner. Never `msg.sender`: the ledger is
    ///        deployed through the shared CREATE2 deployer, which would own it.
    ///        Nothing per chain is in the init code.
    constructor(address _owner) {
        if (_owner == address(0)) revert LedgerAddressInvalid();
        owner = _owner;
        emit IPeniwalletOrders.OwnershipTransferred(address(0), _owner);

        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator();
    }

    // ─── the account's functions ───────────────────────────────────────────
    //
    // Authenticated by `msg.sender`, which under EIP-7702 is code running at
    // the user's own account. The ledger names no core.

    /// @notice Records a fill of `order` and returns the terms the caller must
    ///         settle it on. The authentication and the arithmetic of every
    ///         fill (ADR-0008 decision 4).
    /// @dev The checks run in this order and the first failure decides the
    ///      error. Nothing is written and nothing is emitted before the last
    ///      one has passed. The write happens before the caller runs any route
    ///      or makes any payment.
    ///
    ///       1  the caller is `order.account`                  NotSigningAccount
    ///       2  `signature` is the account's, over the digest  OrderSignatureInvalid
    ///       3  the order is well formed                       OrderMalformed
    ///       4  creation time and lifetime                     OrderLifetimeInvalid
    ///       5  the deadline has not passed                    OrderDeadlinePassed
    ///       6  the order is not cancelled                     OrderIsCancelled
    ///       7  the order signs the account's current epoch    OrderEpochMismatch
    ///       8  `0 < swapIn <= fillIn`; an under-swap only on
    ///          an order with the full surplus share           FillAmountInvalid
    ///       9  the fill fits in what is left                  OrderOverfilled
    ///      10  the fill and the tail it leaves are not
    ///          smaller than `minFillIn`                       FillTooSmall
    ///      11  the taker is listed                            TakerNotAllowed
    ///      12  a self-submitted claim: the account itself
    ///          sent the transaction                           SelfSubmitNotOrigin
    ///      13  otherwise: a fill authority is set             FillAuthorityUnset
    ///      14  otherwise: the permit's expiry is in range     FillPermitExpiryOutOfRange
    ///      15  otherwise: `fill.permit` is the authority's    FillNotPermitted
    ///
    ///      `fill.selfSubmitted` is the caller's claim. A true claim is accepted
    ///      only when `tx.origin == msg.sender`; otherwise it reverts at check
    ///      12 and never falls through to the permit checks, so one request is
    ///      never read two ways. With the flag true, `permitMinOut`,
    ///      `permitExpiry` and `permit` are ignored.
    ///
    ///      The permit's digest is built from the STORED filled amount, never
    ///      from an argument: a permit signed against an older state does not
    ///      recover, so a permit is good for one fill.
    /// @return orderHash The order's full EIP-712 digest. The caller uses this
    ///         and computes none itself.
    /// @return terms The limit amount, the least output at which the fill may
    ///         settle (`max(F, permitMinOut)`; `F` when self-submitted) and
    ///         the two fee shares.
    function recordFill(Order calldata order, bytes calldata signature, FillRequest calldata fill)
        external
        returns (bytes32 orderHash, FillTerms memory terms)
    {
        // 1
        if (msg.sender != order.account) revert NotSigningAccount();
        // 2. A zero result is refused by itself: the recover answers zero for
        //    a malformed signature, and an `eth_call` with no `from` has a zero caller.
        orderHash = hashOrder(order);
        address signer = _recover(orderHash, signature);
        if (signer == address(0) || signer != msg.sender) revert OrderSignatureInvalid();
        // 3
        if (!_wellFormed(order)) revert OrderMalformed();
        // 4
        if (uint256(order.createdAt) > block.timestamp + _MAX_CREATED_AHEAD) revert OrderLifetimeInvalid();
        if (uint256(order.deadline) > uint256(order.createdAt) + _MAX_LIFETIME) revert OrderLifetimeInvalid();
        // 5
        if (block.timestamp > order.deadline) revert OrderDeadlinePassed();
        // 6. With the flag clear the slot is the filled amount itself.
        uint256 filled = orderSlot[msg.sender][orderHash];
        if (filled >= _CANCELLED) revert OrderIsCancelled();
        // 7
        uint64 currentEpoch = epoch[msg.sender];
        if (order.epoch != currentEpoch) revert OrderEpochMismatch(currentEpoch);
        // 8
        uint256 fillIn = fill.fillIn;
        if (fill.swapIn == 0 || fill.swapIn > fillIn) revert FillAmountInvalid();
        if (fill.swapIn != fillIn && order.surplusShareBps != _BPS) revert FillAmountInvalid();
        // 9. `filled` never exceeds `amountIn`: it only ever grows by a `fillIn`
        //    that passed this check, under a key that binds `amountIn`.
        uint256 remaining = order.amountIn - filled;
        if (fillIn > remaining) revert OrderOverfilled(remaining);
        // 10. The remainder rule: a tail smaller than `minFillIn` could never fill.
        if (fillIn < order.minFillIn) revert FillTooSmall(order.minFillIn, remaining);
        if (fillIn != remaining && remaining - fillIn < order.minFillIn) {
            revert FillTooSmall(order.minFillIn, remaining);
        }
        // 11
        if (!isTaker[fill.taker]) revert TakerNotAllowed();
        // 12 to 15
        uint256 permitMinOut;
        if (fill.selfSubmitted) {
            if (tx.origin != msg.sender) revert SelfSubmitNotOrigin();
        } else {
            permitMinOut = _checkFillPermit(orderHash, fill, filled);
        }

        uint256 filledAfter = filled + fillIn;
        orderSlot[msg.sender][orderHash] = filledAfter;
        emit IPeniwalletOrders.OrderFillRecorded(
            orderHash, msg.sender, order.tokenIn, order.tokenOut, fillIn, filledAfter
        );

        terms = _terms(order, fillIn);
        if (permitMinOut > terms.floorOut) terms.floorOut = permitMinOut;
    }

    /// @notice Records a multi-token swap, once, and returns the relay fee the
    ///         caller may charge for the legs it runs (ADR-0008 decision 9).
    /// @dev The checks run in this order and the first failure decides the
    ///      error. Nothing is written and nothing is emitted before the last
    ///      one has passed.
    ///
    ///      1  the caller is `batch.account`                   NotSigningAccount
    ///      2  `signature` is the account's, over the digest   BatchSignatureInvalid
    ///      3  the signed batch is well formed                 BatchMalformed
    ///      4  the deadline has not passed                     BatchDeadlinePassed
    ///      5  the deadline is at most 1 hour ahead            BatchDeadlineTooFar
    ///      6  the batch signs the account's current epoch     BatchEpochMismatch
    ///      7  `legMask` names only legs of the batch, and at
    ///         least `minLegs` of them                         BatchTooFewLegs
    ///      8  the batch has not been recorded before          BatchAlreadyUsed
    ///
    ///      Check 3 reads only what the account signed and check 7 only the
    ///      mask, which the relayer supplies: `BatchMalformed` always means a
    ///      defect of the signed batch and `BatchTooFewLegs` always a defect of
    ///      the request. The shape rules apply to every leg, in the mask or not.
    ///
    ///      Check 5 is a proximity rule, not an age limit: a batch signed with a
    ///      deadline far ahead is refused today and becomes recordable in the
    ///      hour before that deadline.
    ///
    ///      There is no permit and no origin rule here, and no single-batch
    ///      cancel: the order slot and its cancelled flag are never read. What
    ///      voids an unsubmitted batch is `cancelAll()`, for a batch signed with
    ///      the current epoch or an earlier one. The native-coin sentinel is an
    ///      ordinary address in every check.
    /// @param legMask Bit `i` set means leg `i` runs.
    /// @return batchHash The batch's full EIP-712 digest.
    /// @return feeCharged `floor(fee * legsRun / legs.length)`: the whole fee
    ///         on a full mask. Proportional to the NUMBER of legs run, not to
    ///         their value.
    function recordBatch(BatchSwap calldata batch, bytes calldata signature, uint256 legMask)
        external
        returns (bytes32 batchHash, uint256 feeCharged)
    {
        // 1
        if (msg.sender != batch.account) revert NotSigningAccount();
        // 2
        batchHash = hashBatch(batch);
        _checkBatchSignature(batchHash, signature);
        // 3
        if (!_batchWellFormed(batch)) revert BatchMalformed();
        // 4
        if (block.timestamp > batch.deadline) revert BatchDeadlinePassed();
        // 5
        if (uint256(batch.deadline) > block.timestamp + _BATCH_WINDOW) revert BatchDeadlineTooFar();
        // 6
        uint64 currentEpoch = epoch[msg.sender];
        if (batch.epoch != currentEpoch) revert BatchEpochMismatch(currentEpoch);
        // 7. Check 3 has shown 2 to 16 legs, so the shift is in range.
        uint256 legCount = batch.legs.length;
        if (legMask >> legCount != 0) revert BatchTooFewLegs();
        uint256 legsRun = _countBits(legMask, legCount);
        if (legsRun < batch.minLegs) revert BatchTooFewLegs();
        // 8
        if (batchUsed[msg.sender][batchHash]) revert BatchAlreadyUsed();

        batchUsed[msg.sender][batchHash] = true;
        // `fee < 2^127` and `legsRun <= 16`: the product fits.
        feeCharged = (batch.fee * legsRun) / legCount;
        emit IPeniwalletOrders.BatchRecorded(batchHash, msg.sender, legMask, feeCharged);
    }

    /// @notice Cancels one order of the caller, for good. The filled amount is kept.
    /// @dev Takes the whole order and not its hash: one word of calldata is
    ///      something a venue template could produce as the account. It checks
    ///      neither the signature nor the filled amount. It reverts when the
    ///      flag is already set, so `OrderCancelled` is emitted at most once
    ///      per order by this function.
    function cancel(Order calldata order) external {
        if (msg.sender != order.account) revert NotSigningAccount();
        bytes32 orderHash = hashOrder(order);
        uint256 slot = orderSlot[msg.sender][orderHash];
        if (slot >= _CANCELLED) revert OrderIsCancelled();
        orderSlot[msg.sender][orderHash] = slot | _CANCELLED;
        emit IPeniwalletOrders.OrderCancelled(orderHash, msg.sender, msg.sender);
    }

    /// @notice Raises the caller's epoch by one: every order and every
    ///         unsubmitted batch it signed with the old epoch or an earlier one
    ///         is void.
    /// @dev It does NOT void what was signed with a later epoch: an order or a
    ///      batch signed with exactly the new epoch becomes usable by this
    ///      call (ADR-0008 decision 8). The one account-authenticated write
    ///      with short calldata; its selector is pinned out of every venue
    ///      template by tooling.
    function cancelAll() external {
        uint64 newEpoch = epoch[msg.sender] + 1;
        epoch[msg.sender] = newEpoch;
        emit IPeniwalletOrders.OrdersCancelledAll(msg.sender, newEpoch);
    }

    // ─── the cancel authority's function ───────────────────────────────────

    /// @notice Marks each `(accounts[i], orderHashes[i])` cancelled. It can
    ///         only cancel: it moves no funds and changes no filled amount.
    /// @dev A pair whose flag is already set is skipped with no event, so one
    ///      stale entry does not revert a list of cancels. It may cancel a hash
    ///      the ledger has never seen: a wrong hash or a wrong account succeeds,
    ///      emits `OrderCancelled` and leaves the real order live, so a cancel
    ///      is confirmed by reading `orderState` for the full order, never from
    ///      the event. It sets the order slot only; `batchUsed` is not touched.
    ///      While the cancel authority is zero nobody can call it, a zero
    ///      caller (an `eth_call` with no `from`) included.
    function cancelOrders(address[] calldata accounts, bytes32[] calldata orderHashes) external {
        address authority = cancelAuthority;
        if (authority == address(0) || msg.sender != authority) revert NotCancelAuthority();
        uint256 n = accounts.length;
        if (n != orderHashes.length) revert CancelListMalformed();
        for (uint256 i = 0; i < n; ++i) {
            uint256 slot = orderSlot[accounts[i]][orderHashes[i]];
            if (slot < _CANCELLED) {
                orderSlot[accounts[i]][orderHashes[i]] = slot | _CANCELLED;
                emit IPeniwalletOrders.OrderCancelled(orderHashes[i], accounts[i], msg.sender);
            }
        }
    }

    // ─── the ledger owner's functions ──────────────────────────────────────
    //
    // Each reverts `NotLedgerOwner()` for any other caller. Every setter writes
    // and emits unconditionally, also when the value does not change. There is
    // no way to renounce ownership.

    /// @notice Adds `taker` to the taker list or removes it.
    /// @dev Refuses the zero address and the ledger itself.
    function setTaker(address taker, bool allowed) external {
        if (msg.sender != owner) revert NotLedgerOwner();
        if (taker == address(0) || taker == address(this)) revert LedgerAddressInvalid();
        isTaker[taker] = allowed;
        emit IPeniwalletOrders.TakerSet(taker, allowed);
    }

    /// @notice Appoints the signer of fill permits. Zero is allowed and switches
    ///         every fill off except one in a transaction the account sent itself.
    function setFillAuthority(address newFillAuthority) external {
        if (msg.sender != owner) revert NotLedgerOwner();
        fillAuthority = newFillAuthority;
        emit IPeniwalletOrders.FillAuthoritySet(newFillAuthority);
    }

    /// @notice Appoints the cancel authority. Zero is allowed and switches the
    ///         operator cancel off.
    function setCancelAuthority(address newCancelAuthority) external {
        if (msg.sender != owner) revert NotLedgerOwner();
        cancelAuthority = newCancelAuthority;
        emit IPeniwalletOrders.CancelAuthoritySet(newCancelAuthority);
    }

    /// @notice First step of a hand-over: names the address that may accept.
    /// @dev The owner does not change. The zero address is accepted and clears
    ///      `pendingOwner`, which withdraws a pending hand-over.
    function transferOwnership(address newOwner) external {
        if (msg.sender != owner) revert NotLedgerOwner();
        pendingOwner = newOwner;
        emit IPeniwalletOrders.OwnershipTransferStarted(msg.sender, newOwner);
    }

    /// @notice Second step of a hand-over: the pending owner becomes the owner.
    /// @dev A zero `pendingOwner` means no hand-over is pending, and then nobody
    ///      can accept, a zero caller included (an `eth_call` with no `from`
    ///      has one). So the owner is never the zero address: there is no way
    ///      to renounce ownership.
    function acceptOwnership() external {
        address pending = pendingOwner;
        if (pending == address(0) || msg.sender != pending) revert NotPendingLedgerOwner();
        address previousOwner = owner;
        owner = msg.sender;
        pendingOwner = address(0);
        emit IPeniwalletOrders.OwnershipTransferred(previousOwner, msg.sender);
    }

    // ─── views ─────────────────────────────────────────────────────────────

    /// @notice The state of `order` as a watcher needs it: its digest, a
    ///         status, the amount filled and a balance-only bound on the next fill.
    /// @dev `status`, evaluated in this order (ADR-0008 decision 4):
    ///        0 invalid          fails check 3 of `recordFill`, or its deadline
    ///                           is more than 365 days after `createdAt`
    ///        2 filled           `filledIn == amountIn`. It outranks cancelled,
    ///                           so a later mass cancel never rewrites an
    ///                           executed order
    ///        3 cancelled        the flag is set, or `order.epoch` is below the
    ///                           account's epoch
    ///        4 expired          the deadline has passed
    ///        5 not yet active   `order.epoch` is above the account's epoch, or
    ///                           `createdAt` is more than 900 seconds ahead.
    ///                           NOT terminal: the signature is live
    ///        1 open             none of the above
    ///      The view ranks cancelled above expired while `recordFill` checks
    ///      the deadline first; both are terminal, only the reason differs.
    ///
    ///      `fillableIn` is 0 unless the order is open. Otherwise it is the
    ///      largest `fillIn` that passes checks 9 and 10 of `recordFill` and
    ///      that the account can fund with its fee share from its `tokenIn`
    ///      balance (the coin balance for the native sentinel; wrapped native is
    ///      not counted). It ignores price, the taker list and permits.
    ///
    ///      A failed balance read, or one that returns fewer than 32 bytes,
    ///      counts as 0. The read is given at most `_BALANCE_READ_GAS` gas, so a
    ///      `tokenIn` whose `balanceOf` needs more than that, or spends all it
    ///      is given, also counts as 0.
    ///
    ///      The view does not revert for a well-encoded order, whatever
    ///      `tokenIn` is, when it is called with at least 600,000 gas. The gas
    ///      limit of the read is what makes that true: the whole answer of the
    ///      read is copied to memory, the token pays for the memory it answers
    ///      from out of the limit, and so the copy can cost this contract only
    ///      a little more than the limit. A caller that supplies less gas can
    ///      see the view run out of gas on a hostile `tokenIn`, and can see 0
    ///      for an honest token whose read was starved; `recordFill` reads no
    ///      balance and is not affected either way.
    function orderState(Order calldata order)
        external
        view
        returns (bytes32 orderHash, uint8 status, uint256 filledIn, uint256 fillableIn)
    {
        orderHash = hashOrder(order);
        uint256 slot = orderSlot[order.account][orderHash];
        bool cancelled = slot >= _CANCELLED;
        filledIn = cancelled ? slot ^ _CANCELLED : slot;
        uint64 currentEpoch = epoch[order.account];

        if (!_wellFormed(order) || uint256(order.deadline) > uint256(order.createdAt) + _MAX_LIFETIME) {
            status = 0;
        } else if (filledIn == order.amountIn) {
            status = 2;
        } else if (cancelled || order.epoch < currentEpoch) {
            status = 3;
        } else if (block.timestamp > order.deadline) {
            status = 4;
        } else if (order.epoch > currentEpoch || uint256(order.createdAt) > block.timestamp + _MAX_CREATED_AHEAD) {
            status = 5;
        } else {
            status = 1;
            fillableIn = _fillable(order, filledIn);
        }
    }

    /// @notice The terms `recordFill` would return for a fill of `fillIn` with
    ///         no permit minimum: `floorOut` is the order's own floor `F`.
    /// @dev Applies check 3 of `recordFill` (`OrderMalformed`) and requires
    ///      `0 < fillIn <= amountIn` (`FillAmountInvalid`). No signature,
    ///      caller, lifetime, epoch, stored-state, taker, permit or balance check.
    ///      Declared `view`, as ADR-0008 section 3.1 and `IPeniwalletOrders`
    ///      declare it, although it reads no state.
    function previewFill(Order calldata order, uint256 fillIn) external view returns (FillTerms memory) {
        if (!_wellFormed(order)) revert OrderMalformed();
        if (fillIn == 0 || fillIn > order.amountIn) revert FillAmountInvalid();
        return _terms(order, fillIn);
    }

    /// @notice The stored slot of one order: the amount filled and the
    ///         cancelled flag. It does not reflect the epoch, the deadline or
    ///         whether such an order is valid.
    function fillState(address account, bytes32 orderHash) external view returns (uint256 filledIn, bool cancelled) {
        uint256 slot = orderSlot[account][orderHash];
        cancelled = slot >= _CANCELLED;
        filledIn = cancelled ? slot ^ _CANCELLED : slot;
    }

    /// @notice The raw slots of many orders of one account: the amount filled
    ///         in the low 255 bits, the cancelled flag in the top bit.
    function fillStates(address account, bytes32[] calldata orderHashes)
        external
        view
        returns (uint256[] memory packed)
    {
        uint256 n = orderHashes.length;
        packed = new uint256[](n);
        for (uint256 i = 0; i < n; ++i) {
            packed[i] = orderSlot[account][orderHashes[i]];
        }
    }

    // ─── EIP-712 digests ───────────────────────────────────────────────────

    /// @notice The domain separator: name `PeniwalletOrders`, version `1`, this
    ///         chain, this ledger.
    function DOMAIN_SEPARATOR() public view returns (bytes32) {
        return block.chainid == _CACHED_CHAIN_ID ? _CACHED_DOMAIN_SEPARATOR : _buildDomainSeparator();
    }

    /// @notice The full EIP-712 digest of `order` (`0x1901 ‖ separator ‖
    ///         hashStruct`). It is the order hash: it binds the chain and this
    ///         ledger, and it keys the order's state under its account.
    /// @dev `Order` is all-static, so `abi.encode(ORDER_TYPEHASH, order)` is the
    ///      typehash followed by the 18 members in declared order, each as one
    ///      full 32-byte word: exactly `abi.encode(ORDER_TYPEHASH, account, ...,
    ///      salt)`.
    function hashOrder(Order calldata order) public view returns (bytes32) {
        return _digest(keccak256(abi.encode(ORDER_TYPEHASH, order)));
    }

    /// @notice The full EIP-712 digest of `batch`.
    /// @dev `legs` is an array of structs: EIP-712 encodes it as the keccak256
    ///      of the concatenated struct hashes of its elements, with no length
    ///      and no offset. `keccak256(abi.encode(batch.legs))` compiles and is
    ///      WRONG (it hashes an offset word, a length word and the raw members).
    function hashBatch(BatchSwap calldata batch) public view returns (bytes32) {
        uint256 n = batch.legs.length;
        bytes32[] memory legHashes = new bytes32[](n);
        for (uint256 i = 0; i < n; ++i) {
            // `BatchLeg` is all-static: the typehash, then its four members as full words.
            legHashes[i] = keccak256(abi.encode(BATCH_LEG_TYPEHASH, batch.legs[i]));
        }
        return _digest(
            keccak256(
                abi.encode(
                    BATCH_SWAP_TYPEHASH,
                    batch.account,
                    keccak256(abi.encodePacked(legHashes)),
                    batch.minLegs,
                    batch.feeToken,
                    batch.fee,
                    batch.deadline,
                    batch.epoch,
                    batch.salt
                )
            )
        );
    }

    /// @notice The full EIP-712 digest of a `FillPermit`, the approval the fill
    ///         authority signs for one fill.
    /// @param orderHash The order's full digest (`hashOrder`), NOT its struct hash.
    /// @param stepsHash `keccak256(abi.encode(steps))` of the route, as the core computes it.
    /// @param filledBefore The order's stored filled amount before the fill.
    function hashFillPermit(
        bytes32 orderHash,
        uint256 fillIn,
        uint256 swapIn,
        address taker,
        bytes32 stepsHash,
        uint256 filledBefore,
        uint256 minOut,
        uint64 expiry
    ) public view returns (bytes32) {
        return _digest(
            keccak256(
                abi.encode(
                    FILL_PERMIT_TYPEHASH, orderHash, fillIn, swapIn, taker, stepsHash, filledBefore, minOut, expiry
                )
            )
        );
    }

    // ─── internals ─────────────────────────────────────────────────────────

    /// @dev Check 3 of `recordFill`. The four amount bounds are what make every
    ///      product in `_terms` and `_fillable` safe.
    function _wellFormed(Order calldata order) private pure returns (bool) {
        return order.tokenIn != order.tokenOut && order.amountIn != 0 && order.amountIn < _AMOUNT_BOUND
            && order.minAmountOut != 0 && order.minAmountOut < _AMOUNT_BOUND && order.feeIn < _AMOUNT_BOUND
            && order.feeOut < _AMOUNT_BOUND && order.minFillIn != 0 && order.minFillIn <= order.amountIn
            && order.fillSlippageBps < _BPS && order.surplusShareBps <= _BPS && order.fillPolicy <= 1
            && order.triggerDirection <= 2;
    }

    /// @dev Check 2 of `recordBatch`: `signature` is the caller's own, over the
    ///      batch digest. The caller is `batch.account` (check 1). A zero result
    ///      is refused by itself: the recover answers zero for a malformed
    ///      signature, and an `eth_call` with no `from` has a zero caller.
    ///
    ///      THE ONE `virtual` FUNCTION OF THE LEDGER. It exists so that the
    ///      simulation-only stub (`contracts/orders/sim/`, never deployed, never
    ///      the `ORDERS` of any core) can leave out this one check and nothing
    ///      else (ADR-0008 section 8, decision 10). Nothing else here may be
    ///      made `virtual`.
    function _checkBatchSignature(bytes32 batchHash, bytes calldata signature) internal view virtual {
        address signer = _recover(batchHash, signature);
        if (signer == address(0) || signer != msg.sender) revert BatchSignatureInvalid();
    }

    /// @dev Check 3 of `recordBatch`. It reads only what the account signed.
    ///
    ///      2 to 16 legs; the fee below 2^127; `1 <= minLegs <= legs.length`;
    ///      every leg has two different tokens and both amounts in (0, 2^127);
    ///      and the legs are one to many (every `tokenIn` is the shared token,
    ///      the `tokenOut`s pairwise distinct) or many to one (every `tokenOut`
    ///      is the shared token, the `tokenIn`s pairwise distinct), with
    ///      `feeToken` the shared token. All on raw addresses.
    ///
    ///      `feeToken` must be the shared token, so the side of leg 0 that
    ///      equals it names the shape. The two shapes exclude each other: with
    ///      two legs or more the same side cannot be both all equal and
    ///      pairwise distinct. A leg whose other token is the shared token has
    ///      two equal tokens and fails the leg rule.
    function _batchWellFormed(BatchSwap calldata batch) private pure returns (bool) {
        uint256 legCount = batch.legs.length;
        if (legCount < _MIN_LEGS || legCount > _MAX_LEGS) return false;
        if (batch.fee >= _AMOUNT_BOUND) return false;
        if (batch.minLegs == 0 || batch.minLegs > legCount) return false;

        address shared = batch.feeToken;
        bool oneToMany = batch.legs[0].tokenIn == shared;
        for (uint256 i = 0; i < legCount; ++i) {
            BatchLeg calldata leg = batch.legs[i];
            if (leg.tokenIn == leg.tokenOut) return false;
            if (leg.amountIn == 0 || leg.amountIn >= _AMOUNT_BOUND) return false;
            if (leg.minAmountOut == 0 || leg.minAmountOut >= _AMOUNT_BOUND) return false;
            if ((oneToMany ? leg.tokenIn : leg.tokenOut) != shared) return false;
            address other = oneToMany ? leg.tokenOut : leg.tokenIn;
            for (uint256 j = 0; j < i; ++j) {
                if ((oneToMany ? batch.legs[j].tokenOut : batch.legs[j].tokenIn) == other) return false;
            }
        }
        return true;
    }

    /// @dev The number of set bits among the low `width` bits of `mask`. A
    ///      plain loop: solc emits the `CLZ` opcode only for an explicit Yul
    ///      `clz`, and one chain this ledger is deployed on does not have it.
    function _countBits(uint256 mask, uint256 width) private pure returns (uint256 count) {
        for (uint256 i = 0; i < width; ++i) {
            if ((mask >> i) & 1 != 0) count += 1;
        }
    }

    /// @dev Checks 13 to 15 of `recordFill`, for a fill that is not
    ///      self-submitted. Returns the permit's `minOut`.
    /// @param filled The STORED filled amount before this fill: the permit's `filledBefore`.
    function _checkFillPermit(bytes32 orderHash, FillRequest calldata fill, uint256 filled)
        private
        view
        returns (uint256)
    {
        // 13
        address authority = fillAuthority;
        if (authority == address(0)) revert FillAuthorityUnset();
        // 14. A proximity rule, not an age limit.
        uint256 expiry = fill.permitExpiry;
        if (block.timestamp > expiry || expiry > block.timestamp + _PERMIT_WINDOW) {
            revert FillPermitExpiryOutOfRange();
        }
        // 15. `authority` is not zero here, so a zero result of the recover fails.
        bytes32 permitDigest = hashFillPermit(
            orderHash,
            fill.fillIn,
            fill.swapIn,
            fill.taker,
            fill.stepsHash,
            filled,
            fill.permitMinOut,
            fill.permitExpiry
        );
        if (_recover(permitDigest, fill.permit) != authority) revert FillNotPermitted();
        return fill.permitMinOut;
    }

    /// @dev The four terms of a fill of `fillIn`, with `floorOut` the order's
    ///      own floor. The caller has shown the order well formed and
    ///      `0 < fillIn <= amountIn`, so every factor is below 2^127.
    ///
    ///      Rounding always favours the user: the limit rounds up and the fees
    ///      round down. The ceiling is `p / d` plus one when `p % d != 0`.
    ///      `floorOut >= 1`: `limitOut >= 1` and the tolerance is below 10,000.
    function _terms(Order calldata order, uint256 fillIn) private pure returns (FillTerms memory terms) {
        uint256 amountIn = order.amountIn;
        uint256 product = order.minAmountOut * fillIn;
        uint256 limitOut = product / amountIn;
        if (product % amountIn != 0) limitOut += 1;
        terms.limitOut = limitOut;
        terms.floorOut = limitOut - (limitOut * order.fillSlippageBps) / _BPS;
        terms.feeInShare = (order.feeIn * fillIn) / amountIn;
        terms.feeOutShare = (order.feeOut * fillIn) / amountIn;
    }

    /// @dev `fillableIn` of an open order (ADR-0008 decision 4). A fill of `y`
    ///      is fundable when `y + floor(feeIn * y / amountIn) <= balance`.
    function _fillable(Order calldata order, uint256 filled) private view returns (uint256) {
        uint256 amountIn = order.amountIn;
        uint256 feeIn = order.feeIn;
        uint256 minFillIn = order.minFillIn;
        uint256 remaining = amountIn - filled;
        // An open order always has at least `minFillIn` left (the remainder rule).
        if (remaining < minFillIn) return 0;
        uint256 balance = _balanceOf(order.tokenIn, order.account);

        uint256 candidate = remaining;
        if (remaining + (feeIn * remaining) / amountIn > balance) {
            // Here `balance < remaining + feeIn < 2^128`, so the product fits.
            // The fee share rounds down, so the largest fundable fill is `x` or `x + 1`.
            candidate = (balance * amountIn) / (amountIn + feeIn);
            uint256 next = candidate + 1;
            if (next + (feeIn * next) / amountIn <= balance) candidate = next;
            // `candidate < remaining`: the whole remainder is not fundable, and
            // what a fill costs grows with the fill.
        }
        // The tail rule of check 10: never leave less than `minFillIn` unfilled.
        if (candidate != remaining && remaining - candidate < minFillIn) candidate = remaining - minFillIn;
        return candidate < minFillIn ? 0 : candidate;
    }

    /// @dev The balance `orderState` sizes a fill against. A failed call, or
    ///      one that returns fewer than 32 bytes (an address with no code
    ///      returns none), counts as 0. A longer answer is read by its first
    ///      word; all of it is copied to memory first, and the gas limit of the
    ///      call bounds what that copy can cost (see `orderState`).
    function _balanceOf(address token, address account) private view returns (uint256) {
        if (token == _NATIVE) return account.balance;
        // 0x70a08231 = balanceOf(address)
        (bool ok, bytes memory returned) =
            token.staticcall{gas: _BALANCE_READ_GAS}(abi.encodeWithSelector(0x70a08231, account));
        if (!ok || returned.length < 32) return 0;
        return abi.decode(returned, (uint256));
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, _NAME_HASH, _VERSION_HASH, block.chainid, address(this)));
    }

    function _digest(bytes32 structHash) private view returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash));
    }

    /// @dev The ledger's own canonical recover. A signature is exactly 65 bytes
    ///      `r ‖ s ‖ v`, with low `s` (EIP-2) and `v` in {27, 28}.
    ///
    ///      It RETURNS THE ZERO ADDRESS AND NEVER REVERTS for a signature that
    ///      is not exactly 65 bytes, has a high `s`, has `v` outside {27, 28}, or
    ///      recovers to zero. The caller then fails its own check with its own
    ///      named error, because the expected signer is never zero where the
    ///      check runs. No other signature error exists in the ledger.
    function _recover(bytes32 digest, bytes calldata signature) private pure returns (address) {
        if (signature.length != 65) return address(0);
        bytes32 r = bytes32(signature[0:32]);
        bytes32 s = bytes32(signature[32:64]);
        uint8 v = uint8(signature[64]);
        if (uint256(s) > _HALF_N) return address(0);
        if (v != 27 && v != 28) return address(0);
        return ecrecover(digest, v, r, s);
    }
}

contracts/interfaces/IPeniwalletOrders.sol

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

import {Order, BatchSwap, FillRequest, FillTerms} from "../orders/OrderTypes.sol";

/**
 * @title IPeniwalletOrders: the orders ledger (ADR-0008 section 3.1).
 * @notice The whole external surface of `PeniwalletOrders`, and its events. The
 *         ledger is immutable with no proxy, so this function set is final:
 *         anything it lacks is added by a later core generation calling these
 *         functions as the account, or by a new ledger.
 * @dev Imports `OrderTypes.sol` only. It is in the ledger's compile closure, so
 *      it is frozen with the ledger; the core's own shapes live in
 *      `IPeniwalletV12Orders.sol`, which this file must never import.
 */
interface IPeniwalletOrders {
    // ─── events ────────────────────────────────────────────────────────────

    /// @notice A fill was recorded. `fillIn` is this fill; `filledIn` is the
    ///         stored amount after it. Authoritative for the amount consumed
    ///         only: execution and proceeds are in the account's `OrderFilled`.
    event OrderFillRecorded(
        bytes32 indexed orderHash,
        address indexed account,
        address tokenIn,
        address tokenOut,
        uint256 fillIn,
        uint256 filledIn
    );
    /// @notice `by` is `msg.sender`: the account for `cancel`, the cancel
    ///         authority for `cancelOrders`.
    event OrderCancelled(bytes32 indexed orderHash, address indexed account, address indexed by);
    event OrdersCancelledAll(address indexed account, uint64 newEpoch);
    event BatchRecorded(bytes32 indexed batchHash, address indexed account, uint256 legMask, uint256 feeCharged);
    event TakerSet(address indexed taker, bool allowed);
    event FillAuthoritySet(address indexed fillAuthority);
    event CancelAuthoritySet(address indexed cancelAuthority);
    event OwnershipTransferStarted(address indexed owner, address indexed pendingOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    // ─── the account's functions ───────────────────────────────────────────

    /// @notice Authenticates and records one fill of `order` (ADR-0008 decision
    ///         4). Caller: `order.account`.
    function recordFill(Order calldata order, bytes calldata signature, FillRequest calldata fill)
        external
        returns (bytes32 orderHash, FillTerms memory terms);

    /// @notice Authenticates and records a multi-token swap, once (ADR-0008
    ///         decision 9). Caller: `batch.account`.
    function recordBatch(BatchSwap calldata batch, bytes calldata signature, uint256 legMask)
        external
        returns (bytes32 batchHash, uint256 feeCharged);

    /// @notice Sets the cancelled flag of `order`. Caller: `order.account`.
    function cancel(Order calldata order) external;

    /// @notice Raises the caller's epoch by one.
    function cancelAll() external;

    // ─── the cancel authority's function ───────────────────────────────────

    /// @notice Sets the cancelled flag of each (account, order hash) pair.
    function cancelOrders(address[] calldata accounts, bytes32[] calldata orderHashes) external;

    // ─── the ledger owner's functions ──────────────────────────────────────

    /// @notice Refuses the zero address and the ledger itself.
    function setTaker(address taker, bool allowed) external;

    /// @notice Zero is allowed and switches relayed fills off.
    function setFillAuthority(address newFillAuthority) external;

    /// @notice Zero is allowed and switches the operator cancel off.
    function setCancelAuthority(address newCancelAuthority) external;

    /// @notice Sets `pendingOwner`. The owner does not change. Zero withdraws a
    ///         pending hand-over.
    function transferOwnership(address newOwner) external;

    /// @notice The pending owner becomes the owner.
    function acceptOwnership() external;

    // ─── views ─────────────────────────────────────────────────────────────

    /// @notice The order's digest, status (0 invalid, 1 open, 2 filled, 3
    ///         cancelled, 4 expired, 5 not yet active), stored filled amount and
    ///         a balance-only bound on the next fill (ADR-0008 decision 4).
    function orderState(Order calldata order)
        external
        view
        returns (bytes32 orderHash, uint8 status, uint256 filledIn, uint256 fillableIn);

    /// @notice The terms `recordFill` would return for `fillIn`, with no permit
    ///         (`floorOut = F`).
    function previewFill(Order calldata order, uint256 fillIn) external view returns (FillTerms memory);

    /// @notice The stored slot. It does not reflect the epoch, the deadline or validity.
    function fillState(address account, bytes32 orderHash) external view returns (uint256 filledIn, bool cancelled);

    /// @notice Raw slots: the filled amount in the low 255 bits, the cancelled flag in the top bit.
    function fillStates(address account, bytes32[] calldata orderHashes) external view returns (uint256[] memory packed);

    /// @notice The full EIP-712 digest of `order` in this ledger's domain.
    function hashOrder(Order calldata order) external view returns (bytes32);

    /// @notice The full EIP-712 digest of `batch` in this ledger's domain.
    function hashBatch(BatchSwap calldata batch) external view returns (bytes32);

    /// @notice The full EIP-712 digest of a `FillPermit` in this ledger's domain.
    ///         `orderHash` is the order's digest, not its struct hash.
    function hashFillPermit(
        bytes32 orderHash,
        uint256 fillIn,
        uint256 swapIn,
        address taker,
        bytes32 stepsHash,
        uint256 filledBefore,
        uint256 minOut,
        uint64 expiry
    ) external view returns (bytes32);

    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function isTaker(address taker) external view returns (bool);

    function epoch(address account) external view returns (uint64);

    function batchUsed(address account, bytes32 batchHash) external view returns (bool);

    function fillAuthority() external view returns (address);

    function cancelAuthority() external view returns (address);

    function owner() external view returns (address);

    function pendingOwner() external view returns (address);
}

contracts/orders/OrderTypes.sol

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

/**
 * @title Order types: the signed types, typehashes and errors of the orders ledger.
 * @notice ADR-0008 sections 3.1, 4 and 9. Everything `PeniwalletOrders` compiles
 *         and nothing else: this file imports nothing, and it holds no type of
 *         the core (those are in `contracts/interfaces/IPeniwalletV12Orders.sol`,
 *         which the ledger never imports).
 * @dev The ledger is immutable. The member order and the integer widths of
 *      `Order`, `BatchLeg` and `BatchSwap` are exactly those of the type strings
 *      below: the typehashes, the ledger's function selectors and every signature
 *      a user makes depend on them. Once the ledger is deployed this file is
 *      frozen: a comment or whitespace edit moves the ledger's address.
 */

// ─── signed types ─────────────────────────────────────────────────────────

/// @notice A limit order, signed by `account` in the ledger's EIP-712 domain
///         (ADR-0008 section 4.1). All-static: 18 members, 18 words.
struct Order {
    /// @notice The signer, and the account whose funds move. Proceeds stay here.
    address account;
    /// @notice The token sold. The native sentinel is allowed.
    address tokenIn;
    /// @notice The token bought. The native sentinel is allowed. Differs from `tokenIn`.
    address tokenOut;
    /// @notice The most `tokenIn` the order may ever sell. In (0, 2^127).
    uint256 amountIn;
    /// @notice With `amountIn`, the price. Net: what the user keeps after `feeOut`. In (0, 2^127).
    uint256 minAmountOut;
    /// @notice The smallest fill, and the smallest remainder a fill may leave. In (0, amountIn].
    uint256 minFillIn;
    /// @notice The relayer's fee in `tokenIn`, on top of `amountIn`, for the whole order. Below 2^127.
    uint256 feeIn;
    /// @notice The relayer's fee in `tokenOut`, from the swap output, for the whole order. Below 2^127.
    uint256 feeOut;
    /// @notice How far below the limit amount a fill may deliver. Below 10,000.
    uint16 fillSlippageBps;
    /// @notice The share of the surplus the taker receives. At most 10,000.
    uint16 surplusShareBps;
    /// @notice 0 = our relayers only, 1 = also a filler a later core generation permits.
    uint8 fillPolicy;
    /// @notice 0 = none, 1 = at or below the trigger level, 2 = at or above it. Not enforced on chain.
    uint8 triggerDirection;
    /// @notice With `amountIn`, the trigger level as a price in raw units. Not enforced on chain.
    uint256 triggerOut;
    /// @notice A spare signed slot. The ledger hashes it and never reads it.
    bytes32 extra;
    /// @notice Unix time the order was created. Bounds the deadline.
    uint64 createdAt;
    /// @notice Unix time after which the order cannot fill.
    uint64 deadline;
    /// @notice Must equal the account's current ledger epoch.
    uint64 epoch;
    /// @notice Uniqueness only. No on-chain rule.
    uint256 salt;
}

/// @notice One leg of a multi-token swap (ADR-0008 section 4.3). All-static.
struct BatchLeg {
    address tokenIn;
    address tokenOut;
    /// @notice Exactly how much `tokenIn` this leg's route may spend. In (0, 2^127).
    uint256 amountIn;
    /// @notice The least this leg's own route must deliver. In (0, 2^127).
    uint256 minAmountOut;
}

/// @notice A multi-token swap, signed by `account` in the ledger's EIP-712
///         domain (ADR-0008 section 4.3).
struct BatchSwap {
    /// @notice The signer. Proceeds stay in this account.
    address account;
    /// @notice 2 to 16 legs, one to many or many to one.
    BatchLeg[] legs;
    /// @notice The fewest legs that must run. In [1, legs.length].
    uint8 minLegs;
    /// @notice The token the relay fee is paid in: the token every leg shares.
    address feeToken;
    /// @notice The relay fee for the whole batch. Below 2^127.
    uint256 fee;
    /// @notice Unix time. At most 1 hour after the block that records the batch.
    uint64 deadline;
    /// @notice Must equal the account's current ledger epoch.
    uint64 epoch;
    /// @notice Uniqueness only.
    uint256 salt;
}

// ─── ledger call types (not signed) ───────────────────────────────────────

/// @notice What the caller of `recordFill` supplies beside the order and its
///         signature (ADR-0008 section 3.1).
struct FillRequest {
    /// @notice How much of the order this fill consumes.
    uint256 fillIn;
    /// @notice How much `tokenIn` is actually swapped.
    uint256 swapIn;
    address taker;
    /// @notice `keccak256(abi.encode(steps))`, computed by the core.
    bytes32 stepsHash;
    /// @notice The caller's claim that the account submits its own fill. Accepted
    ///         only when `tx.origin == msg.sender` (ADR-0008 decision 4, check 12).
    bool selfSubmitted;
    /// @notice The `FillPermit`'s `minOut`. Ignored when `selfSubmitted`.
    uint256 permitMinOut;
    uint64 permitExpiry;
    /// @notice The `FillPermit` signature. Ignored when `selfSubmitted`.
    bytes permit;
}

/// @notice What `recordFill` and `previewFill` return (ADR-0008 decision 4).
struct FillTerms {
    /// @notice `L = ceil(minAmountOut * fillIn / amountIn)`.
    uint256 limitOut;
    /// @notice `max(F, M)`: the least output, after `feeOutShare`, at which the fill may settle.
    uint256 floorOut;
    /// @notice `floor(feeIn * fillIn / amountIn)`.
    uint256 feeInShare;
    /// @notice `floor(feeOut * fillIn / amountIn)`.
    uint256 feeOutShare;
}

// ─── EIP-712 typehashes ───────────────────────────────────────────────────
//
// Every type string is one line: one space between a type and its name, nothing
// after a comma. The literal values are in ADR-0008 section 4 and are pinned by
// test/OrderTypehash.t.sol and schema/orders_eip712_v1.json.

/// @dev 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f
bytes32 constant EIP712_DOMAIN_TYPEHASH =
    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

/// @dev 0xedb889c4ab4d017361dfa17b38a681f6bcb6ff1065a0ac128fa5c725f07ee50f
bytes32 constant ORDER_TYPEHASH = keccak256(
    "Order(address account,address tokenIn,address tokenOut,uint256 amountIn,uint256 minAmountOut,uint256 minFillIn,uint256 feeIn,uint256 feeOut,uint16 fillSlippageBps,uint16 surplusShareBps,uint8 fillPolicy,uint8 triggerDirection,uint256 triggerOut,bytes32 extra,uint64 createdAt,uint64 deadline,uint64 epoch,uint256 salt)"
);

/// @dev 0x024e1bb9030d86d6ed5e5cfe872129bc2166ef04be48964db0868c662ab0d8fa
///      Signed by the fill authority, never by the user. `orderHash` is the
///      order's full digest, not its struct hash.
bytes32 constant FILL_PERMIT_TYPEHASH = keccak256(
    "FillPermit(bytes32 orderHash,uint256 fillIn,uint256 swapIn,address taker,bytes32 stepsHash,uint256 filledBefore,uint256 minOut,uint64 expiry)"
);

/// @dev 0xdc9045a1bf4dab681173b9a1c82d3303b767920f73b45ccf960269f397998320
///      The referenced type `BatchLeg(...)` is appended, as EIP-712 `encodeType` requires.
bytes32 constant BATCH_SWAP_TYPEHASH = keccak256(
    "BatchSwap(address account,BatchLeg[] legs,uint8 minLegs,address feeToken,uint256 fee,uint64 deadline,uint64 epoch,uint256 salt)BatchLeg(address tokenIn,address tokenOut,uint256 amountIn,uint256 minAmountOut)"
);

/// @dev 0x7503f9e809444c6fbca2db452977d89017a6535ae896a5a9fe4fa1abab7d9eaa
bytes32 constant BATCH_LEG_TYPEHASH =
    keccak256("BatchLeg(address tokenIn,address tokenOut,uint256 amountIn,uint256 minAmountOut)");

// ─── the ledger's errors (ADR-0008 section 9) ─────────────────────────────
//
// Each name is new: no selector equals any function or error selector of the
// core, Storage, the Validator, the collector, the factories, the bridge stack
// or an adapter. The backend decodes reverts by selector alone.

/// @dev 0x4207a3eb. `msg.sender` is not the order's or the batch's account.
error NotSigningAccount();
/// @dev 0x9cd3191d
error OrderSignatureInvalid();
/// @dev 0x48413eee
error OrderMalformed();
/// @dev 0xcb5acec6
error OrderLifetimeInvalid();
/// @dev 0x0c1ffacd
error OrderDeadlinePassed();
/// @dev 0xe3cc7933
error OrderIsCancelled();
/// @dev 0x69fafa34. `current` is the account's epoch in the ledger.
error OrderEpochMismatch(uint64 current);
/// @dev 0x9821bd08
error FillAmountInvalid();
/// @dev 0x9eeb8f2e. `remaining` is `amountIn - filled`, before this fill.
error OrderOverfilled(uint256 remaining);
/// @dev 0x399cf14d. `minFillIn` is the order's; `remaining` is `amountIn - filled`, before this fill.
error FillTooSmall(uint256 minFillIn, uint256 remaining);
/// @dev 0xf774ea08
error TakerNotAllowed();
/// @dev 0x11544a80. `selfSubmitted` was claimed in a transaction the account did not send.
error SelfSubmitNotOrigin();
/// @dev 0xa924751d
error FillAuthorityUnset();
/// @dev 0x693adf6b
error FillPermitExpiryOutOfRange();
/// @dev 0xddaa7b1f
error FillNotPermitted();
/// @dev 0x73143219
error BatchSignatureInvalid();
/// @dev 0x0b79ae40
error BatchMalformed();
/// @dev 0xa76f325b
error BatchDeadlinePassed();
/// @dev 0x7580be87
error BatchDeadlineTooFar();
/// @dev 0x2564d5eb. `current` is the account's epoch in the ledger.
error BatchEpochMismatch(uint64 current);
/// @dev 0x738f34b6
error BatchTooFewLegs();
/// @dev 0xf56e3b4d
error BatchAlreadyUsed();
/// @dev 0xa2df1842
error NotLedgerOwner();
/// @dev 0xedb72199
error NotPendingLedgerOwner();
/// @dev 0xeb9338d7
error NotCancelAuthority();
/// @dev 0x5e5769aa. The zero address, or the ledger itself, where neither is accepted.
error LedgerAddressInvalid();
/// @dev 0xff1d2c2b
error CancelListMalformed();
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.