xln

FinTS: TypeScript Safety Standard

Status: normative for new and modified first-party TypeScript.

FinTS is xln’s coding standard for deterministic financial software. Its goal is to prevent invalid states, authority confusion, consensus divergence, unsafe recovery, and accidental fail-soft behavior before code reaches production.

No type system can make a financial protocol perfect. TypeScript guarantees only apply after untrusted bytes have been decoded and validated. FinTS combines compile-time modeling, runtime validation, deterministic serialization, behavioral invariants, replay tests, and fail-stop operations.

The words MUST, MUST NOT, SHOULD, and MAY are normative.

1. Safety hierarchy

When rules conflict, use this order:

  1. Financial and authority correctness.
  2. Deterministic Runtime -> Entity -> Account replay.
  3. Canonical hashes, state roots, wire bytes, and WAL bytes.
  4. Crash safety and recovery.
  5. Compile-time precision.
  6. Convenience and aesthetics.

A prettier type is a regression if it changes bytes, weakens validation, hides an exception, or creates a second production path.

2. Canonical machine boundaries

The three machines have different trust boundaries and MUST remain separate:

Layer Live value Committed state Input Transaction Frame
Runtime RuntimeReplica RuntimeState RuntimeInput RuntimeTx RuntimeFrame
Entity EntityReplica EntityState EntityInput EntityTx EntityFrame
Account AccountReplica AccountState AccountInput AccountTx AccountFrame

Each transition MUST behave as a pure machine:

(replica, validated input, deterministic context) -> { replica, outputs }

2.1 Account commitment boundaries

AccountReplica is not interchangeable with AccountState:

Value Bilateral accountStateRoot Parent Entity commitment Runtime-only
AccountState financial fields yes through the Account root/frame no
pendingFrame, Account input, ACK/resend coordination no yes, as Account replica envelope no
transport sockets, retry timers, WAL handles no no yes

A field may move between these columns only as an explicit protocol migration. Crash/replay tests MUST cover both the bilateral root and the Entity-owned replica envelope; equality of one does not prove equality of the other.

3. Classify every value before typing it

Every protocol value belongs to exactly one class.

3.1 Untrusted bytes

Examples: WebSocket payloads, JSON bodies, LevelDB records, recovery bundles, RPC responses, environment variables, and files.

3.2 Consensus and durable values

Examples: state, frames, transactions, evidence, Entity context, WAL records, and objects nested inside them.

3.3 Ephemeral internal values

Examples: validation results, local effect plans, decoded views, and phase predicates that are never serialized or hashed.

These are the safest place for discriminated unions, branded identifiers, closed result types, and exhaustive switches.

4. Make illegal states unrepresentable

4.1 Closed results, never boolean bags

Financial and consensus code MUST NOT return a boolean plus independent optional payloads:

// Forbidden
type Result = {
  success: boolean;
  error?: string;
  secret?: string;
  committedFrames?: AccountFrame[];
};

Use a closed union whose payload exists only in the valid branch:

type Result<T, E> =
  | Readonly<{ ok: true; value: T }>
  | Readonly<{ ok: false; error: E }>;

type HtlcResolveResult =
  | Readonly<{
      ok: true;
      outcome: 'secret';
      secret: HtlcSecret;
      hashlock: Hashlock;
      events: readonly string[];
    }>
  | Readonly<{
      ok: true;
      outcome: 'error';
      reason: HtlcResolutionReason;
      events: readonly string[];
    }>
  | Readonly<{
      ok: false;
      rejection: AccountTxRejection;
      events: readonly string[];
    }>;

Rules:

4.2 Existing tags before new tags

Use an existing runtime tag when it already participates in the schema. For a hash-reachable object, do not add kind, phase, status, or a phantom field only to improve narrowing.

Prefer negation over new bytes:

type DraftSettlement = SettlementWorkspace & {
  status: 'draft';
  leftHanko?: never;
  rightHanko?: never;
  settlementHash?: never;
};

This is valid only when it describes the existing runtime representation.

4.3 Phase views, not phase clones

Draft, proposed, locked, certified, and committed frames may be the same object as signatures are attached. Model phases with predicates and intersection views over the same object:

type LockedEntityFrame = EntityFrame & {
  collectedSigs: Map<SignerId, readonly string[]>;
};

function isLockedEntityFrame(frame: EntityFrame): frame is LockedEntityFrame {
  return frame.collectedSigs instanceof Map && frame.collectedSigs.size > 0;
}

Account proposals and ACKs follow the same rule. Their draft/certified views MUST refine the existing frameHanko and optional dispute-hanko Hanko fields; they MUST NOT add a second status or clone the frame to claim certification.

4.4 Lifecycle state

Use a stored discriminated union only when the discriminant is already part of the canonical schema or when an explicit protocol migration approves it.

