@lifi/compose-spec 0.2.0-staging.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Canonical wire-format types for the standalone `POST /simulate` endpoint.
3
+ *
4
+ * `/simulate` takes a raw, pre-encoded transaction (a `to` address, hex `data`,
5
+ * optional native `value`), funds a sender, runs it in one `eth_call`, and
6
+ * reports the watched balances before and after, their signed deltas, and the
7
+ * inner-call gas. Unlike `POST /compose`, its response body is **un-enveloped**:
8
+ * `{ status, block, timestamp, ... }` lives at the top level (no `{ data }`
9
+ * wrapper).
10
+ *
11
+ * These are the single source of truth for the request/response shapes. The
12
+ * server-side Zod schemas in `@lifi/api-schemas` (`src/routes/simulate.ts`)
13
+ * validate the same contract and are kept in lockstep by a compile-time
14
+ * conformance assertion (`src/routes/simulate.typecheck.ts`).
15
+ *
16
+ * Mirrors the hand-authored style of `src/compile.ts`.
17
+ */
18
+
19
+ /**
20
+ * Maximum number of watched `(token, owner)` pairs accepted by `POST /simulate`.
21
+ *
22
+ * The limit comes from the VM's hard register budget (~123 usable registers,
23
+ * checked on the final ISA layout). Each pair costs two result registers — a
24
+ * before-read and an after-read — that are both live at the closing abi-encode,
25
+ * so the compiler cannot coalesce them; that `2 × N` is the cost that scales.
26
+ * Token and owner address literals do not scale it, since constant-propagation
27
+ * merges identical-valued literals into one register. The cap leaves headroom
28
+ * for the inner-call / gas-measurement / abi-encode scaffolding.
29
+ */
30
+ export const SIMULATE_MAX_TRACKED_BALANCES = 40;
31
+
32
+ /**
33
+ * Maximum number of funding `requirements` accepted by `POST /simulate`.
34
+ *
35
+ * Each requirement triggers a slot-discovery cycle (access-list probe + sentinel
36
+ * verification + RPC round trips) in slot-finder, so an unbounded array lets a
37
+ * single request amplify into arbitrary upstream RPC work. Bounded here at the
38
+ * trust boundary and re-enforced server-side in `rawSimulation.ts`.
39
+ */
40
+ export const SIMULATE_MAX_REQUIREMENTS = 40;
41
+
42
+ /** A `(token, owner)` pair whose balance is watched across the simulation. */
43
+ export interface TrackedBalance {
44
+ /** Token to watch (use the zero address for native balance). */
45
+ readonly token: string;
46
+ /** Account whose balance of `token` is watched. */
47
+ readonly owner: string;
48
+ }
49
+
50
+ /**
51
+ * Funding instruction: seed an ERC-20 balance on a wallet before simulation.
52
+ * Amounts accept `bigint | string` — the SDK serialises `bigint` to a decimal
53
+ * string; the string side covers values already stringified.
54
+ */
55
+ export interface Erc20BalanceRequirement {
56
+ readonly type: 'Erc20Balance';
57
+ readonly wallet: string;
58
+ readonly token: string;
59
+ readonly balance: bigint | string;
60
+ }
61
+
62
+ /** Funding instruction: seed a native balance on a wallet before simulation. */
63
+ export interface NativeBalanceRequirement {
64
+ readonly type: 'NativeBalance';
65
+ readonly wallet: string;
66
+ readonly balance: bigint | string;
67
+ }
68
+
69
+ /** Funding instruction: seed an ERC-20 allowance before simulation. */
70
+ export interface Erc20AllowanceRequirement {
71
+ readonly type: 'Erc20Allowance';
72
+ readonly owner: string;
73
+ readonly spender: string;
74
+ readonly token: string;
75
+ readonly allowance: bigint | string;
76
+ }
77
+
78
+ /**
79
+ * The funding-instruction union applied before a simulation. Three variants,
80
+ * discriminated by `type`.
81
+ */
82
+ export type SlotFinderRequirement =
83
+ | Erc20BalanceRequirement
84
+ | NativeBalanceRequirement
85
+ | Erc20AllowanceRequirement;
86
+
87
+ /** Request body for `POST /simulate`. */
88
+ export interface SimulateRequest {
89
+ /** EVM chain id. */
90
+ readonly chainId: number;
91
+ /**
92
+ * Sender of the simulated transaction. The VM bytecode is injected here so
93
+ * the inner call carries `msg.sender == from`.
94
+ */
95
+ readonly from: string;
96
+ /** Target contract of the raw transaction. */
97
+ readonly to: string;
98
+ /** Pre-encoded transaction calldata (`0x`-prefixed hex). */
99
+ readonly data: string;
100
+ /**
101
+ * Native value (wei) sent with the inner call. Accepts `bigint | string`;
102
+ * defaults to `"0"` server-side when omitted.
103
+ */
104
+ readonly value?: bigint | string;
105
+ /**
106
+ * Block number to simulate against. Omitted ⇒ the chain head. Named tags
107
+ * (e.g. "latest") are rejected with HTTP 400.
108
+ */
109
+ readonly block?: number;
110
+ /** Funding instructions applied before simulation (max 40). */
111
+ readonly requirements?: readonly SlotFinderRequirement[];
112
+ /** Balances to read before and after the transaction (1–40 pairs). */
113
+ readonly trackedBalances: readonly TrackedBalance[];
114
+ }
115
+
116
+ /**
117
+ * One watched balance in a simulation response. `amount` is a decimal string;
118
+ * for `deltas` it is signed (`after - before`).
119
+ */
120
+ export interface SimulateBalanceEntry {
121
+ readonly token: string;
122
+ readonly owner: string;
123
+ readonly amount: string;
124
+ }
125
+
126
+ /**
127
+ * HTTP 200, `status: "ok"`: the simulation ran successfully. Balance arrays are
128
+ * ordered to match the request `trackedBalances`. `gasUsed` is inner-call
129
+ * execution gas only.
130
+ *
131
+ * Note: the array element types are intentionally mutable (`SimulateBalanceEntry[]`,
132
+ * not `readonly SimulateBalanceEntry[]`) so they stay structurally identical to
133
+ * the Zod-inferred wire types, which `z.array(...)` infers as mutable `T[]`. The
134
+ * bidirectional conformance assertion in `@lifi/api-schemas` relies on this.
135
+ */
136
+ export interface SimulateOkResult {
137
+ readonly status: 'ok';
138
+ readonly block: number;
139
+ readonly timestamp: number;
140
+ readonly balancesBefore: SimulateBalanceEntry[];
141
+ readonly balancesAfter: SimulateBalanceEntry[];
142
+ readonly deltas: SimulateBalanceEntry[];
143
+ readonly gasUsed: string;
144
+ }
145
+
146
+ /** Decoded revert diagnostics, when slot-finder can parse the revert reason. */
147
+ export interface SimulateRevertDecodeResult {
148
+ readonly errorCandidates?: {
149
+ readonly decodedErrorSignature: string;
150
+ readonly decodedParams: string[];
151
+ }[];
152
+ readonly error?: string;
153
+ }
154
+
155
+ /**
156
+ * HTTP 200, `status: "revert"`: the simulation ran but the transaction reverted
157
+ * on-chain. A revert is a *successful simulation*, not a transport error.
158
+ */
159
+ export interface SimulateRevertResult {
160
+ readonly status: 'revert';
161
+ readonly block: number;
162
+ readonly timestamp: number;
163
+ readonly revertReason?: string;
164
+ readonly code?: number;
165
+ readonly rawErrorBytes?: string;
166
+ readonly decodeResult?: SimulateRevertDecodeResult;
167
+ }
168
+
169
+ /**
170
+ * HTTP 422, `status: "error"`: the request was well-formed but the simulation
171
+ * could not be set up or run. `message` is intentionally generic.
172
+ */
173
+ export interface SimulateSetupErrorResult {
174
+ readonly status: 'error';
175
+ readonly message: string;
176
+ }
177
+
178
+ /**
179
+ * Discriminated result of `POST /simulate`. `switch (result.status)` narrows to
180
+ * one member: `ok` and `revert` come back with HTTP 200, `error` with HTTP 422.
181
+ */
182
+ export type SimulateResult =
183
+ SimulateOkResult | SimulateRevertResult | SimulateSetupErrorResult;
package/src/zodSchemas.ts CHANGED
@@ -1,51 +1,57 @@
1
- import z from "zod";
1
+ import z from 'zod';
2
+
3
+ import { BYTES32_LOWER_HEX } from './hexPatterns.js';
4
+
5
+ // A positive integer chain id. Zod mirror of the Effect `ChainIdSchema` in
6
+ // `flowSchema.ts`, single-sourced so the wire schemas stay consistent.
7
+ export const chainIdZod = z.number().int().positive();
2
8
 
