Skip to content
UMBRA
Terminal

@umbra/engine — deterministic clearing engine (Gate 2 sandbox)

Gate 2 sandbox: synthetic vectors only, not used by the public site, rule pending approval (spec §15 items 8–10). Nothing here is market data, a live venue, or a statement about live UMBRA activity. The clearing rule, tie-break and allocation below are a CANDIDATE rule taken from spec §5.2 and docs/auction-mechanics.md. They are not approved for launch.

A small, pure TypeScript library (no runtime dependencies) that implements:

ModuleWhat it does
src/clear.tsUniform-price call-auction clearing for one market and one epoch (clear(orders, params))
src/epoch.tsEpoch lifecycle state machine with collateral reservations and the abort path
src/commitment.tsCanonical commitment encoding + SHA-256 commitment / reveal check
src/errors.tsTyped errors with stable codes
src/types.tsOrder, ClearingParams, ClearingResult, …

All prices are integer ticks and all quantities integer lots, held as bigint. Clearing math has no floating point anywhere. (The benchmark script uses Math.random-style numbers only to generate synthetic books.)

npm test          # vitest + fast-check
npm run typecheck # tsc --noEmit (strict)
npm run bench     # node bench/bench.ts — 10k / 100k synthetic orders

Requires Node ≥ 23.6 (native TypeScript type stripping) for npm run bench; sources use .ts import specifiers and erasable-only syntax.

Clearing rule (CANDIDATE, pending approval)

For one market and one epoch:

validate(orders, params)          // typed errors; duplicate commitment ids rejected
sort orders by id                 // input order can never matter
C := candidate prices (ascending)
for p in C:
  B(p) := Σ qty of buys  with limitPrice >= p
  S(p) := Σ qty of sells with limitPrice <= p
  V(p) := min(B(p), S(p))
P := best p in C by, in order:
  1. maximise V(p)
  2. minimise |B(p) − S(p)|                 (imbalance)
  3. minimise |p − referencePrice|          (precommitted reference price)
  4. choose the LOWER price                 (final, side-independent)
if V(P) = 0: no clearing — price = null, nothing fills

Step 4 can only ever see two survivors (ref − d and ref + d), so "lower price" is a total, deterministic rule. It depends only on the price, not on which side submitted it, on order ids, or on arrival time.

Candidate prices and why they are sufficient

B is non-increasing and only steps down just after a buy limit; S is non-decreasing and only steps up at a sell limit. Outside [min limit, max limit] one side is empty, so V = 0.

Maximising V. For any price p with V(p) > 0, let q be the highest sell limit ≤ p. No sell limit lies in (q, p], so S(q) = S(p), and B(q) ≥ B(p) because q ≤ p. Hence V(q) ≥ V(p): the maximum of V over all integer ticks is always attained at a submitted limit price. (Property test: V is the maximum … over every integer tick.)

Tie-break caveat — a spec ambiguity we had to decide. Restricting to limit prices is not sufficient for tie-break steps 1–2. Between two consecutive limit prices L_i < L_{i+1}, every interior tick has B = B(L_{i+1}), S = S(L_i), which can have strictly lower imbalance than both endpoints. Example (in test/clear.unit.test.ts): buys 5@100 and 10@110, sells 10@100 and 5@110. Both 100 and 110 give V = 10 with imbalance 5, while every tick in 101–109 gives V = 10 with imbalance 0.

So the engine offers two explicit price domains via params.priceDomain:

  • 'limitPrices' (default, as requested for Gate 2): the clearing price is always a submitted limit price.
  • 'allTicks': any integer tick. This is still computed exactly in O(n log n). Inside each gap (L_i, L_{i+1}), B, S and the imbalance are constant, so the only interior point that can win is the one closest to the reference: clamp(ref, L_i + 1, L_{i+1} − 1). The candidate set is the limit prices plus one such point per gap. A differential test checks this against brute force over every tick.

Both domains always reach the same maximum V; they can differ only in which price wins the tie-break. Which domain to use is part of open decision §15.10.

Allocation

All fills execute at the single uniform price P, and V = V(P).

  • Short side (eligible quantity = V): every eligible order fills in full. If B = S, both sides are short.
  • Long side: price priority between levels, pro-rata within the marginal level, and never time priority.
    • Walk the eligible levels from most aggressive (highest bid / lowest ask). A level fills completely while its total fits in the remaining volume.
    • The first level that does not fit is the marginal level. With R = remaining lots and Q = level quantity, order i gets base_i = floor(R·q_i / Q) and has remainder frac_i = (R·q_i) mod Q.
    • R − Σ base_i leftover lots go one each to orders ranked by largest frac_i first, then ascending order id. Arrival time is never used; the engine never sees it, and extra fields are dropped during normalisation.
    • Less aggressive levels get 0.
  • Each order receives at most its quantity, and Σ buy fills = Σ sell fills = V. The engine checks this internally and throws if it ever fails.