For presence-in-map lifecycles such as HTLC locks and routes:

4.5 EntityInput remains a multiplexed envelope

EntityInput currently passes through a sequential pipeline and merge logic may legally combine transactions, proposals, precommits, and J-prefix evidence. Only leaderTimeoutVote is required to use a dedicated routed lane today.

Therefore:

4.6 Account has three authority-distinct inputs

Do not flatten Account input into “just transactions”. Preserve three modes:

Mode Producer Bilateral Hanko required
local AccountTx[] owning Entity no, until included in an ack_frame proposal
network AccountInput (ack / ack_frame) bilateral counterparty yes
external_finality authenticated Jurisdiction event no; peer veto is forbidden

The decoder and phase views MUST make the selected mode explicit and reject illegal mixtures. A finality event is authority from Jurisdiction, not an unsigned network transaction. A standalone AccountInput.kind = "frame" is forbidden; ack_frame is the proposal-carrying superset.

5. Brands and units

Brands prevent values with identical primitive representations from being confused. They do not validate data and disappear at runtime.

5.1 Approved brands

Use brands where confusion has protocol consequences:

Time and height units are especially important. Off-chain milliseconds, on-chain seconds, and J-height MUST be distinct types at conversion boundaries.

5.2 Minting brands

5.3 What not to brand

6. Type-level programming policy

6.1 Approved techniques

Use simple techniques that both TypeScript 5 and native TypeScript 7 can compile predictably:

Example of a catalog that is runtime data and a literal type source:

const ENTITY_REJECTION_CODES = {
  malformedInput: 'ENTITY_INPUT_MALFORMED',
  authorityMismatch: 'ENTITY_AUTHORITY_MISMATCH',
} as const satisfies Record<string, string>;

type EntityRejectionCode =
  (typeof ENTITY_REJECTION_CODES)[keyof typeof ENTITY_REJECTION_CODES];

6.2 Rejected techniques

If a type takes longer to understand than the invariant it protects, use a small validated constructor and a direct union instead.

7. Exact constructors and decoders

Every important union or evidence shape SHOULD have one owning constructor or decoder module.

The constructor MUST:

  1. accept already validated dependencies;
  2. validate cross-field invariants;
  3. construct exact keys, omitting absent keys rather than assigning undefined;
  4. preserve canonical container types;
  5. return one precise union variant;
  6. perform no I/O, time reads, or randomness inside a reducer;
  7. never return a partial object.

The return type MUST be the narrowest phase that the constructor proves. A constructor that can only create UnsignedSettlementWorkspace must not return the wider SettlementWorkspace, because that discards a fact the caller needs to make illegal transitions unrepresentable.

AST gates SHOULD forbid direct discriminant-bearing object literals outside the owner module when that pattern is practical.

Decoder tests MUST include:

8. Serialization and hashing

TypeScript structure is not the serialization contract. xln has multiple encoders with intentionally different behavior:

Encoder undefined object field Map behavior Main use
encodeCanonicalConsensusBytes rejected, including nested values sorted by canonical key bytes, then value bytes on ties Entity/frame consensus hashes
tagged JSON / safeStringify omitted tagged and sorted; undefined entries omitted logs, APIs, portable JSON
Account canonical RLP omitted committed through canonical map roots Account state roots
canonical msgpack WAL preserved sorted by canonical key bytes durable Runtime history

Consequences:

Nested values need coverage too. Top-level state-field coverage is insufficient when Delta, SettlementWorkspace, HtlcRoute, a lock, or transaction payload is structurally encoded. Every hash-reachable nested type MUST have either:

Solidity coverage is codec coverage. Every runtime ProofBody, Payment, Pull, settlement, and dispute projection MUST be checked against its exact ABI field set, ordering, signedness, left/right convention, and inclusive or exclusive deadline semantics. TypeScript field coverage alone cannot prove contract parity.

Hashed safe-integer fields are protocol-ranged, not number-ranged. Every version or counter field committed by an Account frame hash — canonically RebalancePolicy.policyVersion — MUST lie in 0..=9_007_199_254_740_991 (Number.MAX_SAFE_INTEGER). Above that bound a TypeScript number rounds silently while the Rust engine rejects the same u64 as unsafe, so the two engines would diverge on one frame hash. Admission MUST reject an out-of-range value before the mempool in both engines; the frame-hash layer MUST treat meeting one as an admission bug and throw rather than hash.

9. Errors and failure containment

9.1 Error classes

Errors have four categories:

