stock-bot/apps/stock/config/src/contracts/canonical-execution.ts

291 lines
10 KiB
TypeScript

/** Trusted durable-host wire boundary. Native checkpoints are opaque custody,
* not a TypeScript accounting implementation or a strategy mutation API. */
import { z } from 'zod';
export type { financialDecimal };
import type { financialDecimal, FinancialDecimal } from '@stock-bot/types';
import {
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialStrategyDecision,
} from '@stock-bot/types';
import {
nativeFinancialViewSchema,
nativeManagedOrderSchema,
nativeMatchingOutcomeSchema,
replayConfigSchema,
} from './canonical-replay';
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
const decimal: z.ZodType<FinancialDecimal, z.ZodTypeDef, string> = z
.string()
.transform(value => parseFinancialDecimal(value));
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const identitySchema = z.object({ sessionId: id, accountId: id }).strict();
export type CanonicalExecutionIdentity = z.infer<typeof identitySchema>;
export const canonicalMatchingConfigSchema = replayConfigSchema.shape.matching.extend({
series: z.array(
replayConfigSchema.shape.matching.shape.series.element.extend({
mode: z.enum(['Open', 'Quote']),
})
),
});
export type CanonicalMatchingConfig = z.input<typeof canonicalMatchingConfigSchema>;
const eventKeySchema = z
.object({
at: time,
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
instrumentId: id,
sourceSequence: counter,
})
.strict();
const venueSessionSchema = z.object({ sessionId: id, opensAt: time, closesAt: time }).strict();
const riskSessionSchema =
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession;
export const matchingCommandSchema = z
.object({
commandId: id,
key: eventKeySchema,
body: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('submit'),
decisions: z.array(z.unknown().transform(value => parseFinancialStrategyDecision(value))),
})
.strict(),
z
.object({
kind: z.literal('execute'),
seriesId: id,
observation: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('open'),
opensAt: time,
price: positive,
capacity: nonnegative,
})
.strict(),
z
.object({
kind: z.literal('quote'),
observedAt: time,
bid: positive,
ask: positive,
bidSize: nonnegative,
askSize: nonnegative,
})
.strict(),
]),
})
.strict(),
z
.object({ kind: z.literal('mark'), seriesId: id, price: positive, observedAt: time })
.strict(),
z.object({ kind: z.literal('openSession'), session: venueSessionSchema }).strict(),
z.object({ kind: z.literal('closeSession'), sessionId: id }).strict(),
z.object({ kind: z.literal('riskSessionBoundary'), riskSession: riskSessionSchema }).strict(),
z.object({ kind: z.literal('finish') }).strict(),
]),
})
.strict();
export type CanonicalMatchingCommand = z.input<typeof matchingCommandSchema>;
/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */
export function compareEventKeys(
a: CanonicalMatchingCommand['key'],
b: CanonicalMatchingCommand['key']
): number {
const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phases[a.phase] - phases[b.phase] ||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
a.sourceSequence - b.sourceSequence
);
}
/** Metadata and shapes only. Rust restores and validates all nested receipts,
* reservations, accounting and indexes before any transition. */
export const canonicalExecutionCheckpointSchema = z
.object({
version: z.literal(1),
config: canonicalMatchingConfigSchema,
risk: z.record(z.unknown()),
revision: counter,
status: nativeMatchingOutcomeSchema.shape.status,
cursor: eventKeySchema.nullable(),
orders: z.array(nativeManagedOrderSchema),
sessions: z.array(z.tuple([id, venueSessionSchema])),
receipts: z.array(z.record(z.unknown())),
})
.strict();
export type CanonicalExecutionCheckpoint = z.infer<typeof canonicalExecutionCheckpointSchema>;
export const financialTransactionRequestSchema = z.discriminatedUnion('kind', [
z
.object({
version: z.literal(1),
kind: z.literal('initialize'),
identity: identitySchema,
config: canonicalMatchingConfigSchema,
})
.strict(),
z
.object({
version: z.literal(1),
kind: z.literal('apply'),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
command: matchingCommandSchema,
})
.strict(),
]);
export type FinancialTransactionRequest = z.input<typeof financialTransactionRequestSchema>;
const riskOutcomeSchema = z
.object({
replayed: z.boolean(),
revision: counter,
disposition: z.union([z.literal('Accepted'), nativeManagedOrderSchema.shape.status.options[1]]),
financial: z
.object({
replayed: z.boolean(),
effects: z.unknown().transform(value => parseFinancialEffects(value)),
})
.strict()
.nullable(),
remaining: z.record(z.unknown()).nullable(),
releasedOrder: id.nullable(),
resetBaseline: nonnegative.nullable(),
})
.strict();
const matchingEffectSchema = z.union([
z.object({ Order: nativeManagedOrderSchema }).strict(),
z
.object({
Risk: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
z
.object({
Operator: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
]);
export const financialTransactionResultSchema = z
.object({
version: z.literal(1),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
view: nativeFinancialViewSchema,
outcome: nativeMatchingOutcomeSchema.nullable(),
journal: z.array(
z
.object({
index: counter,
effect: matchingEffectSchema,
viewAfter: nativeFinancialViewSchema,
})
.strict()
),
})
.strict();
export type FinancialTransactionResult = z.infer<typeof financialTransactionResultSchema>;
export type CanonicalFinancialView = z.infer<typeof nativeFinancialViewSchema>;
// JSON object key order is not semantically significant (including opaque commands).
function equalJson(left: unknown, right: unknown): boolean {
if (left === right) {
return true;
}
if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
return false;
}
if (Array.isArray(left) || Array.isArray(right)) {
return (
Array.isArray(left) &&
Array.isArray(right) &&
left.length === right.length &&
left.every((value, index) => equalJson(value, right[index]))
);
}
const a = left as Record<string, unknown>,
b = right as Record<string, unknown>;
return (
Object.keys(a).length === Object.keys(b).length &&
Object.keys(a).every(key => Object.hasOwn(b, key) && equalJson(a[key], b[key]))
);
}
export function parseFinancialTransactionResult(
input: string,
expectedIdentity: CanonicalExecutionIdentity
): FinancialTransactionResult {
const result = financialTransactionResultSchema.parse(JSON.parse(input));
const expected = identitySchema.parse(expectedIdentity),
ledger = result.checkpoint.config.risk.ledger;
if (
!equalJson(result.identity, expected) ||
ledger.sessionId !== expected.sessionId ||
ledger.accountId !== expected.accountId ||
result.view.admissionRevision !== result.checkpoint.revision
) {
throw new Error('Native financial transaction identity or revision mismatch');
}
const checkView = (view: CanonicalFinancialView) => {
if (
view.portfolio.sessionId !== expected.sessionId ||
view.portfolio.accountId !== expected.accountId ||
view.portfolio.baseCurrency !== ledger.baseCurrency ||
view.portfolio.reserveOwnerId !== ledger.reserveOwnerId
) {
throw new Error('Native financial transaction view identity mismatch');
}
};
checkView(result.view);
if (result.outcome === null) {
if (
result.checkpoint.revision !== 0 ||
result.checkpoint.status !== 'Running' ||
result.checkpoint.cursor !== null ||
result.checkpoint.orders.length !== 0 ||
result.checkpoint.sessions.length !== 0 ||
result.view.orders.length !== 0 ||
result.view.reservations.length !== 0 ||
result.journal.length !== 0 ||
result.checkpoint.receipts.length !== 0
) {
throw new Error('Invalid initialized financial transaction');
}
} else if (result.outcome.replayed) {
if (result.journal.length !== 0 || result.outcome.revision > result.checkpoint.revision) {
throw new Error('Replayed financial transaction cannot publish effects');
}
} else {
if (
result.outcome.revision !== result.checkpoint.revision ||
!equalJson(result.outcome.status, result.checkpoint.status) ||
result.journal.length !== result.outcome.effects.length
) {
throw new Error('Native financial transaction outcome mismatch');
}
for (const [index, row] of result.journal.entries()) {
checkView(row.viewAfter);
if (
row.index !== index ||
row.viewAfter.admissionRevision !== result.checkpoint.revision - 1 ||
!equalJson(row.effect, matchingEffectSchema.parse(result.outcome.effects[index]))
) {
throw new Error('Native financial transaction journal mismatch');
}
}
}
return result;
}