3
9
  const SolTypeZod = z.enum([
4
- "uint8",
5
- "uint16",
6
- "uint32",
7
- "uint64",
8
- "uint128",
9
- "uint256",
10
- "int128",
11
- "int256",
12
- "address",
13
- "bool",
14
- "bytes",
15
- "bytes4",
16
- "bytes32",
17
- "string",
10
+ 'uint8',
11
+ 'uint16',
12
+ 'uint32',
13
+ 'uint64',
14
+ 'uint128',
15
+ 'uint256',
16
+ 'int128',
17
+ 'int256',
18
+ 'address',
19
+ 'bool',
20
+ 'bytes',
21
+ 'bytes4',
22
+ 'bytes32',
23
+ 'string',
18
24
  ]);
19
25
 
20
26
  export const ResourcePortZod = z.object({
21
- kind: z.literal("resource"),
27
+ kind: z.literal('resource'),
22
28
  name: z.string(),
23
- accepts: z.enum(["erc20", "native", "any"]),
24
- mode: z.enum(["linear", "copy"]),
29
+ accepts: z.enum(['erc20', 'native', 'any']),
30
+ mode: z.enum(['linear', 'copy']),
25
31
  optional: z.boolean().optional(),
26
32
  });
27
33
 
28
34
  export const HANDLE_UNITS = [
29
- "raw",
30
- "wad",
31
- "ray",
32
- "bps",
33
- "token-decimals",
35
+ 'raw',
36
+ 'wad',
37
+ 'ray',
38
+ 'bps',
39
+ 'token-decimals',
34
40
  ] as const;