type FailureDisposition =
  | 'reject'
  | 'retry'
  | 'dispute'
  | 'halt_runtime';
  1. Reject: authenticated or unauthenticated external input is invalid. Return a typed rejection code. Do not mutate committed state.
  2. Retry/defer: a known temporary condition occurred before commit. Return a typed reason with bounded retry policy.
  3. Dispute: authenticated signed evidence cannot be safely discarded or replayed as an ordinary Account input. Persist the exact evidence and start the canonical on-chain dispute path. Clock mismatch alone is never this case.
  4. Halt Runtime: invariant violation, storage corruption, replay divergence, impossible authority state, or unknown exception.

Control flow MUST NOT depend on message.startsWith, includes, regexes over human text, or emoji. Use a literal code, typed payload, and instanceof at the trust boundary. Log messages may remain stable for operators but are not the machine taxonomy.

This is enforced structurally: production catch/classifier code may inspect a typed disposition or an exact code catalog, never error.message. Before a mainnet candidate, every expected failure at a money/authority boundary MUST be categorized; an uncategorized failure still halts only the affected Runtime.

9.2 Fail-stop Runtime, live host

An invariant failure does not need to crash the entire multi-Runtime host, but the affected Runtime MUST NOT continue applying inputs.

The outer supervisor MUST:

  1. abort the candidate and publish no uncommitted state or effects;
  2. preserve the authoritative WAL and full incident dump;
  3. transition that Runtime to HALTED_REQUIRES_OPERATOR;
  4. stop its scheduling, ingress, signing, routing, and jurisdiction outputs;
  5. keep read-only health and inspection available;
  6. require explicit operator restart/replay to resume.

Unknown exceptions halt the affected Runtime. They MUST NOT be guessed to be “nonfinancial” and swallowed. Expected peer failures are modeled as reject or retry results and never reach this boundary.

9.3 Never swallow errors

10. Financial and authority invariants

10.1 Financial math

10.2 Authority

10.3 Time and deadline parity

10.4 Atomic groups and retries

10.5 Entity apply ownership

10.6 Persistent candidates, never machine clones or content-addressed storage

Runtime and Entity state are unbounded financial indexes. Their candidate paths MUST use in-memory overlays over dirty Merkle paths; a frame may never copy or traverse the whole machine merely to isolate a candidate, compute a root, or append the WAL.

The canonical overlay API follows the cascade instead of pretending that all roots have the same authority:

TypeScript has no linear types, so nominal brands and dependency gates enforce the ownership visible to the compiler while one runtime lifecycle token closes the remaining double-use case. Proxy traps, weak collections, Map subclassing, ambient caches keyed by committed objects, and handler-visible lifecycle functions are prohibited.

Root composition is lifecycle-partitioned. Small fixed trust-boundary records bind child roots; path-compressed Patricia maps exist only below growing collection slots. AccountReplicaRoot binds the bilaterally signed AccountStateRoot and the bounded Entity-certified Account envelope root. EntityStateRoot binds its bounded header, Account-replica index root, unified same/cross order-book root, and other typed collection roots. Book pages share the Entity lifecycle and therefore are not a separate durable machine.

11. Compiler and static-analysis policy

Runtime compiler options MUST retain:

Frontend enables the same options incrementally by directory. A frontend unused-code cleanup is a standalone change, never bundled with consensus types.

Required AST/static ratchets:

Type coverage MAY be ratcheted upward per protocol directory. It MUST NOT reward casts, unknown laundering, or generated declarations that are never used.

12. Type-level tests

@ts-expect-error and other suppressions are forbidden. After Milestone 4 closes the first financial result unions, new authority-bearing types SHOULD use a dedicated negative compiler harness. This harness is not a Milestone 0 gate:

  1. a fixture contains one intentionally illegal construction;
  2. the fixture is included in an explicit negative-test tsconfig;
  3. the harness requires compilation to fail;
  4. it verifies the expected diagnostic file/location or stable diagnostic class;
  5. a paired positive fixture must compile;
  6. a mutation check widens the target type and proves the negative fixture would stop constraining it.

Also use positive type equalities and field coverage:

type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends
  (<T>() => T extends B ? 1 : 2) ? true : false;

type Expect<T extends true> = T;
type Covered = Expect<Equal<keyof HtlcRoute, HtlcRouteField>>;

A multiplexed protocol envelope needs coverage by operation, not merely one top-level keyof assertion. EntityInput must account for every field in its clone, merge, hash, receipt, and routing policies. Adding a field without an explicit decision on all five axes is a compile-time failure.

Keep utilities shallow and compatible with both supported TypeScript compilers.

13. Verification ladder for every milestone

L1: exact local proof

L2: targeted flow

L3: broad evidence

Do not rerun L3 while an L1/L2 failure is still being localized.

14. Golden and differential evidence

Byte-neutral milestones MUST preserve:

Do not use the production encoder to generate the expected golden in the same test. Expected literals come from an independent oracle or previously approved fixture.

Differential replay compares, at minimum:

same persisted RuntimeInput bytes
  -> same RuntimeState
  -> same Entity/Account roots
  -> same outputs/effects
  -> same WAL post-state hash

15. Smooth migration method

Each milestone is one coherent, independently revertible commit. No adapters, V2 aliases, parallel readers, or compatibility branches survive the commit.

The implementation through Milestone 11 is present on the current candidate. Completion is executable, not editorial: bun run soundcheck:fast owns the fast FinTS policy, bun run check owns the complete source/build gate, and the release E2E profiles own browser/runtime evidence. A checked milestone may not be claimed while any owning gate is red.

FinTS invariant Executable owner
Strict compiler/module policy check:fints-compiler-policy
Decoder-only brand minting and negative types check:fints-negative-types
No unsafe casts, suppressions, new non-null debt, or JS-error guessing check:unsafe-types
Determinism, including randomness, clocks, and weak collections check:determinism:static, check:no-weak-collections
Dependency direction and dead surface check:runtime-dependencies, check:dead-code, check:unused-surface
Hash-reachable field coverage check:nested-hash-coverage
Persistent Runtime/Entity candidates; no full-machine clones check:no-machine-clones
Typed failure disposition and fail-stop security:failure-taxonomy

Milestone 0: behavioral prerequisites

Before type reshaping, fix and test active correctness blockers on the same surfaces, including:

These boxes describe the current candidate, not a completion claim. They become authoritative only after Milestone 1 records a green immutable SHA and the required behavioral regressions.

Milestone 1: freeze the baseline

Milestone 2: close hash-coverage gaps

Milestone 3: validate existing lifecycle tags

Milestone 4: close financial result unions

Milestone 5: typed failure taxonomy and Runtime fail-stop

Milestone 6: decoder-minted brands and units

Milestone 7: evidence and frame phase views

Milestone 8: settlement, dispute, and candidate typestate

Milestone 9: HTLC narrow views

Milestone 10: EntityInput phase views

Milestone 11: remaining strictness

16. Stop and rollback criteria

Immediately stop and revert the milestone if any of these occur without an explicitly approved protocol change:

Rollback is git revert of the single milestone commit. Do not patch around a failed milestone with aliases or fallback readers.

17. Pull-request checklist

Model

Determinism and bytes

Finance and authority

Evidence

18. Human review order

Review a protocol change in this order:

  1. Authority: who may create, sign, accept, reject, and finalize it?
  2. State ownership: Runtime, Entity, Account, or Jurisdiction?
  3. Input bytes and decoder: what exact untrusted value reaches the machine?
  4. Transition: what state and effects change on success, reject, retry, and throw?
  5. Commitment: which hash/root/WAL record binds the change?
  6. Replay: can the exact input be applied twice or after restart?
  7. Atomicity: can one leg/state/effect commit without the others?
  8. Enforcement: what on-chain behavior must exactly match?
  9. Recovery: what happens at every crash boundary?
  10. Observability: can operators distinguish reject, retry, dispute, and halt?

Only after these questions are answered should a reviewer judge local code style or abstraction quality.

18.1 xln module reading order

An independent protocol reviewer SHOULD read modules in this order. The order follows financial authority and irreversible effects, not directory size:

  1. core/account/consensus, core/account/tx, core/account/state, core/types/account.ts: bilateral authorization, Delta math, locks, settlement, lending, replay, collision, and Account root ownership.
  2. core/protocol/dispute, core/protocol/settlement, jurisdictions/contracts: exact off-chain/on-chain parity, ProofBody, transformer execution, deadlines, nonces, and Hanko domains.
  3. core/entity/consensus, core/entity/tx, core/entity/auth: validator authority, candidate isolation, child Account inputs, frame certification, and single-signer versus threshold application.
  4. core/hanko, core/board-registry: current/previous board authority, nested claims, observer-root binding, signer roles, and grace windows.
  5. core/runtime, core/frame, core/storage: single-writer ordering, WAL-before-effects, crash recovery, cache healing, replay, and publication.
  6. core/extensions/cross-j, core/routing, core/network: two-leg atomic groups, reliable delivery, retry bounds, authenticated transport, gossip evidence, and unverified online assertions.
  7. core/entity/profile, core/orchestrator, core/api: route/profile certification and ingress boundaries. Review UI/CLI last; they must not own protocol calculations or financial authority.

For each group, read the production transition first, then its state/root or codec, then the closest adversarial L1, then one restart/on-chain L2. Never infer the protocol solely from tests, docs, generated bundles, or UI projections.

19. References

The following articles provide useful background, but this document overrides their examples where xln’s deterministic protocol requires stricter rules:

Use these for concepts, not copy-paste. Some examples rely on unchecked casts, @ts-expect-error, or type-level arithmetic that FinTS explicitly forbids.