Note: the marginal level is often, but not always, the level at P. Example: buy 10 @105, sell 5 @100, ref 100. Every p in 100–105 ties on V and imbalance, and ref picks P = 100, yet the buy at 105 is the marginal level and gets 5/10. "Orders strictly better than P fill fully" therefore holds for the short side and for every long-side level above the marginal one, not unconditionally.

Result

{ price, volume, imbalance (= B−S, signed), eligibleBuy (B(P)), eligibleSell (S(P)), buyVolume, sellVolume, fills[{id, side, filled, remaining, status}], carryForward, expired }

fills, carryForward and expired are sorted by ascending id. carryForward lists GTE orders with remaining > 0; expired lists IOC orders with remaining > 0. When nothing clears, every order is unfilled and goes to one of those two lists according to its TIF.

Input validation (typed errors)

  • id must be lowercase 0x-hex (the commitment hash).
  • limitPrice and quantity must be bigint > 0. A JS number is rejected, so floats cannot get in.
  • side ∈ {buy, sell}, tif ∈ {IOC, GTE}, and referencePrice must be bigint > 0.
  • Duplicate ids raise DuplicateCommitmentError, because a commitment is consumed at most once.

Errors: InvalidOrderError, DuplicateCommitmentError, InvalidParamsError (all EngineError with .code).

Epoch state machine (src/epoch.ts)

OPEN → LOCKED → REVEAL → CLEAR → SETTLE → FINALIZED, with ABORT allowed from OPEN | LOCKED | REVEAL | CLEAR. transition(state, event) is pure: it returns a new frozen state or throws IllegalTransitionError.

  • RESERVE {id, amount}: only while OPEN. The amount must be positive and the id must not already be reserved.
  • ABORT {reason}: moves every outstanding reservation into released and empties the map. ABORTED is terminal, so release happens exactly once.
  • BEGIN_SETTLE: hands reservations to settlement (handedToSettlement). Abort is illegal from there on, so a settled epoch can never also release.

Commitments (src/commitment.ts)

commitment = 0x‖sha256(encodeCommitment(fields)).

The preimage is the domain tag UMBRA/order-commitment/v0, followed by the fields chainId, venue, market, epoch, alias, nonce, expiry, side, limitPrice, quantity, tif, salt in that fixed order. Each field is encoded as tag(1) ‖ length(4, BE) ‖ value:

  • integers: 32-byte big-endian uint256
  • strings: NFC UTF-8, non-empty
  • side / tif: 1 byte
  • salt: exactly 32 bytes

The tag and length prefixes make the encoding injective. verifyReveal returns false for any field mismatch.

SHA-256 (node:crypto) keeps the package dependency-free. keccak256 / EIP-712 typed data is a Gate 3 decision. So is canonicalising venue as an address; right now the venue is an opaque string, so 0xAB… and 0xab… are different venues.

Invariants → tests

Invariant (spec §5.4 / auction-mechanics)Test(s)
Clearing result deterministic for identical inputsclear.property determinism: … any permutation, … repeated calls; clear.unit extra fields such as timestamps …
Buy fills = sell fills = Vclear.property core invariants (both generators); internal guard in clear()
No fill exceeds order quantity; remaining = qty − filledclear.property core invariants
Filled buys have limit ≥ P, filled sells limit ≤ Pclear.property core invariants
V(P) is the max over candidate prices (and over all ticks)clear.property V is the maximum …, both price domains …
Price priority between levels: no better order is left unfilled while worse ones fill; short side fills fullyclear.property core invariants (priority check)
Pro-rata within level: |filled_i·Q − R·q_i| < Qclear.property core invariants
Remainder lots by largest remainder, then ascending id, never arrivalclear.unit allocation block
Tie-break sequence 1→2→3→4clear.unit tie-break block; differential tests
Independent implementation agreesclear.property differential: test/reference.ts brute force (all ticks, and limit prices), 2000 random books each
Each commitment consumed at most onceclear.unit duplicate commitment ids are rejected
Invalid input rejected with typed errorsclear.unit input validation
TIF: GTE carried forward, IOC expiredclear.property core invariants; clear.unit degenerate books
Empty / single-side / non-crossing / huge bigint booksclear.unit degenerate books
Only specified epoch transitions are legalepoch exhaustive transition table
Abort releases reservations exactly onceepoch abort releases … exactly once, property: … released at most once, settled epochs cannot abort
Commitment bound to chain, venue, market, epoch, alias, nonce, expiry (and order fields, salt)commitment changing %s changes the commitment (all 12 fields) + random-field property
No replay across epoch / venuecommitment replay across epoch or venue …
Reveal must match commitmentcommitment a reveal that differs …

Not covered in Gate 2: settlement atomicity, collateral/margin limits, operator fabrication, withholding, late reveal penalties, and multi-epoch carry-forward re-entry. Those need the on-chain and settlement design from Gate 3 and later.

Layout

src/      library (types, errors, clear, epoch, commitment, index)
test/     vitest + fast-check suites, reference.ts (naive brute-force oracle), arbitraries.ts
bench/    bench.ts (fixed-seed synthetic books, 10k and 100k orders)
NextPrivacy & threat model→