35
41
 
36
42
  // NOTE: the uint members below must stay in sync with the `UintN` union in
37
43
  // `ts/packages/lifi_ir1_ts/src/types/ValueHandle.ts`. When adding a new
38
44
  // uintN width, update both locations.
39
45
  export const STATIC_SOL_TYPES = [
40
- "uint256",
41
- "uint128",
42
- "uint64",
43
- "uint32",
44
- "uint16",
45
- "uint8",
46
- "address",
47
- "bool",
48
- "bytes32",
46
+ 'uint256',
47
+ 'uint128',
48
+ 'uint64',
49
+ 'uint32',
50
+ 'uint16',
51
+ 'uint8',
52
+ 'address',
53
+ 'bool',
54
+ 'bytes32',
49
55
  ] as const;
50
56
 
51
57
  export const HandleUnitsZod = z.enum(HANDLE_UNITS);
@@ -58,30 +64,30 @@ export const isStaticSolType = (value: string): value is StaticSolType =>
58
64
  STATIC_SOL_TYPE_SET.has(value);
59
65
 
60
66
  export const HandlePortZod = z.object({
61
- kind: z.literal("handle"),
67
+ kind: z.literal('handle'),
62
68
  name: z.string(),
63
69
  type: SolTypeZod,
64
- mode: z.enum(["linear", "copy"]),
70
+ mode: z.enum(['linear', 'copy']),
65
71
  expose: z.boolean().optional(),
66
72
  units: HandleUnitsZod.optional(),
67
73
  });
