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.
When rules conflict, use this order:
A prettier type is a regression if it changes bytes, weakens validation, hides an exception, or creates a second production path.
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 }
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.
Every protocol value belongs to exactly one class.
Examples: WebSocket payloads, JSON bodies, LevelDB records, recovery bundles, RPC responses, environment variables, and files.
unknown until validation finishes.JSON.parse(...) as T, decodeBuffer<T>(...), and exported generic
deserialize<T> functions MUST NOT mint protocol authority.as T inside a decoder is permitted only when the preceding code
proves every property of T. The decoder requires adversarial tests.Examples: state, frames, transactions, evidence, Entity context, WAL records, and objects nested inside them.
Map, object, array, tuple, and set are
not interchangeable.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.
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:
success to ok during migration so stale consumers fail compile.Result variant.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.
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.
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:
EntityInput remains a multiplexed envelopeEntityInput 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:
EntityInput with a globally exclusive union.keyof coverage check so every new EntityInput
field is deliberately handled by clone, merge, hash, receipt, and routing.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.
Brands prevent values with identical primitive representations from being confused. They do not validate data and disappear at runtime.
Use brands where confusion has protocol consequences:
EntityId, SignerId, RuntimeId, and jurisdiction identity.ReplicaKey, AccountPairKey, frame/state/evidence hashes.Hashlock, HtlcSecret, token identifier.UnixMs, UnixS, J-height, Runtime height, Entity height, Account height.Time and height units are especially important. Off-chain milliseconds, on-chain seconds, and J-height MUST be distinct types at conversion boundaries.
as EntityId, as Hashlock, or equivalent casts are forbidden.brand<T>() escape hatch.bigint amount. Financial arithmetic must remain usable
through canonical formulas such as deriveDelta.SignerId an EVM address if the protocol also allows aliases.Use simple techniques that both TypeScript 5 and native TypeScript 7 can compile predictably:
?: never for existing shapes;as const satisfies for canonical catalogs and transition tables;[T, ...T[]];keyof residual checks;assertNever for exhaustive control flow;Readonly and readonly arrays at pure boundaries.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];
@ts-expect-error or unchecked casts;{ } as State;Partial<ProtocolType> as a builder.If a type takes longer to understand than the invariant it protects, use a small validated constructor and a direct union instead.
Every important union or evidence shape SHOULD have one owning constructor or decoder module.
The constructor MUST:
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:
undefined where forbidden;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:
undefined are equivalent.field: maybeUndefined.Map with Record, or vice versa.JSON.stringify for financial or protocol state.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.
Errors have four categories:
type FailureDisposition =
| 'reject'
| 'retry'
| 'dispute'
| 'halt_runtime';
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.
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:
HALTED_REQUIRES_OPERATOR;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.
.catch(() => null) in an authority, financial, storage, or
consensus path.deriveDelta(delta, isLeft) for credit/capacity views.byLeft, iAmLeft, and senderIsLeft are different authorities. Derive
them at their exact frame/account boundary and never substitute one for
another merely because all three are booleans.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.
(runtimeHeight, outputIndex). Runtime outbox values are exact flat
MessagePack rows; the Runtime frame commits their ordered byte digest and
count, not references to another graph.Account, Entity, Runtime, Book, evidence and history stores follow the same rule. Signed hashes remain protocol identities, but never become LevelDB addresses.
RuntimeReplica and RuntimeState are never cloned.EntityReplica, EntityState, their Account map, and their orderbook maps
are never cloned as a unit. Reads do not claim or copy values for mutation.AccountReplica and AccountState are not cloned. Account, Entity, Book and
Runtime overlays are separate ephemeral transition caches outside every
committed *State and live *Replica; an Entity candidate receives only the
resulting touched Account roots/nodes, never ownership of Account overlays.The canonical overlay API follows the cascade instead of pretending that all roots have the same authority:
beginEntityOverlay is owned by the Entity transition coordinator.beginAccountOverlay may run only as a nested child of that Entity overlay.
An Account root is independently authenticated by the bilateral Account
frame, but it has no independent WAL, snapshot, cursor, or durable publish
step. Runtime remains the only durable writer.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.
Runtime compiler options MUST retain:
strict;noUncheckedIndexedAccess;exactOptionalPropertyTypes;noImplicitReturns;noPropertyAccessFromIndexSignature;noFallthroughCasesInSwitch;noUnusedLocals and noUnusedParameters;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:
any, double assertion, TS suppression, or unchecked brand cast;Type coverage MAY be ratcheted upward per protocol directory. It MUST NOT reward
casts, unknown laundering, or generated declarations that are never used.
@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:
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.
bun run check once on the unchanged final candidate.Do not rerun L3 while an L1/L2 failure is still being localized.
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
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 |
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.
bun run check.Delta, locks, SettlementWorkspace, HtlcRoute, evidence, and
transaction payloads.ApplyAccountTxResult, Account consensus results, and
direct handler results.HALTED_REQUIRES_OPERATOR behavior.UnixMs/UnixS and height distinctions at conversion points.never fields already represented in the wire schema.?: never to forbid invalid combinations.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.
Partial, cast, or suppression bypasses construction.bun run check is green on the unchanged candidate.Review a protocol change in this order:
Only after these questions are answered should a reviewer judge local code style or abstraction quality.
An independent protocol reviewer SHOULD read modules in this order. The order follows financial authority and irreversible effects, not directory size:
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.core/protocol/dispute, core/protocol/settlement,
jurisdictions/contracts: exact off-chain/on-chain parity, ProofBody,
transformer execution, deadlines, nonces, and Hanko domains.core/entity/consensus, core/entity/tx, core/entity/auth:
validator authority, candidate isolation, child Account inputs, frame
certification, and single-signer versus threshold application.core/hanko, core/board-registry: current/previous board authority,
nested claims, observer-root binding, signer roles, and grace windows.core/runtime, core/frame, core/storage: single-writer ordering,
WAL-before-effects, crash recovery, cache healing, replay, and publication.core/extensions/cross-j, core/routing, core/network:
two-leg atomic groups, reliable delivery, retry bounds, authenticated
transport, gossip evidence, and unverified online assertions.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.
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.