Deterministic escrow fund-release state machine + campaign fee calculator, reproduced from the ALLWEB3 portfolio case study (three-sided Web3 growth marketplace: creators, campaign managers, governance admins; escrow release anchored to oracle-verified KPIs).
TypeScript, zero runtime dependencies. The case study's on-chain contracts are not included here — this is the off-chain logic: who can move money, when, and exactly how the numbers are computed.
Node.js ≥ 20.
npm install
npm run build
npm test # 3305 tests, all localimport { Escrow, calculateDeposit, settleRelease } from "./dist/src/index.js";
// 1. Deterministic fee preview (numbers from the case study)
const fees = calculateDeposit({
creatorPool: 10000,
baseFee: 600,
complexityMultiplier: 1.0,
loyaltyDiscount: 30,
oracleFee: 60,
});
console.log(fees.deposit); // 10630
// 2. Milestone escrow lifecycle
const escrow = new Escrow("CMP-2026-042");
escrow.dispatch("FUND", "wire received", 10630); // optional amount: FUND-only,
// validated as a finite non-negative number and recorded on the audit entry
escrow.dispatch("SUBMIT_MILESTONE", "deliverable URLs + IPFS metadata hash");
escrow.dispatch("VERIFY_PASS", "KPIs validated by oracle");
escrow.dispatch("RELEASE");
console.log(escrow.state); // RELEASED
// 3. Gross-to-net settlement on release (5% pro fee)
console.log(settleRelease({ gross: 1000, proFeeBps: 500 }));
// { gross: 1000, proFee: 50, referralCredits: 0, net: 950 }Or run the bundled demo — one command drives a deterministic escrow
through CREATED → FUNDED → MILESTONE_SUBMITTED → VERIFIED → RELEASED
(the golden 10,630 deposit, fixed timestamps) and prints the audit
history plus the balanced settlement report. Its fee-breakdown segment
also runs the same funding through calculateDepositCents — the golden
vector as 1,063,000¢ and the fractional 1.25x vector as 1,077,999¢ —
cross-checking both against the dollar path ×100 to the cent, then shows
the cents-derived $10,630 deposit refused by a 10,000 maxDeposit cap
with the pinned error and no audit residue. It then shows
parseMinorUnits parsing the same amounts from their text form —
"106.30" to 10630¢, "0.05" to 5¢, "106" to 10600¢ — with the
golden deposit parsed from "10630.00" landing on the same 1,063,000¢
the cents segment computed, and "10.005" and "abc" refused with the
pinned strict-decimal error. It then runs
verifyHistoryChain on that history — the intact, genesis-linked
chain passes — and on a detached copy whose FUND entry's amount is
altered by 1, which fails verification (the stored hash no longer
recomputes), while the escrow's own history stays untouched — then builds the signed
settlement webhook for the released escrow (fixed eventId/at,
demo-only secret printed in src/demo.ts — not a real credential)
and verifies it the way a receiver would. The same settlement is
then signed a second way — with the opt-in Ed25519 private key
(fixed demo-only seed, only the keyId printed), the receiver
verifying it against the published public key and through a
keyId → key resolver, while a copy whose deposit moved by one
unit and a verification under an unknown keyId both fail closed.
It then re-verifies that webhook under requireEventId: true — the keyed payload passes,
while a twin with eventId stripped and re-signed is refused even
though its signature is valid, and still verifies with the option
off (the legacy signature-only behavior). It then runs that same
webhook through verifySettlementWebhookStrict — the recommended
receiver path with all three gates on by default — which passes
fresh (1 minute after at), refuses the identical signed body 10
minutes later, and refuses the keyless twin at the fresh instant.
The receiver side then
runs that webhook's eventId through SettlementEventDedupe on a
fixed clock (1-hour TTL, starting at the webhook's at): the first
delivery is new and booked, an immediate redelivery is a duplicate
and skipped, and after the clock advances by exactly the TTL the
same id counts as new again. The receiver side then probes that
same story read-only: a fresh dedupe on the same fixed clock answers
has on one fixed id — unseen before any record (and the record
after still counts as first sighting), seen on both probes after the
record with the counters untouched, and unseen again once the clock
advances by exactly the TTL, the probes having renewed nothing and
the expired probe having revived nothing — the check-before-verify
probe a receiver runs before spending a signature verification. The receiver side then seals that
same story: a fresh dedupe on the same fixed clock records two fixed ids, exports them with
exportSignedSnapshot() under a fixed demo-only secret, and the envelope is round-tripped through
JSON — a detached copy with one byte changed in the first entry's seenAtMs is refused by
restoreSignedSnapshot() with the pinned MAC-mismatch error, while the untampered envelope
restores with the counters at zero, the has probe reading both ids as seen and an unseen id as
new without recording anything, and a final checkAndRecord pass confirming both ids still read
as duplicates and the unseen id as new — the signed restore does not reopen the dedupe window. The sender side then parses
Retry-After hints with parseRetryAfter on the same fixed
clock: a fixed corpus (delay-seconds, a whitespace-padded value,
future and past HTTP-dates, a signed value, a garbage string,
an over-ceiling delay-seconds value, a 30-day-out HTTP-date,
and null) is printed value by value — both hint forms normalize
to milliseconds, a past date yields 0, and unparsable or absent
values yield undefined, the sender's cue to fall back to
exponential backoff (on a 429 the parsed hint, clamped by
maxRetryDelayMs, sets the wait before the next attempt); the two
over-ceiling hints both clamp to the Node timer ceiling
(2^31 - 1 ms), so a server-prescribed long backoff waits the
ceiling instead of misfiring after ~1ms.
A second escrow then walks
the dispute branch: VERIFY_FAIL into DISPUTED, a 2-of-3 arbitrator
quorum collected vote by vote — remainingApprovals() is read before
the first vote, after it, and at threshold (2 → 1 → 0, collected +
remaining = threshold at each step) — after the first vote the quorum
is snapshotted, round-tripped through JSON, and restored with
restoreQuorum at the identical 1-of-2 count (the arbitration-restart
path), a below-threshold dispatchArbitration
attempt is refused with the escrow untouched — and the reached quorum
refunding the sponsor in full to REFUNDED with its refund settlement
report. Right after the refund, the demo rebuilds the main settlement's
webhook twice with no eventId option: both builds carry the same
deterministically derived eventId
(settlement-DEMO-ESC-001-4-b63d4915502f) and the same signature, the
dispute escrow's settlement derives a different id, an explicit eventId
still overrides, and a fresh receiver dedupe counts the first build new
and the rebuild a duplicate — the rebuild is dropped, not booked twice.
Right after that, the demo chains strict verification into the receiver
dedupe as one booking decision: the fresh delivery verifies strict and is
new, so the settlement is booked; the same-instant replay still verifies
strict — the signature is authentic and the 5-minute window has not
closed — but the dedupe catches it, so the second booking is skipped;
and a forged twin re-signed with an unrelated secret fails strict, never
reaches the dedupe, and a later has on its id reads false, proving
the forgery was never recorded.
Right after that, the demo seals a fresh 2-of-3 quorum at
threshold into an HMAC-signed snapshot envelope with
exportSignedQuorumSnapshot: a detached copy with exactly one byte
changed inside the snapshot is refused at restore with the pinned
MAC-mismatch error, the untampered envelope restores at the identical
2-of-2 count, and an envelope sealed with a past expiresAt and a
restore under the wrong secret are each refused with their pinned
errors — the tamper-evident restart. A signed-approvals segment then
shows the other half of quorum trust: a fresh 2-of-3 quorum with
Ed25519 public keys registered for two of the three arbitrators
collects votes with approveSigned() — a valid signature counts and
marks the log entry verified: true, a signature made with the wrong
key is refused and records nothing, and the signer with no registered
key cannot use approveSigned() at all; the key pairs are generated
fresh on every run and only the verdicts are printed, never a key or
a signature. A verified-only arbitration segment then shows what that
proof is for: a fresh disputed escrow (DEMO-ESC-046) with a mixed
quorum — one Ed25519-verified vote and one plain claim — reaches the
plain threshold 2/2 while the verified count reads 1/2, so
dispatchArbitration(..., { requireVerifiedApprovals: true }) refuses
with the pinned arbitration requires quorum: 1/2 verified approvals
error and leaves the escrow untouched, and after the plain claim
upgrades in place to verified the same call releases it, the audit
note recording only the verified signers. A time-travel segment then walks a
fresh escrow through FUND → SUBMIT_MILESTONE → PARTIAL_RELEASE on
fixed timestamps and asks stateAt what state it was in at five fixed
moments — before the first entry (CREATED), exactly on the FUND entry
(FUNDED: the boundary is inclusive), between SUBMIT_MILESTONE and
PARTIAL_RELEASE (MILESTONE_SUBMITTED), exactly on the
PARTIAL_RELEASE entry and after it (FUNDED both times) — with the
module-level stateAtFromHistory agreeing on the raw log and an
unparseable time refused with the pinned error. The demo closes with the day-end batch pipeline over all three
escrows (a third escrow is left FUNDED): buildSettlementReports
builds one report per escrow with per-item error isolation — the
still-FUNDED escrow lands as {escrowId, error} in the middle of
the batch without blocking the refunded report after it — and
summarizeSettlementReports prints the batch's reconciliation
summary (2 reports, 1 error, totals of 21,260 on the two golden
deposits, and a still-locked remaining of 0 — both successful
reports are fully settled, so neither carries a remainder). Right
after the summary, the demo renders it three ways —
renderSettlementReportsSummary as plain text,
renderSettlementReportsSummaryCsv and
renderSettlementReportsSummaryJson as the interchange forms — reads
the CSV and JSON back (each import deep-equals the summary and
re-renders byte-identically), re-summarizes the batch with one more
escrow settled (DEMO-ESC-040, released on the golden deposit) and
diffs the two summaries with diffSettlementReportsSummaries (total
3 → 4, reports 2 → 3, released 1 → 2, totals 21,260 → 31,890, creator
net 10,098.50 → 20,197, platform net 531.50 → 1,063, sponsor net
−10,630 → −21,260; errors, refunded, remaining, and balanced
unchanged and absent from the diff), and refuses a CSV with a tampered
header with the pinned error. Right after that, the demo runs unreconciledSettlements over the
day-end batch plus two extra cases — a release carrying a
settlementRef (wire-2026-03-09-001) and an arbitration release —
and prints the two releases still missing payment evidence: the main
escrow (released, no ref) and the arbitration-released escrow (no
RELEASE entry, so no ref is possible), while the with-ref release,
the still-FUNDED escrow, and the refunded escrow are excluded.
Between the summary and the webhooks, the demo re-settles the main escrow
at 600 bps (up from 500) and runs diffSettlementReports on the two
reports of the same escrow: the diff carries exactly
settlementChanged (proFee 531.5 → 637.8, net 10,098.5 → 9,992.2,
gross 10,630 unchanged) and partiesChanged (creator and platform
nets move, sponsor/referrer untouched, nothing added or removed),
while outcome, currency, totals, balanced flag and event count are
unchanged and absent from the diff — and two identical reports diff
to {}. The batch results then go straight into
buildSettlementWebhooks, which signs one webhook per successful
report under the shared demo secret at one fixed batch timestamp —
one factory-generated eventId per report (evt_demo_batch_001,
evt_demo_batch_002, never reused, so a receiver deduplicating on
eventId keeps both), the failed entry forwarded as
{escrowId, error} — and the demo prints a receiver-side
verifySettlementWebhook verdict on each built webhook's line.
The demo closes with a watchdog screening over three further
escrows on one fixed now: staleEscrows selects by dwell in the
current state (7-day budgets; the escrow funded 17 days earlier is
stale even though its deadline is still ahead) while
expiredEscrows selects the same batch by absolute deadline (the
escrow submitted 1 day earlier is expired, not stale) — different
axes, different subsets — and actOnStaleEscrows then expires the
one stale escrow with its dispatch pinned to the same fixed now,
leaving the other two untouched. The demo then closes with a
deadline-watchdog section over three more escrows on the same
fixed now: expiredEscrows screens the batch by deadline and
expireOverdueEscrows executes that selection with per-item
isolation — the past-deadline DISPUTED escrow has no EXPIRE
edge (expiry must not let a party walk out of arbitration) and
lands as {expired: false, error} without blocking the
past-deadline FUNDED escrow after it, which expires, while the
stale-only escrow (deadline still ahead) is never attempted, so
the deadline and stale axes pick disjoint subsets of this batch
too. (The executor pins the fixed screening now as each EXPIRE
entry's at, so the appended entries are deterministic too; the
demo prints no timestamp for them and its printed output stays
deterministic.) Before either executor runs, the demo rehearses
both axes with dryRun: true over the same batches: the stale axis
would act on the one stale escrow, the deadline axis would expire
the past-deadline FUNDED escrow and classifies the DISPUTED
one unexpirable — and a closing rehearsal segment prints both
verdicts, the zero-residue check (no state or history change
through either dry run), and the rehearsal==live match — the
"rehearse first, then execute" shape a finance operator runs
before any batch expiry. The demo then screens the same deadline
batch once more with stuckEscrows() after the executor ran:
only the past-deadline DISPUTED escrow is stuck — the FUNDED
one is now EXPIRED (terminal) and the stale-only one was never
overdue — the stuck set equals the executor's own unexpirable
list, stuck + expirable partitions the overdue set, and the stuck
escrow kept its DISPUTED state and history length through the
dry run and the live run, so the operator routes it to an
arbitrator instead of retrying expiry. The demo
then prints an allowed-events listing that runs
allowedEvents() over all 8 states in transition-table order and
prints one line per state — the query an escrow-list UI or a
watchdog consults to decide what an escrow can do next — with the
three terminal states (RELEASED / REFUNDED / EXPIRED) returning
the empty list, and the main escrow's own RELEASED state called
out on its own line as that same empty set. The demo then prints
a deposit-provenance segment: depositAmountFromHistory
traces the locked deposit back out of the main escrow's audit
history alone — 10,630, the sum of every FUND amount, matching
the settlement report's deposit — and a fixed copy of that
history with every FUND entry removed fails with the explicit
settlement requires a FUND amount error, shown on one FAILED
line (a history that cannot corroborate a deposit settles
nothing, rather than guessing). A locked-balance segment then
reads the still-locked remainder straight from a fresh escrow's
audit history (DEMO-ESC-047): lockedBalanceFromHistory reads
6,378 after one 4,252 tranche of the golden 10,630 deposit, and
0 after the terminal RELEASE — while a plain deposit - released subtraction still reads 6,378, overstating the
balance, because the RELEASE entry carries no amount. The demo
finally closes with a
settlement-split segment: settleRelease splits that same
golden deposit in isolation — gross 10,630 at the main escrow's
500 bps pro fee yields a 531.50 platform fee and a 10,098.50
creator net with zero referral credits, the three parts summing
back to the deposit exactly — the same split the settlement
report above was built on, shown as the pure function's own
input and output. Right after it, an integer-cents settlement
segment settles that same golden deposit in whole cents —
settleReleaseCents yields proFeeCents 53,150 and netCents
1,009,850, exactly the dollar split ×100; settleRefundCents
returns the full 1,063,000 cents to the sponsor; and
settlePartialReleaseCents splits it in two tranches (425,200
then 637,800) with fees 21,260 and 31,890 summing back to the
single-release split — and pins the one-cent float-dust
disagreement: 115 cents at 5000 bps fees 58 cents exactly, while
the dollar twin fees 0.57. An over-release of 1,063,001 cents
against the 1,063,000-cent gross is refused with the pinned
error. Right after that, an arbitrated-split segment
walks the third arbitration outcome: a disputed escrow split
70/30 by a 2-of-3 quorum, settled in whole cents by
settleArbitrationSplitCents — creator net 706,895 cents,
platform fee 37,205 cents, sponsor refund 318,900 cents,
conserving the 1,063,000-cent gross — and the demo now reports that
split through buildSettlementReport (outcome split,
splitSettlement the dollar twin of the cents split — gross 10,630,
creator 7,441, sponsor 3,189, proFee 372.05, creator net 7,068.95,
balanced — party rows sponsor 3,189 in / 10,630 out, creator 7,068.95
in, platform 372.05 in, referrer 0). For a partial release, settlePartialRelease
charges the fee on the released amount only and returns the
remaining locked balance; it is pure arithmetic and does not
change escrow state — state advancement still goes through
dispatch. The demo shows it splitting the same golden deposit
in two tranches — 4,252 (40%) then the remaining 6,378 — with
tranche fees 212.60 and 318.90 and nets 4,039.40 and 6,059.10
summing back to the single-release split (531.50 / 10,098.50),
so splitting a release never double-charges the fee. The demo then
settles that same deposit in one settlePartialReleases batch —
[4,252, 6,378] with totals identical to the single path — and shows
the cumulative guard refusing [600, 600] against a gross of 1,000
as a whole, leaving DEMO-ESC-036 FUNDED and untouched. The demo then
reports that same first tranche through buildSettlementReport with
partialRelease: outcome partially-released on a still-FUNDED
DEMO-ESC-035, remaining 6,378 still locked, sponsor outflow the
whole 10,630 against inflow 6,378, creator net 4,039.40 and platform
fee 212.60, totals 10,630 / 10,630 and balanced — the day-end view
of a partial release. For a refund, settleRefund returns the full deposit
to the sponsor with every other party at 0 and no fee charged,
matching the REFUNDED branch of buildSettlementReport exactly. The demo then shows a settlement-reconciliation segment: reconcileSettlements pairs three settled reports against a four-row external ledger — one matched at 10,630, one report-only at 1,100, one amount mismatch (report 10,630 vs ledger 10,000), and one ledger-only row at 500. The demo also shows a batch-filter
segment: escrowsByState / escrowsByActor / escrowsByEvent slice one four-escrow
batch three ways — the FUNDED slice is DEMO-FILTER-01 and
DEMO-FILTER-03, the sponsor-touched slice is DEMO-FILTER-01,
DEMO-FILTER-02 and DEMO-FILTER-04 (DEMO-FILTER-04 matching once
despite two sponsor entries), and the SUBMIT_MILESTONE slice is
DEMO-FILTER-02 and DEMO-FILTER-04, while the anonymous DEMO-FILTER-03
appears in no actor's slice — the state lens, the actor lens, and the
event lens are orthogonal, and all three calls are pure. The demo then shows a combined-filter segment: escrowsByFilters takes the one escrow that is DISPUTED, sponsor-touched, and ever disputed out of a four-escrow batch — "FUNDED and ever disputed" would be empty by construction, since DISPUTE moves an escrow out of FUNDED — and settlementAging buckets the same batch at the fixed 2026-03-09T09:00:00.000Z now (DEMO-AGING-03 at 4 days under 7 days, DEMO-AGING-02 at 12 days in 7–30 days, DEMO-AGING-01 at 36 days over 30 days, DEMO-AGING-04 unknown as never funded), printing the oldest unsettled funds, DEMO-AGING-01 at 36 days, so finance ops chase the over-30-day bucket first. The demo then shows a settlement-reference-filter segment: escrowsBySettlementRef takes the two escrows settled under wire-2026-03-09-001 (DEMO-ESC-037 and DEMO-SETTLEMENT-REF-02) out of a seven-escrow day-end batch, the one escrow under wire-2026-03-10-002 (DEMO-SETTLEMENT-REF-03), and nothing for an unknown ref — and escrowsByFilters with the settlementRef axis agrees with the single-axis selector; the escrow released without a ref and the arbitration-released escrow never match, and all calls are pure. The demo then shows a snapshot-comparison segment: diffEscrowSnapshots diffs one escrow's before/after snapshots across a single SUBMIT_MILESTONE step — stateChanged FUNDED -> MILESTONE_SUBMITTED with history appended seq 2..2 — alongside an identical pair reporting {} and a cross-escrow diff rejected with the pinned error. The demo then shows a quorum-snapshot-comparison segment: diffQuorumSnapshots diffs two snapshots of the same committee taken under different charters — threshold 3 vs 4, one signer added (arb-6, so 5 signers become 6), and the approval window doubled from 3600000 to 7200000 ms — reporting exactly the three charter keys with approvalsChanged: false, since the same two votes sit at the same fixed timestamps in both; an identical pair reports { approvalsChanged: false }, the always-present master switch. The demo then shows a webhook-outbox segment: the main escrow's signed webhook is delivered to the billing endpoint through a scripted fetch that answers 500 three times — each failure recorded in a SettlementWebhookOutbox on a fixed clock — so after two failures the pair is still pending (attempts 2) and after the third it dead-letters at the maxAttempts cap of 3, the one that needs a human; a second event fails once and then delivers 200, so its success clears its own pair and the ledger ends pending 0, dead letter 1. The demo then shows the outbox's error cap: a fixed 1500-char failure is truncated to exactly 1024 chars ending with the …[truncated] marker, a short error is kept verbatim, and the same long error recorded in a fresh outbox lands in the ledger already truncated. The demo then shows the dead letter coming back: redrive() at a fixed later clock moves the pair back to pending with attempts reset to 0, a second redrive while pending is rejected with the pinned error, and one scripted 200 after the fix clears the pair, so the ledger ends pending 0, dead letter 0. The demo then shows the retry loop over a fresh ledger: retrySettlementWebhookOutbox re-delivers the one pending pair — first attempt 500, second 200 — with maxRounds: 2, backoffMs: 0, jitterMs: 0, so the summary reports attempted 2, acknowledged 1, still pending 0, dead letter 0; a dryRun: true rehearsal over a second pending pair reports wouldRetry 1 with attempted 0 and acknowledged 0 and leaves the ledger unchanged. The demo then shows a state-visit-budget segment: a branch escrow with maxVisitsByState: { FUNDED: 2 } spends one FUNDED visit on the first FUND and the second on the first milestone round's PARTIAL_RELEASE back to FUNDED, so the second round's PARTIAL_RELEASE is refused with the pinned state visit budget exhausted: FUNDED already visited 2 of 2 times error and leaves state, history, and the locked total untouched, while a control escrow with no budget runs the same three milestone rounds and every one passes. The demo then shows the read side of that budget: a branch escrow with the same maxVisitsByState: { FUNDED: 2 } reads remainingVisits("FUNDED") as 2 → 1 → 0 across the first FUND and the first milestone round, with used + remaining = budget cross-checked at each step, while the unbudgeted states read Infinity and the second round's PARTIAL_RELEASE is refused at exactly 0 with the same pinned error. The demo then shows a caller-string-length-limits segment: the five caller-supplied short-identifier caps (dispatch actor, webhook eventId, escrow id, quorum approval evidence, dispatch idempotencyKey) each refuse a one-over-the-cap value with the pinned error and zero residue, then accept the exact at-cap value — the at-cap FUND replay is a no-op and the at-cap eventId webhook still verifies. The demo finally closes with an event-level RBAC segment: a dedicated escrow constructed with a pinned rolePolicy (FUND only by sponsor, DISPUTE only by moderator, arbitration only by arbiter) refuses a covered event from a wrong actor — or with no actor at all — with the pinned actor not authorized for … error and no state or history residue, while an allowlisted actor advances it and events the policy does not cover run with no actor at all; a second escrow built without a policy drives the same route with no actor at all.
npm run demostateDiagram-v2
[*] --> CREATED
CREATED --> FUNDED : FUND
CREATED --> EXPIRED : EXPIRE
FUNDED --> FUNDED : FUND
FUNDED --> FUNDED : PARTIAL_RELEASE
FUNDED --> MILESTONE_SUBMITTED : SUBMIT_MILESTONE
FUNDED --> DISPUTED : DISPUTE
FUNDED --> EXPIRED : EXPIRE
MILESTONE_SUBMITTED --> VERIFIED : VERIFY_PASS
MILESTONE_SUBMITTED --> DISPUTED : VERIFY_FAIL
MILESTONE_SUBMITTED --> FUNDED : PARTIAL_RELEASE
MILESTONE_SUBMITTED --> DISPUTED : DISPUTE
MILESTONE_SUBMITTED --> EXPIRED : EXPIRE
VERIFIED --> RELEASED : RELEASE
VERIFIED --> DISPUTED : DISPUTE
VERIFIED --> EXPIRED : EXPIRE
DISPUTED --> RELEASED : ARBITRATE_RELEASE
DISPUTED --> REFUNDED : ARBITRATE_REFUND
DISPUTED --> RELEASED : ARBITRATE_SPLIT
RELEASED --> [*]
REFUNDED --> [*]
EXPIRED --> [*]
(EXPIRE is available from CREATED, FUNDED, MILESTONE_SUBMITTED,
and VERIFIED once the campaign deadline passes — not from DISPUTED, where the
outcome is decided by arbitration (a verified-but-unreleased escrow that
passes its deadline expires back to the sponsor instead of locking funds
forever; a disputed escrow never expires out of arbitration); terminal states are
RELEASED, REFUNDED, EXPIRED. The diagram is generated from
transitionTable() in src/stateMachine.ts by stateDiagram() — do not
edit it by hand; regenerate it with npm run diagram (prints the block to
stdout; node dist/src/diagram.js --check exits 1 if the README copy
drifts; --write <file> writes bare mermaid source for standalone .mmd
use). test/stateDiagram.test.ts asserts edge parity and
test/diagram.test.ts guards the generator and CLI.)
transition(state, event)is a pure function; invalid transitions throw.Escrowwraps it with an append-only history (the case study's "immutable operational audit log"): every dispatch records seq, event, from → to, timestamp, and an optional note. Notes are capped atMAX_NOTE_LENGTH(32,768 characters, exported from the package entry):dispatch()and the snapshot/history parsers both reject longer notes, so an unbounded note can never inflate the append-only log or a persisted snapshot. Evidence references are capped the same way atMAX_EVIDENCE_LENGTH(32,768 characters, exported from the package entry):dispatch()and the snapshot/history parsers both reject longer references outright, never truncating them, so an oversized reference can never inflate the log or a persisted snapshot. Actor names are capped the same way atMAX_ACTOR_LENGTH(256 characters, exported from the package entry):dispatch()and the snapshot/history parsers both reject longer actors outright, never truncating them, so an oversized actor can never inflate the log or a persisted snapshot (rolePolicynames carry no cap — a policy is configuration, not audit data, and a name longer than the cap can never match a legal dispatch anyway; seeMAX_ACTOR_LENGTHinsrc/stateMachine.ts). Escrow ids are capped the same way atMAX_ESCROW_ID_LENGTH(256 characters, exported from the package entry): the constructor and the snapshot/history parsers (includingEscrow.fromHistory) all reject longer ids outright, never truncating them — an id is identity, and truncation would change which escrow a log belongs to — so an oversized id can never inflate the log, a snapshot, an NDJSON export, a settlement report, or a webhook payload. Each entry is also hash-chained:prevHashlinks to the previous entry'shash(genesis links to the"GENESIS"constant) andhashis SHA-256 over the canonical entry serialization, so a rewritten entry in a persisted JSON snapshot is detectable —verifyHistoryChain(history)returnsfalse, andEscrow.fromJSON()rejects a broken chain — naming the first entry whose link or hash fails (invalid snapshot: history[N]: history hash chain is broken (…) at entry seq <n>, so a long audit log points at the tampered entry; NDJSON import retags that entry to its physical line number) — andbuildSettlementReport()verifies the chain before producing any accounting (legacy hashless snapshots are still accepted and chained on rehydration; mixed chained/hashless snapshots are rejected, naming their first off-pattern entry the same way). A malformed history is not a verdict either way:verifyHistoryChainthrowsinvalid history: history must be an arrayfor a non-array history andinvalid history: entry[N]: entry must be an objectfor a non-object entry (an array entry included), the same wordsparseEscrowHistoryuses — only a well-shaped history gets a true/false verdict. By default the chain is unkeyed tamper evidence, not a MAC — see SECURITY.md for the honest limits. An optional keyed mode upgrades it to a real MAC: construct the escrow withnew Escrow(id, { auditKey })and every link becomes HMAC-SHA256 under that key, so a full-log rewrite with recomputed hashes is detected without the key. Verification is fail-closed across modes (a keyed chain needs its key viaverifyHistoryChain(history, key)/Escrow.fromJSON(snapshot, { auditKey }); an unkeyed chain rejects a supplied key), and the key is never written into snapshots. The CLI demo (npm run demo) walks the keyed mode end to end on a branch escrow: the correct key verifies the HMAC-chained history, a wrong key and no key both fail closed, and a detached copy with a rewritten middle entry fails even under the correct key. The demo's key is a fixed printed placeholder, not a real secret — key management stays the caller's problem, exactly as in a real deployment.FUNDaccepts an optionalamountargument — it is validated as a finite non-negative number at the dispatch boundary (anything else throws) and recorded on the audit entry; passing an amount with any other event throws, exceptPARTIAL_RELEASE(below).FUNDfromCREATEDis the initial deposit;FUNDfromFUNDEDis a self-loop that adds a top-up to the locked total — real escrows often need extra collateral, and the locked total is always the sum of everyFUNDentry's amount minus everyPARTIAL_RELEASEentry's amount (seedepositAmountFromHistory/releasedAmountFromHistory/lockedBalanceFromHistory).PARTIAL_RELEASEpays out one tranche while the escrow staysFUNDED— milestone-based staged payouts, one tranche per completed milestone. It is legal fromFUNDED(self-loop) and fromMILESTONE_SUBMITTED(back toFUNDED, re-opening the milestone for the remaining tranches). The amount is mandatory: it must be greater than zero, no larger than the still-locked balance (FUND total minus released total), and is rounded to cents like every other amount; zero, negative, non-finite, missing, or over-balance amounts throw with no history residue and consume no idempotency key. Releasing exactly the remaining balance is legal and still recordsPARTIAL_RELEASE— it is not silently rewritten as a fullRELEASE, which still requiresVERIFY_PASSfirst.releasedAmountFromHistoryreads the paid-out tranche total back out of the audit history (0 when nothing was released; it throws when aPARTIAL_RELEASEentry carries no amount), so reports and webhook payloads can read the still-locked balance straight fromlockedBalanceFromHistory— deposit minus released while the escrow is open, 0 once a terminal settlement event (RELEASE, arbitrated release/refund/split, or EXPIRE) has landed. A plain subtraction would overstate the balance after a full release, because the terminal leg is never counted in the released total; themaxDepositcap is judged on that net locked balance.RELEASEaccepts an optionalsettlementRefinopts— a chain transaction hash, bank transfer reference, or payout batch id — recorded verbatim on the RELEASE audit entry so finance ops can reconcile the release against the ledger without a second lookup. It is accepted only on RELEASE (any other event throws), must be a non-empty string no longer thanMAX_SETTLEMENT_REF_LENGTH(256 characters, exported from the package entry), and is rejected outright when oversized, never truncated. A RELEASE without a ref stays legal; no uniqueness is enforced, so one ref may settle several escrows (one payout batch, one bank transfer), mirroring the dataquest lifecycle'spayoutRef. The ref is covered by the hash chain — rewriting it in a persisted snapshot breaksverifyHistoryChain— and survivestoJSON()/fromJSON(),fromHistory(), and NDJSON round-trips.escrowsBySettlementRef(escrows, ref)lists every escrow whose RELEASE entry carries that exact ref (case-sensitive), andescrowsByFilters()gains the samesettlementRefaxis.allowedEvents(state)lists valid next events for UI gating.isTerminal(state)is a standalone pure function for the same question without an instance — batch screening and transition-table checks can ask whether a state is terminal (RELEASED,REFUNDED,EXPIRED) without constructing an escrow. Unknown states fail closed (throw), so a typo can never read as "not terminal".Escrow.isTerminaldelegates to it, so the getter and the function can never drift apart.transitionTableJson()exports the whole transition table as canonical JSON;test/__snapshots__/transitionTable.snapshot.jsonis the committed snapshot (test/transitionSnapshot.test.tsfails if the table ever changes without regenerating it).- Retry safety:
dispatchaccepts a fourth argumentoptswith an optionalidempotencyKey(non-empty string, no longer thanMAX_IDEMPOTENCY_KEY_LENGTH— 256 characters, exported from the package entry). A dispatch whose key was already seen with the same fingerprint is a no-op — it returns the current state and appends nothing to the audit history, so a retriedFUNDcan never double-count the deposit. The fingerprint binds the key to the dispatch it first executed:eventplusactor,amount(rounded to cents the waydispatchrecords it),settlementRef,refundRef,splitCents, andevidence;at,expectedSeq, andnoteare deliberately excluded, so a legitimate retry may carry a fresh timestamp or annotation. A dispatch under a seen key with a different fingerprint throwsdispatch conflict: idempotency key "<key>" was already used for <event>, got <event>and leaves state, history, and the key untouched — a$200release can no longer hide behind a$100key. The conflict is checked after theexpectedSeqguard and before transition and RBAC checks, so a stale sequence still reports itself first. An oversized key is rejected outright atdispatch, at constructor seeding (idempotencyKeys), and on snapshot restore — never truncated, because truncation would change which deliveries the key dedupes, and a rejected dispatch consumes no key. Keys are recorded only after a successful dispatch (a failed dispatch leaves the key unused, so the caller can retry with corrected input), and ARE part oftoJSON()/fromJSON()snapshots: the consumed set rides along asidempotencyKeys(written only when non-empty, so a keyless snapshot keeps its legacy shape) with the per-key binding asidempotencyKeyFingerprints, and a restored escrow still treats an already-consumed key as a duplicate — replays stay exactly-once across restarts as long as snapshots are persisted throughtoJSON(). A key with no fingerprint — seeded through the constructor, or restored from a snapshot written before fingerprints existed — keeps the old any-event no-op: the binding is recorded where the dispatch happened, never invented afterwards.diffEscrowSnapshotsreports a binding change asidempotencyKeyFingerprintsChanged, even when the key set is identical. This is per-escrow retry protection, not a distributed idempotency store: two processes restoring the same snapshot independently can each execute the same key once. Unknownoptskeys fail closed:dispatchthrowsinvalid dispatch options: unknown option "<key>"before any field is read, so a typo'didempotencykeyis reported instead of silently dropping the dedupe, and a typo'dactorrinstead of silently dropping the audit attribution. The check runs after theexpectedSeqguard (which stays first of all) and before the actor shape validation and the dedupe; the seven known keys areactor,idempotencyKey,evidence,settlementRef,refundRef,at, andexpectedSeq. - Injectable audit timestamps:
dispatchopts also acceptat(Date | string) to pin the audit entry's timestamp — for deterministic dispatch tests and replay (quorum approvals and webhook payloads already had injectable clocks; the audit clock did not). ADateis normalized viatoISOString(); a string must already be canonical ISO-8601 (the same rule snapshot validation enforces) and must not be earlier than the previous entry'sat. Invalid or backwards values throw before anything is appended, and a rejected dispatch consumes no idempotency key. When omitted, the wall clock is used as before. The injected value is covered by the entry's hash chain like every other field. - Deposit caps:
new Escrow(id, { maxDeposit })caps the total locked deposit at a finite non-negative number (risk control / contract limits). AFUNDwhose amount would push the locked total — the sum of everyFUNDentry's amount minus everyPARTIAL_RELEASEentry's amount, the net locked balance — above the cap throws adeposit cap exceedederror after transition and amount validation and appends nothing, so a failed FUND leaves no audit residue. A partial release frees locked room again: after releasing, a top-up up to the freed amount is legal.FUNDdispatches without an amount carry no money and are never capped. The cap IS part oftoJSON()/fromJSON()snapshots (maxDeposit, written only when a cap is set, so a cap-free snapshot keeps its legacy shape), so a restored escrow keeps enforcing it — a legacy snapshot without the field restores uncapped — and an explicitEscrow.fromJSON(snapshot, { maxDeposit })overrides the snapshot's cap entirely. The audit key is the deliberate exception: it is never written into a snapshot. - State visit budgets (opt-in):
new Escrow(id, { maxVisitsByState })caps how many times the escrow may enter each listed state — the state-level answer to the milestone loop the transition table otherwise leaves unbounded (FUNDED → SUBMIT_MILESTONE → MILESTONE_SUBMITTED → PARTIAL_RELEASE → FUNDEDre-opens the milestone for the remaining tranches). A visit counts as 1 for the escrow's initial state plus 1 per history entry landing in that state, so the count is derived from the append-only history and survivestoJSON()/fromJSON()round-trips without resetting (the used count is never stored separately, so it cannot drift from the audit log). A dispatch whose target state already used its budget throwsstate visit budget exhausted: …after the transition, RBAC, and amount / deposit-cap checks and appends nothing, so a failed dispatch leaves no audit residue and does not consume an idempotency key. States absent from the map are unlimited, and omitting the map disables the check entirely. Each budget must be a positive integer (0 is a construction error: the initial visit already spent it). The budget IS part oftoJSON()/fromJSON()snapshots (maxVisitsByState, written only when non-empty), and an explicitEscrow.fromJSON(snapshot, { maxVisitsByState })overrides it entirely; a bare history carries no budget, soEscrow.fromHistory(id, history, { maxVisitsByState })is the way to re-attach it there. Read the count any time withescrow.visitCount(state)(unknown states throw), and the remaining entries withescrow.remainingVisits(state)— the same count subtracted from the budget, clamped at 0,Infinityfor an unbudgeted state, and the same unknown-state throw. A 0 remaining means the next dispatch into that state is rejected, and thestate visit budget exhausted: …error names the same used and budget numbers. Honest limit: the budget caps re-entry into a state, not total history length, and a budget of 1 onCREATEDdoes not block the firstFUND(no edge re-entersCREATED). - Event-level RBAC (opt-in):
new Escrow(id, { rolePolicy })maps events to the actor names allowed to dispatch them, e.g.{ RELEASE: ["treasury"], ARBITRATE_RELEASE: ["dao-arbitrator"] }.dispatchthen requiresopts.actor(a non-empty string of at mostMAX_ACTOR_LENGTH(256) characters, recorded on the audit entry and covered by its hash chain) to exactly match the allowlist for gated events — a missing or non-allowlisted actor throwsactor not authorized for …after the transition-legality check and before anything is appended, and does not consume an idempotency key, so a retry with an authorized actor and the same key succeeds. Events the policy does not list are unrestricted, and an escrow with no policy behaves exactly as before. Invalid policies (unknown event, non-array value, empty array, empty/non-string actor name) throwinvalid option: rolePolicy …at construction. Like the deposit cap and the evidence gate, the policy IS part oftoJSON()/fromJSON()snapshots (rolePolicy, only when non-empty; a tampered policy in a stored snapshot is rejected), and an explicitEscrow.fromJSON(snapshot, { rolePolicy })overrides the snapshot's policy entirely. Honest limit: this is a caller-supplied allowlist, not identity authentication — the caller asserts the actor string and nothing verifies who the caller is (see SECURITY.md). The bundled demo's closing segment drives this end to end (npm run demo, event-level RBAC: wrong-actor and actor-less dispatches rejected, allowlisted actors advance, uncovered events and policy-free escrows unrestricted). - Audit attribution (opt-in):
new Escrow(id, { requireActor: true })makes everydispatchwithout anactorthrowactor required: dispatch must carry a non-empty actor when requireActor is enabled. The gate runs after the transition-legality, RBAC, and deposit-cap checks and before anything is appended, so a rejected dispatch leaves no history residue and does not consume an idempotency key — a retry with an actor and the same key still executes. It complementsrolePolicy: a policy only constrains the events it lists, whilerequireActorconstrains all of them (a listed event without an actor still reports the RBAC error first, since that check runs earlier). Non-boolean values throwinvalid option: requireActor …at construction. Like the deposit cap and the evidence gate, the switch IS part oftoJSON()/fromJSON()snapshots (requireActor, only when true; a tampered gate in a stored snapshot is rejected), and an explicitEscrow.fromJSON(snapshot, { requireActor: false })overrides it. A legacy snapshot without the field restores with the gate off, so a restored escrow keeps enforcing attribution instead of silently dropping it. A bare history carries no gate, soEscrow.fromHistory(id, history, { requireActor: true })is still the way to re-attach it there. Honest limit: requiring an actor cannot verify who the actor really is — it only guarantees the audit trail names one (see SECURITY.md). - Settlement reference (opt-in):
new Escrow(id, { requireSettlementRef: true })makesdispatch("RELEASE")without asettlementRefthrowsettlement reference required: RELEASE must carry a non-empty settlementRef when requireSettlementRef is enabled. The gate runs after the transition-legality, RBAC, and deposit-cap checks (after therequireActorgate) and before anything is appended, so a rejected dispatch leaves no history residue and does not consume an idempotency key — a retry with a reference and the same key still executes. It only constrains RELEASE; other events are unaffected, and the default (gate off) keeps a reference-free RELEASE legal. Non-boolean values throwinvalid option: requireSettlementRef …at construction. LikerequireActor, the switch IS part oftoJSON()/fromJSON()snapshots (requireSettlementRef, only when true; a tampered gate in a stored snapshot is rejected), and an explicitEscrow.fromJSON(snapshot, { requireSettlementRef: false })overrides it. A legacy snapshot without the field restores with the gate off, so a restored escrow keeps enforcing the reference instead of silently dropping it. A bare history carries no gate, soEscrow.fromHistory(id, history, { requireSettlementRef: true })is still the way to re-attach it there. Honest limit: requiring a reference cannot verify the external settlement happened — it only guarantees the audit trail says which transfer it was (see SECURITY.md). - Refund reference (opt-in):
new Escrow(id, { requireRefundRef: true })makesdispatch("ARBITRATE_REFUND")without arefundRefthrowrefund reference required: ARBITRATE_REFUND must carry a non-empty refundRef when requireRefundRef is enabled. The gate runs after the transition-legality, RBAC, and deposit-cap checks (after therequireActorandrequireSettlementRefgates) and before anything is appended, so a rejected dispatch leaves no history residue and does not consume an idempotency key — a retry with a reference and the same key still executes. It only constrains ARBITRATE_REFUND; other events are unaffected, and the default (gate off) keeps a reference-free ARBITRATE_REFUND legal. Non-boolean values throwinvalid option: requireRefundRef …at construction. LikerequireSettlementRef, the switch IS part oftoJSON()/fromJSON()snapshots (requireRefundRef, only when true; a tampered gate in a stored snapshot is rejected), and an explicitEscrow.fromJSON(snapshot, { requireRefundRef: false })overrides it. A legacy snapshot without the field restores with the gate off, so a restored escrow keeps enforcing the reference instead of silently dropping it. A bare history carries no gate, soEscrow.fromHistory(id, history, { requireRefundRef: true })is still the way to re-attach it there. Honest limit: requiring a reference cannot verify the external refund happened — it only guarantees the audit trail says which transfer it was (see SECURITY.md). The CLI demo (npm run demo) walks both gates end to end on branch escrows: a reference-free RELEASE on arequireSettlementRef: trueescrow is refused with state and history untouched, the same dispatch carrying a settlement reference is accepted and recorded verbatim, a snapshot restore keeps refusing the reference-free RELEASE and then releases with the reference, and a default escrow (flag off) keeps the pre-gate behavior; the refund side mirrors all four shapes for ARBITRATE_REFUND underrequireRefundRef: true. The demo's references are fixed strings, not verified transfers — the gates only guarantee the audit trail names the external transfer or refund. - Optimistic concurrency (opt-in):
dispatchopts acceptexpectedSeq— the history length (the last entry'sseq;0for an empty history) the caller based its decision on. When set, the guard runs before every other dispatch check (option validation, the idempotency dedupe, transition legality, RBAC, amount/cap): a mismatch throwsdispatch conflict: expected seq <n> but escrow is at seq <m>and changes nothing — no state move, no history entry, no idempotency key consumed, no listener notified — so two writers racing off the same snapshot cannot both advance the escrow, and the loser can re-read and retry with the fresh seq. A non-integer or negative value throwsinvalid dispatch options: …. Honest limit: this is a single-process optimistic lock only; two processes that each restored the same snapshot can still race, and cross-process writers need compare-and-swap in the durable store itself. - Deadlines (advisory):
escrow.setDeadline(date)attaches a deadline (stored as canonical ISO-8601; unparseable input throws), andnew Escrow(id, { deadline })attaches the same deadline at construction (same validation, so a bad deadline fails the constructor) — which also letsEscrow.fromHistory(id, history, { deadline })carry a deadline into a history-only rebuild, where the bare log itself holds none; onfromJSON, an explicitopts.deadlineoverrides the snapshot's deadline, mirroring therolePolicyoverride rule, and omitting it restores the snapshot's deadline as before.getDeadline()/clearDeadline()read and remove it. The deadline is advisory: nothing auto-expires — a watchdog (or a human) readsisOverdue(escrow)and dispatchesEXPIREexplicitly, so expiry stays auditable in the append-only history.isOverdue()returns false with no deadline and for terminal states (a settled escrow is never "overdue"). It fails fast on bad input instead: a non-Escrowargument throwsinvalid isOverdue: escrow must be an Escrow, got …and an invalidnowthrowsinvalid now: expected a valid Date, so a watchdog never mistakes a malformed call for "not overdue".expiredEscrows(escrows)filters a batch down to the overdue non-terminal ones in one line — it never mutates or dispatches.expireOverdueEscrows(escrows)goes one step further and performs the explicitEXPIREdispatch per overdue escrow, returning per-escrow{ escrow, expired, error?, entry?, unexpirable? }outcomes — a successful outcome also carriesentry, a frozen detached copy of the appended EXPIRE audit entry, so an expiry operations report can cite it without re-readingescrow.history; failed outcomes leave it absent. The executor exists because of a real trap:DISPUTEDescrows have noEXPIREedge in the transition table, so a naive hand-written loop aborts the whole batch on the first such escrow — the executor instead classifies them{ expired: false, unexpirable: true }(no error, no dispatch attempted, escrow untouched) and keeps going. The two outcomes are distinct on purpose:errormeans the expiry was attempted and failed (a backdatednow, or arolePolicythat does not admitsystem);unexpirablemeans the escrow can never expire from its current state and belongs in arbitration, not in a retry queue.stuckEscrows(escrows)lists exactly that unexpirable subset of an overdue batch —stuckEscrowsplus the expirable overdue escrows partitionsexpiredEscrowswith no overlap and no gap. Failed escrows are left untouched. The executor pins the screeningnowas theatof everyEXPIREentry it appends (dispatch("EXPIRE", …, { actor: "system", at: now })), so a fixed screening instant produces identical audit entries across the batch and across replays — the wall clock never leaks in. Passopts.at({ at }, aDateor a canonical ISO-8601 string) to stamp the entries with a different known instant instead — screening atnow, auditing atat— for deterministic replay or backfilling history; a malformed pin throwsinvalid at: …fail-fast before any escrow is touched, and a dry run only validates it. Thesystemattribution also means the executor passes an escrow's opt-inrequireActorgate, and arolePolicythat listsEXPIREmust includesystemfor the watchdog to get through (otherwise the refusal reports"system" is not in [...], per escrow, batch continues). (Consequence:nowmust not predate an escrow's last history entry; a backdatednowlands as a per-escrow{expired: false, error}and the batch continues.) For a safe rehearsal before expiring a batch, pass{ dryRun: true }:expireOverdueEscrows(escrows, now, { dryRun: true })screens the same set in the same order but dispatches nothing — no state change, no history append, no subscription notification — and each result carrieswouldExpire(true exactly when the live run would have expired that escrow) and, when false, either the same-wordingerrorthe live run would have reported (backdatednow, or arolePolicythat does not admitsystem) orunexpirable: truewhen the escrow's state has noEXPIREedge — the live run classifies those the same way, with no error;expiredis false throughout andentryis never present. A dry run leaves no residue, so the same batch can immediately be expired for real. Illegal options throw fail-fast, and so does an invalidnow(not aDate, or an invalidDate): it throwsinvalid now: expected a valid Datebefore any escrow is screened, instead of screening nothing and failing later on a bareRangeError. The scheduler companion isnextEscrowDeadline(escrows, now?): it returns the non-terminal escrow whose deadline comes first, as{ escrow, deadline }(canonical ISO), orundefinedwhen none qualifies — terminal escrows are settled, overdue ones belong toexpiredEscrows, deadline-less ones have nothing to schedule, and a deadline exactly atnowis due, not upcoming; ties keep batch order. It is pure (no mutation, no dispatch): a caller arms one timer for the returned deadline and, when it fires, re-screens withexpiredEscrowsand expires viaexpireOverdueEscrows, so a deadline that moved or an escrow that settled in between cannot expire something that should no longer expire. The warn-before-it-is-too-late companion isescrowsApproachingDeadline(escrows, withinMs, now?): it returns the non-terminal escrows whose deadline falls inside the half-open window(now, now + withinMs]— a deadline exactly atnowis due, not upcoming, and belongs toexpiredEscrows, so the two helpers never double-report the same escrow, while a deadline exactly atnow + withinMsis included. It is pure (no mutation, no dispatch): a caller takes the returned list, nudges the parties, and when a deadline actually passes still expires viaexpireOverdueEscrows. An invalidwithinMs(negative, non-finite, non-number) or an invalidnowthrows fail-fast instead of silently returning an empty list. The plain listing companions areescrowsByState(escrows, state),escrowsByActor(escrows, actor),escrowsByEvent(escrows, event), andescrowsBySettlementRef(escrows, settlementRef): the first returns every escrow currently in the given state (terminal states included), the second every escrow whose audit history carries at least one entry by that actor (note-only, actor-less entries never match), the third every escrow whose audit history carries at least one entry for that event (a terminal escrow still answers whether it was ever disputed), and the fourth every escrow whose RELEASE entry carries that exact settlement reference (an escrow released without a ref never matches; one ref may settle several escrows). All four are pure, return the same escrow objects in input order, and fail fast on an unknown state, an empty/non-string actor, an unknown event, or an empty/non-string ref instead of silently returning an empty list. The four selectors above each filter on one axis.escrowsByFilters()combines them: give any subset ofstate,actor,event,settlementRef, andoverdue, and it returns the escrows matching every condition given, in input order, in a single pass over the batch — the patrol query "escrows alice touched that are currently DISPUTED after a dispute" without chaining filters and intersecting the results. ThesettlementRefaxis followsescrowsBySettlementRef's rule (only a RELEASE entry carrying that exact ref counts). Theoverdueaxis followsisOverdue's rule (past deadline, non-terminal, boundarynow >= deadlineinclusive);falseselects the complement, and omitting it leaves the deadline out of the match. Its screening instant is the optional third argumentnow(default: the real clock). Each condition uses its single-axis selector's rule and validation, an empty condition object returns every escrow, and a typo in any axis throws instead of returning [] — including a typo in a filter key itself: an unknown key such asstatesthrowsinvalid escrowsByFilters: unknown filter "states"instead of being silently ignored and returning the unfiltered batch, and a non-object filters argument throws a configuration error. (One honest limit: a DISPUTE always moves an escrow out of FUNDED, so "FUNDED and ever disputed" is empty by construction — the transition table has no edge back.) The deadline rides along intoJSON()/fromJSON()snapshots (a tampered or non-canonical deadline is rejected by snapshot validation). A distinct screening isstaleEscrows(escrows, maxAgeByState, now?): where the deadline helpers ask "past an absolute deadline", it asks "stuck in the current state too long" — dwell is measured from the last history entry'sat, against a per-state millisecond budget, and an escrow is stale only when dwell is strictly past its state's budget (terminal states never qualify, states with no budget are ignored, and an escrow with no history has no measurable dwell). A FUNDED escrow whose milestone nobody submits for 30 days is picked up here even when its deadline is months away. It is a pure filter; its executor companion isactOnStaleEscrows(escrows, action, maxAgeByState, now?, opts?), which runs a caller-supplied action for each stale escrow and returns per-escrow{ escrow, acted, error?, entry? }outcomes, isolating failures so one unactionable escrow never aborts the batch. The action receives a second argument,{ at }— the pinned audit timestamp for the run (opts.atwhen given, otherwise the screeningnow) — so a dispatch-style action can stamp its entries with the run's pinned instant (dispatch(…, { at: context.at })) instead of the wall clock; a notify-only action ignores it. Pass{ dryRun: true }to rehearse instead: the executor screens the same stale set, in the same order, but calls the action for none of them, returning{ escrow, acted: false, wouldAct: true }per selected escrow —wouldActanswers only "selected", never "would succeed", because an arbitrary caller-supplied action can still be illegal from the escrow's state. A successful outcome also carriesentry, a frozen detached copy of the audit entry the action appended, when the action appended one (a notify-only action leaves it absent; failed actions leave it absent too). There is deliberately no default action: expiry is the single obvious action for an overdue escrow, but a stale escrow's right disposition — notify the parties, escalate to arbitration, or expire it — is a state-dependent caller decision, so the action is a required argument. A distinct aging view issettlementAging(escrows, now?): it buckets every funded, non-terminal escrow by whole days since its most recentFUNDentry —under7Days/days7To30/over30Days, with exactly 7 days landing indays7To30and exactly 30 inover30Days— so finance ops can chase the stalest locked funds first (a top-up re-ages the escrow). Terminal escrows never appear; a non-terminal escrow with noFUNDentry (never funded) lands inunknownrather than being silently dropped. It mirrors the dataquest lifecycle'spayoutAgingand is pure. The released-side counterpart isunreconciledSettlements(escrows): it returns the RELEASED escrows whose RELEASE entry carries nosettlementRef— releases with no pointer to the real-world payment — so finance ops can chase the missing evidence instead of hand-scanning histories. An arbitration-released escrow is unreconciled too (itsARBITRATE_RELEASEentry carries no ref by construction); REFUNDED, EXPIRED, and in-progress escrows never appear. It mirrors the dataquest lifecycle'sunreconciledPayoutsand is pure. - Dispatch subscriptions (in-process fan-out seam):
escrow.subscribe(listener)registers a listener called with(event, from, to, entry)after every successful dispatch, in subscription order; the returned function unsubscribes (idempotent). Listeners run after the audit entry is appended and can never roll it back — a throwing listener is isolated (its error is swallowed, remaining listeners still run, dispatch returns normally); pass{ onError }to observe those failures. The entry handed to listeners is a frozen, detached copy, so listeners cannot rewrite the audit trail. Failed dispatches and idempotency-key no-ops produce zero notifications. Subscriptions are in-memory only: they are NOT part oftoJSON()/fromJSON()snapshots, and there is no durable fan-out (queues, webhooks, retries) — that stays the caller's infrastructure. - Persistence-ready snapshots:
escrow.toJSON()exports a plain-JSON{ v, id, state, history }snapshot (a detached deep copy;JSON.stringify(escrow)goes through it), andEscrow.fromJSON(snapshot)rebuilds a working escrow — the input is strictly validated as if untrusted (seq restarts at 1 with no gaps, from→to chain continuous fromCREATED, every edge a legal transition, canonical ISO-8601 non-decreasing timestamps,amountfinite and non-negative on FUND and PARTIAL_RELEASE entries only); malformed snapshots throw a descriptiveinvalid snapshot: …error instead of yielding a corrupt escrow. Unknown fields are rejected fail-closed at both levels — top level allows onlyv/id/state/history/deadline/idempotencyKeys/rolePolicy/maxDeposit/maxVisitsByState/requireVerifyEvidence/requireActor/requireSettlementRef/requireRefundRefand an entry onlyseq/event/from/to/at/actor/note/amount/evidence/settlementRef/refundRef/prevHash/hash— so a typo likedeadllineoramoutthrowsinvalid snapshot: unknown field "…"instead of silently losing a deadline or a FUND amount. AsettlementRefis only legal on RELEASE entries (and, likeevidence, must be a non-empty string no longer thanMAX_SETTLEMENT_REF_LENGTH— 256 characters). Snapshots carry a schema version (v: 1): a missingvis a legacy pre-versioning snapshot and is still accepted, while any othervvalue throwsunsupported snapshot version(checked before the history/hash-chain validation), so a future format change stays distinguishable from corruption. The consumed idempotency-key set is part of the snapshot (idempotencyKeys, only when non-empty; entries must be non-empty strings and duplicates are deduped on restore) —vstays 1 because the field is optional and additive: snapshots without it load exactly as before, but a snapshot carrying it is rejected as an unknown field by older parsers that predate it (an old binary must not silently drop replay protection). The deposit cap (maxDeposit, only when set), the verify-evidence gate (requireVerifyEvidence, only when true), the audit-attribution gate (requireActor, only when true), the settlement-reference gate (requireSettlementRef, only when true), and the refund-reference gate (requireRefundRef, only when true) are likewise part of the snapshot — a restored escrow keeps enforcing all five, a legacy snapshot without them restores uncapped with the gates off, and an explicitfromJSONopt overrides any of them entirely; a tampered cap or gate in a stored snapshot is rejected. The per-state visit budget (maxVisitsByState, only when non-empty) is likewise part of the snapshot — the budget is restored, the used count is derived from the restored history, and an explicitfromJSONopt overrides the budget entirely; a tampered budget in a stored snapshot is rejected. The audit key is never in a snapshot. Signed snapshots close the remaining gap: the hash chain covers history entries only, so the snapshot-level fields (state,deadline,rolePolicy,idempotencyKeys,maxDeposit,maxVisitsByState,requireVerifyEvidence,requireActor,requireSettlementRef,requireRefundRef) sit outside it — a rewritten persisted file could push a deadline back, loosen a policy, clear consumed keys, lift a cap, or widen a visit budget without breaking any history link.escrow.exportSignedSnapshot(secret)wraps the snapshot in{ v: 1, snapshot, mac }(HMAC-SHA256 over the canonical JSON of the whole snapshot, same envelope shape as theSettlementEventDedupesigned snapshot), andEscrow.restoreSignedSnapshot(envelope, secret, opts?)(aliasfromSignedSnapshot) verifies the MAC in constant time before any snapshot parsing — a tampered field, a wrong secret, or a smuggled extra field fails closed with no escrow produced, and a MAC-valid envelope whose snapshot is itself malformed still fails strict snapshot validation.opts.auditKeyis handed through tofromJSON, so a keyed history chain still needs its own key on restore; the envelope secret need not equal the audit key. The secret is never written into the envelope, the MAC is integrity protection only (not encryption), and the unsigned path is unchanged — the two forms never accept each other, so a signed restore cannot silently downgrade to trusted configuration. An envelope can also carry an optional expiry:exportSignedSnapshot(secret, { expiresAt })or{ maxAgeMs, now? }writes a canonical ISO-8601 UTCexpiresAtinto the envelope, covered by the MAC, so a stolen envelope cannot resurrect the escrow's state after its expiry;restoreSignedSnapshotrejects an expired envelope (now > expiresAt— restoring at exactlyexpiresAtstill succeeds) after the MAC check and before any snapshot parsing, withopts.nowinjecting the clock for deterministic tests. An envelope withoutexpiresAtnever expires, exactly as before. Unknown export option keys fail closed: a typo'dexpirythrowsEscrow: exportSignedSnapshot: unknown option "expiry"instead of silently producing a never-expiring envelope. Snapshot diffing:diffEscrowSnapshots(before, after)reports only what changed (stateChanged/deadlineChanged/historyAppended/rolePolicyChanged/depositCapChanged/evidenceGateChanged/actorGateChanged/settlementRefGateChanged/refundRefGateChanged/idempotencyKeysChanged— the consumed-key set, compared as a set, so a key consumed or dropped between two stored snapshots shows up instead of silently vanishing); a later history that is not an append-only extension of the earlier one throws instead of reporting progress. Both inputs are shape-checked first (invalid snapshot diff: …): an unknown state, a malformedrolePolicy/idempotencyKeys, or a missing field fails here rather than diffing as a phantom move or a bareTypeError— the diff is a comparison, not a validation, so transition legality and the hash chain are still the parser's job. A snapshot is an export, not a datastore — there is still no built-in storage or locking. - History-only restore (event sourcing):
Escrow.fromHistory(id, history)rebuilds a working escrow from a bare audit history — the history is the only source of truth and the state is derived from its last entry (an empty history rebuilds a freshCREATEDescrow), so a holder of a bare log (e.g. the receiving end of the NDJSON transport below) no longer has to hand-wrap entries in a snapshot envelope with a state field it derived itself. Validation is the exactparseEscrowHistorycode path (seq/chain/edge/timestamp rules, hash chain re-verified withauditKeywhen keyed); legacy hashless histories are chained on rehydration exactly as infromJSON, and a rebuilt escrow keeps dispatching with no seq gap. Options re-attach as infromJSON(snapshot, opts)(requireVerifyEvidence/maxDeposit/requireActor/requireSettlementRef/requireRefundRef/auditKey/rolePolicy/idempotencyKeys) — with one honest difference: a snapshot carries itsrolePolicy,maxDeposit,requireVerifyEvidence,requireActor,requireSettlementRef, andrequireRefundRef, so there the option overrides stored state, while a bare history carries none of them, so here the option is the only source. What a bare history cannot restore at all: the deadline and subscriptions live only in the envelope / in memory, so afromHistoryrebuild starts with no deadline and zero listeners — usefromJSONwhen those must survive a restart. The consumed idempotency-key set is re-attached the same way as the other options: passidempotencyKeys(the log itself carries none, so the caller supplies them); omit it and the rebuild still starts with an empty key set, so a key consumed before the log was taken would re-execute. Time travel over the same log needs no rebuild at all:escrow.stateAt(time)(or the module-levelstateAtFromHistory(log, time, auditKey?)for a bare log) returns the state the escrow was in at a moment — thetoof the last entry at or before it (inclusive boundary, a time before the first entry returnsCREATED); a keyed chain needs itsauditKey, and a broken chain throws instead of returning a guessed state. - NDJSON audit-log streaming:
historyToNdjson(history | escrow)/historyFromNdjson(text)(src/ndjson.ts) export and import only the audit log — one canonical JSON entry per line, line order =seqorder, trailing newline, empty history exports to"". Use a snapshot when you need state + configuration restored; use NDJSON when the log itself should stream to disk or a log pipeline. Import is as strict as the snapshot parser (it runs throughparseEscrowHistory, the same code path): seq from 1 with no gaps, from/to chain continuous, the hash chain re-verified — a tampered, deleted, or reordered line throws, a non-JSON line throws naming its 1-based line number, and empty/whitespace-only input throws (a missing log is not a log of zero events). CRLF input is accepted. Keyed (HMAC) histories need the sameauditKeyon import, and the key never appears in the text. Imported entries feedEscrow.fromHistory(id, entries)directly when a working escrow — not just the log — is what the receiving end needs.
-
Is this a smart contract? No. This is pure TypeScript with zero runtime dependencies, running on Node.js ≥ 20. It reproduces the off-chain transition rules from the ALLWEB3 portfolio case study. There is no Solidity, no EVM bytecode, and no on-chain state here.
-
Where does the fee formula come from? From the case study's "Deterministic Fee Calculator & Escrow Preview":
deposit = creatorPool + baseFee × complexityMultiplier − loyaltyDiscount + oracleFee. The golden vector (10,000 / 600 / 1.0 / −30 / +60 → 10,630) is asserted bytest/economics.test.ts. It is the case study's formula, not a general pricing engine. -
The case study anchors settlement in Chainlink + zk-SNARK + TEE verification. Where is that here? It isn't — deliberately. "Verification" here is the
VERIFY_PASSevent: dispatching it is a caller trust decision. This repo does not verify oracle signatures, zero-knowledge proofs, or TEE attestations. A production build would have to gateVERIFY_PASSon those.What is supported is an auditable opt-in:
new Escrow(id, { requireVerifyEvidence: true })makesdispatch("VERIFY_PASS")require a non-emptyevidencereference (Chainlink request ID, zk proof commitment, TEE quote hash — passed viaDispatchOptions.evidence) and records it verbatim on the audit entry, survivingtoJSON()/fromJSON()round-trips. Evidence references are capped atMAX_EVIDENCE_LENGTH(32,768 characters, exported from the package entry):dispatch()and the snapshot/history parsers reject longer references outright, never truncating them. It turns "someone said pass" into "someone said pass, citing X" — the reference is auditable but still not verified by the library. The flag IS part of the snapshot (requireVerifyEvidence, written only when true): a restored escrow keeps enforcing the gate, a legacy snapshot without the field restores with the gate off, and an explicitEscrow.fromJSON(snapshot, { requireVerifyEvidence: false })overrides it. The CLI demo (npm run demo) walks the gate end to end on branch escrows: an evidence-freeVERIFY_PASSis refused with state and history untouched, the same dispatch carrying an evidence reference is accepted and recorded verbatim, and a default escrow (flag off) keeps the pre-gate behavior. The demo's evidence reference is a fixed string, not a verified oracle response — the gate is a caller-side hook shape, not a claim that any real oracle or proof was checked. -
What about the 5/9 multi-sig DAO arbitration? Partially modeled:
DISPUTE→ARBITRATE_RELEASE/ARBITRATE_REFUND/ARBITRATE_SPLITare the arbitration outcomes, andsrc/quorum.tsmodels the counting rule of an M-of-N quorum (createQuorum({ threshold, signers }), idempotentapprove(),revoke()before the threshold is reached,hasQuorum()— see the usage example in its JSDoc). Per-signer Ed25519 signature verification is opt-in (see below); that is verification of individual votes, not a threshold signature scheme or an on-chain multi-sig contract.approvalLog()records who approved and when (timestamps injectable viaQuorumConfig.nowfor deterministic tests). The arbitration audit entry itself also carries the counted signer list (quorum 5/9 [dao-1, dao-2, dao-3, dao-4, dao-5]), so the history alone proves who approved even after theQuorumobject is dropped. Asplitoutcome divides the still-locked balance between creator and sponsor (splitCents, whole cents, summing exactly to the locked balance — fee on the creator leg persettleArbitrationSplit(float dollars) or its exact-cents twinsettleArbitrationSplitCents) and lands inRELEASED;buildSettlementReportreports it with outcomesplit, reusing thesettleArbitrationSplitCentsmath (fee on the creator leg only, sponsor leg refunded in full) and readingsplitCentsfrom theARBITRATE_SPLITaudit entry — a missing or mismatchedsplitCentsstill refuses fail-closed, so a split escrow is never restated as a full release. The division itself is caller-asserted, not quorum-endorsed: the quorum endorses only the outcome"split"— a split-scoped quorum dispatches a 99/1 split as readily as 70/30 — and the report's sum check is an arithmetic guardrail, not approval of the division (see SECURITY.md).approve()also accepts an optionalevidencereference — a vote-record link, governance proposal id, or attestation reference — carried on the log entry and the snapshot. Evidence is a caller assertion, exactly likeVERIFY_PASSevidence: the quorum records it verbatim, never verifies that it is real, and counting is identical with or without it. Evidence is capped at 32,768 characters (the sameMAX_EVIDENCE_LENGTHceiling as escrow history evidence), enforced atapprove(),approveSigned(), and snapshot restore — oversized evidence is rejected, never truncated. Signer ids are capped at 256 characters (MAX_ACTOR_LENGTH): they are written verbatim into the approval log and snapshots, so they are audit data, unlikeRolePolicynames, which are uncapped configuration. Opt-in signature verification is available: register Ed25519 public keys inQuorumConfig.signerPublicKeysand collect votes withapproveSigned(signerId, signature)— each vote is verified against the canonical statementescrow-quorum:approve:<signerId>(exact bytes; see the exportedapprovalStatement()helper), orescrow-quorum:approve:<signerId>:<statementContext>when the quorum is configured withstatementContext— a signature minted for one arbitration then cannot be replayed into another quorum configured with a different context, or with no context at all — and the log entry is markedverified: true. By defaultdispatchArbitrationcounts verified and unverified approvals identically — a plain claim releases the escrow once the threshold is reached. PassrequireVerifiedApprovals: truein the arbitration options to gate on signature-verified votes only: the threshold is re-counted fromverifiedApprovalCount()/verifiedApprovals()(same expiry semantics ashasQuorum()), a short verified count throwsarbitration requires quorum: <verified>/<threshold> verified approvalsand leaves the escrow untouched, and the audit note records the verified count and verified signers only.hasQuorum()/approvalCount()/approvals()keep reporting the full count — the option changes only what the gate requires. Averifiedflag is signature authenticity, not arbitration fairness: it proves the signer held the key, not that the outcome is just; and a quorum restored from an unsigned snapshot reads 0 verified votes until its signers re-earn the flag with a freshapproveSigned(). A quorum can also be bound to one escrow — and, when pinned, one arbitration outcome — withQuorumConfig.statementScope: { escrowId, outcome? }(outcomeis"release","refund", or"arbitration"): the scope is minted into every signed statement, so a vote for escrow A cannot verify in a quorum scoped to escrow B, or for the other outcome, anddispatchArbitrationrefuses a quorum scoped to a different escrow or outcome before it checks the count. Without a scope the statement carries no escrow or outcome segment, exactly as a context-less statement carries no context.approveSigned()also accepts an optional single-usenonce, minted into the statement and consumed only when the signature verifies, so a captured (nonce, signature) pair cannot be re-submitted. Revoking a signature-verified approval tombstones the SHA-256 digest of its signature, so replaying that exact signature after the revoke is refused — Ed25519 signatures are deterministic, so re-signing the same statement mints identical bytes and is not a way back in; a fresh nonce is. Tombstones and consumed nonces are instance state, never written into the log or a snapshot. A failed verification throws and records nothing; a signer with no registered key cannot useapproveSigned()at all, and non-Ed25519 or private keys are rejected at construction. Verified and unverified approvals count identically toward the threshold — the flag only records how the vote was proven. Two honest limits: without a configuredstatementContextorstatementScopethe statement binds the signer id only, not an escrow or outcome, so use one quorum per arbitration (thedispatchArbitrationpattern) unless one of them is set — with either set, the same signer keys can vote in several arbitrations and the statement itself carries the binding. The recommendation is to give every escrow its own uniquestatementContext(the escrow id is the natural value): without one, a single captured signature verifies in any quorum that registers the same signer key and can count toward, and dispatch, two different escrows — pinned intest/quorumNoContextCrossEscrowReuse.test.ts, which records the default-configuration reuse as-is and the binding once distinct contexts are set; and an unsignedrestoreQuorum()drops the recordedverifiedflags — the snapshot carries no signature to re-verify, so every restored approval is an unverified claim until a freshapproveSigned()re-earns the flag (the HMAC-signed envelope restore is the one exception: its MAC authenticates the snapshot, so the flags it carries survive). (statementContextandstatementScopeare configuration, not snapshot data: a restored quorum verifies new signatures under the restoring config's context and scope.) An optionalmaxApprovalAgeMsgives approvals a shelf life: past the window (boundary inclusive) they stop counting toward the threshold —hasQuorum()can fall back to false — but they stay inapprovalLog(), and re-approving records a fresh timestamp; revoking an expired approval is allowed and removes its entries. The injected clock must return a finite number of milliseconds since the epoch: aNaN,Infinity, or non-number reading fails closed withquorum: now must return a finite number of milliseconds since the epoch, got …— atapprove()/approveSigned()before anything is recorded, and at the counting reads (hasQuorum()/approvalCount()/approvals()/remainingApprovals()) instead of silently reporting the approvals as expired — so a bad clock can never silently lock the quorum at zero votes, and the audit log can never be poisoned with an unprintable timestamp (the same fail-closed contract asSettlementEventDedupe.resolveNow). A caller that needs to show how many votes are still missing readsremainingApprovals()—Math.max(0, threshold - approvalCount())from the same counted set, so expired approvals are excluded automatically and it reads 0 exactly whenhasQuorum()is true; it is a pure read and needs no new snapshot field, sosnapshot()/restoreQuorum()preserve it.src/arbitration.tswires the two together:dispatchArbitration(escrow, quorum, outcome)refuses to dispatch untilhasQuorum()is true and auto-recordsquorum <approvals>/<threshold> [signer, …]in the audit note — the counted signers, in approval-time order, deduplicated, with expired approvals excluded — so the history alone proves who approved, not just how many; a null or foreign escrow/quorum is refused first with a namedinvalid dispatchArbitration: …error (after the outcome check, before the quorum gate) instead of dying as a bareTypeError, and the escrow is left untouched. An optional final argument forwards retry-safety metadata to the arbitration entry — an injectable audit timestamp / actor (the sameat/actorthe plain dispatch accepts) plus anidempotencyKey(a repeated, e.g. timed-out, arbitration call with the same key is a pure no-op instead of aninvalid transitionfailure; the key is consumed only by a successful dispatch — a below-threshold rejection never "uses it up", so the caller can gather approvals and retry) and anexpectedSeqoptimistic-concurrency guard (a stale seq raisesdispatch conflictloudly instead of no-op'ing through the dedupe) — plusrequireVerifiedApprovalsto gate on signature-verified votes only (see the quorum FAQ entry above; the flag is consumed by the gate and never forwarded to the dispatch). A quorum's collected approvals can survive a process restart:quorum.snapshot()exports the full approval log plus the configuration it was collected under as plain JSON, andrestoreQuorum(config, snapshot)restores it under strict validation (unknown signers, duplicate entries, bad timestamps, illegal evidence, and config mismatches are rejected; expiry keeps aging from the original timestamps, never refreshed by the restore). UnknownQuorumConfigkeys fail closed too:createQuorum/restoreQuorumreject them (quorum: unknown option "<key>") before any field is read, so a typo'dmaxApprovalAgecannot silently disable the expiry window and a typo'dthreshholdcannot silently leave the threshold at 1;restoreSignedQuorumSnapshotlikewise rejects unknown restore options (onlynowis legal). When the snapshot crosses an untrusted boundary, wrap it instead in the HMAC-signed envelope:exportSignedQuorumSnapshot(quorum, secret)returns{ v: 1, snapshot, mac }(same envelope shape as the escrow signed snapshot), andrestoreSignedQuorumSnapshot(config, envelope, secret, opts?)verifies the MAC in constant time before any snapshot parsing — a tampered approval (including a flippedverifiedflag), a wrong secret, or a smuggled extra field fails closed with no quorum produced, and a MAC-valid envelope whose snapshot is itself malformed still fails strict snapshot validation. The envelope can also carry an optional expiry ({ expiresAt }or{ maxAgeMs, now? }, covered by the MAC; restoring at exactlyexpiresAtstill succeeds), and unknown export option keys fail closed: a typo'dexpirythrowsQuorum: exportSignedQuorumSnapshot: unknown option "expiry"instead of silently producing a never-expiring envelope. The secret is never written into the envelope — the MAC is integrity protection only, not encryption. The snapshot is an export format, not a built-in store, and restored approvals are still caller-persisted data: an unsignedrestoreQuorum()drops the recordedverifiedflags — the snapshot carries no signature to re-verify, so every restored approval is an unverified claim until a freshapproveSigned()re-earns the flag; only the HMAC-signed envelope restore keeps them, because its MAC authenticates the snapshot. Two stored snapshots can be compared without hand-written field compares:diffQuorumSnapshots(a, b)reports only what moved —thresholdChanged/signersChanged(compared as a set, so a pure reorder is not a change) /maxApprovalAgeMsChanged(each withfrom/to), the approval set asapprovalsAdded/approvalsRemoved/approvalsModified, and an always-presentapprovalsChangedmaster switch (identical snapshots diff to{ approvalsChanged: false }). An approval's identity is its signer id plus its timestamp, so an expired signer's re-approval is exactly one added entry (the old entry stays in the trail) and a lateverifiedflag —approveSigned()upgrading a still-counted approval in place — is exactly one modified entry, never an add-plus-remove pair. Both inputs pass the same strict shape validationrestoreQuorumapplies (minus the config match, since the two snapshots may come from different configurations), so a malformed snapshot throws instead of being silently compared; the diff is pure and returns detached copies. There is still no key management and no DAO governance in this repo — recording approvals is a caller trust decision for plainapprove()votes, exactly likeVERIFY_PASS, whileapproveSigned()votes carry a verified Ed25519 signature over the canonical statement. Production would need the approvals wired to real key management. -
How precise is the money math? All amounts are rounded to cents (
round2). Newdispatch("FUND", …)amounts are normalized to cents at entry — no new dispatch can produce a sub-cent amount in the audit trail (legacy snapshots with sub-cent amounts are still accepted by the parsers, not re-normalized). Callers that already keep money as integer cents can skip float dollars entirely withcalculateDepositCents(the recommended path): it takes and returns whole cents (creatorPoolCents/baseFeeCents/loyaltyDiscountCents/oracleFeeCents, thecomplexityMultiplierunchanged), applies the multiplier once and rounds a single time, half-up, to the nearest cent — so it agrees withcalculateDepositto the cent on the same inputs, with no0.1 + 0.2dust to mop up. The product and the sum are computed in exactBigInt(the multiplier is read as the rational named by its shortest decimal string, so100¢ × 1.005is exactly 101¢), and money inputs must be safe integers: a value pastNumber.MAX_SAFE_INTEGERfails at the input gate, and an exact result past the ceiling throws instead of returning a rounded-off amount. The golden vector is 1,063,000 cents. Non-integer, negative, non-safe-integer, or non-finite cent inputs fail fast, as do a non-positive multiplier, a negative deposit, and an overflowing computation (same error messages as the dollar version). Integer cents can be rendered exactly for statements and reconciliation text withformatMinorUnits(1,063,000cents →"10630.00": exactly two decimals, no thousands separator, no currency symbol, negative amounts keep a leading minus,-0formats as"0.00"), and parsed back with the strictparseMinorUnits(optional minus, at most 2 decimal places, no separators or scientific notation;BigIntarithmetic, so values pastNumber.MAX_SAFE_INTEGERthrow instead of rounding, andparseMinorUnits(formatMinorUnits(n)) === nround-trips, including negatives). Both fail loudly outside the safe range:formatMinorUnitsthrows on a non-safe integer instead of printing float dust, andparseMinorUnitsrejects an input carrying more than 19 digits before any parsing work, with a short fixed message; the other rejection messages quote at most the first 32 characters of the input, so an error can never embed an unbounded caller-supplied string. Both mirror the dataquest sibling's helpers. The settlement path has the same integer-cents form:settleReleaseCents/settlePartialReleaseCents/settlePartialReleasesCents/settleRefundCentstake and return whole cents (grossCents/releasedCents/depositCents, theproFeeBpsunchanged), round the fee a single time, half-up, in exact integer arithmetic (BigInt, so even aNumber.MAX_SAFE_INTEGERgross stays exact) — and agree with the dollar helpers to the cent on the same inputs, except where the float version's dust flips a half-cent: gross 1.15 at 5000 bps fees 0.57 insettleReleasebut 58 cents exactly here, which is why the cents form is the recommended path for new callers. The dollar helpers stay unchanged for existing callers. The batch helper's cumulative guard compares againstgrossCents - cumulativeinstead of adding first, so a batch near the safe-integer ceiling cannot over-pay by float addition rounding either. Finite-but-huge fee inputs that would overflow the deposit computation toInfinityare rejected:calculateDepositthrowsdeposit computation overflowed: inputs too largeinstead of returning{ deposit: Infinity }, which would poison every downstream settlement ledger. The release path has the same guard:settleReleasethrowssettlement computation overflowed: inputs too largewhen the fee or the net overflows (a 0 bps fee on a 1e308 gross would otherwise return{ net: Infinity }, since the negative check never fires onInfinity). The partial-release paths share that error:settlePartialReleasethrows it when the delegated release overflows or when the remaining balance itself overflows (round2(gross - released)on a 1e308 gross with a smaller release), andsettlePartialReleasesthrows it when its cumulative total or its per-tranche still-locked balance overflows the cent rounding — a batch that would over-pay on finite inputs still takes the separate cumulative route instead. The integer-cents helpers never reach that error: they take only safe integers, so a 1e308-scale split is rejected at the input gate, and atNumber.MAX_SAFE_INTEGERthe split settles exactly and stays balanced. Unknown keys in fee or settlement inputs are rejected (<fn>: unknown field "<name>") instead of being silently ignored, so a typo'd field can never quietly drop out of the math;buildSettlementReportapplies the same rule to its own inputs, thedepositbreakdown, and the nestedsettlement/partialReleaseobjects. Invariant tests assert fund conservation within ±1 cent. This is not big-decimal arithmetic and has not been audited. -
Can I use this in production? No.
Escrowis in-memory with no built-in store (snapshots are a JSON export viatoJSON()/Escrow.fromJSON(), not a database), no concurrency control beyond the single-processexpectedSeqoptimistic guard ondispatch(cross-process writers still need store-level compare-and-swap), idempotency keys that persist only inside each escrow's own snapshot (no shared/distributed store),EXPIREis dispatched by the caller — there is an advisory deadline field plusisOverdue()/expiredEscrows()watchdog helpers and anexpireOverdueEscrows()batch executor (which skips escrows with no legalEXPIREedge instead of aborting the batch), but no background timer or auto-expiry — and there is no identity authentication: the opt-inrolePolicyRBAC is only a caller-supplied actor allowlist (the caller asserts the actor string; nothing verifies who they are). Reference and demo use only.
- Off-chain reproduction only. The case study anchors settlement in smart contracts (Chainlink + zk-SNARK + TEE verification, 5/9 Safe multi-sig arbitration). None of that is implemented here — this models the rules, not the chain.
- Simplified roles. This repo now has opt-in event-level RBAC
(
rolePolicy: a caller-supplied actor allowlist, persisted in snapshots) and an opt-inrequireActorgate (every dispatch must name an actor; configuration only, never persisted), but real deployments still need identity authentication on top of it (the library cannot verify who an actor really is), a real deadline scheduler (this repo has an advisory deadline field withisOverdue()/expiredEscrows()watchdog helpers plus anexpireOverdueEscrows()batch executor and anextEscrowDeadline()scheduler helper that names the next due escrow, but no background timer or auto-expire), and a shared/distributed idempotency store (this repo's consumed keys persist only inside each escrow's own snapshot); theEscrowclass is in-memory. - No durable queue.
deliverSettlementWebhookkeeps no memory of failed deliveries, and theSettlementWebhookOutboxfailure ledger is in-process only: a process that dies loses it unless it exported a snapshot first. The outbox itself never retries, but the opt-inretrySettlementWebhookOutboxrunner re-delivers the pending pairs in-process (bounded rounds, exponential backoff, dead letters never retried) — it is still process-local and persists nothing, so a deployment that needs retries across restarts or processes must build them over shared storage (a database outbox table, a queue, …) instead. - Fee formula is the case study's, not a general pricing engine: arbitrary fee schedules are out of scope.
- Trust boundaries. What the library enforces (money input validation,
fail-closed constant-time webhook verification, strict snapshot validation,
opt-in Ed25519 quorum signature verification) versus what stays the
caller's responsibility (plain
approve()quorum votes have no signature verification, webhook secret distribution, cents-rounding money math) is documented in SECURITY.md — every statement there is verifiable against the source.
Settled escrows can be pushed to accounting/bookkeeping systems as signed webhook notifications:
import {
buildSettlementReport,
buildSettlementWebhook,
verifySettlementWebhook,
} from "escrow-state-machine-ts";
const report = buildSettlementReport({ /* escrowId, history, finalState, deposit, settlement */ });
const { payload, signature } = buildSettlementWebhook(report, { secret: process.env.WEBHOOK_SECRET! });
// POST payload as JSON with header `X-Signature: signature` (shape: `sha256=<hex>`).
// On the receiving end, verify over the raw body bytes:
const ok = verifySettlementWebhook(rawBody, receivedSignature, secret);payload is { event: "escrow.settled", eventId, escrowId, outcome, releasePath?, deposit, parties, at },
derived entirely from the audit-backed settlement report. The comparison is
constant-time (timingSafeEqual); malformed signatures fail closed as
false, never throw.
Ed25519 public-key signing (opt-in). When receivers verify against a published public key instead of a shared secret, pass a signing key instead of a secret — the two paths are mutually exclusive:
import { generateKeyPairSync } from "node:crypto";
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
const { payload, signature, keyId } = buildSettlementWebhook(report, {
signingKey: { keyId: "ed-key-2026-12", privateKey },
});
// signature is `ed25519=<base64>` (raw 64-byte signature, base64-encoded);
// delivery sends the keyId as the `X-Key-Id` header.
const ok = verifySettlementWebhook(rawBody, signature, { publicKey });
// or resolve per keyId: verifySettlementWebhook(rawBody, signature,
// { keyResolver: (id) => keys.get(id), keyId: receivedKeyId });The signature covers exactly the same canonical body bytes as the HMAC
path, so a receiver can verify either scheme over the same payload. An
unknown keyId fails closed as false, never throws; a sha256=
signature verified with only a public key (or an ed25519= signature
with only a secret) fails closed the same way. verifySettlementWebhookStrict
accepts the same publicKey / keyResolver / keyId options.
Dual credentials for an HMAC → Ed25519 migration (opt-in). While
senders migrate from the shared secret to Ed25519 signing, pass the
rotation list together with one Ed25519 shape — { secrets, publicKey }
or { secrets, keyResolver, keyId } — to accept either scheme in a
single call:
// The sender still signs one way or the other per notification;
// the receiver accepts both while the migration runs.
const ok = verifySettlementWebhook(rawBody, signature, {
secrets: [newSecret, oldSecret],
publicKey,
});The signature's scheme prefix selects the one path attempted, so a
sha256= signature is tried only against the HMAC candidates and an
ed25519= signature only against the Ed25519 key — the other credential
can never rescue a wrong-scheme signature — and the freshness /
eventId gates still run once, after whichever path matched. A dual
call is two alternative credentials for one signature, not two
signatures that must both pass, and never a double signature. The
single-secret overload (a bare string/Buffer third argument) does not
compose with an Ed25519 shape; the migration shape is always the
rotation list. verifySettlementWebhookStrict passes dual credentials
through unchanged, with its three gates on by default. Key
distribution is the caller's responsibility: the sender keeps the private
key and publishes the public key (or its keyId → public-key mapping)
out of band — a public key is not a secret, but a receiver that resolves
keys from an untrusted directory can be pointed at an attacker's key, so
the mapping itself must come from a source the receiver trusts. The
batch build (buildSettlementWebhooks) and fan-out delivery
(deliverSettlementWebhookToMany, per-endpoint signingKey) accept the
same opt-in; an endpoint with neither credential fails as its own
per-endpoint result, never blocking the others.
releasePath is present only on released payloads: it is the report's
release path copied verbatim (e.g. "VERIFY_PASS → RELEASE" for the normal
path, "DISPUTE → ARBITRATE_RELEASE" for an arbitration release), so a
receiver can route arbitration settlements to manual review without
re-querying the settlement report. refunded/expired payloads omit the
key entirely. It sits between outcome and deposit in the canonical key
order and is covered by the signature — tampering with or stripping it
fails verification.
currency is present only when the report was built with one: it is the
report's currency copied verbatim (e.g. "USD"), sits after deposit
in the canonical key order, and is covered by the signature — changing
it or stripping it fails verification. Reports built without a currency
keep the legacy payload shape exactly. The code is a label only: no
conversion is performed anywhere. The CSV export carries it too:
renderReportCsv writes the code into a currency column on every row
(empty when the report was built without one), so a multi-currency
bookkeeping import can tell USD rows from EUR rows, and
parseSettlementReportCsv reads it back.
eventId is the receiver's idempotency key: for a report built by
buildSettlementReport from a hash-chained history, the default is derived
deterministically from the report's settlement-evidence anchor
(settlement-<escrowId>-<terminalSeq>-<first 12 hex of terminalHash>), so
rebuilding the same settlement re-issues the same eventId and a receiver
deduplicating on it drops the rebuild instead of booking the settlement
twice; a report without an anchor (hand-built, or built from a legacy
hashless history) still gets a fresh UUID v4. Inject your own via
BuildWebhookOptions.eventId to override either default (for deterministic
tests, or a short id when the derived one would exceed the length cap),
and the signature covers it, so tampering with it fails verification.
Retries of the same notification reuse the original eventId; two
independent settlements never share one. An eventId longer than
MAX_EVENT_ID_LENGTH (256 characters) is rejected wherever it can enter
the system — the build, SettlementEventDedupe.checkAndRecord, and
SettlementWebhookOutbox.recordAttempt, plus both snapshot restores —
never truncated, since truncation would change the deduplication key.
The default UUID is 36 characters, so the cap leaves orders of magnitude
of headroom; a caller that needs a longer reference should store it
out-of-band and deduplicate on a short id. Store seen eventIds on the
receiving end and drop duplicates — that is how you tell "retry re-send"
apart from "second settlement":
import { SettlementEventDedupe } from "escrow-state-machine-ts";
const dedupe = new SettlementEventDedupe({ ttlMs: 24 * 60 * 60_000 }); // defaults: 1h TTL, 10_000 entries
// in the webhook handler, after verifySettlementWebhook(rawBody, sig, secret):
if (dedupe.checkAndRecord(payload.eventId)) {
return { status: 200, note: "duplicate delivery" };
}
// ... process the settlement exactly onceFor a whole batch, buildSettlementWebhooks(buildSettlementReports(inputs), { secret }) pipes the batch report results straight into signed webhooks — one { escrowId, webhook } per settled escrow, an { escrowId, error } per failed entry (forwarded untouched, never blocking later entries), a shared secret and now, and a distinct eventId per settlement via eventIdFactory (default crypto.randomUUID()), so receivers deduplicating on eventId never drop a settlement as an apparent duplicate. A factory bug that repeats an eventId is caught in the batch itself: the later report fails as { escrowId, error } with a duplicate eventId message, is never signed, and does not block later reports — only successfully signed ids are recorded, so a report whose build fails never claims its id. A repeated escrowId in the batch is the one exception to per-entry isolation, mirroring buildSettlementReports: it aborts the whole batch with an error naming the duplicate id(s) and produces no webhooks, since two signed webhooks with different eventIds for one settlement would look like two different settlements to a receiver deduplicating on eventId.
Option typos fail closed on the build side too: buildSettlementWebhook and buildSettlementWebhooks scan their options against their known keys (secret, signingKey, now, eventId / secret, signingKey, now, eventIdFactory) before any signing, and an unknown key throws cannot build settlement webhook(s): unknown option "<key>". A typo'd secrett is therefore reported as itself instead of surfacing as a bare TypeError on the missing secret, and a typo'd eventIdFactory can never silently fall back to the default randomUUID factory. A missing or non-string/Buffer secret likewise throws a configuration error, never a bare TypeError.
A hand-built report is validated before it is signed: buildSettlementWebhook (and the batch and fan-out paths, which share the same payload builder) checks that the report is an object with a non-empty-string escrowId, an outcome in the SettlementOutcome union (released, refunded, expired, partially-released), an object deposit with a finite non-negative deposit, and an array parties whose entries are objects with finite inflow/outflow/net. A malformed report throws a cannot build settlement webhook: … configuration error before anything is signed, so it can neither crash the signer with a bare TypeError nor ship a signed webhook whose figures are nonsense. Reports built by buildSettlementReport always pass this check.
checkAndRecord(eventId) returns false on first sighting and true
for a repeat within the TTL ("true = is a replay"); at exactly ttlMs
the record has expired and the id counts as unseen again, and a
duplicate hit never extends the window.
A first sighting is stamped at the latest time the store has observed,
never earlier: if the clock jumps backwards (NTP correction, a VM
restore), an id recorded during the rewind keeps its nominal TTL
instead of expiring early, and a restart restores the same floor from
the snapshot — the rewind shortens no window and retains no entry past
its TTL. At capacity, expired entries
are reclaimed before the least recently seen entry is evicted.
Illegal configuration (ttlMs not a positive finite number,
maxEntries not a positive integer) throws at construction, and an
unknown option key throws SettlementEventDedupe: unknown option "<key>" before any field is read — a typo'd ttl is reported as
itself instead of silently falling back to the 1-hour default and
widening the replay window the caller thought it had narrowed.
An empty, non-string, or overlong (longer than MAX_EVENT_ID_LENGTH)
eventId throws instead of silently passing.
size and stats() ({ size, hits, misses, evictions }) expose
observability, and clear() resets both. For a read-only question —
"have I seen this eventId?" asked before the signature is verified,
e.g. for logging or metrics — use has(eventId, now?): it returns
true when the id was recorded within the TTL and false otherwise,
without recording anything, so a forged delivery probed before
verification cannot make the later genuine delivery look like a
duplicate. It never refreshes LRU recency, never reclaims expired
entries, and never moves the hits/misses/evictions counters; an
expired id reads false (the TTL boundary matches checkAndRecord),
and an empty, non-string, or overlong eventId throws the same way.
An explicit now (milliseconds since the epoch) overrides the
injected clock for that one probe. Honest limit: the store is
single-process and in-memory only — two receiver processes cannot see
each other's records, so a multi-process receiver must deduplicate
over shared storage (a database unique constraint, Redis, …) instead.
A single process can still carry its ids across its own restart:
exportSnapshot() returns a detached, JSON-serializable
{ v: 1, entries: [eventId, seenAtMs][] } of the entries still live
against the store's clock, and SettlementEventDedupe.restore(snapshot, opts)
(alias fromSnapshot) rebuilds a store from it:
// before shutdown:
persist(JSON.stringify(dedupe.exportSnapshot()));
// at startup:
const dedupe2 = SettlementEventDedupe.restore(JSON.parse(saved), { ttlMs: 24 * 60 * 60_000 });Restore validates strictly — a wrong version, a non-array entries,
a malformed entry, or an unknown top-level field throws instead of
silently disabling deduplication. Entries already expired are dropped
at load, an over-maxEntries snapshot evicts the oldest seenAtMs
first, and TTLs keep counting from each id's original first-seen time
— restoring never grants a fresh window. The hits/misses/
evictions counters are not part of the snapshot: a restored store
starts them at zero. The snapshot bridges one process across its own
restart only; two processes restoring the same snapshot afterwards
diverge, so it is not a substitute for shared storage.
The unsigned snapshot above is trusted configuration: anyone who can
rewrite the persisted file can delete a consumed eventId (a retried
duplicate settlement is then processed a second time) or inject a
forged one (a legitimate settlement is then dropped as an apparent
duplicate). When the persisted file is not fully trusted, use the
signed envelope instead — exportSignedSnapshot(secret) returns
{ v: 1, snapshot, mac } with mac = HMAC-SHA256 over the canonical
JSON of the snapshot, and
SettlementEventDedupe.restoreSignedSnapshot(envelope, secret, opts)
(alias fromSignedSnapshot) verifies it before restoring:
// before shutdown:
persist(JSON.stringify(dedupe.exportSignedSnapshot(process.env.DEDUPE_SNAPSHOT_SECRET!)));
// at startup:
const dedupe2 = SettlementEventDedupe.restoreSignedSnapshot(JSON.parse(saved), process.env.DEDUPE_SNAPSHOT_SECRET!, { ttlMs: 24 * 60 * 60_000 });The secret is never written into the envelope, and the two forms do
not accept each other — a signed envelope is rejected by the unsigned
restore(), and an unsigned snapshot is rejected by the signed
restore, so a signed restore cannot silently downgrade to the
trusted-configuration path. A tampered entry, a tampered seenAtMs,
a tampered mac, or a wrong secret all fail closed with no store
produced, and a MAC-valid envelope whose snapshot is itself malformed
still fails the strict snapshot validation. The envelope can also
carry an optional expiry: exportSignedSnapshot(secret, { expiresAt })
or { maxAgeMs, now? } writes a canonical ISO-8601 UTC expiresAt
into the envelope, covered by the MAC; restore rejects an expired
envelope (now > expiresAt — restoring at exactly expiresAt still
succeeds) after the MAC check and before any snapshot parsing, with
opts.now as the clock. An envelope without expiresAt never
expires, exactly as before. Unknown export option keys fail closed:
a typo'd expiry throws SettlementEventDedupe: exportSignedSnapshot: unknown option "expiry" instead of silently producing a
never-expiring envelope. The MAC is integrity
protection only, not encryption: the eventIds inside are wire-visible
values, so keep the secret where the snapshot writer keeps its other
signing-side secrets. This mirrors the sibling rfc9421
ReplayCache signed snapshot (exportSignedSnapshot /
restoreSignedSnapshot), same envelope shape and canonical form.
On the sending side, delivery itself keeps no memory: a failed
deliverSettlementWebhook call only tells you that one call failed.
SettlementWebhookOutbox is the in-memory ledger that answers "which
(endpoint, eventId) pairs are still undelivered, and which have
exhausted their retries":
import { SettlementWebhookOutbox } from "escrow-state-machine-ts";
const outbox = new SettlementWebhookOutbox({ maxAttempts: 3 });
try {
await deliverSettlementWebhook(url, webhook, { retries: 0 });
outbox.acknowledge(url, webhook.payload.eventId);
} catch (err) {
outbox.recordAttempt({ endpoint: url, eventId: webhook.payload.eventId, ok: false, error: (err as Error).message });
}
outbox.pending(); // failed but not yet exhausted — still worth a retry
outbox.deadLetter(); // 3 consecutive failures — needs a human: fix the endpoint, then redrive() it
outbox.stats(); // { size, pending, deadLettered, totalAttempts } — the same counts without materializing the listsstats() is a pure read: size equals the size getter
(pending + dead-lettered), totalAttempts sums attempts over every
tracked pair — dead-lettered pairs included, at their capped value —
and the call changes nothing in the ledger, so a dashboard or health
check that only needs the counts never pays for pending() /
deadLetter() copies.
A dead letter is not a dead end: once the downstream endpoint is
fixed, redrive(endpoint, eventId) moves that pair back to
pending() for a fresh delivery round — attempts reset to 0,
lastAt stamped with the redrive time, and the old lastError
dropped, so a later failure counts from 1 again and the pair
re-enters the retrySettlementWebhookOutbox runner's next pass.
Only a dead-lettered pair can be redriven: redriving a pending pair
(it still has retries left) or an untracked pair throws.
redrive(endpoint, eventId, { now }) takes an explicit timestamp
for deterministic tests. Redrive is distinct from restore(),
which replays a persisted ledger with its failure counts intact —
a redriven pair exports with attempts: 0, which restore()
accepts, so a persisted ledger never loses a pair that was moved
back to pending.
A failed attempt increments the pair's consecutive-failure count
(capped at maxAttempts, while later failures still refresh
lastError/lastAt); a success (ok: true, or acknowledge())
clears the pair, so a later failure counts from 1 again. The stored
lastError is capped at MAX_OUTBOX_ERROR_LENGTH (1024 characters)
at record time — a longer error keeps its prefix and ends with
…[truncated], so one oversized failure (a full HTML error page, a
long stack trace) cannot bloat the ledger or the snapshot exported
from it. The full error body belongs in the log where the delivery
happened; the outbox keeps only the diagnostic hint. Pairs are
keyed by (endpoint, eventId), so one endpoint's failures never
pollute another's retry count, and an eventId longer than
MAX_EVENT_ID_LENGTH (256 characters) is rejected at recordAttempt()
and at snapshot restore, never truncated — truncation would change
the pair's key. The ledger is capped at maxEntries pairs (default
10_000, mirroring SettlementEventDedupe): recording a failure for a
new pair past the cap evicts dead-lettered pairs first (oldest
lastAt first) and only then the oldest pending pair, so a burst of
fresh failures never discards a pair that still has retries left
while a dead letter is available; re-failing a pair the ledger
already tracks never evicts anything, because the ledger does not
grow. restore() trims an over-capacity snapshot to the newest
maxEntries pairs by lastAt instead, so a persisted snapshot can
never resurrect a ledger past the cap. exportSnapshot() /
SettlementWebhookOutbox.restore() carry the ledger across a restart
of the same process (unsigned, trusted-configuration snapshot — the
same posture as the dedupe's unsigned snapshot above). When the
persisted file is not fully trusted, use the signed envelope instead
— exportSignedSnapshot(secret) returns { v: 1, snapshot, mac }
with mac = HMAC-SHA256 over the canonical JSON of the snapshot,
and SettlementWebhookOutbox.restoreSignedSnapshot(envelope, secret, opts) (alias fromSignedSnapshot) verifies it before restoring:
// before shutdown:
persist(JSON.stringify(outbox.exportSignedSnapshot(process.env.OUTBOX_SNAPSHOT_SECRET!)));
// at startup:
const outbox2 = SettlementWebhookOutbox.restoreSignedSnapshot(JSON.parse(saved), process.env.OUTBOX_SNAPSHOT_SECRET!, { maxAttempts: 3 });The secret is never written into the envelope, and the two forms do
not accept each other — a signed envelope is rejected by the unsigned
restore(), and an unsigned snapshot is rejected by the signed
restore, so a signed restore cannot silently downgrade to the
trusted-configuration path. A tampered attempts count, a tampered
lastError/lastAt, a tampered (endpoint, eventId) key, a tampered
mac, or a wrong secret all fail closed with no outbox produced, and
a MAC-valid envelope whose snapshot is itself malformed still fails
the strict snapshot validation. The envelope can also carry an
optional expiry: exportSignedSnapshot(secret, { expiresAt }) or
{ maxAgeMs, now? } writes a canonical ISO-8601 UTC expiresAt
into the envelope, covered by the MAC; restore rejects an expired
envelope (now > expiresAt — restoring at exactly expiresAt still
succeeds) after the MAC check and before any snapshot parsing, with
opts.now as the clock. An envelope without expiresAt never
expires, exactly as before. Unknown export option keys fail closed:
a typo'd expiry throws SettlementWebhookOutbox: exportSignedSnapshot: unknown option "expiry" instead of silently
producing a never-expiring envelope, and the outbox constructor
likewise rejects unknown options, so a typo'd restore clock cannot
silently fall back to wall-clock. The MAC is integrity protection only,
not encryption: the endpoints and eventIds inside are wire-visible
values, so keep the secret where the snapshot writer keeps its other
signing-side secrets. Same envelope shape and canonical form as the
dedupe envelope above.
The outbox records only — it never retries on its own. The opt-in
retrySettlementWebhookOutbox(outbox, deliverOne, opts?) runner is
the one correct retry loop over the ledger, so callers do not have to
hand-write it (and hand-write its two easiest mistakes: retrying a
dead letter, and forgetting to clear a pair after a success). You
supply the re-delivery — usually one line wrapping
deliverSettlementWebhook — and the runner takes the pending list,
re-delivers each pair, acknowledges successes, records failures
toward the dead letter, and sleeps the exponential backoff between
rounds:
import { retrySettlementWebhookOutbox } from "escrow-state-machine-ts";
const summary = await retrySettlementWebhookOutbox(
outbox,
async (endpoint, eventId) => {
try {
// Rebuild the signed webhook for this (endpoint, eventId) pair
// and deliver it; `true` means the receiver answered 2xx.
await deliverSettlementWebhook(endpoint, webhook, { retries: 0 });
return true;
} catch {
return false;
}
},
{ maxRounds: 3, backoffMs: 1000 },
);
// summary: { attempted, acknowledged, stillPending, deadLettered, aborted }Each round re-reads outbox.pending(), so dead-lettered pairs are
never re-delivered and a pair that dead-letters mid-run is not
revisited. maxRounds (default 1) bounds the loop; backoffMs
(default 1000) is the exponential base between rounds, with opt-in
jitterMs; maxConcurrency (default 1, serial) bounds the
in-flight re-deliveries the same way deliverSettlementWebhookToMany
bounds its fan-out; signal aborts at round boundaries with
already-made attempts kept. A deliverOne that throws is recorded
as a failed attempt with its message, never a runner crash. Pass
dryRun: true to rehearse instead of retrying: the runner takes
one pass over outbox.pending() and reports each pair as
{ endpoint, eventId, wouldRetry: true } on the summary's
wouldRetry field — no delivery, no ledger writes, no sleep — so a
retry storm over dozens of pending pairs can be previewed before it
is really sent. A dry run never changes the ledger, so rehearsing
and then running the live retry still delivers every pair; an
already-aborted signal reports aborted: true with an empty
wouldRetry list. wouldRetry answers only "in the pending
selection", never "would succeed": a pair whose delivery would fail
is still listed, because the dry run never calls deliverOne. The
CLI demo runs the runner over a scripted ledger (npm run demo,
webhook-outbox retry segment): one pending pair fails its first
re-delivery (500) and succeeds on the second (200), and a dry run
rehearses a second pair without touching the ledger. Honest
limit: the runner is in-process only and persists nothing — a dead
process loses the ledger unless it exported a snapshot first (see
Limitations).
Secret rotation: while you roll from an old secret to a new one, pass both as candidates — any candidate that matches verifies, all-mismatch still fails closed:
const ok = verifySettlementWebhook(rawBody, receivedSignature, {
secrets: [process.env.WEBHOOK_SECRET_NEW!, process.env.WEBHOOK_SECRET_OLD!],
});An empty secrets array (or an empty secret inside it) is a caller
configuration error and throws instead of silently passing. The library does
not generate, store, or schedule the rotation itself — it only accepts the
candidate set the caller hands it (see SECURITY.md).
Signatures don't expire by themselves: a legitimately-signed payload from a
year ago still verifies. For an opt-in replay bound, pass maxAgeMs — the
signature is checked first, and only if it matches is payload.at checked
against the window (an unparseable at fails closed as false):
// Reject replays older than 5 minutes; `now` is injectable in tests.
const ok = verifySettlementWebhook(rawBody, receivedSignature, {
secrets: [process.env.WEBHOOK_SECRET!],
maxAgeMs: 5 * 60 * 1000,
now: Date.now(), // optional; defaults to the real clock
});maxAgeMs alone leaves the future direction unbounded: a
legitimately-signed payload issued far into the future (a sender clock
set wrong or fast) would gain a near-unbounded replay window. Pass
maxFutureSkewMs to bound that direction too:
const ok = verifySettlementWebhook(rawBody, receivedSignature, {
secrets: [process.env.WEBHOOK_SECRET!],
maxAgeMs: 5 * 60 * 1000,
maxFutureSkewMs: 60 * 1000,
now: Date.now(), // optional; defaults to the real clock
});
// => false when the signature is valid but payload.at - now > maxFutureSkewMsIt is enforced only after the signature matches, fails closed as
false, and its boundary is likewise inclusive (a skew of exactly
maxFutureSkewMs passes); an illegal value throws the same style of
configuration error as maxAgeMs. Together the two fields form a
two-sided freshness window. Left unset, maxFutureSkewMs changes
nothing — far-future timestamps still pass, exactly as before — and
neither bound replaces deduplication on eventId.
A signed payload can still arrive without an eventId — the type
says it is required, but a raw string body bypasses the type layer,
and a keyless notification that verifies leaves a receiver that
deduplicates on eventId with no key (the dedupe step either crashes
or silently skips, and replay detection is defeated while the
signature looks fine). Pass requireEventId: true to close that gap:
const ok = verifySettlementWebhook(rawBody, receivedSignature, {
secrets: [process.env.WEBHOOK_SECRET!],
requireEventId: true,
});
// => false when the signature is valid but the payload carries no
// non-empty string eventIdIt runs only after the signature matches — a forged signature still
fails on the signature comparison, never on this gate — and a missing,
non-string, or empty eventId (or an unparseable string body) fails
closed as false, never throws. A non-boolean value throws the same
style of configuration error as the other options. It composes with
the freshness window: both gates must pass. The sending side is
unaffected — buildSettlementWebhook always issues an eventId, and
deliverSettlementWebhookToMany verifies per endpoint with the
sender's own options, never this receiver-side requirement — so
enabling it only hardens receivers. Defaults to false: without it,
a keyless payload verifies on its signature alone, exactly as before.
New receivers should prefer the strict entry point instead of assembling the three opt-in gates by hand:
verifySettlementWebhookStrict(rawBody, receivedSignature, secret);
// => maxAgeMs 5 * 60_000, maxFutureSkewMs 60_000, requireEventId: trueIt is verifySettlementWebhook with all three gates switched on by
default: a legitimately-signed payload older than 5 minutes or more
than 60 seconds in the future returns false, as does a signed
payload without a usable eventId. Each default is overridable per
field — pass an explicit maxAgeMs (one hour accepts a 10-minute-old
payload), maxFutureSkewMs, or requireEventId: false — and an
explicit undefined for a window field means "use the strict
default". Two combinations throw a configuration error instead of
verifying: explicitly passing maxAgeMs: undefined — or
maxFutureSkewMs: undefined — together with requireEventId: false,
which would strip two of the three gates at once, so strict cannot
be quietly downgraded back to signature-only verification. The
defaults themselves are exported as
STRICT_SETTLEMENT_WEBHOOK_MAX_AGE_MS and
STRICT_SETTLEMENT_WEBHOOK_MAX_FUTURE_SKEW_MS. The legacy
verifySettlementWebhook() defaults are unchanged — receivers that
already rely on signature-only verification keep verifying exactly as
before. Strict is defense-in-depth only: receivers MUST still
deduplicate on eventId after a successful verify. End-to-end replay
coverage pins the split between the two layers: the same captured
bytes verify on first delivery, are rejected 1ms past the 5-minute
window (while the signature itself still verifies), and are caught by
SettlementEventDedupe when replayed inside the window.
Option typos fail closed: the options object is scanned against the
five known keys (secrets, maxAgeMs, maxFutureSkewMs,
requireEventId, now) after the secrets non-empty check and
before any other field is read or the signature is compared, and an
unknown key throws cannot verify settlement webhook: unknown option "<key>". A typo'd maxAge can therefore never silently drop the
freshness window it was meant to set. The string/Buffer single-secret
overload takes no options object and is unaffected.
Delivery is handled by deliverSettlementWebhook(url, webhook, options) —
still zero runtime dependencies (Node ≥ 20 global fetch):
import { deliverSettlementWebhook } from "escrow-state-machine-ts";
const result = await deliverSettlementWebhook(
"https://ledger.example.com/hooks/escrow",
{ payload, signature },
{ retries: 3, backoffMs: 1000, timeoutMs: 10000, maxRetryDelayMs: 60000 }, // all optional; these are the defaults
});
// result: { status: 200, attempts: 1 }
// Cancel a delivery stuck in retries or a hung request:
const controller = new AbortController();
const pending = deliverSettlementWebhook(url, { payload, signature }, {
retries: 5,
signal: controller.signal, // aborts the in-flight request and any backoff sleep
});
controller.abort(); // pending rejects with `webhook delivery aborted`, never retriedOption typos fail closed on the delivery side too: deliverSettlementWebhook
scans its options against the eight known keys before any other validation or
request is made, and an unknown key throws
cannot deliver settlement webhook: unknown option "<key>" — a typo'd
timeouMs is reported as itself instead of silently running with the default
10s timeout, and a typo'd retry instead of silently running with the default
3 retries. The scan runs first, so an unknown key is never masked by a value
error on a known key. deliverSettlementWebhookToMany scans its call-level
options the same way (the eight delivery keys plus now, eventId,
maxEndpoints, maxConcurrency, overallDeadlineMs), throwing before any
request when a key is unknown — a typo'd maxEndpoint can therefore never
silently drop the fan-out size cap, nor a typo'd overallDeadline the
wall-clock budget. A typo'd per-endpoint override is a per-endpoint
configuration failure instead: it is reported as that endpoint's
{ ok: false, attempts: 0, error } result, the endpoint makes no request, and
the other endpoints still deliver.
Semantics: the payload is POSTed as JSON with the X-Signature header,
byte-identical to what buildSettlementWebhook signed so the receiver can
verify it over the raw body. Every attempt also carries an X-Event-Id
header equal to the payload's eventId (the same value on every retry),
so a gateway can deduplicate on the header without parsing the body first.
Every attempt also carries an Idempotency-Key header with exactly the
same value, for receivers that deduplicate on the standard payment-gateway
idempotency header rather than on a vendor-specific one; fan-out endpoints
share the same logical eventId, so they share the same header value. Both
headers are transport hints only — neither is covered by the signature,
so a receiver must verify the signature and then trust the body's
eventId, never a header, as the deduplication key. 2xx returns
{ status, attempts }; 429, 5xx,
and network errors (including timeouts) are retried with exponential backoff
(retry n waits backoffMs * 2^(n-1)). Opt-in jitterMs (default 0) adds a
Math.random() * jitterMs spread on top of each backoff wait, so endpoints
that failed together do not retry in lockstep and thundering-herd the
receiver on restart. This is best-effort de-synchronization only: it does
not guarantee a uniform spread of retries, and it does not coordinate
retries across processes or restarts. A 429 Retry-After response header
(delay seconds or an HTTP-date) takes precedence over the backoff; an
absent or unparsable value falls back to it. A non-string value passed to
parseRetryAfter directly is a caller type error and throws
parseRetryAfter: value must be a string, got … instead of dying as a
bare TypeError; only an absent or unparsable string falls back to
backoff. The honored hint is clamped to
maxRetryDelayMs (default 60,000ms): a faulty or hostile server returning
Retry-After: 31536000 can never stall the delivery promise beyond the cap.
Every wait the delivery arms — backoff sleeps, the per-attempt timeout,
and the fan-out deadline — is additionally capped at the Node setTimeout
ceiling (2^31 - 1 ms, about 24.8 days): an exponential schedule that grows
past it waits the ceiling instead of misfiring after 1ms, and an
above-ceiling timeout or deadline still enforces its wait up to the
ceiling. The exported parseRetryAfter returns a value already clamped
to the same ceiling, so a caller arming setTimeout directly on a
Retry-After hint never hits the 1ms misfire either. Other 3xx/4xx throw
immediately without retrying, and redirects are never followed: a 3xx
response is returned as-is (the signed payload is never re-posted to a
third-party redirect target), surfacing as failed with status 301 (not retried) so the caller fixes the endpoint URL. Plaintext http: endpoint
URLs are refused by default with refusing to POST over plaintext http
(the signed payload plus the X-Signature header are replayable over the
clear): pass allowInsecureHttp: true to explicitly opt out for local
loopback/dev servers; https: URLs are never gated, and the refusal does
not validate certificates or pin TLS. When every attempt fails, the error reads
webhook delivery to <url> failed after <n> attempts: <last cause>; a
per-attempt timeout surfaces as timed out after <timeoutMs>ms. An optional
signal (AbortSignal) aborts both the in-flight request and any pending
backoff sleep — the promise rejects with webhook delivery aborted and the
request is never retried after an abort (an abort is a caller request to
stop, not a retryable failure). Pass fetchImpl to replace the global
fetch for every attempt (same (url: string, init) shape): inject a stub
in tests to exercise delivery with no network at all, or a custom transport
(proxy, mTLS, record/replay) in production. The per-attempt timeout and the
external signal are still wired into init.signal, so the implementation
must honor it like the global fetch does — one that ignores its signal
cannot be force-stopped by a timeout or an abort. A non-function
fetchImpl is a configuration error thrown before any request. Secret
distribution remains the caller's responsibility: whoever holds it can forge
signatures.
Multi-endpoint fan-out is included too:
deliverSettlementWebhookToMany(report, endpoints) delivers ONE
settlement event concurrently to every endpoint — the shape where
accounting, notifications, and reconciliation systems must all hear
about the same settlement at once, each holding its own secret:
import { deliverSettlementWebhookToMany } from "escrow-state-machine-ts";
const out = await deliverSettlementWebhookToMany(report, [
{ url: "https://ledger.example.com/hooks/escrow", secret: ledgerSecret },
{ url: "https://notify.example.com/hooks/escrow", secret: notifySecret },
]);
// out: { results: SettlementWebhookEndpointResult[], delivered: number, failed: number, deadlineExceeded: boolean }
// results[i] corresponds to endpoints[i], in input order, and
// delivered + failed always equals endpoints.length.The payload body is built once from the report — one shared eventId,
one shared at — and signed independently per endpoint with that
endpoint's own secret (one endpoint's secret cannot verify another's
delivery). Each endpoint is delivered through
deliverSettlementWebhook itself, so the retry/backoff/Retry-After
semantics above apply unchanged, with retry budgets counted per
endpoint; an endpoint can also override retries/backoffMs/
timeoutMs/maxRetryDelayMs/jitterMs/signal/fetchImpl for itself.
One endpoint's failure — retries exhausted, network error, even an invalid
URL or an empty secret — marks only that endpoint's result
{ ok: false, attempts, status?, error } and never blocks the others.
Call-level configuration errors still throw before any request: an
empty/non-array endpoints list, invalid global delivery options, or
an invalid shared now/eventId.
Fan-out limits: pass maxEndpoints to cap the fan-out size (more
endpoints than the cap throws before any request, so one settlement
event cannot turn into an endpoint explosion) and
overallDeadlineMs to cap the whole call's wall-clock time. When the
deadline expires, every still-in-flight endpoint is aborted through a
deadline signal composed with that endpoint's own signal — a
per-endpoint signal override does not exempt an endpoint from the
deadline — the stopped endpoint reports
settlement webhook delivery timed out: overall deadline of <ms>ms exceeded,
endpoints that already completed keep their results, and the
aggregate carries deadlineExceeded: true. Both options are
call-level configuration: invalid values throw before any request.
The deadline timer is additionally capped at the Node setTimeout
ceiling (2^31 - 1 ms), so an above-ceiling budget still stops hanging
endpoints, just no later than the ceiling.
Pass maxConcurrency to cap how many deliveries run at once: the
fan-out then runs as a bounded pool (a new endpoint starts only when
one settles), so a 50-endpoint fan-out never opens 50 simultaneous
connections. Unset, every endpoint starts at once, as before. A
deadline that fires while endpoints are still queued reports those
endpoints as deadline failures with 0 attempts and no request made;
results stay in endpoint order either way.
Honest limit: there is no durable queue. If the process dies
mid-fan-out, some endpoints may have received the event and others
not — the caller reconciles by re-delivering and letting receivers
deduplicate on the shared eventId (see the receiver-side dedupe
example above).
For a whole batch of escrows, buildSettlementReports(inputsList) takes
the same per-escrow inputs as buildSettlementReport and returns one
{ escrowId, report } or { escrowId, error } result per input, in input
order — a non-terminal escrow or a corrupted history fails only its own
entry, never the whole batch, and building reports mutates nothing.
One exception: a repeated escrowId in the batch aborts the whole call —
it throws an error naming the duplicate id(s) and produces no reports, so
a mistyped batch list can never double-count one settlement in
summarizeSettlementReports. Calling the single-escrow
buildSettlementReport twice for the same escrow stays legitimate.
summarizeSettlementReports(results) aggregates such a batch into one
reconciliation summary — per-outcome counts, error count, total locked
deposit, total inflow/outflow, the still-locked remainder
(totalRemaining, the sum of each successful report's remaining —
the money still held in partially-released escrows), and per-party net
totals — summing the already cent-rounded figures from each report
(aggregates are round2 as well); error entries are counted but never
enter the money totals, and an empty batch yields an all-zero summary.
A repeated escrowId among the reports throws
invalid summarizeSettlementReports: duplicate report escrowId: "<id>"
before any figure is summed — the same settlement must never be counted
twice in the day-end totals (the batch builder and reconcileSettlements
already refuse duplicates the same way); error entries carry no report
and never trigger the check. A null or non-object entry in the batch
throws invalid summarizeSettlementReports: results[N] must be an object, got … naming the first offending index, also before any figure
is summed — a mistyped entry can no longer die as a bare TypeError or
be silently counted as a failed escrow.
If any running total would leave the finite range — a hand-built or
upstream report carrying astronomical figures, or a batch whose figures
sum past Number.MAX_VALUE — the call throws
settlement reports summary computation overflowed: inputs too large
instead of returning Infinity totals; and every successful report is
shape-checked with the same assertReportShape the JSON/CSV renderers
apply before any figure is summed — an unknown outcome, an unknown
party role, a non-array parties, or a missing/non-finite deposit /
total / remaining throws
invalid settlement reports summary: … and returns no summary, so a
hand-built report can no longer produce an outcome count of NaN
(serialized as null) while its inflow is still added. Error entries
carry no report and are never checked; a hand-built report should go
through parseSettlementReportJson or buildSettlementReport first.
Read the still-locked remainder from totalRemaining, not from
totalDeposit - totalOutflow: a partial report's ledger runs over the
full deposit, so that difference is 0 even while money is still
locked. The summary also carries a per-currency breakdown,
byCurrency, keyed by each report's ISO 4217 code (reports built
without a currency land in the UNSPECIFIED bucket): each bucket sums
only its own currency's reports, so a mixed-currency batch can be read
bucket by bucket as single-currency money, and each bucket carries its
own totalRemaining on the same rule. The top-level totals are kept
for backward compatibility and still sum raw figures across currencies
— read byCurrency, not the top-level totals, when the batch may mix
currencies.
The summary also has canonical text forms, so a caller doing batch reconciliation no longer has to hand-write the export — the same strict render/parse paradigm as the single-report CSV/JSON pair, for the whole summary:
import {
parseSettlementReportsSummaryCsv,
parseSettlementReportsSummaryJson,
renderSettlementReportsSummary,
renderSettlementReportsSummaryCsv,
renderSettlementReportsSummaryJson,
summarizeSettlementReports,
} from "@toniadreal/escrow-state-machine-ts";
const summary = summarizeSettlementReports(results);
renderSettlementReportsSummaryCsv(summary);
// => "section,key,count,total,reports,errors,totalDeposit,totalInflow,totalOutflow,totalRemaining,net,balanced\nsummary,,,4,3,1,31890.00,31890.00,31890.00,6378.00,,true\noutcome,released,1,..."
renderSettlementReportsSummaryJson(summary);
// => '{"total":4,"reports":3,"errors":1,"outcomes":{"released":1,...},"totalDeposit":31890,...}'
renderSettlementReportsSummary(summary);
// => "Settlement reports summary\nReports: 3 (errors: 1)\nReleased: 1\n..."
parseSettlementReportsSummaryCsv(renderSettlementReportsSummaryCsv(summary)); // => the same summary
parseSettlementReportsSummaryJson(renderSettlementReportsSummaryJson(summary)); // => the same summaryFor a log line or a terminal paste, renderSettlementReportsSummary
renders the same summary as plain human-readable text — title line,
counts line, four outcome rows, four money lines, one row per party,
one row per currency bucket, a balanced line, and a units line, in
that fixed order. Money is spelled with exactly two decimals, the
same spelling the CSV uses. It is a display form, not an interchange
form: there is no parser back (the CSV and JSON renderers are the
round-trippable text forms), and the units line says so in the output
itself — the top-level totals sum raw figures across currencies, so a
mixed-currency batch must be read bucket by bucket. The renderer
applies the same shape check as the CSV/JSON renderers and throws
cannot render settlement reports summary: … on a malformed summary
instead of emitting a document that reads consistent but is not.
The CSV is a table with one summary row (the batch totals), four
outcome rows in fixed order, four party rows in canonical role
order, and one currency row per byCurrency bucket in alphabetical
order (the UNSPECIFIED bucket sorts as the literal string it is) —
a row that pastes straight into a reconciliation spreadsheet or a
settlement statement. Money is the same cent value the JSON form
carries as a number, spelled with exactly two decimals; counts are
canonical integers. The JSON writes the same eleven fields as
numbers, in canonical key order, for the API/storage hop. Unlike the
single-report CSV, which drops the deposit breakdown and audit
window, the summary CSV carries the whole summary: a parsed value is
the full summary and re-renders byte-identically. Both parsers are
strict and fail closed — a bad header, a wrong column count, rows out
of canonical order, a non-canonical amount (31890.0, 1e3,
007), a negative count or total, a total that does not equal
reports + errors, outcome counts that do not sum to reports,
party ledgers whose sums disagree with the totals, currency buckets
whose sums disagree with the top-level totals (including
totalRemaining), a balanced: true over disagreeing totals, a
missing or unknown field, or string amounts in JSON all throw with
the direction's prefix instead of returning a half-summary — and both
renderers apply the same shape check before emitting text, so a
malformed object never becomes a plausible-looking document. CRLF
endings, a trailing newline, trailing blank lines, a UTF-8 BOM, and
RFC 4180 quoted fields are transport artifacts and parse. Top-level
totals still sum raw figures across currencies — read byCurrency,
not the top-level totals, when the batch may mix currencies — and
import is structural validation only, not a re-verification of the
audit histories the summary claims to summarize.
Against an external payment ledger, reconcileSettlements(reports, ledger)
pairs reports with ledger rows by escrowId and returns five groups —
matched, reportOnly, ledgerOnly, amountMismatch, and
currencyMismatch — so both directions of a gap are visible: a
settlement the ledger never paid, and a ledger payment no report
accounts for. The report's amount is its totalOutflow, compared at
cent precision — except for a partially-released report, which is
compared against partialSettlement.released, the slice that actually
left escrow; a mismatch there reports reportAmount as the released
slice with a reason naming the partial-release basis, so a ledger
carrying the honest slice (4,252 of a 10,630 deposit) matches instead
of being misread as a 6,378 shortfall. A ledger row with no recorded amount matches on the
reference alone, and a duplicated report or ledger id or a malformed row fails
fast instead of pairing ambiguously. An escrowId longer than 256 characters
on either side is rejected outright (invalid reconcileSettlements: … must be at most 256 characters, got N): the library can never mint an id that long
(the escrow constructor caps it at MAX_ESCROW_ID_LENGTH), so an overlong id
at the reconcile entry is a malformed input, not a pairing to attempt. The
same cap applies where a report is restored from CSV or JSON, so a
hand-built document carrying an overlong id is refused at the shape check
instead of only at reconciliation. The build path enforces it too:
buildSettlementReport throws cannot build settlement report: … on an
empty or overlong escrowId before the currency check, the chain check,
or any money math runs, so a report the library builds can always be
parsed and reconciled by the library itself; before even that, a
non-object inputs (or a missing/non-object deposit) throws the same
named family instead of a bare TypeError from destructuring. In the
batch wrapper a build failure is recorded per escrow, never aborting
the batch. The history
helpers depositAmountFromHistory / releasedAmountFromHistory validate
an explicitly passed label the same way; omit the label and the default
"escrow" is only an error-message label, not a report identity. When both sides carry a currency
code and the codes differ, the pair lands in currencyMismatch and in
no other group, even when the amounts also disagree; when either side
omits the code, the previous rules apply unchanged. The function is
pure: it reads both inputs, dispatches nothing, and an empty batch
against an empty ledger returns five empty groups.
To answer what changed between two stored reports of the same escrow,
diffSettlementReports(a, b) compares them field by field and returns
a SettlementReportDiff carrying only the fields that moved — an
identical pair diffs to {}. Money compares at integer-cent precision,
never on raw floats, so sub-cent noise is not a change; a moved
settlementRef is its own entry too, so a re-settlement against a new
payment is visible even when every figure agrees, and a moved
refundRef is its own entry the same way, so a re-refund against a new
refund is visible even when every figure agrees; parties align
by role, with a role present on one side only reported as added or
removed instead of silently dropped; and a balanced flip is its own
entry, so a report that stopped balancing is visible even when no
single amount looks wrong. Both inputs must be reports at all first:
a missing deposit, parties, total, event count, or balanced
flag, a wrong-type money figure, or an unknown outcome throws
invalid settlement report diff: … before any field compare
(backlog #1293), so a record-shaped but field-missing input no longer
dies with a bare TypeError or reports a phantom move. Reports of
different escrows throw
settlement report diff failed: cannot diff reports of different escrows …,
the same fail-fast identity rule diffEscrowSnapshots uses for
snapshots. The function is pure and returns detached copies.
To answer what changed between two stored batch summaries — the same
reconciliation question one level up — diffSettlementReportsSummaries(a, b)
compares two SettlementReportsSummary values field by field and
returns a SettlementReportsSummaryDiff carrying only the fields that
moved; identical summaries diff to {}. Counts compare exactly and
money compares at integer-cent precision, the same rule as the
single-report diff; outcomes is one entry carrying the whole
four-tier record, parties align by role, and currency buckets align by
code, with a code present on one side only reported as added or
removed instead of silently dropped — a summary always carries
exactly the four party roles, so a missing role throws the shape
error below instead of diffing as removed. Both inputs must be
summaries at all first: a missing or unknown field, a non-integer
count, a non-cent-exact or non-finite money figure, a malformed
party entry, or a malformed currency bucket throws
invalid settlement reports summary diff: … before any field
compare (backlog #1292), so a record-shaped but field-missing input
no longer dies with a bare TypeError or reports a phantom move.
A summary carries no batch id,
so — unlike the single-report diff, which refuses to cross escrows —
there is no identity guard: diffing summaries of two different batches
is the caller's responsibility. The function is pure and returns
detached copies, and like the single-report diff it is a comparison,
not a validation: it does not re-check that either summary's
totalRemaining equals the sum of its reports' remaining, that its
currency buckets sum to the top-level totals, or that balanced
agrees with its totals.
Currency: buildSettlementReport({ ..., currency: "USD" }) accepts an
optional ISO 4217 alpha-3 code — exactly three uppercase letters, checked
for shape only, not against the published registry. Anything else throws
invalid settlement currency: … before any money math runs, and in the
batch wrapper that failure is recorded per escrow, never aborting the
batch. The code rides the report, the webhook payload, and both batch
wrappers verbatim; omit it and every shape stays exactly as before. It
is a label only: amounts are never converted, so a batch mixing
currencies still sums raw figures at the top level of the summary — read
the summary's per-currency byCurrency buckets, not the top-level
totals, when the batch may mix currencies. Each bucket also carries its
own totalRemaining, so the still-locked remainder is readable per
currency too. Reconciliation is the one place a currency
difference is a first-class finding: reconcileSettlements puts a
report/ledger pair whose codes differ into currencyMismatch (a
ledger row may carry its own optional currency, shape-checked the
same way), so a USD report paired with a stablecoin-denominated ledger
row is flagged instead of silently matching on equal numbers.
Settlement reference: a released report carries the terminal
RELEASE entry's settlementRef on SettlementReport.settlementRef —
the one pointer from the audit report to the real-world payment (bank
wire, chain transaction, payout id) that settled the escrow. A release
without a ref, and every other outcome, omit the key, so those shapes
are unchanged. The ref rides the CSV export (a settlementRef column
on every row, empty when absent) and the JSON export verbatim, appears
as a Settlement ref: line in the plain-text render, and is a
first-class diff field: diffSettlementReports reports a moved ref as
settlementRefChanged, so a re-settlement against a new payment is
visible even when every figure agrees. CSV files written before the
column existed (7-column header) still parse, with the ref simply
absent. An illegal ref on the terminal entry (empty, non-string, or
over MAX_SETTLEMENT_REF_LENGTH characters — the history parser's
rule) fails the build instead of minting a report the library's own
parsers would refuse, and a ref on an ARBITRATE_RELEASE entry is
rejected the same way. The batch summary is unaffected: it aggregates
money, not pointers, and carries no ref field.
Refund reference: a refunded report carries the terminal
ARBITRATE_REFUND entry's refundRef on SettlementReport.refundRef —
the mirror of settlementRef for the refund side, the one pointer from
the audit report to the real-world refund (bank refund reference,
payment-gateway refund id, payout batch id) that refunded the escrow.
A refund without a ref, and every other outcome, omit the key, so those
shapes are unchanged. The ref rides the CSV export (a refundRef
column on every row, empty when absent) and the JSON export verbatim,
appears as a Refund ref: line in the plain-text render, and is a
first-class diff field: diffSettlementReports reports a moved ref as
refundRefChanged, so a re-refund against a new refund is visible even
when every figure agrees. CSV files written before the column existed
(7- or 8-column header) still parse, with the ref simply absent. An
illegal ref on the terminal entry (empty, non-string, or over
MAX_SETTLEMENT_REF_LENGTH characters — the history parser's rule)
fails the build instead of minting a report the library's own parsers
would refuse, and a ref on any other terminal entry is rejected the
same way. The batch summary is unaffected: it aggregates money, not
pointers, and carries no ref field.
Keyed histories: an escrow built with EscrowOptions.auditKey produces
an HMAC-chained history, so its report must be built with the same key
(buildSettlementReport({ ..., auditKey })); without it, or with the
wrong key, the chain check fails closed and no report is produced. The
batch wrapper takes the same per-escrow auditKey through the shared
inputs shape, so a batch mixing keyed and unkeyed escrows reports each
under its own key. An invalid key (empty, or not a string/Buffer) throws
invalid audit key: … before any money math runs.
Partial release: a still-FUNDED escrow can be reported on one released
slice (buildSettlementReport({ ..., partialRelease: { released, proFeeBps, referralCredits? } })),
yielding outcome "partially-released". The slice is settled per
settlePartialRelease with gross = the locked deposit (fee charged on
the released amount only, released must not exceed the deposit), and
the ledger is kept over the full deposit so the report still balances:
creator gets the slice net, platform the slice pro fee, referrer the
credits, and the sponsor's row carries the remaining balance as still
held — remaining is also a top-level field, with the full
partialSettlement beside it. With released equal to the deposit the
ledger is identical to the full-release report's. The escrow itself
stays FUNDED — a partial release is evidence of a slice, not a state
change — and partialRelease with a terminal state throws, as does a
FUNDED escrow reported without it. Since this release, the slice can also
be recorded as a real transition: dispatch("PARTIAL_RELEASE", note, amount)
from FUNDED or MILESTONE_SUBMITTED appends the tranche to the audit
history and stays FUNDED, so a staged payout is auditable tranche by
tranche instead of living only in the report inputs — releasedAmountFromHistory
reads the paid-out total back, and the report's partialRelease slice is
still a proposed slice, not a read-back of the recorded tranches. The batch wrapper inherits the
outcome, the summary counts it under outcomes["partially-released"]
and sums the still-locked remainder into totalRemaining (top level
and per-currency bucket), and the JSON/CSV round-trips carry it (the
CSV carries the same four party rows; the remaining figure is the
sponsor's inflow there).
For a multi-tranche payout, settlePartialReleases takes the whole list
of releases at once and returns the per-tranche ledger plus totals
(totalReleased / totalProFee / totalReferralCredits / totalNet /
remaining). The cumulative released amount is checked against the
gross before each tranche settles, so two individually-legal releases
can no longer over-pay in total (600 then 600 against a gross of 1000
fails with the cumulative figures in the error); each tranche still
settles through settlePartialRelease, so fee and net semantics cannot
drift from the single path. One rounding caveat, pinned by test: each
tranche's fee is half-up rounded separately, so the batched total fee
can differ from the one-shot fee on the same total released amount by
up to ⌊n/2⌋ cents for n tranches (each rounding moves the fee by at
most half a cent, and the bound is tight — two 10-cent tranches at 250
bps charge 0 cents against a 1-cent one-shot fee, ten 1-cent tranches
at 5000 bps charge 10 cents against a 5-cent one-shot fee). The golden
split happens to be exact, and net conservation still holds exactly
(nets + remaining = gross − fees − credits). Referral credits for the batch land on the
first tranche only, so the total is never double-counted, and credits
with no releases throw instead of being silently dropped. A terminal
report accounts for recorded tranches the same way: a RELEASED report
settles the whole escrow as one cumulative batch — the recorded
tranches plus the still-locked remainder as the final tranche — so the
platform fee is never charged twice on a released slice and the
settlement figures are the lifetime totals (by default the prior
tranches' splits are re-derived at the terminal settlement's rate: the
trail records only the released amounts, not the rate each slice was
reported at — pass priorTrancheSettlements with each tranche's
actual { released, proFeeBps, referralCredits? } to settle each
prior tranche at its own recorded rate instead, with only the
remainder at the terminal rate). A REFUNDED / EXPIRED report refunds
only the still-locked remainder, with the released total shown on the
creator's row as money already paid out (same limitation: the prior
fee split is not recorded, so by default the platform fee portion of
prior tranches is folded into that figure while the sponsor's own
figures stay exact — with priorTrancheSettlements supplied, the
creator row instead shows the tranches' net total and the platform row
their pro-fee total). A supplied split whose amount or count does not
line up with the trail's tranches fails closed instead of settling the
wrong slices. An over-released trail — recorded tranches totalling more than the
deposit, possible only in a hand-built history since dispatch caps
every tranche at the locked balance — fails closed in both branches
instead of settling or refunding a negative remainder.
Reconciliation is the one exception to the full-deposit ledger: a
partially-released report pairs against a ledger row carrying the
released slice, not the deposit (see the reconciliation paragraph
above), so an honest ledger is not misread as a shortfall.
For bookkeeping imports, renderReportCsv(report) renders the same
report as CSV — the machine-readable counterpart to renderReport's
human-readable text, so an importer never has to parse prose lines:
header escrowId,outcome,currency,settlementRef,refundRef,role,inflow,outflow,net, one row per party in
fixed sponsor/creator/platform/referrer order (zero-amount parties
included, never silently absent), amounts at exactly two decimals with
no thousands separators, and a final TOTAL row whose columns are the
sums over the party rows. The currency column carries the report's ISO
4217 code on every row (empty when the report was built without one),
so a multi-currency import can tell USD rows from EUR rows without
re-querying the report. The settlementRef column carries the report's
external payment reference on every row (empty when the report carries
none), so an import can pair the report with the real-world payment
without re-querying it. The refundRef column carries the report's
external refund reference on every row (empty when the report carries
none), so an import can pair a refunded report with the real-world
refund without re-querying it. String fields follow RFC 4180 escaping
(comma/quote/newline fields are quoted, inner quotes doubled), and the
TOTAL row repeats the report's escrowId/outcome/currency/settlementRef/refundRef so imports can group
rows back to their escrow. As with the JSON renderer, the CSV renderer
shape-checks its input first: a non-object report, an empty escrowId,
an illegal outcome, an illegal currency, an illegal settlementRef
(empty, or over MAX_SETTLEMENT_REF_LENGTH characters), an illegal refundRef
(empty, or over MAX_SETTLEMENT_REF_LENGTH characters), an empty parties array, an unknown party role,
or a non-finite party amount throws
cannot render settlement report as CSV: … instead of emitting an
Infinity/NaN row — only the CSV-carried fields are required, so a
parsed SettlementReportCsv still re-renders.
parseSettlementReportCsv(text) is the inverse for the receiving end of
that hop: it parses the header, the four party rows, and the TOTAL row
with an RFC 4180 record parser (quoted fields may carry commas, quotes,
and line breaks), and it cross-checks the document before returning
anything — same escrowId/outcome/currency/settlementRef/refundRef on every row, exactly one row per
party role, every amount a finite two-decimal figure, every party net
equal to its inflow − outflow, and the TOTAL row equal to the sums
over the party rows. Anything else throws
cannot parse settlement report CSV: …. A CSV written before the
settlementRef column existed (7-column header) still parses, with the
ref simply absent, as does a CSV written before the refundRef column
existed (8-column header). The return value is a
SettlementReportCsv: the CSV-carried subset (escrowId, outcome,
currency when the report was built with one, settlementRef when it
carries one, refundRef when it carries one, party ledgers, totals,
balanced), not a full SettlementReport — the
CSV carries no deposit breakdown, settlement parameters, releasePath,
eventCount, or audit window, and the import does not invent them, so
a parsed value re-renders byte-identically through renderReportCsv
(a legacy 7- or 8-column file re-renders in the new 9-column shape)
but must not be read as the original breakdown. As with the JSON import,
this is structural validation only, not a re-verification of the audit
chain.
For programmatic consumers instead of imports, renderReportJson(report)
renders the same report as JSON — JSON.stringify of the report itself,
so it carries exactly the SettlementReport fields (escrowId, outcome,
releasePath when present, settlementRef when present, refundRef when present, deposit breakdown, settlement when present, the
four party ledgers, totals, balanced flag, and audit window) with no field
added, renamed, or dropped. The one deliberate difference from CSV: amounts
stay JSON numbers (10098.5), not two-decimal strings ("10098.50"), so
a bookkeeping API or database gets typed money figures rather than text
to re-parse. A value that is not a report at all — or a money figure that
is not finite — throws cannot render settlement report as JSON: …
instead of serializing (plain JSON.stringify would silently turn
Infinity/NaN into null). parseSettlementReportJson(text) is the
inverse for the receiving end of that hop: it applies exactly the same
shape check in the other direction and throws
cannot parse settlement report JSON: … on unparseable text, a
non-report JSON value, an empty escrowId, an illegal outcome, an
empty parties array, or a non-finite figure, so a report stored with
renderReportJson comes back as a typed SettlementReport that
re-renders byte-identically. The three exports therefore cover three
audiences: renderReport for humans, renderReportCsv for spreadsheet
imports, renderReportJson for APIs and storage — and the import is
structural validation only, not a re-verification of the audit chain:
a hand-built document with consistent fields parses, and chain
verification still belongs to verifyHistoryChain over the escrow's own
history.
npm test runs 3305 tests, including the portfolio's exact fee numbers as a
golden vector (10,000 / 600 / 1.0x / −30 / +60 → 10,630). No network; the
only randomness asserted is that two generated eventIds differ (UUID v4),
everything else is deterministic.
npm run bench measures locally-observed throughput for the hot
paths (3000 timed iterations per op after 200 warmup, printing the Node
version and CPU): hash-chained dispatch, verifyHistoryChain
(over the same detached 4-entry history, with the genesis link —
the first entry's prevHash is GENESIS_PREV_HASH — and every
successor link checked on every iteration, and a detached
tampered copy — the middle SUBMIT_MILESTONE entry gaining a
note it never carried — returning false once, outside the
timed loop),
single-step transition dispatch (benchTransition restoring the
fixed FUNDED snapshot — one FUND entry, the golden 10,630 at the
fixed base instant — on every iteration and dispatching one
SUBMIT_MILESTONE step pinned at BASE + 1s, with the restore
cost inside the timed region because dispatch mutates the
escrow; every iteration checks the one-step advance
FUNDED → MILESTONE_SUBMITTED, exactly one appended entry, and a
gap-free seq continuation, and outside the timed loop an
exhaustive pure-transition() check pins all 8 states × 11
events — the 18 legal edges returning their hand-pinned targets
and every other pair throwing the exact
invalid transition: <event> from <state> message, including
the illegal RELEASE dispatch from FUNDED),
event-sourced replay (Escrow.fromHistory rebuilding a live escrow
from the same detached 4-entry history, full validation and chain
re-verification on every call — with the rebuilt escrow's id, state,
and full history checked entry for entry, hashes included,
field-wise and through the canonical NDJSON serializer, on every
iteration, and a detached tampered copy — the FUND amount altered
from 10,630 to 10,631 — rejected with the hash-chain error once,
outside the timed loop),
release settlement netting (settleRelease over 4 fixed
representative inputs — the golden 10,630 at 500 bps, 1,000 at
500 bps with 100 referral credits, a large gross of 1,000,000 at
250 bps with 1,250.25 credits, and a 10-at-125-bps half-cent
rounding edge — each checked against hand-computed proFee / net
expectations on every iteration),
refund settlement arithmetic (settleRefund over 4 fixed
representative inputs — the golden 10,630, 1,000, a large
1,000,000, and a 0.01 cent edge — each checked on every iteration
for the sponsor receiving the full deposit, creator / platform /
referrer exactly 0, totalOutflow equal to the deposit, and
balanced true, with a negative deposit pinned once outside the
timed loop to throw the exact configuration error),
refund settlement arithmetic in integer cents (settleRefundCents
over 4 fixed representative inputs in whole cents — the golden
1,063,000, 100,000, a large 100,000,000, and a 1-cent edge — each
checked on every iteration for the sponsor receiving the full
deposit, creator / platform / referrer exactly 0,
totalOutflowCents equal to the deposit, and balanced true, with
the dollar settleRefund agreement at exactly ×100 re-checked on
every iteration, and a negative and a fractional depositCents
pinned once outside the timed loop to throw the exact
configuration error),
release settlement netting in integer cents (settleReleaseCents
over 4 fixed representative inputs in whole cents — the golden
1,063,000, 100,000, a large 100,000,000, and a 1,000-at-125-bps
half-cent rounding edge — each checked on every iteration against
hand-computed proFeeCents / netCents expectations, with net
conservation (net + fee + credits = gross, so the still-locked
remainder is exactly 0 on a full release) and the dollar
settleRelease agreement at exactly ×100 re-checked on every
iteration, and the half-up 115-at-5000-bps boundary (fee 58) and the
over-release refusal pinned once outside the timed loop to throw
the exact configuration error),
partial-release settlement netting (settlePartialRelease over
4 fixed representative inputs — the golden 10,630 split in two
tranches, 4,252 of 10,630 then the remaining 6,378 in full, both
at 500 bps, plus a mid-size 500-of-2,000 release with 25 referral
credits and a 10-at-125-bps half-cent rounding edge — each
checked against hand-computed proFee / net / remaining
expectations on every iteration, with the two tranches' fees
summing to the single-release fee 531.50 and their nets to
10,098.50 on every iteration, and released-over-gross plus
negative inputs pinned once outside the timed loop to throw their
exact configuration errors),
cumulative partial-release settlement (settlePartialReleases
over 4 fixed representative batches — the golden 10,630 settled
in one batch [4,252, 6,378] at 500 bps, a mid-size 2,000 batch
with 25 referral credits, a large gross of 1,000,000 at 250 bps
with 1,250.25 credits, and a 10-at-125-bps half-cent rounding
edge — each checked against hand-computed per-tranche proFee /
net / remaining and batch totals on every iteration, with the
golden batch's tranches re-checked against the single
settlePartialRelease helper and its totals against the
single-release split, and the [600, 600]-against-1,000 over-pay
pinned once outside the timed loop to throw the exact cumulative
error),
cumulative partial-release settlement in integer cents
(settlePartialReleasesCents over 4 fixed representative batches
in whole cents — the golden 1,063,000 settled in one batch
[425,200, 637,800] at 500 bps, a mid-size 200,000 batch with
2,500 referral credits, a large gross of 100,000,000 at 250 bps
with 125,025 credits, and ten 1-cent tranches at 5,000 bps — each
checked against hand-computed per-tranche proFee / net / remaining
and batch totals on every iteration, with net conservation
re-checked on every batch, the ten-tranche batch's fee pinned
exactly 5 cents above the one-shot fee on the same 10 cents — the
⌊n/2⌋ divergence bound attained, not just respected — the golden
batch's totals re-checked against the dollar
settlePartialReleases on the same inputs at exactly ×100 (±0¢),
and the [60,000, 60,000]-against-100,000 over-pay pinned once
outside the timed loop to throw the exact cumulative error),
arbitrated-split settlement in integer cents
(settleArbitrationSplitCents over the golden 70/30 split —
gross 1,063,000, creator 744,100 at 500 bps: proFee 37,205,
creator net 706,895, sponsor 318,900, outflow 1,063,000,
balanced — one call per measured op, checked against the
hand-written expectations on every iteration, with the creator
leg re-checked against the independent settlePartialReleaseCents
call on the same amount; the 10,000-credit variant, the half-up
115-at-5000-bps edge, the golden split's agreement with the dollar
settleArbitrationSplit at exactly ×100, and the over-gross
refusal pinned once outside the timed loop),
arbitrated-split settlement in float dollars
(settleArbitrationSplit over the golden 70/30 split — gross
10,630, creator 7,441 at 500 bps: proFee 372.05, creator net
7,068.95, sponsor 3,189, outflow 10,630, balanced — one call per
measured op, checked against the hand-written expectations on
every iteration, with the creator leg re-checked against the
independent settlePartialRelease call on the same amount; the
100-referral-credit variant, the half-up 1.15-at-5000-bps edge
(fee 0.57 here — float dust — versus 58 cents exactly in the
cents twin), the golden split's agreement with the cents
settleArbitrationSplitCents at exactly ×100, and the over-gross
refusal pinned once outside the timed loop),
settlement reconciliation (reconcileSettlements over a fixed
3-report / 3-row fixture — one matched, one report-only, one
amount mismatch, plus one ledger-only row — with the four group
counts (1 / 1 / 1 / 1), the group ids in input order, the
mismatch's report / ledger amounts (10,630 / 10,000), and the
matched outflow total (10,630) checked on every iteration, and a
duplicated ledger id pinned once outside the timed loop to throw
the exact duplicate-ledger error),
snapshot comparison (diffEscrowSnapshots over a fixed pair of
snapshots of one escrow with a long history — FUND 10,630 plus 20
top-ups of 100, then one more top-up and a SUBMIT_MILESTONE step —
with the change-key set (exactly stateChanged + historyAppended),
the FUNDED -> MILESTONE_SUBMITTED transition, and the appended seq
range 22..23 checked on every iteration, and an identical pair
reporting {} plus a rewritten history entry throwing the exact
divergence error pinned once outside the timed loop),
settlement-report comparison (diffSettlementReports over a fixed
pair of reports of one escrow — the golden released report at
500 bps, re-settled at 600 bps: proFee 531.5 -> 637.8, net
10,098.5 -> 9,992.2, gross 10,630 unchanged, creator and platform
nets moving while sponsor / referrer stay untouched — with the
change-key set (exactly settlementChanged + partiesChanged), the
settlement figures and the two moved party nets checked on every
iteration, and an identical pair reporting {} plus a cross-escrow
pair throwing the exact identity error pinned once outside the
timed loop),
batch-summary rendering (renderSettlementReportsSummary over the
fixed batch-4 summary — 3 reports + 1 error: released 2, refunded
1, totals 31,890, UNSPECIFIED currency bucket — with the rendered
text checked byte-for-byte, all 17 lines in order, on every
iteration),
batch-summary CSV rendering (renderSettlementReportsSummaryCsv over
the fixed batch-4 summary — 3 reports + 1 error: released 2,
refunded 1, totals 31,890, UNSPECIFIED currency bucket — with the
rendered CSV checked byte-for-byte, all 11 lines in order, on every
iteration),
batch-summary JSON rendering (renderSettlementReportsSummaryJson
over the same fixed batch-4 summary — with the rendered JSON parsed
back and checked field for field against the hand-pinned batch-4
figures and stringified to the export text itself on every
iteration),
batch-summary comparison (diffSettlementReportsSummaries over a
fixed pair of summaries — the batch-4 summary against the top-up
batch-2 summary: total 4 -> 2, reports 3 -> 2, errors 1 -> 0,
refunded 1 -> 0, totals 31,890 -> 15,630, sponsor / creator /
platform ledgers moving while referrer stays untouched,
UNSPECIFIED bucket 3 -> 2 reports, balanced staying true — with
the change-key set (exactly the eight moved top-level fields plus
partiesChanged and byCurrencyChanged, with totalRemaining and
balanced absent), the moved figures, and the three moved party
ledgers checked on every iteration, and an identical pair reporting
{} pinned once outside the timed loop),
batch-summary CSV parsing (parseSettlementReportsSummaryCsv over
the fixed batch-4 summary — 3 reports + 1 error: released 2,
refunded 1, totals 31,890, UNSPECIFIED currency bucket — with one
measured op rendering the summary to CSV and parsing it back, the
round-tripped summary checked field for field against the
hand-pinned batch-4 figures and re-rendered byte-identically on
every iteration, and a summary-row totalDeposit 1 higher than the
currency buckets' sum pinned once outside the timed loop to throw
the exact import error),
batch-summary JSON parsing (parseSettlementReportsSummaryJson over
the same fixed batch-4 summary — with one measured op rendering the
summary to JSON and parsing it back, the round-tripped summary
checked field for field against the hand-pinned batch-4 figures,
re-rendered byte-identically, and stringified to the export text
itself on every iteration, and a copy with the parties field
removed pinned once outside the timed loop to throw the exact
import error),
buildSettlementReport,
settlement report release path (buildSettlementReport over the
fixed released history — outcome released and releasePath
VERIFY_PASS → RELEASE checked verbatim on every iteration, the
rendered Outcome: released (via VERIFY_PASS → RELEASE) line
pinned once outside the timed loop, a refunded report pinned
outside the timed loop to carry no releasePath field, its
webhook serialization pinned to contain no releasePath key,
and the released webhook's key order pinned to the canonical
order with releasePath between outcome and deposit),
settlement report audit time window (buildSettlementReport over
the same fixed released history — eventCount 4 and
firstEventAt / lastEventAt verbatim
2026-01-01T00:00:00.000Z / 2026-01-01T00:00:03.000Z checked on
every iteration, the rendered
Audit: 4 events, 2026-01-01T00:00:00.000Z → 2026-01-01T00:00:03.000Z
line pinned once outside the timed loop, and the degenerate
empty-history shape — eventCount 0 with no window endpoints at
all, which the public API fail-fasts on by design, so the shape is
pinned via a hand-built report object — pinned to render exactly
Audit: 0 events),
settlement report rendering (renderReport over the fixed golden
released report — deposit 10,630, released via
VERIFY_PASS → RELEASE, 4 party rows — with the rendered text
checked against hand-written expected lines — header / outcome,
the deposit formula line, and the creator net row — on every
iteration),
settlement report rendering — refunded + expired (renderReport
over two fixed non-released reports: the refunded report over a
4-entry FUND/SUBMIT_MILESTONE/DISPUTE/ARBITRATE_REFUND history —
sponsor inflow = outflow = the full deposit, every party net 0,
no releasePath — and the expired report over a 2-entry
FUND/EXPIRE history; both rendered texts checked against
hand-written expected lines — header / outcome, the deposit
formula line, the sponsor and creator rows, the balanced totals
line, and the Audit: window line — with the released-only
oracle-fee note line pinned absent, on every iteration),
settlement report CSV rendering (renderReportCsv over the same
fixed golden released report — deposit 10,630, released via
VERIFY_PASS → RELEASE, 4 party rows — with the rendered CSV
checked against the hand-written 6 lines — header, one row per
party, and the TOTAL row — and the TOTAL columns re-derived from
the party rows on every iteration, with the mismatched-deposit
construction gate pinned once outside the timed loop: a report
whose deposit disagrees with the FUND total recorded in the audit
history is refused before it can reach the renderer),
settlement report JSON rendering (renderReportJson over the same
fixed golden released report — deposit 10,630, released via
VERIFY_PASS → RELEASE, 4 party rows — with the parsed JSON
checked on every iteration against the golden report's amount
fields — escrowId, outcome, releasePath, deposit breakdown, party
ledgers, totals, balanced flag, eventCount — and the creator
inflow pinned as the number 10098.5, not the CSV's two-decimal
text, with a non-finite creator inflow pinned once outside the
timed loop to the exact render error),
settlement report JSON round-trip import
(parseSettlementReportJson over the JSON of the same fixed
golden released report — deposit 10,630, released via
VERIFY_PASS → RELEASE, 4 party rows — with the parsed report
checked on every iteration to deep-equal the golden report and
to re-render byte-identically through renderReportJson, and
outside the timed loop a parties-less copy pinned to the exact
import error and two parses pinned to independent object graphs),
settlement report CSV round-trip import
(parseSettlementReportCsv over the CSV of the same fixed
golden released report — deposit 10,630, released via
VERIFY_PASS → RELEASE, 4 party rows — with the parsed subset
checked on every iteration field for field against the golden
report's CSV-carried fields and re-rendered byte-identically
through renderReportCsv, and outside the timed loop a
TOTAL-mismatched copy pinned to the exact import error and two
parses pinned to independent object graphs),
funded-total summation (depositAmountFromHistory over a fixed
4-shape corpus — a single FUND of the golden 10,630, a two-FUND
top-up sequence summing to 12,630, a FUND recorded without an
amount, and an empty no-FUND history — with the two totals checked
against hand-pinned expectations and both fail-fast shapes checked
against their exact error messages on every iteration),
released-total summation (releasedAmountFromHistory over a fixed
4-shape corpus — a two-tranche release of the golden 10,630 (4,252 +
6,378), a single release of 5,000, a funded escrow with no release at
all, and a PARTIAL_RELEASE recorded without an amount — with the three
totals checked against hand-pinned expectations and the fail-fast shape
checked against its exact error message on every iteration),
buildSettlementReports (batch),
summarizeSettlementReports (batch summary over the batch path's
4 pre-built results — 3 reports + 1 error — aggregating outcome
counts, deposit / inflow / outflow totals, and per-party nets),
buildSettlementWebhooks (batch webhook building over the same
4 pre-built results — 3 signed webhooks with distinct deterministic
eventIds plus the 1 forwarded per-item error, every built webhook
re-verified on every iteration),
settlement webhook build/verify (plus the opt-in Ed25519 pair: one
buildSettlementWebhook signing pass with a pinned signingKey,
checked byte-for-byte against the fixed fixture signature on every
iteration, and one verifySettlementWebhook pass verifying the same
fixed Ed25519-signed webhook twice — a direct publicKey
verification plus a keyResolver lookup for the same keyId — keys
derived once at module load from a pinned 32-byte seed, checked
exactly true on every iteration, with an unknown keyId, a wrong
public key, and a tampered body pinned to false once outside the
timed loop),
Retry-After parsing (parseRetryAfter over a fixed 11-value
corpus — delay-seconds, a fractional value, a whitespace-padded
value, zero, future and past HTTP-dates, signed numbers, a garbage
string, and null / undefined — against one injected fixed instant,
every parsed result checked against hand-pinned expectations on
every iteration), NDJSON
audit-log export/import (historyToNdjson / historyFromNdjson),
quorum approval to threshold (createQuorum approving one
signer at a time with a hasQuorum() check after each vote),
quorum snapshot restore (restoreQuorum rebuilding a live quorum
from a persisted, JSON round-tripped snapshot of the same
9-signer / threshold-5 quorum carrying 7 recorded approvals —
the restart path that strictly re-validates the snapshot's
signer set, threshold, and every audit-trail entry on every
call, self-checked against hand-written expectations on every
iteration),
quorum snapshot export (snapshot() exporting that same
9-signer / threshold-5 quorum carrying 7 recorded approvals —
the checkpoint export an arbitration service pays on every
persist, previously visible only as the restore fixture's
one construction call; the exported envelope is checked
against hand-pinned expectations on every iteration — the
{ v: 1, ... } envelope in its pinned key order, threshold 5,
the 9 signers in config order, no maxApprovalAgeMs key, and
the 7 approval entries in record order with their pinned
canonical timestamps — and outside the timed loop a
detached-copy mutation is pinned to leave a re-export
unchanged and the JSON round-tripped export is pinned to
restore via restoreQuorum into a quorum re-exporting the
restore fixture's persisted snapshot byte-for-byte),
quorum revoke cycle (revoke() on a fresh 5/9 quorum —
approve dao-1..dao-5 to the threshold, revoke dao-3 to drop
to 4/5 below it, then re-approve dao-3 to return to 5/5,
with approvalCount() / hasQuorum() / approvals()
checked against hand-pinned expectations at every stage,
the re-approved signer returning last in approvals()
order because ordering follows each signer's latest
approval, and the unknown-signer / not-approved revoke
rejections pinned to their exact messages once, outside
the timed loop),
quorum approval expiry (the maxApprovalAgeMs counting
views on a fresh 5/9 quorum with a 60-second window on an
advancing injected clock — approvals staggered at BASE,
BASE + 30s, and BASE + 60s, checked while all five count
with dao-1 exactly at the inclusive boundary, then
expiring one at a time as the clock crosses each window,
dao-2 pinned at its own boundary on the way, with
approvalLog() pinned at its full 5 entries throughout
— expiry never deletes — and the two expired signers
re-approving to restore the quorum with the log grown to
7; the fully-expired log retention and the re-approval's
fresh timestamp are pinned once, outside the timed loop),
quorum remainingApprovals (remainingApprovals() reading the
"votes to go" on a fixed pinned 2-of-3 quorum with one vote
in — pinned to 1 on every iteration, with the pure-read
shape (two reads agreeing and the approval log byte-identical
before and after a call) and the threshold-reached 0, the
past-threshold still-0, the revoke-raises-it-again step, and
the fresh-quorum full-threshold read pinned once outside the
timed loop),
settlement webhook fan-out delivery (deliverSettlementWebhookToMany
to 4 endpoints through a fake global fetch — zero network, so the
number measures fan-out overhead only),
settlement webhook fan-out per-endpoint timeoutMs override
(deliverSettlementWebhookToMany to 3 endpoints — one hanging
under a pinned 10 ms per-endpoint timeoutMs override, the
other two answering 200 immediately under the call-level
5000 ms — with result order, the pinned timeout text, and the
normal success shapes checked on every iteration, and the
illegal-0 override and no-override shapes pinned once,
outside the timed loop),
settlement webhook single-target delivery (deliverSettlementWebhook
to 1 fixed endpoint through a fake global fetch answering 200
immediately — zero network, backoffMs 0 — with the result
{ status: 200, attempts: 1 }, exactly one captured call, and the
captured X-Signature checked against the buildSettlementWebhook
signature and verified over the captured body on every iteration,
and a persistent-500 retry-exhaustion error — failed after
3 attempts at retries 2 — pinned once, outside the timed loop),
settlement event dedupe
(SettlementEventDedupe.checkAndRecord duplicate hits cycling over
1,000 pre-recorded eventIds under a fixed injected clock),
settlement event dedupe read-only probe
(SettlementEventDedupe.has probing a live hit, an unseen id, and an
id read exactly one TTL after its first sighting in rotation over a
fixed capacity-3 dedupe with 2 pre-recorded eventIds under a fixed
injected clock, self-checked per iteration for the verdict, with
non-consumption and unmoved stats pinned outside the timed loop),
settlement event dedupe snapshot restore
(SettlementEventDedupe.restore rebuilding a receiver-side dedupe
from a persisted, JSON round-tripped snapshot of 1,000 entries
under the same fixed clock — all entries live at load under the
default TTL and capacity, the observability counters restarting
at zero; the restored ids are checked exhaustively once outside
the timed loop — all 1,000 judged duplicates, an unseen id keeping
first-sighting semantics — and spot-checked (first / middle /
last) on every iteration),
settlement event dedupe snapshot export
(SettlementEventDedupe.exportSnapshot exporting a receiver-side
dedupe holding 1,001 recorded ids — 1,000 live ids plus one entry
aged exactly to its TTL boundary, so it is excluded — under a
stepped fixed injected clock; the exported snapshot is checked
entry for entry against hand-pinned expectations on every
iteration, and a detached-copy mutation plus the empty-store
export — exactly { v: 1, entries: [] } — are pinned once,
outside the timed loop),
settlement event dedupe clear
(SettlementEventDedupe.clear resetting a receiver-side dedupe
holding 1,000 recorded ids under a fixed injected clock — the
fixture is rebuilt on every iteration because clear() mutates
the store, so the reported numbers include the rebuild cost,
prefill plus clear; the size and every observability counter
are pinned at zero right after the clear and the first id is
pinned to record as a new event again, with the counters
re-accumulating from zero, on every iteration, and clearing an
empty dedupe is pinned as a harmless no-op once, outside the
timed loop),
settlement event dedupe stats
(SettlementEventDedupe.stats reading the observability
snapshot of a fixed dedupe on every iteration — 7 ids recorded
under an injectable clock that advances only while the fixture
is built, with a 60-second TTL and a capacity of 6: one id is
LRU-evicted during construction, one id sits expired in the
map at the stats instant, and 5 ids are live; its
per-iteration self-check pins the snapshot to the hand-written
expectation — { size: 5, hits: 1, misses: 7, evictions: 1 },
size counting only the live ids, so the expired id still
sitting in the map is excluded — and outside the timed loop a
mutated detached snapshot is pinned to leave a re-read
unchanged and an empty dedupe is pinned to report all-zero
stats),
settlement webhook outbox
(SettlementWebhookOutbox.recordAttempt recording one failure
per fresh (endpoint, eventId) pair under a fixed injected
clock — maxAttempts: 3, so the dead-letter boundary is the
third consecutive failure — with the ledger size pinned to the
hand-counted total on every iteration; one pair driven through
the 3-failure dead-letter boundary on a fresh outbox on every
iteration, the rebuild cost inside the timed region, the same
accounting the dedupe-clear row uses; pending() /
deadLetter() over a fixed 1,000-pair ledger — 700 pending
(350 at 1 attempt, 350 at 2), 300 dead-lettered at 3 — with the
pinned attempts / error / timestamp spot-checked on every
iteration; acknowledge clearing a pending pair at 2 failures
on a fresh outbox on every iteration, again with the rebuild
cost inside the timed region; stats() reading the observability
snapshot of a fixed 3-pair ledger — 2 pending at 1 and 2 attempts,
1 dead-lettered at 3, one acknowledged pair cleared — pinned to
{ size: 3, pending: 2, deadLettered: 1, totalAttempts: 6 } on every
iteration, with the pure-read shape (the pending / dead-letter lists
byte-identical before and after the call, a mutated detached snapshot
leaving a re-read unchanged, an empty outbox reporting all-zero stats)
and the redrive step to { size: 3, pending: 3, deadLettered: 0, totalAttempts: 3 } pinned once outside the timed loop;
exportSnapshot exporting that
same 1,000-pair ledger and restore rebuilding it from its
JSON round-tripped form, the restored lists checked against the
hand-written composition on every iteration; redrive moving one dead-lettered pair (3 failures, the settled report's own webhook event) back to pending at a fixed later clock and re-delivering its signed webhook through a fake fetch that answers 200 on the first attempt, the success clearing the pair so the ledger ends pending 0, dead letter 0, with the redriven shape and the delivered body and signature pinned on every iteration; retrySettlementWebhookOutbox re-delivering three pending pairs (one recorded 500 failure each) through a stub that answers 500 on a pair's first re-delivery and 200 on its second, with maxRounds: 2, backoffMs: 0, jitterMs: 0, the summary pinned to attempted 6, acknowledged 3, still pending 0, dead letter 0, and the stub's six calls in order, on every iteration, with a dryRun: true rehearsal and a dead letter that is never re-delivered pinned once outside the timed loop; the full
entry-for-entry ledger comparison, the detached-copy and
empty-store export shapes, the restore-keeps-counting shape,
the maxAttempts: 1 boundary re-derivation, and the 7 malformed
snapshots pinned to be rejected by restore all once, outside
the timed loop),
signed-snapshot envelopes
(exportSignedSnapshot / restoreSignedSnapshot on all three
HMAC-SHA256 signed snapshot envelopes — SettlementEventDedupe
#1010, Escrow #1017, SettlementWebhookOutbox #1030 — six
rows over the fixtures the unsigned snapshot rows already pin:
the dedupe exports / restores its fixed 1,000-entry snapshot
(ids bench-restore-0000 .. bench-restore-0999 under the fixed
restore clock), the escrow exports / restores the fixed BENCH-001
FUND -> RELEASED 4-entry chain, and the outbox exports / restores
its fixed 1,000-pair ledger (700 pending, 300 dead-lettered);
the restore rows run through the JSON round-tripped envelope on
every iteration — the persisted form a process reloads at startup
— and every per-iteration self-check pins the restored state
against the hand-written composition (dedupe size 1,000 with the
first / middle / last ids still duplicates, escrow id / state /
4-entry history entry for entry through the canonical NDJSON
serializer, outbox size / pending / dead-letter counts with their
pinned attempts / error / timestamp); outside the timed loop,
each signed envelope's snapshot is pinned byte-identical to its
unsigned snapshot, and a tampered envelope and a wrong secret are
pinned to be rejected by each restoreSignedSnapshot with the
MAC-mismatch error while a previously restored instance keeps its
state — this is the restart cost a gateway pays for
tamper-evident persistence, the canonical-JSON + HMAC overhead
over the unsigned snapshot rows),
settlement webhook verify x dedupe receiver flow
(verifySettlementWebhook + SettlementEventDedupe.checkAndRecord
over the fixed signed webhook — one measured op is three
deliveries: a first sighting that verifies and records as new, a
redelivery that verifies again but reports duplicate, and a
tampered body that fails verification and never reaches the dedupe
step, proven by the tampered delivery's claimed id still recording
as new afterwards; the verify step reuses the fixed signed webhook,
the dedupe step uses per-iteration synthetic ids standing in for
payload.eventId), and
watchdog screening (expiredEscrows / staleEscrows over one fixed
mixed batch of 100 escrows at a fixed screening instant — 40
hand-counted past-deadline non-terminal escrows, 70 hand-counted stale
under FUNDED 7d / MILESTONE_SUBMITTED 30d budgets — with every
screening result checked against the hand-counted expected id list on
every iteration), plus stuck-escrow screening (stuckEscrows over a
second fixed mixed batch of 40 escrows at the same instant — 10
hand-counted stuck DISPUTED, 25 expirable-overdue, 5 not yet overdue —
checked the same way, with the stuck + expirable-overdue partition of
the expired selection pinned once outside the timed loop), and
watchdog execution (expireOverdueEscrows /
actOnStaleEscrows with an EXPIRE-dispatch action over fresh
rebuilds of that same 100-escrow batch on every iteration, because
the executors mutate their inputs — 40 of 40 expire attempts and
70 of 70 stale actions succeed, since both selected states carry
an EXPIRE edge — with result ids, success flags, post-states,
and the appended EXPIRE audit entries checked against the
hand-counted expectations on every iteration; the expire row
additionally checks each successful result's entry against that
escrow's history last entry field for field (seq/event/from/to/at),
so the cited audit record cannot drift from the history itself;
the fresh-fixture
rebuild cost is inside these two rows' timed region, unlike the
pure screening rows above), and
allowed-events lookup (allowedEvents over all 8 states of the
transition table — one pass queries every state once in
declaration order, CREATED through EXPIRED, with each result
checked against its hand-pinned expected event list in
declaration order and the three terminal states — RELEASED,
REFUNDED, EXPIRED — expecting the empty list — on every
iteration), and
fee calculation (calculateDeposit over a fixed 3-shape corpus —
the golden vector (pool 10,000 / base 600 / complexity 1.0 /
loyalty 30 / oracle 60 → deposit 10,630), a complexity-1.5 case
(pool 5,000 / base 800 / loyalty 50 / oracle 40 → adjusted 1,200,
deposit 6,190), and a large-pool case (pool 1,000,000 / base
2,500 / complexity 2.25 / loyalty 500 / oracle 250 → adjusted
5,625, deposit 1,005,375) — with each returned adjustedBaseFee
and deposit checked against hand-computed expectations on
every iteration), and
integer-cents fee calculation (calculateDepositCents over the
exact cents mirror of the same 3-shape corpus — the golden vector
in cents (pool 1,000,000 / base 60,000 / complexity 1.0 / loyalty
3,000 / oracle 6,000 → deposit 1,063,000), a complexity-1.5 case
(pool 500,000 / base 80,000 / loyalty 5,000 / oracle 4,000 →
adjusted 120,000, deposit 619,000), and a large-pool case (pool
100,000,000 / base 250,000 / complexity 2.25 / loyalty 50,000 /
oracle 25,000 → adjusted 562,500, deposit 100,537,500) — with
each returned adjustedBaseFeeCents and depositCents checked
against hand-computed expectations on every iteration, and the
±0¢ agreement with calculateDeposit on the same inputs pinned
once, outside the timed loop), and
arbitration dispatch (dispatchArbitration with outcome
"refund" over a DISPUTED escrow rebuilt from its fixed 2-entry
history prefix via Escrow.fromHistory and a threshold-reached
5/9 quorum rebuilt via createQuorum on every iteration,
because the dispatch mutates the escrow — the rebuild cost is
inside this row's timed region, so the number is a conservative
lower bound on the dispatch-only throughput, the same accounting
the watchdog-execution rows use; the dispatch is pinned to a
fixed audit timestamp, and every iteration checks the REFUNDED
terminal state, exactly one appended ARBITRATE_REFUND entry,
and its quorum 5/5 [dao-1, dao-2, dao-3, dao-4, dao-5] note), and
deadline judgement (isOverdue over a fixed 4-case corpus — a
past-deadline FUNDED escrow, a future-deadline FUNDED escrow, a
deadline-less FUNDED escrow, and a past-deadline terminal
RELEASED escrow — judged against one injected fixed instant,
never the wall clock, with each result checked against its
hand-pinned boolean — true / false / false / false — on every
iteration), and
deadline write cycle (setDeadline + clearDeadline on one
shared FUNDED escrow — set via a Date to 2026-01-31 and read
back pinned, overwritten via a string to 2026-05-01 and read
back pinned, then cleared to undefined so the escrow returns
to its initial deadline-less state for the next iteration, with
state and history checked unchanged on every iteration — a
deadline write is configuration, not a dispatch — and, outside
the timed loop, illegal inputs pinned to their exact
invalid deadline: ... messages and to leaving any stored
value untouched, a non-canonical input pinned to its
normalized canonical form, and a terminal RELEASED probe
pinned to store a past deadline yet never judge overdue), and
money guard (assertNonNegativeMoney over a fixed legal corpus —
0, 0.01, the golden 10,630, and 1,000,000.25 — with the whole
corpus checked to pass without throwing on every iteration; only
the legal branch is timed, while the illegal branch — a negative,
NaN, ±Infinity, a numeric string, undefined, and null, each
throwing the exact amount must be a finite non-negative number
message — is asserted once, outside the timed loop, never timed), and
transition-table JSON export (transitionTableJson with no
arguments — the canonical JSON form in declaration order with
2-space indent and a single trailing newline — parsed back on
every iteration and checked against hand-pinned expectations:
18 edges, the first edge CREATED → FUNDED via FUND, the release
edge VERIFIED → RELEASED via RELEASE at index 12, the last edge
DISPUTED → RELEASED via ARBITRATE_SPLIT, and every edge's keys
in from / event / to order), and
transition-table pure object construction (transitionTable with
no arguments — the plain-object edge list in declaration order,
without any serialization, that the JSON export and the diagram
both derive from — checked on every iteration against hand-pinned
expectations: all 18 edges written out in full in declaration
order with every edge's keys in from / event / to order,
spot-checked against the transitionTableJson edge set through
the shared pinned first / release (index 12) / last edges, and
outside the timed loop compared edge for edge to the parsed JSON
edge set with a hand-pinned non-existent edge
CREATED → RELEASED via RELEASE confirmed absent from both), and
state diagram generation (stateDiagram with no arguments —
the fenced Mermaid stateDiagram-v2 block the README embeds
verbatim — checked on every iteration against hand-pinned
expectations: 25 lines in total, all 18 edge lines written out
in full in declaration order, the start line pinning CREATED,
the 3 terminal lines RELEASED / REFUNDED / EXPIRED, and all 8
declared states present as an edge source or target), and
readme diagram sync check (readmeDiagramInSync with no
arguments — reads only this repo's README, regenerates the
diagram from the transition table, and checks the exact
generated block is embedded — checked on every iteration
against the hand-pinned expectation true, the same
expectation the diagram tests and the diagram CLI --check
pin; file reading is limited to this repo's README), and
dispatch subscription notification (subscribe with 1 fixed
collecting listener on a fresh escrow driven through the same
full CREATED → RELEASED lifecycle — 4 dispatches + 4
notifications per pass — with the notification sequence checked
against hand-written (event, from, to) expectations and the
escrow's own history entry for entry on every iteration, and
unsubscribe and throwing-listener isolation checks outside
the timed loop), and
subscribe onError error routing (subscribe with 1 pinned
throwing listener and a collecting onError on a fresh escrow
driven through a fixed short chain — FUND, SUBMIT_MILESTONE,
VERIFY_PASS to VERIFIED; 3 dispatches + 3 error reports per
pass — with every dispatch checked successful, the history
checked at exactly 3 entries, and the reports checked against
hand-pinned expectations report for report — pinned message
plus event / from / to context, the first report's context
included — on every iteration, and a throwing-onError
probe and the non-function onError rejection pinned to its
exact message outside the timed loop), and
snapshot round-trip (Escrow.fromJSON restoring the fixed
toJSON() snapshot of the same full-lifecycle escrow carrying
a fixed deadline — 2026-01-31T00:00:00.000Z, BASE + 30 days —
with the restored id, state, and deadline and the full history
checked entry for entry — hash chain included — and a
re-export checked identical to the source snapshot on every
iteration, and the serialized snapshot text restored unchanged
after a JSON parse/stringify round-trip once, outside the
timed loop), and
policy snapshot round-trip (Escrow.fromJSON restoring a fixed
policy-carrying escrow — BENCH-1231, rolePolicy
{ DISPUTE: ["moderator"] } and maxDeposit 12,000, driven FUND
of the golden 10,630 at BASE, SUBMIT_MILESTONE at BASE + 1s,
PARTIAL_RELEASE of 1,000 at BASE + 2s back to FUNDED, deadline
2026-01-31T00:00:00.000Z — with the restored id, state, and
deadline and the full history checked entry for entry — hash
chain included — the envelope's rolePolicy byte-identical to the
pinned object and maxDeposit exactly 12,000, and a re-export
checked identical to the source snapshot on every iteration, and
outside the timed loop an unauthorized actor on DISPUTE pinned to
throw the exact actor not authorized for DISPUTE: "intruder" is not in [moderator] error and an over-cap FUND of 3,000 pinned to
throw the exact deposit cap exceeded: locked 9630 + new funding 3000 would exceed maxDeposit 12000 error, both leaving state and
history unchanged), and
standalone history parsing (parseEscrowHistory over the
JSON-serialized text of the same fixed 4-entry RELEASED history
— the text is parsed back and validated standalone, with no
Escrow instance, on every iteration, the parsed entries
checked entry for entry against the original history — hash /
prevHash chain included, field-wise and through the canonical
NDJSON serializer — and a detached tampered text — the middle
SUBMIT_MILESTONE entry's note rewritten and re-serialized —
rejected with the exact hash-chain error once, outside the
timed loop, the original text still parsing afterwards), and
verify-evidence gate dispatch (dispatch("VERIFY_PASS") on a
fresh strict escrow — requireVerifyEvidence: true — rebuilt
on every iteration because dispatch mutates it, driven
FUND → SUBMIT_MILESTONE on fixed timestamps and then verified
with the pinned evidence reference, with the VERIFIED state,
the exactly-one-entry history growth (2 → 3), and the evidence
recorded verbatim on the appended entry checked on every
iteration, and outside the timed loop an evidence-free
VERIFY_PASS pinned to throw the exact gate error and to leave
state and history unchanged entry for entry before the same
escrow passes with evidence, a default escrow pinned to keep
the pre-gate evidence-free behavior with no evidence field on
its entry, and a non-boolean flag value pinned to its exact
constructor configuration error; the library records the
caller's evidence reference — it does not verify the oracle
attestation behind it), and
deposit-cap funding (dispatch("FUND") twice on a fresh
escrow — maxDeposit: 10630, the golden deposit as the cap —
rebuilt on every iteration because dispatch mutates it,
funded 7,000 at BASE and topped up 3,630 at BASE + 1s so the
locked total lands exactly on the cap, with the FUNDED
state, the exactly-two-entry history, and the two pinned
amounts summing to the cap checked on every iteration, and
outside the timed loop a one-cent-over FUND pinned to throw
the exact deposit cap exceeded: locked 10630 + new funding 0.01 would exceed maxDeposit 10630 error and to leave state
and history unchanged entry for entry, a FUND without an
amount pinned to stay uncapped even at the cap — it carries
no money and contributes nothing to the locked total — and
an escrow without the option pinned to keep the pre-cap
behavior), and
state-visit-budget dispatch (dispatch() on a fresh escrow —
maxVisitsByState: { FUNDED: 2 } — rebuilt on every iteration
because dispatch mutates it, funded 10,000 at BASE and driven
through one milestone round — SUBMIT_MILESTONE at BASE + 1s and
PARTIAL_RELEASE of 100 at BASE + 2s back to FUNDED — with the
FUNDED state, visitCount("FUNDED") stepping to 2, and the three
pinned history entries checked on every iteration, and outside
the timed loop a second round's PARTIAL_RELEASE pinned to throw
the exact state visit budget exhausted: FUNDED already visited 2 of 2 times error and to leave state and history unchanged entry
for entry, an escrow without the budget pinned to run three rounds
unimpeded (FUNDED visited 4 times, history 7 entries), and a
toJSON()/fromJSON() round-trip pinned to keep the budget and
the used count so the restored escrow still refuses the third
re-entry with the same error and no trace), and
state-visit-budget remaining read (remainingVisits(state) on
the same fixed budgeted escrow the visit-budget row drives —
maxVisitsByState: { FUNDED: 2 }, funded 10,000 at BASE and
driven through one milestone round so FUNDED is visited 2 of 2 —
with remainingVisits("FUNDED") pinned to 0 and
remainingVisits("MILESTONE_SUBMITTED") pinned to Infinity for
the unbudgeted state on every iteration, and outside the timed
loop the remaining pinned to step down 2 → 1 → 0 as the visits
are spent with visitCount in lockstep, the next re-entry at 0
pinned to throw the exact state visit budget exhausted: FUNDED already visited 2 of 2 times error and to leave the remaining
at 0 with state and history unchanged entry for entry, an
escrow without the budget pinned to read Infinity for FUNDED
even after three milestone rounds (visitCount 4), a budget of 1
on the already-passed CREATED state pinned to read 0 at
construction, and a toJSON()/fromJSON() round-trip pinned to
keep the budget and the used count so the restored escrow still
reads 0 and refuses the third re-entry with the same error), and
optimistic-concurrency dispatch (dispatch("VERIFY_PASS") with
expectedSeq: 2 on a fresh escrow — rebuilt on every iteration
because dispatch mutates it, driven FUND → SUBMIT_MILESTONE on
fixed timestamps so the history holds exactly two entries — then
verified under the guard, with the VERIFIED state, the
exactly-one-entry history growth (2 → 3), and the appended entry
checked field for field on every iteration, and outside the
timed loop a stale expectedSeq pinned to throw the exact
dispatch conflict: expected seq 1 but escrow is at seq 2 error
and to leave state and history unchanged entry for entry, an
empty-history escrow pinned to advance with expectedSeq: 0,
illegal values (-1 and 1.5) pinned to their exact
invalid dispatch options: … configuration errors, and a
guard-free dispatch pinned to keep the pre-guard behavior), and
idempotency-key dispatch (dispatch with idempotencyKey on a
fresh escrow — rebuilt on every iteration because dispatch
mutates it — FUND of the golden 10,630 with a fresh key k1 at
BASE, the same FUND with k1 again returning the same state as a
pure no-op with the history untouched at exactly 1 entry, then
SUBMIT_MILESTONE with a fresh key k2 at BASE + 1s, with both k1
dispatches returning FUNDED, no seq advance on the hit, a
history of exactly 2 entries, the pinned SUBMIT_MILESTONE entry
checked field for field, and the hash chain verified on every
iteration, and outside the timed loop a cross-event key reuse —
a SUBMIT_MILESTONE reusing the FUND key — pinned to the same
no-op, and a failed (negative-amount) dispatch pinned to
consume no key so the same key retries successfully; the dedupe
lookup the webhook-driven dispatcher pays on every delivery,
hit or miss), and
settlement webhook timeout delivery (deliverSettlementWebhook
with timeoutMs: 10 and retries: 0 over the fixed webhook
through a hanging fake global fetch — the fake only ever
rejects when its request signal aborts, so the pinned short
timeout is the only thing that can end the attempt — with the
rejection checked on every iteration for the exact
webhook delivery to … failed after 1 attempt: webhook delivery timed out after 10ms error, the annotated attempt count 1, and
exactly one fetch call, and outside the timed loop an illegal
timeoutMs of 0 pinned to throw the exact
cannot deliver settlement webhook: timeoutMs must be a positive number, got 0 configuration error before any request at zero
fetch calls, and a generous timeoutMs of 5000 over an
immediate 200 pinned to the normal { status: 200, attempts: 1 }
success shape after exactly one fetch; the timeout wait itself
is the object under test at the pinned short 10 ms — no
elapsed-time assertion is made).
Fixtures are deterministic — one escrow driven through the full
CREATED → RELEASED lifecycle (4 hash-chained audit entries, golden
deposit 10,630), with a fixed webhook secret, payload timestamp, and
eventId; the batch path runs one fixed batch of 4 inputs
(released / refunded / released, each a 4-entry history, plus one
deliberately mismatched input that must land as a per-item error);
the NDJSON paths use a second fixed history of 8 chained
entries (the golden deposit funded in five staged FUND dispatches,
then milestone, verification, and release); the quorum path uses a
fixed 9-signer set with threshold 5 on a fixed injected clock; the
restore path reuses that shape, snapshotting a quorum with 7
approvals (dao-1..dao-7, one second apart on a stepped fixed
clock) and restoring the JSON round-tripped snapshot; the
quorum snapshot-export path reuses that same 7-approval
source quorum on every iteration, because snapshot() is
pure; the
quorum-revoke path reuses that shape on a fresh quorum per
iteration, revoking dao-3 below the threshold and
re-approving it; the dedupe
restore path restores a JSON round-tripped snapshot of 1,000 fixed
ids (bench-restore-0000..bench-restore-0999, all first seen at
the restore instant on a fixed clock) under the default TTL and
capacity; the
dedupe export path reuses a stepped fixed clock to record one
entry exactly one TTL before its 1,000 live ids
(bench-export-0000..bench-export-0999, all first seen at the
export instant), so the boundary-aged entry is excluded from the
export; the
watchdog paths screen one fixed batch of 100 escrows (30 past-deadline
FUNDED, 20 in-budget-deadline FUNDED, 10 fresh FUNDED, 10
past-deadline MILESTONE_SUBMITTED, 10 fresh MILESTONE_SUBMITTED, 10
terminal RELEASED with a past deadline, and 10 deadline-less FUNDED);
the watchdog execution paths rebuild that same batch fresh on every
iteration (the executors dispatch EXPIRE and append audit entries,
so no batch can be reused); the
allowed-events path needs no fixture beyond the transition table
itself — all 8 states in declaration order with hand-pinned
expected event lists; the
fee-calculation path needs no fixture beyond its 3 fixed input
shapes with hand-computed expectations; the
arbitration path rebuilds its DISPUTED escrow (FUND 10,630, then
DISPUTE, on the fixed clock) from the detached 2-entry prefix and
its 5/9 quorum from scratch on every iteration; the
deadline-judgement path reuses its 4 fixed escrows on every
iteration, because isOverdue is pure; the
deadline-write-cycle path reuses its one shared FUNDED escrow
on every iteration, because every cycle ends cleared back to
its initial deadline-less state; the
money-guard path needs no fixture beyond its two fixed corpora
(the legal values timed, the illegal values asserted once
outside the timed loop); the
transition-table-JSON path needs no fixture beyond the transition
table itself — its expectations are hand-pinned from the committed
snapshot; the
transition-table pure-construction path likewise needs no fixture
beyond the transition table itself — its expectations are
hand-pinned from the same committed snapshot, written out in full,
and its exhaustive JSON-consistency and absent-edge checks run
once outside the timed loop; the
state-diagram path likewise needs no fixture beyond the transition
table itself — its expectations are hand-pinned from the same
committed snapshot and the diagram tests.
the readme-diagram-sync path needs no fixture beyond this
repo's README itself — its expectation is hand-pinned true
from the diagram tests, and its file reading is limited to
that README;
the subscribe path rebuilds its escrow fresh on every
iteration (one fixed collecting listener subscribed before
any dispatch), because dispatch mutates the escrow;
the subscribe onError path likewise rebuilds its escrow
fresh on every iteration (one pinned throwing listener with
a collecting onError, driven through a fixed 3-dispatch
short chain), because dispatch mutates the escrow;
the snapshot path exports its snapshot once from the same
full-lifecycle escrow plus the fixed deadline above (the
envelope is exactly v 1 / BENCH-001 / RELEASED / 4 entries /
that deadline, with no idempotency-key or role-policy field),
and the timed loop restores that one snapshot on every
iteration;
the standalone-history-parsing path reuses that same history's
serialized JSON text on every iteration (the parser returns
detached copies, so no iteration can mutate the fixture);
the single-step transition path restores its fixed FUNDED
snapshot (one FUND entry, the golden 10,630 at the base
instant) on every iteration, because the one dispatched step
mutates the restored escrow.
the verify-evidence path rebuilds its strict escrow fresh on
every iteration (FUND of the golden 10,630 at BASE,
SUBMIT_MILESTONE at BASE + 1s, VERIFY_PASS with the pinned
evidence reference at BASE + 2s), because the gated dispatch
mutates the escrow;
the deposit-cap path rebuilds its capped escrow fresh on
every iteration (FUND 7,000 at BASE, top-up 3,630 at
BASE + 1s, cap 10,630), because dispatch mutates the
escrow;
the optimistic-concurrency path rebuilds its guarded escrow
fresh on every iteration (FUND of the golden 10,630 at BASE,
SUBMIT_MILESTONE at BASE + 1s, VERIFY_PASS with
expectedSeq: 2 at BASE + 2s), because dispatch mutates
the escrow.
the timeout path reuses the same signed webhook on every
iteration (its hanging fake fetch holds no state beyond the
call count, reset at the start of every run).
the fan-out timeout-override path pins per-endpoint
timeoutMs resolution (endpoint.timeoutMs ?? opts.timeoutMs)
on every iteration — the overridden endpoint fails alone
while the others succeed — with the illegal-0 override and
no-override shapes pinned once, outside the timed loop.
the releasePath path reuses the same released history on
every iteration (its refunded probe and webhook key-order
The new dispatch rolePolicy row measures the
gated-arbitration dispatch a webhook-driven dispatcher
actually pays: a fresh DISPUTED escrow with
ARBITRATE_RELEASE allowlisted to moderator, rebuilt on
every iteration, with a contributor dispatch rejected
(history untouched at 2 entries) and a moderator dispatch
advancing to RELEASED with one pinned entry and an intact
hash chain.
The new deliverSettlementWebhookToMany fan-out limits row
measures the #630 guards as a cost path: every iteration runs
both halves — a 3-endpoint batch under maxEndpoints: 2
throws the pinned cap error before any request (0 fetch calls),
and a fast + hanging pair under a bench-local
overallDeadlineMs: 50 (10,000 ms per-attempt timeout, retries
0) keeps the fast result while the hanging endpoint reports the
pinned deadline error after exactly 1 attempt, aggregate delivered
1 / failed 1 with deadlineExceeded: true. The 50 ms value is
bench-local (the fake fetch answers in microseconds, so it still
proves the deadline — not the per-attempt timeout — stops the
call, without adding ~5 minutes of pure waiting to the
3,000-iteration loop); the 100 ms semantics are pinned by the
#630 unit tests and the #649 demo segment. Outside the timed
loop, an invalid maxEndpoints: 0 is pinned to the exact
configuration error with zero fetch calls, and a cap-equal
2-endpoint batch is pinned to deliver both with
deadlineExceeded: false.
The new deliverSettlementWebhook loopback header-check row
measures the #567/#576 delivery-header contract as a cost path:
every iteration delivers the fixed signed webhook to a real
loopback server with a 500-then-200 script (retries 1, backoffMs
0) and pins both attempts' X-Event-Id and Idempotency-Key
equal to the body eventId and identical across the retry, with
the signed body and X-Signature unchanged. Outside the timed
loop, a forged header value is pinned not to break body
verification (headers are transport hints, not signature-covered)
and a body with a mutated eventId is pinned to fail
verification.
The new deliverSettlementWebhook jitterMs backoff row
measures the #665 jitter option as a cost path: every timed
pass runs two deliveries over a fake fetch answering 500, 500,
200 (backoffMs 100, retries 2) — the jittered delivery, whose
two backoff waits must land inside [100, 1100] and [200, 1200]
(the exponential bases 100 and 200 plus a uniform
Math.random() * 1000 spread), and the zero-jitter control,
whose waits must be exactly [100, 200]. The delivery layer
exposes no sleep injection, so the waits are recorded by a
setTimeout wrapper installed for each delivery only (the same
technique the #679 demo segment uses): it keeps only timers
created inside sleepAbortable and shortens those timers to
0 ms, so the row measures delivery logic, not a wall-clock
backoff, and the wrapper is restored after every delivery.
Outside the timed loop, a stubbed Math.random sequence
[0, 0.5] pins the jittered waits to exactly [100, 700] and the
zero-jitter waits to exactly [100, 200], and the stub's restore
is asserted.
The new deliverSettlementWebhookToMany fan-out jitterMs row
measures the #665 jitter option crossed with fan-out as a cost
path: every timed pass runs two fan-outs to 4 endpoints — one
flaky endpoint on a 500, 500, 200 script plus three endpoints
answering 200 immediately (backoffMs 100, retries 2) — the
jittered fan-out, whose only two backoff waits (the flaky
endpoint's, the healthy endpoints never sleep) must land inside
[100, 1100] and [200, 1200], and the zero-jitter control, whose
waits must be exactly [100, 200]. Every timed iteration also
pins the aggregate (delivered 4 / failed 0), per-endpoint results
in input order (flaky attempts 3 / status 200, healthy attempts
1 / status 200), per-endpoint fetch call counts (3 / 1 / 1 / 1),
and that each endpoint's copy verifies under its own secret. The
waits are recorded with the same setTimeout wrapper as the
single-target jitter row (only timers created inside
sleepAbortable count, shortened to 0 ms, wrapper restored after
every fan-out), so the row measures fan-out + jitter logic, not a
wall-clock backoff. Outside the timed loop, a stubbed
Math.random sequence [0, 0.5] pins the jittered waits to exactly
[100, 700] and the zero-jitter waits to exactly [100, 200], and
the stub's restore is asserted.
The new deliverSettlementWebhookToMany fan-out maxRetryDelayMs row
measures the #716 combination as a cost path: every timed pass runs
one fan-out to 4 endpoints under a call-level maxRetryDelayMs of
50 — one endpoint answering 429 with a one-year
Retry-After: 31536000 hint on its first attempt and 200 on the
retry, plus three endpoints answering 200 immediately — pinning the
aggregate (delivered 4 / failed 0), per-endpoint results in input
order (hinted attempts 2 / status 200, healthy attempts 1 / status
200), per-endpoint fetch call counts (2 / 1 / 1 / 1), and exactly
one recorded backoff wait equal to the 50 ms cap. The wait is
recorded with the same setTimeout wrapper as the jitter rows
(only timers created inside sleepAbortable count, shortened to
0 ms, wrapper restored after every fan-out), so the row measures
fan-out + clamp logic, not a wall-clock backoff.
The new dispatchArbitration rolePolicy row measures the #719 combination as a cost path: every timed iteration rebuilds a DISPUTED escrow via Escrow.fromHistory from its fixed 2-entry prefix with ARBITRATE_RELEASE allowlisted to moderator installed through the fromHistory opts (a bare history carries no policy, so the opts are the only source) plus a threshold-reached 5/9 quorum, then pins a contributor arbitration dispatch rejected with the exact actor-not-authorized error leaving state, history, and quorum count untouched, and a moderator arbitration dispatch advancing to RELEASED with one pinned entry and an intact hash chain. Outside the timed loop, a below-threshold quorum with an unauthorized actor is pinned to the quorum error, never the policy error, proving the quorum gate runs first.
The new verifySettlementWebhook x SettlementEventDedupe receiver-flow row measures the #725 test row as a cost path: one measured op is three deliveries against a dedicated dedupe under a fixed injected clock at capacity 100,000 — a first sighting that verifies and records as new, a redelivery that verifies again but reports duplicate, and a tampered body that fails verification and never reaches the dedupe step, proven by the tampered delivery's claimed id still recording as new afterwards. The verify step reuses the fixed signed webhook and its signature; the dedupe step uses per-iteration synthetic ids standing in for payload.eventId, because the fixed body's own id can only be first-seen once.
The new deliverSettlementWebhookToMany fan-out x SettlementEventDedupe receiver-flow row measures the #741 test row as a cost path and is the escrow-side peer of the dataquest #744 row: one measured op is two fan-outs of the same fresh eventId to the 4 fixed endpoints through a fake global fetch (immediate 200, no network) — the first fan-out delivers 4 / fails 0 with every endpoint's copy verifying under its own secret and recording as a first sighting in that endpoint's own dedupe, and the redelivery delivers 4 / fails 0 again, verifies again, and reports duplicate on all four dedupes. One measured op records exactly one id per dedupe, and warmup + timed calls total 3,200 ops, so 3,200 live entries per dedupe stay far under the 100,000 cap under a fixed injected clock and nothing expires or is evicted in the timed loop. Outside the timed loop, the fixture eventId's first-sighting / redelivery shapes are pinned once.
The new actOnStaleEscrows x subscribe row measures the #735 test row as a cost path: one measured op is one batch action over fresh rebuilds of the same 100-escrow watchdog batch, with one collecting listener subscribed to every escrow — 70 stale escrows EXPIRE and exactly 70 notifications arrive, each carrying the appended EXPIRE entry field for field against that escrow's history tail and the executor's report entry. Outside the timed loop, a notify-only action is pinned to zero notifications with all 70 stale escrows still acted, and an unsubscribe-before-the-executor run is pinned to zero notifications with all 70 still expiring.
The new expireOverdueEscrows x subscribe row measures the #739 test row as a cost path: one measured op is one batch execution over fresh rebuilds of the same 100-escrow watchdog batch, with one collecting listener subscribed to every escrow — 40 overdue escrows EXPIRE and exactly 40 notifications arrive, each carrying the appended EXPIRE entry field for field against that escrow's history tail and the executor's report entry. Outside the timed loop, an unexpirable DISPUTED overdue escrow is pinned to zero notifications with the batch still expiring the rest, and an unsubscribe-before-the-executor run is pinned to zero notifications with all 40 still expiring.
The new deliverSettlementWebhookToMany fan-out x secrets-rotation verify x SettlementEventDedupe receiver-flow row measures the #765 combination as a cost path: one measured op is two fan-outs of the same fresh eventId to the 4 fixed rotation endpoints through a fake global fetch (immediate 200, no network) plus one tampered-copy probe per endpoint — the first fan-out delivers 4 / fails 0 with every endpoint's copy verifying under its own [new, old] candidate list (signed under the old secret, so one failed HMAC trial before the match) and recording as a first sighting in that endpoint's own dedupe, the redelivery delivers 4 / fails 0 again, verifies again, and reports duplicate on all four dedupes, and each tampered copy (that endpoint's fresh eventId swapped for a second id in the body, signature untouched) fails verification and records nothing, proven by each tampered id still recording as new afterwards. One measured op records exactly two ids per dedupe, so warmup + timed calls total 3,200 ops and 6,400 live entries per dedupe stay far under the 100,000 cap under a fixed injected clock.
The new deliverSettlementWebhookToMany fan-out limits x SettlementEventDedupe receiver-flow row measures the #758 test row as a cost path: one measured op is an over-cap batch plus two fan-outs of the same fresh eventId to the 4 fixed endpoints through a fake global fetch (immediate 200, no network) — the 4-endpoint batch under maxEndpoints: 3 throws the pinned cap error before any request (0 fetch calls) and records nothing, proven by the in-limit first fan-out recording as a first sighting on all four dedupes, and the redelivery then reports duplicate on all four dedupes. One measured op records exactly one id per dedupe, so warmup + timed calls total 3,200 ops and 3,200 live entries per dedupe stay far under the 100,000 cap under a fixed injected clock. Outside the timed loop, the fixture eventId's cap / first-sighting / redelivery shapes are pinned once, and an invalid maxEndpoints: 0 is pinned to its exact configuration error with zero fetch calls.
The new buildSettlementReports x top-up row measures the #789 combination as a cost path: one measured op builds a 2-report batch — a topped-up released escrow (FUND 10000 + 630, 5 entries) plus a single-FUND released control (FUND 5000, 4 entries) — and summarizes the two results for the balanced check, pinning the top-up report's deposit at 10630 (the FUND sum, not the first FUND), outcome released, and balanced, the control report's deposit at 5000 and balanced, and the summary at totalDeposit / totalInflow / totalOutflow 15630 with balanced true.
The new day-end pipeline row measures the #809 combination as a cost path: one measured op runs the whole reconciliation job — building the fixed 4-input batch (released / refunded / released / per-item error), building its 3 signed webhooks (bench-batch-event-1..3, error forwarded, no eventId consumed), then fanning each successful report out to the 4 fixed endpoints (3 settlements x 4 endpoints = 12 first-attempt deliveries through a fake fetch answering 200 immediately) — pinning each fan-out at delivered 4 / failed 0 with results in endpoint order (attempts 1, status 200), exactly 12 fetch calls, each endpoint's 3 bodies in batch order byte-identical to the built webhook payloads, and no call carrying the batch's error escrow, with every endpoint's copy pinned once outside the timed loop to verify under its own secret and no other's.
The new escrowsByState / escrowsByActor rows measure the #892
combination as a cost path: one measured op screens one fixed mixed
batch of 60 escrows (12 FUNDED by alice with a bob top-up, 10 FUNDED
by bob, 8 MILESTONE_SUBMITTED funded by carol with an alice milestone,
8 VERIFIED, 6 RELEASED, 6 DISPUTED, 5 CREATED with no history, 5
EXPIRED funded by alice with an actor-less EXPIRE) and pins the
hand-counted hit lists on every iteration — 22 FUNDED ids for the
state filter, 39 alice ids for the actor filter (an escrow with two
alice entries still matches once, actor-less entries match nobody).
Outside the timed loop, the fail-fast shapes are pinned: an unknown
state and an empty or non-string actor each throw their exact error.
The new escrowsByEvent row measures the #932 addition as a cost
path: one measured op screens the same fixed batch of 60 escrows for
the DISPUTE event — the watchdog's "was it ever disputed" listing —
and pins the hand-counted hit list of 6 ids (all of the DISPUTED
group, in batch order) on every iteration. Outside the timed loop,
the other two event slices are pinned: FUND at 55 ids (every escrow
with a history entry, the topped-up group matching once despite its
two FUND entries) and EXPIRE at 5 ids (the actor-less EXPIRE entry
still counts, because the event lens reads entries, not actors),
and the fail-fast shapes are pinned: an unknown event and a state
name passed as an event (DISPUTED) each throw their exact error.
The new escrowsByFilters row measures the #991 combination as a
cost path: one measured op screens the same fixed batch of 60
escrows for { state: "DISPUTED", actor: "carol", event: "DISPUTE" }
— the patrol query "escrows carol disputed that are currently
DISPUTED", the three-axis intersection in one pass instead of
chaining three single-axis filters — and pins the hand-counted hit
list of 6 ids (all of the DISPUTED group, in batch order) on every
iteration. Outside the timed loop, the backlog's literal combo is
pinned to its honest answer: { state: "FUNDED", actor: "bob",
event: "DISPUTE" } returns [], because a DISPUTE always moves an
escrow out of FUNDED, so that slice is empty by construction.
The new escrowsBySettlementRef row measures the #1159 addition
as a cost path: one measured op screens the same fixed batch of 60
escrows for the shared settlementRef — the reconciliation screen's
"which escrows did this bank transfer settle" — and pins the
hand-counted hit list of 6 ids (all of the RELEASED group, whose
RELEASE entries all carry the shared ref, in batch order) on every
iteration. Outside the timed loop, a missing ref returning [], the
case-sensitive miss (lowercase ref matches nothing), and the
empty-ref fail-fast are pinned.
The new settlementAging row measures the #992 combination as a
cost path: one measured op buckets one fixed mixed batch of 10
escrows at the fixed 2026-03-09T09:00:00.000Z now (the same now
the CLI demo pins) — 3 under 7 days, 3 in 7–30 days, 2 over 30
days, 2 never funded — including the pinned 7-day and 30-day
bucket endpoints and the 6-day / 29-day just-inside cases, and
pins the hand-counted bucket contents (ids and ageDays, in batch
order) on every iteration, at fixture build time as well.
The new escrowsApproachingDeadline row measures the #902
combination as a cost path: one measured op screens one fixed mixed
batch of 14 escrows (deadlines in-window, exactly at the inclusive
upper edge, 1 ms past it, beyond the window, overdue, due exactly
now, and absent; terminal RELEASED / EXPIRED / REFUNDED escrows with
in-window deadlines; non-terminal DISPUTED / MILESTONE_SUBMITTED /
VERIFIED / CREATED members) over a fixed 7-day window from
2026-06-01T00:00:00.000Z and pins the hand-counted hit list — 6 ids
in batch order — on every iteration. Outside the timed loop, the
fail-fast shapes are pinned: an invalid window (negative, NaN,
infinite, non-number) and an invalid now each throw their exact
error, a terminal-only batch returns [], and a zero window returns [].
The new nextEscrowDeadline row measures the #930 combination as a
cost path: one measured op screens one fixed mixed batch of 10 escrows
(future deadlines, a tie for the earliest, an overdue deadline, one
due exactly now, and an absent deadline; terminal RELEASED / EXPIRED
escrows carrying earlier deadlines; a non-terminal DISPUTED member)
from 2026-06-01T00:00:00.000Z and pins the hand-counted winner —
BENCH-NEXT-02 at 2026-06-03T00:00:00.000Z — on every iteration.
Outside the timed loop, the fail-fast shape is pinned: an invalid
now throws its exact error, and the empty batch and an
all-excluded batch each return undefined.
The new unreconciledSettlements row measures the #1116 combination
as a cost path: one measured op screens one fixed mixed batch of 10
escrows (2 RELEASED with a settlementRef, 2 RELEASED without one, 1
arbitration-released, 1 arbitration-refunded, 1 EXPIRED, and 3 in
progress — FUNDED, VERIFIED, DISPUTED) and pins the hand-counted hit
list — 3 ids in batch order — on every iteration, at fixture build
time as well. Outside the timed loop, the empty batch returning [] is
pinned.
The new stateAt row measures the #1134 time-travel read as a cost
path: one measured op asks one fixed escrow carrying a 64-entry
hash-chained history (the golden 10,630 funded once, then 60 top-ups
of 1, then SUBMIT_MILESTONE / VERIFY_PASS / RELEASE) what state it
was in at BASE + 31.5s — between the 32nd and 33rd FUND entries —
and pins the hand-counted FUNDED answer on every iteration, plus
that the pure read leaves the escrow RELEASED with its 64 entries
untouched. Outside the timed loop, the before-first-entry answer
(CREATED), the after-last-entry answer (RELEASED), and both inclusive
boundaries (exactly on the first entry: FUNDED; exactly on the last:
RELEASED) are pinned.
The new stateAtFromHistory row measures the #1164 bare-log
time-travel read as a cost path: one measured op asks the same fixed
64-entry hash-chained history — the golden 10,630 funded once, then
60 top-ups of 1, then SUBMIT_MILESTONE / VERIFY_PASS / RELEASE, as
detached plain copies — what state it was in at BASE + 31.5s, and
pins the hand-counted FUNDED answer on every iteration, plus that
the pure read leaves the 64-entry log untouched. Unlike the instance
read, the bare-log query re-validates the whole log
(parseEscrowHistory hash-chain check) on every call, so it runs
about 17x slower than the stateAt row in the same run. Outside the timed loop, the before-first-entry answer
(CREATED), the after-last-entry answer (RELEASED), and both inclusive
boundaries are pinned, and a note-tampered copy is pinned to throw
the hash-chain error while the intact log still answers afterwards.
The new formatMinorUnits x parseMinorUnits round-trip row measures the #1165 minor-unit display/parse path as a cost path: one measured op formats a fixed 12-vector corpus of integer cents (zero, a single cent, the sub-yuan and one-yuan boundaries, the golden 10,630 and 1,063,000, their negatives, a large 1,234,567,890,123, and Number.MAX_SAFE_INTEGER) to its hand-pinned two-decimal strings and parses each back, pinning the exact string and the exact round-trip integer on every iteration. The two directions share one row because the settlement path always pays both — format for the statement, parse back for the import. Outside the timed loop, a fractional format input is pinned to throw the exact integer error, and over-precision, separator, scientific-notation, and empty parse inputs are pinned to throw the strict-decimal error, as is an amount past the safe-integer range, which must overflow loudly instead of returning a rounded-off integer.
The new quorum signed-snapshot round-trip row measures the #1137
envelope as a cost path: one measured op seals the fixed 9-signer /
threshold-5 quorum carrying 7 recorded approvals (dao-1..dao-7, one
second apart on a stepped fixed clock) into its HMAC-signed envelope
and restores it from the JSON round-tripped persisted form, pinning
the envelope shape (v 1, 64-hex MAC, no expiry) and the restored
approvals (7, dao-1..dao-7 in record order, threshold reached, audit
log of 7) on every iteration. Outside the timed loop, a tampered
envelope (one approval rewritten under the original MAC) and a wrong
secret are pinned to throw the MAC-mismatch error, and the
envelope's snapshot is pinned byte-identical to the unsigned
snapshot.
The new approvalStatement row measures the #1166 quorum
approval-statement construction as a cost path: one measured op
constructs the canonical statement bytes for each of the 5
approvers of the fixed 9-signer / threshold-5 quorum (dao-1..dao-5,
the same signers the quorum approval rows approve to the
threshold) and pins every statement byte for byte against its
hand-written escrow-quorum:approve:<signerId> expectation,
pinning on every iteration that the same signer constructed twice
yields byte-identical output and that no two signers share a
statement — the signer id is bound into the bytes, so a signature
for dao-1 can never verify as dao-2's. The five pinned
expectations are checked once at fixture build, outside the timed
loop.
The new truncateOutboxError row measures the #1167 outbox
error-truncation guard as a cost path: one measured op truncates a
fixed 3-case corpus — a short error, one exactly at the
1,024-character cap, and a 10 KB error — and pins every result byte
for byte: the short and at-cap errors pass through unchanged with
no marker, and the 10 KB error truncates to exactly 1,024
characters, keeping its first 1,012 characters and ending with the
…[truncated] marker. Outside the timed loop, the empty error
passing through and an error one character over the cap truncating
to exactly the cap with the marker are pinned.
The new verifySettlementWebhook requireEventId row measures the #1182 opt-in gate as a cost path: one measured op verifies the fixed signed webhook under { secrets: [secret], requireEventId: true } — the signature is checked first and the payload's eventId is read only after a match — and pins true on every iteration. Outside the timed loop, a signed payload built the same way but with eventId stripped before signing is pinned to false under the gate and to true without the option, pinning the legacy signature-only behavior unchanged.
The new verifySettlementWebhookStrict row measures the #1432 recommended receiver path as a cost path: one measured op verifies the fixed signed webhook under { secrets: [secret], now } — only secrets and now are passed, so the three strict defaults resolve on every call (5-minute maxAgeMs, 60-second maxFutureSkewMs, requireEventId: true) — the signature is checked first, then the age gate, the future-skew gate, and the event-id gate, and pins true on every iteration. Outside the timed loop, the same signed body 1 ms past the 5-minute window is pinned to false while the signature itself still verifies under the legacy verifier (only the strict age gate rejects it), the exact 5-minute boundary still verifies (inclusive), and the keyless twin from the requireEventId fixture is pinned to false (fail-closed: a verified signature with no dedupe key is refused).
The new diffQuorumSnapshots row measures the #1186 quorum-snapshot comparison as a cost path: one measured op diffs two snapshots of the fixed 9-signer / threshold-5 quorum carrying 7 recorded approvals — the after snapshot moves the threshold to 6 and swaps dao-9 for dao-10 while the approvals sit at the same fixed timestamps in both — and pins exactly the two charter keys (thresholdChanged 5 -> 6, signersChanged) with approvalsChanged: false on every iteration. Outside the timed loop, an identical pair is pinned to report exactly { approvalsChanged: false }, the always-present master switch.
The new SettlementEventDedupe.has row measures the #1176 read-only
probe as a cost path: one measured op probes exactly one of the three
states in rotation — a live hit, an unseen id, and the first id read
at exactly one TTL after its first sighting (expired, reached through
the explicit-now argument, never by moving the store's clock) — over
a fixed capacity-3 dedupe with 2 pre-recorded ids under a fixed
injected clock (60-second TTL), and pins the verdict on every
iteration. Outside the timed loop, the three probe states are pinned
once, the stats snapshot is pinned identical before and after probing,
and a scratch dedupe pins that a probed unseen id still records as a
first sighting and a probed seen id still reports a duplicate.
The new approveSigned row measures the #1200 quorum signed
approval as a cost path: one measured op builds a fresh 5-of-5
quorum (dao-1..dao-5, Ed25519 public keys registered for all five)
and collects all five pre-signed votes to the threshold, calling
hasQuorum() after each vote, and pins the count of 5, the
approvals in vote order, and every audit-log entry marked
verified: true on every iteration. The key pairs are generated
once, outside the timed loop, and each signer's canonical statement
is pre-signed once with its own key, so the timed region pays only
the Ed25519 verification + counting cost every arbitration vote
pays. Outside the timed loop, a signature made with the wrong
signer's key is pinned to throw the exact verification error and
record nothing.
The new history getter row measures the #1238 defensive-copy read
cost as a cost path: one measured op is a single get history()
call on the fixed 64-entry RELEASED escrow the stateAt row
measures (BENCH-STATEAT-001: FUND of the golden 10,630, 60 top-ups
of 1, then SUBMIT_MILESTONE / VERIFY_PASS / RELEASE), and pins
exactly 64 entries, seq 1..64, a frozen array of frozen entries,
content byte-identical to the fixture baseline, and consecutive
calls never sharing entry references, on every iteration. Outside
the timed loop, a push, a splice, and an entry-field write on the
returned snapshot are pinned to throw, a detached copy mutated
off-timer leaves the internal history untouched, and the escrow's
own hash chain still verifies — the same assertions the
historyFreeze unit tests pin.
The new dispatchArbitration requireVerifiedApprovals row measures the #1540 verified-only arbitration gate as a cost path: every timed iteration rebuilds a DISPUTED escrow via Escrow.fromHistory from its fixed 2-entry prefix plus a mixed 5/9 quorum — dao-1..dao-5 voting with pre-signed Ed25519 votes, dao-6..dao-7 voting with plain approve() claims, so the plain count reads 7/5 while the verified count reads exactly 5/5 — then pins the mixed shape before the gate and the dispatch outcome (REFUNDED, exactly one appended ARBITRATE_REFUND entry, the note listing only the verified signers). Outside the timed loop, a verified-short twin (4 verified, plain still 6/5) is pinned to the exact arbitration requires quorum: 4/5 verified approvals error with the escrow untouched, and the same twin is pinned to pass the plain gate, proving the refusal came from the verified gate. The row is far slower than the plain arbitration row (13,424 ops/sec on the same run) because each iteration rebuilds the mixed quorum with five Ed25519 verifications — the approveSigned row measured 714.6 ops/sec on the same run, so the gate itself costs little beyond the signatures the verified votes require.
The new dispatchArbitration split row measures the #1595 split outcome as a cost path — the escrow-side peer of the dataquest #1582 row: every timed iteration rebuilds a DISPUTED escrow via Escrow.fromHistory from its fixed 2-entry prefix plus a threshold-reached 5/9 quorum, then dispatches the #1449 golden 70/30 split — creator 744,100 cents, sponsor 318,900 cents of the locked 10,630 — pinning the outcome (RELEASED, exactly one appended ARBITRATE_SPLIT entry carrying the golden splitCents verbatim and the quorum note, and an intact hash chain). Outside the timed loop, a split-less dispatch and a wrong-sum split (744,100 / 318,899 — one cent short of the locked 1,063,000) are pinned to their exact errors with the escrow untouched. The row runs at the same speed as the plain arbitration row (22,161 ops/sec vs 26,961 ops/sec on the same run) because the split validation is one BigInt sum comparison on top of the same rebuild cost.
One real run on 2026-12-04:
| path | throughput |
|---|---|
| dispatch (full lifecycle, 4 dispatches) | ~28,484 ops/sec (35.11 µs/op) |
| benchTransition (single step, snapshot restore) | ~47,975 ops/sec (20.84 µs/op) |
| verifyHistoryChain (4 entries) | ~67,747 ops/sec (14.76 µs/op) |
| verifyHistoryChain auditKey (4 entries, keyed) | ~28,440 ops/sec (35.16 µs/op) |
| Escrow.fromHistory (4 entries) | ~11,127 ops/sec (89.87 µs/op) |
| settleRelease (4 fixed inputs) | ~1,015,616 ops/sec (0.98 µs/op) |
| settleRefund (4 fixed inputs) | ~1,288,071 ops/sec (0.78 µs/op) |
| settleRefundCents (4 fixed inputs, integer cents) | ~1,274,609 ops/sec (0.78 µs/op) |
| settleReleaseCents (4 fixed inputs, integer cents) | ~522,943 ops/sec (1.91 µs/op) |
| settlePartialRelease (4 fixed inputs, 2 tranches) | ~572,130 ops/sec (1.75 µs/op) |
| settlePartialReleases (4 fixed batches) | ~227,348 ops/sec (4.40 µs/op) |
| settlePartialReleasesCents (4 fixed batches, integer cents) | ~41,140 ops/sec (24.31 µs/op) |
| settleArbitrationSplitCents (golden 70/30 split, integer cents) | ~808,373 ops/sec (1.24 µs/op) |
| settleArbitrationSplit (golden 70/30 split, float dollars) | ~1,388,907 ops/sec (0.72 µs/op) |
| buildSettlementReport (4 entries) | ~65,100 ops/sec (15.36 µs/op) |
| buildSettlementReport releasePath (released report) | ~52,839 ops/sec (18.93 µs/op) |
| buildSettlementReport audit window (eventCount/firstEventAt/lastEventAt) | ~57,845 ops/sec (17.29 µs/op) |
| renderReport (released report, 4 parties) | ~1,583 ops/sec (631.71 µs/op) |
| renderReport (refunded + expired, 2 reports) | ~869.3 ops/sec (1150.29 µs/op) |
| renderReportCsv (released report, 4 parties) | ~64,171 ops/sec (15.58 µs/op) |
| renderReportJson (released report, 4 parties) | ~71,670 ops/sec (13.95 µs/op) |
| parseSettlementReportJson (released report, 4 parties) | ~49,152 ops/sec (20.35 µs/op) |
| parseSettlementReportCsv (released report, 4 parties) | ~51,481 ops/sec (19.42 µs/op) |
| depositAmountFromHistory (4-shape corpus) | ~1,949 ops/sec (513.02 µs/op) |
| buildSettlementReports (batch 4 x 4 entries) | ~3,235 ops/sec (309.13 µs/op) |
| buildSettlementReports x top-up (batch 2, FUND sum 10630) | ~19,159 ops/sec (52.20 µs/op) |
| summarizeSettlementReports (batch 4 results) | ~50,497 ops/sec (19.80 µs/op) |
| reconcileSettlements (3 reports, 3 ledger rows, 4 groups) | ~409,654 ops/sec (2.44 µs/op) |
| diffEscrowSnapshots (23-entry history, 2 appended) | ~3,812 ops/sec (262.36 µs/op) |
| diffQuorumSnapshots (9 signers, threshold 5 vs 6, 7 approvals) | ~21,026 ops/sec (47.56 µs/op) |
| diffSettlementReports (released report, 500 vs 600 bps) | ~195,228 ops/sec (5.12 µs/op) |
| renderSettlementReportsSummary (batch 4 summary) | ~101,979 ops/sec (9.81 µs/op) |
| renderSettlementReportsSummaryCsv (batch 4 summary) | ~56,592 ops/sec (17.67 µs/op) |
| renderSettlementReportsSummaryJson (batch 4 summary) | ~33,495 ops/sec (29.85 µs/op) |
| diffSettlementReportsSummaries (batch 4 vs top-up batch 2) | ~80,788 ops/sec (12.38 µs/op) |
| parseSettlementReportsSummaryCsv (batch 4 summary, CSV round-trip) | ~19,710 ops/sec (50.74 µs/op) |
| parseSettlementReportsSummaryJson (batch 4 summary, JSON round-trip) | ~24,294 ops/sec (41.16 µs/op) |
| buildSettlementWebhooks (batch 4 results) | ~11,538 ops/sec (86.67 µs/op) |
| buildSettlementReports x buildSettlementWebhooks x deliverSettlementWebhookToMany (batch 4, 3 settlements x 4 endpoints) | ~2,016 ops/sec (495.92 µs/op) |
| buildSettlementWebhook (sign) | ~42,516 ops/sec (23.52 µs/op) |
| buildSettlementWebhook Ed25519 (signingKey) | ~11,812 ops/sec (84.66 µs/op) |
| verifySettlementWebhook | ~73,610 ops/sec (13.59 µs/op) |
| verifySettlementWebhook Ed25519 (publicKey + keyResolver, 2 verifications) | ~3,161 ops/sec (316.38 µs/op) |
| verifySettlementWebhook (secrets rotation, 2 candidates) | ~71,022 ops/sec (14.08 µs/op) |
| verifySettlementWebhook (maxAgeMs freshness window) | ~98,554 ops/sec (10.15 µs/op) |
| verifySettlementWebhook (maxFutureSkewMs future-skew window) | ~101,301 ops/sec (9.87 µs/op) |
| verifySettlementWebhook (requireEventId gate) | ~86,991 ops/sec (11.50 µs/op) |
| verifySettlementWebhookStrict (recommended receiver path, 3 gates on) | ~77,798 ops/sec (12.85 µs/op) |
| verifySettlementWebhook x SettlementEventDedupe receiver flow | ~35,950 ops/sec (27.82 µs/op) |
| parseRetryAfter (11-value corpus) | ~464,423 ops/sec (2.15 µs/op) |
| historyToNdjson (8 entries) | ~21,158 ops/sec (47.26 µs/op) |
| historyFromNdjson (8 entries, chain re-verify) | ~8,758 ops/sec (114.18 µs/op) |
| quorum approve to threshold (5 of 9) | ~176,450 ops/sec (5.67 µs/op) |
| restoreQuorum (snapshot, 7 approvals of 9) | ~34,848 ops/sec (28.70 µs/op) |
| quorum snapshot export (7 approvals of 9) | ~160,453 ops/sec (6.23 µs/op) |
| quorum revoke cycle (5 of 9, revoke + re-approve) | ~125,850 ops/sec (7.95 µs/op) |
| quorum maxApprovalAgeMs expiry (5 of 9, 60s window) | ~18,107 ops/sec (55.23 µs/op) |
| quorum remainingApprovals (2 of 3, 1 approval, 1 to go) | ~4,632,332 ops/sec (0.22 µs/op) |
| deliverSettlementWebhookToMany (4 endpoints) | ~9,193 ops/sec (108.78 µs/op) |
| deliverSettlementWebhookToMany (fan-out x SettlementEventDedupe receiver flow) | ~2,977 ops/sec (335.86 µs/op) |
| deliverSettlementWebhookToMany (fan-out x secrets rotation x SettlementEventDedupe receiver flow) | ~2,391 ops/sec (418.23 µs/op) |
| deliverSettlementWebhookToMany (per-endpoint timeoutMs override) | ~95.4 ops/sec (10487.66 µs/op) |
| deliverSettlementWebhookToMany (fan-out limits, maxEndpoints/overallDeadlineMs) | ~19.7 ops/sec (50783.14 µs/op) |
| deliverSettlementWebhookToMany (fan-out limits x SettlementEventDedupe receiver flow) | ~2,309 ops/sec (433.03 µs/op) |
| deliverSettlementWebhook (single endpoint) | ~69,556 ops/sec (14.38 µs/op) |
| deliverSettlementWebhook (loopback header check, 500→200 retry) | ~433.3 ops/sec (2307.61 µs/op) |
| deliverSettlementWebhook (jitterMs backoff, 500/500→200) | ~167.5 ops/sec (5971.25 µs/op) |
| deliverSettlementWebhookToMany (fan-out jitterMs, 4 endpoints, 500/500→200) | ~181.6 ops/sec (5507.19 µs/op) |
| deliverSettlementWebhookToMany (fan-out maxRetryDelayMs, 4 endpoints, 429 hint) | ~661.1 ops/sec (1512.66 µs/op) |
| deliverSettlementWebhook (pre-aborted signal) | ~110,599 ops/sec (9.04 µs/op) |
| deliverSettlementWebhook (maxRetryDelayMs clamp, 429 hint) | ~830.4 ops/sec (1204.28 µs/op) |
| deliverSettlementWebhook (timeoutMs timeout) | ~70.2 ops/sec (14239.59 µs/op) |
| SettlementEventDedupe checkAndRecord (hit, 1k) | ~658,910 ops/sec (1.52 µs/op) |
| SettlementEventDedupe.has (hit / unseen / expired, 2 recorded ids) | ~2,125,385 ops/sec (0.47 µs/op) |
| SettlementEventDedupe.restore (1,000-entry snapshot) | ~1,189 ops/sec (840.93 µs/op) |
| SettlementEventDedupe.exportSnapshot (1,000-entry snapshot) | ~7,534 ops/sec (132.73 µs/op) |
| SettlementEventDedupe.clear (1,000 recorded ids, fresh fixture) | ~2,235 ops/sec (447.50 µs/op) |
| SettlementEventDedupe.stats (5 live entries, 1 expired) | ~5,227,474 ops/sec (0.19 µs/op) |
| SettlementWebhookOutbox recordAttempt (failure, fresh pair) | ~173,062 ops/sec (5.78 µs/op) |
| SettlementWebhookOutbox recordAttempt (dead-letter boundary, 3 failures, 1 pair) | ~189,441 ops/sec (5.28 µs/op) |
| SettlementWebhookOutbox pending/deadLetter (700 pending + 300 dead-lettered) | ~5,758 ops/sec (173.66 µs/op) |
| SettlementWebhookOutbox acknowledge (pending pair, 2 failures) | ~339,437 ops/sec (2.95 µs/op) |
| SettlementWebhookOutbox exportSnapshot (1,000-pair ledger) | ~7,081 ops/sec (141.23 µs/op) |
| SettlementWebhookOutbox restore (1,000-pair snapshot, JSON round-trip) | ~1,429 ops/sec (699.64 µs/op) |
| SettlementWebhookOutbox redrive + redelivery (dead-lettered pair, fake fetch 200 first attempt) | ~25,646 ops/sec (38.99 µs/op) |
| retrySettlementWebhookOutbox (3 pending pairs, 500→200, maxRounds 2) | ~405.1 ops/sec (2468.30 µs/op) |
| SettlementWebhookOutbox.stats (3 tracked pairs, 2 pending + 1 dead-lettered) | ~748,760 ops/sec (1.34 µs/op) |
| SettlementEventDedupe exportSignedSnapshot (1,000-entry snapshot) | ~644.6 ops/sec (1551.27 µs/op) |
| SettlementEventDedupe restoreSignedSnapshot (1,000-entry snapshot, JSON round-trip) | ~725.6 ops/sec (1378.11 µs/op) |
| Escrow exportSignedSnapshot (4-entry history) | ~49,583 ops/sec (20.17 µs/op) |
| Escrow restoreSignedSnapshot (4-entry history, JSON round-trip) | ~9,083 ops/sec (110.09 µs/op) |
| SettlementWebhookOutbox exportSignedSnapshot (1,000-pair ledger) | ~306.2 ops/sec (3265.85 µs/op) |
| SettlementWebhookOutbox restoreSignedSnapshot (1,000-pair snapshot, JSON round-trip) | ~123.1 ops/sec (8122.43 µs/op) |
| expiredEscrows (batch 100 escrows) | ~39,621 ops/sec (25.24 µs/op) |
| staleEscrows (batch 100 escrows) | ~16,410 ops/sec (60.94 µs/op) |
| stuckEscrows (batch 40 escrows, 10 DISPUTED) | ~71,590 ops/sec (13.97 µs/op) |
| expireOverdueEscrows (batch 100 escrows) | ~579.7 ops/sec (1724.88 µs/op) |
| actOnStaleEscrows (batch 100 escrows) | ~281.3 ops/sec (3554.76 µs/op) |
| actOnStaleEscrows x subscribe (batch 100 escrows, 70 notifications) | ~287.6 ops/sec (3476.80 µs/op) |
| expireOverdueEscrows x subscribe (batch 100 escrows, 40 notifications) | ~299.7 ops/sec (3337.18 µs/op) |
| allowedEvents (all 8 states) | ~325,079 ops/sec (3.08 µs/op) |
| calculateDeposit (3-shape corpus) | ~41,269 ops/sec (24.23 µs/op) |
| calculateDepositCents (3-shape corpus, integer cents) | ~33,411 ops/sec (29.93 µs/op) |
| dispatchArbitration (refund, rebuilt fixture) | ~13,424 ops/sec (74.49 µs/op) |
| dispatchArbitration (split, rebuilt fixture) | ~22,161 ops/sec (45.12 µs/op) |
| dispatchArbitration requireVerifiedApprovals (refund, mixed quorum, rebuilt fixture) | ~567.5 ops/sec (1762.01 µs/op) |
| isOverdue (4-case corpus) | ~909,413 ops/sec (1.10 µs/op) |
| setDeadline + clearDeadline (FUNDED escrow write cycle) | ~366,472 ops/sec (2.73 µs/op) |
| assertNonNegativeMoney (legal corpus) | ~2,443,868 ops/sec (0.41 µs/op) |
| transitionTableJson (18 edges) | ~16,932 ops/sec (59.06 µs/op) |
| transitionTable (18 edges) | ~31,555 ops/sec (31.69 µs/op) |
| stateDiagram (18 edges, 25 lines) | ~17,110 ops/sec (58.44 µs/op) |
| readmeDiagramInSync (README sync check) | ~484.8 ops/sec (2062.76 µs/op) |
| subscribe (full lifecycle, 1 collecting listener) | ~10,304 ops/sec (97.05 µs/op) |
| subscribe onError (short chain, 1 throwing listener) | ~543.7 ops/sec (1839.21 µs/op) |
| Escrow.fromJSON (snapshot round-trip, 4 entries) | ~15,775 ops/sec (63.39 µs/op) |
| Escrow.fromJSON (policy snapshot round-trip, 3 entries, rolePolicy + maxDeposit) | ~10,644 ops/sec (93.95 µs/op) |
| parseEscrowHistory (4 entries, JSON text) | ~7,738 ops/sec (129.24 µs/op) |
| requireVerifyEvidence VERIFY_PASS (evidence gate) | ~18,586 ops/sec (53.81 µs/op) |
| maxDeposit FUND (deposit cap, funds to cap) | ~25,974 ops/sec (38.50 µs/op) |
| dispatch maxVisitsByState (visit budget, 2 FUNDED visits) | ~25,757 ops/sec (38.82 µs/op) |
| remainingVisits (FUNDED spent, 0 + unbudgeted Infinity) | ~2,916,404 ops/sec (0.34 µs/op) |
| dispatch expectedSeq (optimistic concurrency) | ~23,075 ops/sec (43.34 µs/op) |
| dispatch idempotencyKey (key hit/miss) | ~29,473 ops/sec (33.93 µs/op) |
| dispatch rolePolicy (moderator arbitrate, contributor rejected) | ~1,996 ops/sec (500.99 µs/op) |
| dispatchArbitration rolePolicy (moderator arbitrate, contributor rejected) | ~2,035 ops/sec (491.28 µs/op) |
| escrowsByState (batch 60 escrows, 22 FUNDED) | ~240,434 ops/sec (4.16 µs/op) |
| escrowsByActor (batch 60 escrows, 39 alice) | ~16,809 ops/sec (59.49 µs/op) |
| escrowsByEvent (batch 60 escrows, 6 DISPUTE) | ~20,920 ops/sec (47.80 µs/op) |
| escrowsByFilters (batch 60 escrows, 6 DISPUTED+carol+DISPUTE) | ~58,369 ops/sec (17.13 µs/op) |
| escrowsBySettlementRef (batch 60 escrows, 6 shared ref) | ~16,176 ops/sec (61.82 µs/op) |
| settlementAging (batch 10 escrows, 3/3/2/2 buckets) | ~132,371 ops/sec (7.55 µs/op) |
| unreconciledSettlements (batch 10 escrows, 3 unreconciled) | ~50,651 ops/sec (19.74 µs/op) |
| stateAt (64-entry history, mid-history query) | ~25,472 ops/sec (39.26 µs/op) |
| stateAtFromHistory (64-entry history, mid-history query) | ~1,494 ops/sec (669.24 µs/op) |
| formatMinorUnits x parseMinorUnits round-trip (12-vector corpus) | ~48,995 ops/sec (20.41 µs/op) |
| quorum exportSignedQuorumSnapshot x restoreSignedQuorumSnapshot round-trip (7 approvals of 9, JSON round-trip) | ~5,889 ops/sec (169.80 µs/op) |
| escrowsApproachingDeadline (batch 14 escrows, 6 approaching) | ~119,170 ops/sec (8.39 µs/op) |
| nextEscrowDeadline (batch 10 escrows, earliest 2026-06-03) | ~76,727 ops/sec (13.03 µs/op) |
| approvalStatement (5 of 9 signers, canonical statement bytes) | ~129,267 ops/sec (7.74 µs/op) |
| approveSigned (5 of 5 signers, Ed25519 verify to threshold) | ~714.6 ops/sec (1399.35 µs/op) |
| truncateOutboxError (3-case corpus, short/at-cap/10 KB) | ~835,622 ops/sec (1.20 µs/op) |
| history getter (defensive copy, 64 entries) | ~13,593 ops/sec (73.57 µs/op) |
| releasedAmountFromHistory (4-shape corpus) | ~3,547 ops/sec (281.90 µs/op) |
| lockedBalanceFromHistory (2-shape corpus) | ~942,814 ops/sec (1.06 µs/op) |
The two batch-filter rows, the escrowsApproachingDeadline row, and the settlePartialRelease row above were measured on 2026-11-05 runs; the nextEscrowDeadline row and the escrowsByEvent row above were measured on 2026-11-06 runs; the settlePartialReleases row above was measured on a 2026-11-08 run; the escrowsByFilters and settlementAging rows above were measured on a 2026-11-09 run; the outbox rows above were measured on a 2026-11-10 run; the signed-snapshot rows above were measured on a 2026-11-11 run; the diffSettlementReports row above was measured on a 2026-11-13 run; the renderSettlementReportsSummary and diffSettlementReportsSummaries rows above were measured on a 2026-11-13 run; the unreconciledSettlements row above was measured on a 2026-11-14 run; the stateAt row above was measured on a 2026-11-15 run; the stateAtFromHistory row above was measured on a 2026-11-15 run; the formatMinorUnits x parseMinorUnits round-trip row above was measured on a 2026-11-15 run; the quorum signed-snapshot round-trip row above was measured on a 2026-11-15 run; the calculateDepositCents row above was measured on a 2026-11-15 run; the escrowsBySettlementRef row above was measured on a 2026-11-15 run; the parseSettlementReportsSummaryCsv and parseSettlementReportsSummaryJson rows above were measured on a 2026-11-15 run; the renderSettlementReportsSummaryCsv and renderSettlementReportsSummaryJson rows above were measured on a 2026-11-15 run; the approvalStatement row above was measured on a 2026-11-15 run; the truncateOutboxError row above was measured on a 2026-11-15 run; the verifySettlementWebhook requireEventId row above was measured on a 2026-11-16 run; the diffQuorumSnapshots row above was measured on a 2026-11-16 run; the SettlementEventDedupe.has row above was measured on a 2026-11-16 run; the approveSigned row above was measured on a 2026-11-16 run; the dispatch maxVisitsByState row above was measured on a 2026-11-17 run; the retrySettlementWebhookOutbox row above was measured on a 2026-11-17 run; the SettlementWebhookOutbox.stats row above was measured on a 2026-11-18 run; the quorum remainingApprovals row above was measured on a 2026-11-18 run; the remainingVisits row above was measured on a 2026-11-18 run; the policy snapshot round-trip row above was measured on a 2026-11-18 run; the history getter row above was measured on a 2026-11-18 run; the releasedAmountFromHistory row above was measured on a 2026-11-21 run; the stuckEscrows row above was measured on a 2026-11-28 run (Node v24.22.1, AMD EPYC 9D25); the settlePartialReleasesCents row above was measured on a 2026-11-28 run (Node v24.22.1, AMD EPYC 9D25); the settleArbitrationSplitCents row above was measured on a 2026-11-29 run (Node v24.22.1, AMD EPYC 9D25); the verifySettlementWebhookStrict row above was measured on a 2026-11-29 run (Node v24.22.1, AMD EPYC 9D25); the settleRefundCents row above was measured on a 2026-11-30 run (Node v24.22.1, AMD EPYC 9D25); the settleArbitrationSplit row above was measured on a 2026-11-30 run (Node v24.22.1, AMD EPYC 9D25); the settleReleaseCents row above was measured on a 2026-12-01 run (Node v24.22.1, AMD EPYC 9D25); the dispatchArbitration requireVerifiedApprovals row above was measured on a 2026-12-02 run (Node v24.22.1, AMD EPYC 9D25); the lockedBalanceFromHistory row above was measured on a 2026-12-02 run (Node v24.22.1, AMD EPYC 9D25); the buildSettlementWebhook Ed25519 and verifySettlementWebhook Ed25519 rows above were measured on a 2026-12-04 run (Node v24.22.1, AMD EPYC 9D25); the dispatchArbitration split row above was measured on a 2026-12-05 run (Node v24.22.1, AMD EPYC 9D25); the rest of the table is the 2026-11-04 run. Those runs' other rows came in mixed under shared-host load, so refreshing the whole table would misreport changes in paths these additions never touched.
MIT