68
74
 
69
- export const InputPortZod = z.discriminatedUnion("kind", [
75
+ export const InputPortZod = z.discriminatedUnion('kind', [
70
76
  ResourcePortZod,
71
77
  HandlePortZod,
72
78
  ]);
73
79
 
74
80
  export const ResourceOutputPortZod = z.object({
75
- kind: z.literal("resource_output"),
81
+ kind: z.literal('resource_output'),
76
82
  name: z.string(),
77
- mode: z.enum(["linear", "copy"]),
78
- availability: z.enum(["now", "future"]).optional(),
83
+ mode: z.enum(['linear', 'copy']),
84
+ availability: z.enum(['now', 'future']).optional(),
79
85
  providesMinimum: z.boolean().optional(),
80
86
  omitIfZero: z.boolean().optional(),
81
87
  deliveryAddressInput: z.string().optional(),
82
88
  });
83
89
 
84
- export const OutputPortZod = z.discriminatedUnion("kind", [
90
+ export const OutputPortZod = z.discriminatedUnion('kind', [
85
91
  ResourceOutputPortZod,
86
92
  HandlePortZod,
87
93
  ]);
@@ -94,32 +100,32 @@ export const ManifestOperationZod = z.object({
94
100
  configSchema: z.unknown().optional(),
95
101
  });
96
102
 
97
- const PortKindEnum = z.enum(["resource", "resource_output", "handle"]);
103
+ const PortKindEnum = z.enum(['resource', 'resource_output', 'handle']);
98
104
 
99
105
  const SelectorMatchZod = z.object({
100
106
  kind: z.union([PortKindEnum, z.array(PortKindEnum)]),
101
- mode: z.enum(["linear", "copy"]).optional(),
102
- type: z.enum(["erc20", "native", "any"]).optional(),
107
+ mode: z.enum(['linear', 'copy']).optional(),
108
+ type: z.enum(['erc20', 'native', 'any']).optional(),
103
109
  });
104
110
 
105
111
  const ConfigSelectionZod = z.object({
106
- kind: z.literal("config"),
112
+ kind: z.literal('config'),
107
113
  configKey: z.string(),
108
- cardinality: z.enum(["one", "many"]),
114
+ cardinality: z.enum(['one', 'many']),
109
115
  });
110
116
 
111
117
  const AllMatchingSelectionZod = z.object({
112
- kind: z.literal("all_matching"),
118
+ kind: z.literal('all_matching'),
113
119
  });
114
120
 
115
- const SelectorSelectionZod = z.discriminatedUnion("kind", [
121
+ const SelectorSelectionZod = z.discriminatedUnion('kind', [
116
122
  ConfigSelectionZod,
117
123
  AllMatchingSelectionZod,
118
124
  ]);
119
125
 
120
126
  export const GuardSelectorZod = z.object({
121
127
  binding: z.string(),
122
- source: z.enum(["inputs", "outputs"]),
128
+ source: z.enum(['inputs', 'outputs']),
123
129
  match: SelectorMatchZod,
124
130
  selection: SelectorSelectionZod,
125
131
  });
@@ -138,7 +144,7 @@ export const ManifestGuardZod = z.object({
138
144
  export const ManifestMaterialiserZod = z.object({
139
145
  kind: z.string(),
140
146
  description: z.string().optional(),
141
- accepts: z.enum(["resource", "handle", "any"]),
147
+ accepts: z.enum(['resource', 'handle', 'any']),
142
148
  configSchema: z.unknown().optional(),
143
149
  });
144
150
 
@@ -158,6 +164,158 @@ export const ComposeManifestZod = z.object({
158
164
  preconditions: z.array(ManifestPreconditionZod).optional(),
159
165
  });
160
166
 
167
+ // HTTP-layer mirror of `Phase1ArtifactSchema` (the Effect schema in
168
+ // `continuation.ts`). The Effect schema validates the Flow; this Zod schema
169
+ // validates the `/compose` response. `transaction` carries an optional
170
+ // `transactionRequest` only if a venue later needs it; for v1 it is just
171
+ // `{ kind: "transaction" }` and the client funds via the existing
172
+ // response-level `transactionRequest`.
173
+ export const Phase1ArtifactZod = z.discriminatedUnion('kind', [
174
+ z.object({
175
+ kind: z.literal('transaction'),
176
+ transactionRequest: z
177
+ .object({
178
+ to: z.string(),
179
+ data: z.string(),
180
+ value: z.string(),
181
+ })
182
+ .optional(),
183
+ }),
184
+ z.object({
185
+ kind: z.literal('signables'),
186
+ typedData: z.array(z.unknown()),
187
+ }),
188
+ z.object({
189
+ kind: z.literal('none'),
190
+ }),
191
+ ]);
192
+
193
+ // HTTP-layer mirror of `CheckSchema` (the Effect schema in `continuation.ts`).
194
+ // A readiness predicate the client can poll and that is also embedded into
195
+ // `nextFlow` as an on-chain assertion. Amounts are decimal strings on the wire.
196
+ // Address/bytes fields require a `0x` prefix (lenient, mirroring `CheckSchema`).
197
+ const hexStringZod = z.string().startsWith('0x');
198
+
199
+ // Mirror of `AssertionOwnerSchema` (continuation.ts): a concrete hex address or
200
+ // one of the two symbolic owners resolved at settlement. Applies ONLY to the
201
+ // derivation-only delta members — the wire `Check` members keep hex-only
202
+ // owners (see the note in continuation.ts).
203
+ const assertionOwnerZod = z.union([
204
+ hexStringZod,
205
+ z.enum(['escrow', 'delivery']),
206
+ ]);
207
+
208
+ export const CheckZod = z.discriminatedUnion('kind', [
209
+ z.object({
210
+ kind: z.literal('erc20BalanceGte'),
211
+ chainId: chainIdZod,
212
+ token: hexStringZod,
213
+ owner: hexStringZod,
214
+ minAmount: z.string(),
215
+ }),
216
+ z.object({
217
+ kind: z.literal('nativeBalanceGte'),
218
+ chainId: chainIdZod,
219
+ owner: hexStringZod,
220
+ minAmount: z.string(),
221
+ }),
222
+ z.object({
223
+ kind: z.literal('call'),
224
+ chainId: chainIdZod,
225
+ to: hexStringZod,
226
+ calldata: hexStringZod,
227
+ comparator: z.enum(['gte', 'eq', 'lte']),
228
+ value: z.string(),
229
+ }),
230
+ ]);
231
+
232
+ // HTTP-layer mirror of `AssertionSpecSchema` (continuation.ts): the three
233
+ // `Check` members plus the two derivation-only members. Reuses `CheckZod`'s
234
+ // options so the shared members cannot drift from `Check`.
235
+ export const AssertionSpecZod = z.discriminatedUnion('kind', [
236
+ ...CheckZod.options,
237
+ z.object({
238
+ kind: z.literal('erc20BalanceDeltaGte'),
239
+ chainId: z.number().int().positive(),
240
+ token: hexStringZod,
241
+ owner: assertionOwnerZod,
242
+ minDelta: z.string(),
243
+ }),
244
+ z.object({
245
+ kind: z.literal('nativeBalanceDeltaGte'),
246
+ chainId: z.number().int().positive(),
247
+ owner: assertionOwnerZod,
248
+ minDelta: z.string(),
249
+ }),
250
+ ]);
251
+
252
+ export type AssertionSpecWire = z.infer<typeof AssertionSpecZod>;
253
+
254
+ // HTTP-layer mirror of the GD-3 descriptor union `AssertedPredicateSchema`
255
+ // (descriptor.ts, seam C4). It is the disclosure-path widening of
256
+ // `AssertionSpecZod`: the two balance-`Gte` members accept a symbolic owner
257
+ // (`assertionOwnerZod`) as well as hex, because the derivation resolves symbolic
258
+ // owners to validator-injected slots at settlement. The wire `Check` members
259
+ // stay hex-only (`CheckZod`); this widening is confined to the descriptor. The
260
+ // `call` member and the two derivation-only delta members are reused verbatim by
261
+ // selecting them from `AssertionSpecZod.options` by their `kind` literal, so
262
+ // they cannot drift from the source union.
263
+ const assertionSpecOptionByKind = (kind: string) => {
264
+ const option = AssertionSpecZod.options.find(
265
+ (o) => o.shape.kind.value === kind,
266
+ );
267
+ if (option === undefined) {
268
+ throw new Error(`AssertionSpecZod has no member with kind "${kind}"`);
269
+ }
270
+ return option;
271
+ };
272
+
273
+ export const AssertedPredicateZod = z.discriminatedUnion('kind', [
274
+ z.object({
275
+ kind: z.literal('erc20BalanceGte'),
276
+ chainId: z.number().int().positive(),
277
+ token: hexStringZod,
278
+ owner: assertionOwnerZod,
279
+ minAmount: z.string(),
280
+ }),
281
+ z.object({
282
+ kind: z.literal('nativeBalanceGte'),
283
+ chainId: z.number().int().positive(),
284
+ owner: assertionOwnerZod,
285
+ minAmount: z.string(),
286
+ }),
287
+ assertionSpecOptionByKind('call'),
288
+ assertionSpecOptionByKind('erc20BalanceDeltaGte'),
289
+ assertionSpecOptionByKind('nativeBalanceDeltaGte'),
290
+ ]);
291
+
292
+ export const VerificationDescriptorZod = z.object({
293
+ validationProgramHash: z.string().regex(BYTES32_LOWER_HEX),
294
+ // The C5 echo's second hash (GD-8): the params-vector content hash
295
+ // (`paramsHash`, C1). Required and jointly necessary with the value-blind
296
+ // `validationProgramHash`.
297
+ paramsHash: z.string().regex(BYTES32_LOWER_HEX),
298
+ assertedPredicate: z.array(AssertedPredicateZod),
299
+ });
300
+
301
+ export type AssertedPredicateWire = z.infer<typeof AssertedPredicateZod>;
302
+ export type VerificationDescriptorWire = z.infer<
303
+ typeof VerificationDescriptorZod
304
+ >;
305
+
306
+ // HTTP-layer mirror of `ContinuationPlanSchema`. `nextFlow` is typed
307
+ // `z.unknown()` rather than mirroring the full Flow schema in Zod: the client
308
+ // treats it as an opaque, re-submittable document and POSTs it back to
309
+ // `/compose`, where the Effect `FlowSchema` validates it. The internal
310
+ // `ContinuationPlan` type keeps `nextFlow: Flow` precisely typed.
311
+ export const ContinuationPlanZod = z.object({
312
+ chainId: chainIdZod,
313
+ nextFlow: z.unknown(),
314
+ check: CheckZod,
315
+ validity: z.object({ expiresAtMs: z.number() }),
316
+ correlationId: z.string().optional(),
317
+ });
318
+
161
319
  export type ResourcePort = z.infer<typeof ResourcePortZod>;
162
320
  export type HandlePort = z.infer<typeof HandlePortZod>;
163
321
  export type HandleUnits = z.infer<typeof HandleUnitsZod>;
@@ -172,3 +330,5 @@ export type ManifestGuard = z.infer<typeof ManifestGuardZod>;
172
330
  export type ManifestMaterialiser = z.infer<typeof ManifestMaterialiserZod>;
173
331
  export type ManifestPrecondition = z.infer<typeof ManifestPreconditionZod>;
174
332
  export type ComposeManifest = z.infer<typeof ComposeManifestZod>;
333
+ export type Phase1ArtifactWire = z.infer<typeof Phase1ArtifactZod>;
334
+ export type ContinuationPlanWire = z.infer<typeof ContinuationPlanZod>;