@lifi/compose-spec 0.6.3 → 0.7.1

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.
@@ -4,7 +4,14 @@ import {
4
4
  nativeCheckPolicy,
5
5
  normalizeNativeTokenAddress,
6
6
  } from './chainCapabilities.js';
7
- import { ChainIdSchema, FlowSchema } from './flowSchema.js';
7
+ import {
8
+ ChainIdSchema,
9
+ EpochMsSchema,
10
+ EVMAddressString,
11
+ FlowSchema,
12
+ HexBytesString,
13
+ IntegerString,
14
+ } from './flowSchema.js';
8
15
 
9
16
  // The op id of the self-describing commitment carrier node embedded in a
10
17
  // persisted committed continuation action (verified continuations, plan GD-8,
@@ -18,16 +25,20 @@ export const CONTINUATION_COMMITMENT_OP_ID = 'continuation.commitment';
18
25
  // A single committed outcome of a deferred settlement: at least `minAmount` of
19
26
  // `token` must be delivered to `destination` on `chainId`. Amounts are decimal
20
27
  // strings on the wire because JSON has no bigint; `chainId` reuses the shared
21
- // `ChainIdSchema` from `flowSchema.ts`.
28
+ // `ChainIdSchema` from `flowSchema.ts`. `token` becomes a `Resource` in
29
+ // `continuation.settle`'s output and `destination` its owner, so both take the
30
+ // address rule; every consumer reads `minAmount` as a uint256. A zero
31
+ // `minAmount` is well-formed here (a persisted commitment re-decodes this
32
+ // schema); `continuation.settle`'s precheck rejects it for a new flow.
22
33
  const RawContinuationOutcomeSchema = Schema.Struct({
23
- token: Schema.String,
24
- minAmount: Schema.String,
25
- destination: Schema.String,
34
+ token: EVMAddressString,
35
+ minAmount: IntegerString,
36
+ destination: EVMAddressString,
26
37
  chainId: ChainIdSchema,
27
38
  });
28
39
 
29
- // Decode transform mirroring `ResourceSchema`: `token` is a bare string that
30
- // never flows through `ResourceSchema`, so on `as-erc20` chains the native
40
+ // Decode transform mirroring `ResourceSchema`: `token` never flows through
41
+ // `ResourceSchema`, so on `as-erc20` chains the native
31
42
  // sentinel is rewritten to the chain's ERC-20 here — otherwise downstream would
32
43
  // treat the delivery asset as native. Encode is the identity (the ERC-20 form
33
44
  // is valid wire input).
@@ -59,7 +70,7 @@ export const ContinuationIntentSchema = Schema.Struct({
59
70
  // `NonEmptyArray` enforces ≥1 outcome at the parse boundary, so downstream needs no guard.
60
71
  outcomes: Schema.NonEmptyArray(ContinuationOutcomeSchema),
61
72
  continuationFlow: Schema.optional(FlowSchema),
62
- validity: Schema.Struct({ expiresAtMs: Schema.Number }),
73
+ validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
63
74
  perpetual: Schema.optional(Schema.Boolean),
64
75
  provider: Schema.optional(Schema.String),
65
76
  // Funding-path mode. The HTTP wire contract is documented by
@@ -67,10 +78,47 @@ export const ContinuationIntentSchema = Schema.Struct({
67
78
  funding: Schema.optional(Schema.Literal('inline', 'external')),
68
79
  });
69
80
 
70
- // Internal phase-1 artifact. The HTTP layer projects `transaction` artifacts
71
- // to metadata and publishes real external-funding calldata through
81
+ // A `0x`-prefixed string, prefix checked only. Continuation vocabulary no
82
+ // longer uses it for addresses (those take `EVMAddressString`); it remains
83
+ // for the escrow record below, which the settlement service returns, and for
84
+ // op configs not yet tightened. `zodSchemas.ts` mirrors it as `hexStringZod`.
85
+ export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
86
+
87
+ // The escrow a settlement provider registered for a settle node, disclosed on
88
+ // the `transaction` artifact and projected onto the wire as
89
+ // `settlements[nodeId].escrow`. Present only when the provider registered one;
90
+ // providers that fund no escrow never set it. Every field is present whenever
91
+ // the record is. Mirrored by `SettlementEscrowZod`.
92
+ //
93
+ // - `chainId` + `address` — the escrow and its chain. The escrow is keyed by
94
+ // the funding user, so the pair identifies that user's escrow on the chain,
95
+ // not one settlement.
96
+ // - `token` + `amount` — the funding asset (native → `EVM_NATIVE_SENTINEL`)
97
+ // and the raw amount the phase-1 funding transfer sends.
98
+ // - `cap` — the committed funding allocation: the most a fill may spend from
99
+ // the escrow. A balance above it stays in the escrow.
100
+ // - `owner` — the account that controls the escrow and can sweep it.
101
+ // - `refund` — where the escrow balance returns when the settlement expires.
102
+ // - `expiresAtMs` — when the settlement expires: the effective expiry the
103
+ // settlement service stores, which can be earlier than the authored
104
+ // `validity.expiresAtMs` or, for a re-registered perpetual escrow, the
105
+ // existing escrow's expiry (later, or already past); after it the escrow is
106
+ // never filled and its balance is refunded.
107
+ const Phase1EscrowSchema = Schema.Struct({
108
+ chainId: ChainIdSchema,
109
+ address: HexStringSchema,
110
+ token: HexStringSchema,
111
+ amount: Schema.String,
112
+ cap: Schema.String,
113
+ owner: HexStringSchema,
114
+ refund: HexStringSchema,
115
+ expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive()),
116
+ });
117
+
118
+ // Internal phase-1 artifact. The HTTP layer projects its `escrow` onto
119
+ // `settlements` and publishes external-funding calldata and typed data through
72
120
  // `ComposeActionsSchema`. The internal `transactionRequest` remains optional
73
- // because inline funding and dry runs do not produce a submittable transfer.
121
+ // because inline funding does not produce a submittable transfer.
74
122
  export const Phase1ArtifactSchema = Schema.Union(
75
123
  Schema.Struct({
76
124
  kind: Schema.Literal('transaction'),
@@ -83,6 +131,7 @@ export const Phase1ArtifactSchema = Schema.Union(
83
131
  chainId: Schema.Number,
84
132
  }),
85
133
  ),
134
+ escrow: Schema.optional(Phase1EscrowSchema),
86
135
  }),
87
136
  Schema.Struct({
88
137
  kind: Schema.Literal('signables'),
@@ -103,13 +152,11 @@ export const Phase1ArtifactSchema = Schema.Union(
103
152
  // - `call` — a generic `eth_call` to `to` with `calldata`, comparing the
104
153
  // returned value against `value` using `comparator`.
105
154
  //
106
- // Address/bytes fields (`token`/`owner`/`to`/`calldata`) require a `0x` prefix.
107
- // Validation is intentionally lenient (prefix only, not full 40-hex) to match
108
- // the rest of the compose wire format — `ContinuationOutcomeSchema.token`/
109
- // `destination` are bare strings too — and to keep placeholder fixtures usable;
110
- // the exact address is validated by `toAddress` when the check is lowered to an
111
- // on-chain assertion. The prefix gate still rejects empty/garbage values early.
112
- export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
155
+ // Addresses (`token`/`owner`/`to`) take `EVMAddressString`, `calldata` takes
156
+ // `HexBytesString`, and amounts (`minAmount`/`value`, and `minDelta` below)
157
+ // take `IntegerString`, so a malformed value fails at decode instead of in
158
+ // lowering. Amounts are not positive-only: a persisted descriptor re-decodes
159
+ // these members, and a zero threshold is well-formed (just vacuous).
113
160
 
114
161
  // A balance owner in a derivation-only assertion spec. Concrete addresses stay
115
162
  // hex; the two symbolic owners `"escrow"` / `"delivery"` are resolved to
@@ -121,7 +168,7 @@ export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
121
168
  // throw at lowering); keeping `Check` owners hex-only rejects such a value
122
169
  // cleanly at validation instead.
123
170
  export const AssertionOwnerSchema = Schema.Union(
124
- HexStringSchema,
171
+ EVMAddressString,
125
172
  Schema.Literal('escrow', 'delivery'),
126
173
  );
127
174
  export type AssertionOwner = typeof AssertionOwnerSchema.Type;
@@ -133,25 +180,25 @@ export type AssertionOwner = typeof AssertionOwnerSchema.Type;
133
180
  export const Erc20BalanceGteSpecSchema = Schema.Struct({
134
181
  kind: Schema.Literal('erc20BalanceGte'),
135
182
  chainId: ChainIdSchema,
136
- token: HexStringSchema,
137
- owner: HexStringSchema,
138
- minAmount: Schema.String,
183
+ token: EVMAddressString,
184
+ owner: EVMAddressString,
185
+ minAmount: IntegerString,
139
186
  });
140
187
 
141
188
  export const NativeBalanceGteSpecSchema = Schema.Struct({
142
189
  kind: Schema.Literal('nativeBalanceGte'),
143
190
  chainId: ChainIdSchema,
144
- owner: HexStringSchema,
145
- minAmount: Schema.String,
191
+ owner: EVMAddressString,
192
+ minAmount: IntegerString,
146
193
  });
147
194
 
148
195
  export const CallCheckSpecSchema = Schema.Struct({
149
196
  kind: Schema.Literal('call'),
150
197
  chainId: ChainIdSchema,
151
- to: HexStringSchema,
152
- calldata: HexStringSchema,
198
+ to: EVMAddressString,
199
+ calldata: HexBytesString,
153
200
  comparator: Schema.Literal('gte', 'eq', 'lte'),
154
- value: Schema.String,
201
+ value: IntegerString,
155
202
  });
156
203
 
157
204
  // The shape shared by the wire `nativeBalanceGte` check and the descriptor's
@@ -240,16 +287,16 @@ export const CheckSchema = Schema.transformOrFail(
240
287
  export const Erc20BalanceDeltaGteSpecSchema = Schema.Struct({
241
288
  kind: Schema.Literal('erc20BalanceDeltaGte'),
242
289
  chainId: ChainIdSchema,
243
- token: HexStringSchema,
290
+ token: EVMAddressString,
244
291
  owner: AssertionOwnerSchema,
245
- minDelta: Schema.String,
292
+ minDelta: IntegerString,
246
293
  });
247
294
 
248
295
  export const NativeBalanceDeltaGteSpecSchema = Schema.Struct({
249
296
  kind: Schema.Literal('nativeBalanceDeltaGte'),
250
297
  chainId: ChainIdSchema,
251
298
  owner: AssertionOwnerSchema,
252
- minDelta: Schema.String,
299
+ minDelta: IntegerString,
253
300
  });
254
301
 
255
302
  export const AssertionSpecSchema = Schema.Union(
@@ -271,7 +318,7 @@ export const ContinuationPlanSchema = Schema.Struct({
271
318
  chainId: ChainIdSchema,
272
319
  nextFlow: FlowSchema,
273
320
  check: CheckSchema,
274
- validity: Schema.Struct({ expiresAtMs: Schema.Number }),
321
+ validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
275
322
  correlationId: Schema.optional(Schema.String),
276
323
  });
277
324
 
package/src/descriptor.ts CHANGED
@@ -5,11 +5,14 @@ import {
5
5
  CallCheckSpecSchema,
6
6
  decodeNativeBalanceGte,
7
7
  Erc20BalanceDeltaGteSpecSchema,
8
- HexStringSchema,
9
8
  NativeBalanceDeltaGteSpecSchema,
10
9
  } from './continuation.js';
11
10
  import type { AssertionSpec } from './continuation.js';
12
- import { ChainIdSchema } from './flowSchema.js';
11
+ import {
12
+ ChainIdSchema,
13
+ EVMAddressString,
14
+ IntegerString,
15
+ } from './flowSchema.js';
13
16
  import { BYTES32_LOWER_HEX } from './hexPatterns.js';
14
17
 
15
18
  // The neutral per-leg verification descriptor (verified continuations, plan
@@ -24,8 +27,8 @@ import { BYTES32_LOWER_HEX } from './hexPatterns.js';
24
27
  // of the same `AssertionSpec[]` the validation program is derived from, so
25
28
  // disclosure cannot drift from enforcement — both are projections of one array.
26
29
 
27
- // `ChainIdSchema` (from `flowSchema.ts`) and `HexStringSchema` (from
28
- // `continuation.ts`) are reused directly, so the widened members below differ
30
+ // `ChainIdSchema`, `EVMAddressString` and `IntegerString` (from
31
+ // `flowSchema.ts`) are reused directly, so the widened members below differ
29
32
  // from their readiness counterparts in exactly one field (`owner`) with no
30
33
  // risk of a drifting re-declaration.
31
34
 
@@ -46,16 +49,16 @@ export const Bytes32HexSchema = Schema.String.pipe(
46
49
  export const AssertedErc20BalanceGteSpecSchema = Schema.Struct({
47
50
  kind: Schema.Literal('erc20BalanceGte'),
48
51
  chainId: ChainIdSchema,
49
- token: HexStringSchema,
52
+ token: EVMAddressString,
50
53
  owner: AssertionOwnerSchema,
51
- minAmount: Schema.String,
54
+ minAmount: IntegerString,
52
55
  });
53
56
 
54
57
  export const AssertedNativeBalanceGteSpecSchema = Schema.Struct({
55
58
  kind: Schema.Literal('nativeBalanceGte'),
56
59
  chainId: ChainIdSchema,
57
60
  owner: AssertionOwnerSchema,
58
- minAmount: Schema.String,
61
+ minAmount: IntegerString,
59
62
  });
60
63
 
61
64
  // The disclosed predicate: the five `AssertionSpec` kinds, with symbolic owners
package/src/flowSchema.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import { Schema } from 'effect';
2
2
 
3
3
  import { normalizeResource } from './chainCapabilities.js';
4
+ import {
5
+ DECIMAL_UINT,
6
+ EVM_ADDRESS_HEX,
7
+ HEX_BYTES,
8
+ MAX_DATE_MS,
9
+ MAX_UINT256,
10
+ } from './hexPatterns.js';
4
11
 
5
12
  export const SolTypeSchema = Schema.Literal(
6
13
  'uint8',
@@ -26,11 +33,64 @@ export const ChainIdSchema = Schema.Number.pipe(
26
33
  Schema.positive(),
27
34
  );
28
35
 
36
+ // The one wire rule for an EVM address in flow documents and op configs.
37
+ // Compose ops import it from here, so every address field fails with the same
38
+ // message and advertises the same pattern in the manifest.
39
+ export const EVMAddressString = Schema.String.pipe(
40
+ Schema.pattern(EVM_ADDRESS_HEX, {
41
+ message: () => 'expected a 0x-prefixed 20-byte EVM address',
42
+ }),
43
+ ).annotations({
44
+ description: 'EVM address: 0x followed by 40 hex characters',
45
+ });
46
+
47
+ // Whole-byte hex payload (`0x` + an even number of hex digits). Stricter than
48
+ // builtins' `HexDataString`, which keeps odd-length acceptance for op configs:
49
+ // see `HEX_BYTES`.
50
+ export const HexBytesString = Schema.String.pipe(
51
+ Schema.pattern(HEX_BYTES, {
52
+ message: () => 'expected 0x-prefixed hex of whole bytes',
53
+ }),
54
+ ).annotations({
55
+ description: 'Hex bytes: 0x followed by an even number of hex characters',
56
+ });
57
+
58
+ // An epoch-millisecond timestamp a `Date` can represent. Pure and
59
+ // clock-independent, so it holds at decode; whether it is still in the future
60
+ // is the consumer's registration-time check.
61
+ export const EpochMsSchema = Schema.Number.pipe(
62
+ Schema.int(),
63
+ Schema.between(-MAX_DATE_MS, MAX_DATE_MS),
64
+ );
65
+
66
+ // The one wire rule for a raw-unit uint256 amount carried as a decimal string
67
+ // (JSON has no bigint). Compose ops import it from here, as they do
68
+ // `EVMAddressString`.
69
+ //
70
+ // Effect's JSONSchema emitter drops a filter with no `jsonSchema` annotation,
71
+ // so the constraint never reaches `manifest.json` or the generated SDK types.
72
+ // Annotating it churns the generated artifacts and `manifestHash`: tracked as
73
+ // COM-1717.
74
+ export const IntegerString = Schema.String.pipe(
75
+ // Both checks live in one filter so the uint256-bound test only ever runs
76
+ // `BigInt` on a string the digit check already accepted — order-independent
77
+ // and never throws on malformed input.
78
+ Schema.filter((value) => {
79
+ if (!DECIMAL_UINT.test(value)) {
80
+ return 'amount must be a decimal integer string';
81
+ }
82
+ if (BigInt(value) > MAX_UINT256) {
83
+ return 'amount must not exceed uint256 max';
84
+ }
85
+ return undefined;
86
+ }),
87
+ );
88
+
29
89
  const RawResourceSchema = Schema.Union(
30
90
  Schema.Struct({ kind: Schema.Literal('native'), chainId: ChainIdSchema }),
31
91
  Schema.Struct({
32
92
  kind: Schema.Literal('erc20'),
33
- token: Schema.String,
93
+ token: EVMAddressString,
34
94
  chainId: ChainIdSchema,
35
95
  }),
36
96
  );
@@ -98,8 +158,19 @@ export const AppliedGuardSchema = Schema.Struct(
98
158
  { key: Schema.String, value: Schema.Unknown },
99
159
  );
100
160
 
161
+ // A node id keys the compiler's and the response's per-node records. Those are
162
+ // plain objects, and `__proto__` there sets the prototype instead of adding a
163
+ // key; the response serializer's `z.record` also drops a `__proto__` key. So
164
+ // the id can never round-trip, and the one flow schema rejects it for every
165
+ // flow it decodes, including an embedded manual-relay `continuationFlow`.
166
+ const NodeIdSchema = Schema.String.pipe(
167
+ Schema.filter((id) => id !== '__proto__', {
168
+ message: () => 'node id "__proto__" is reserved; choose another node id',
169
+ }),
170
+ );
171
+
101
172
  export const CallSchema = Schema.Struct({
102
- id: Schema.String,
173
+ id: NodeIdSchema,
103
174
  op: Schema.String,
104
175
  bind: Schema.optionalWith(
105
176
  Schema.Record({ key: Schema.String, value: BindValueSchema }),
@@ -112,12 +183,37 @@ export const CallSchema = Schema.Struct({
112
183
  guards: Schema.optional(Schema.Array(AppliedGuardSchema)),
113
184
  });
114
185
 
186
+ // A canonical lowercase UUID, the identity zap-backend mints per HTTP request
187
+ // and returns as `X-Flow-Id`.
188
+ export const UuidSchema = Schema.String.pipe(
189
+ Schema.pattern(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/),
190
+ );
191
+
192
+ // Journey lineage of a non-atomic flow (COM-1253). The server writes it into
193
+ // every flow it hands out for a later compile — a manual-relay `nextFlow`, an
194
+ // intent-factory committed action — so a journey's legs share one id without
195
+ // the caller carrying anything. A root flow has no `lineage`.
196
+ //
197
+ // It has no program semantics: nothing lowers it and nothing executes it. Only
198
+ // the compile pipeline (which turns it into the on-chain `ProgramExecution`
199
+ // word) and the request-tracking scrub read it.
200
+ //
201
+ // Trust: a caller may hand-write or copy a stamp and the system accepts it.
202
+ // The link is server-asserted where the flow is committed (intent-factory
203
+ // registers the stamped blob) and telemetry-grade where the caller can edit
204
+ // the flow (manual-relay).
205
+ export const LineageSchema = Schema.Struct({
206
+ journeyId: UuidSchema,
207
+ parentRequestId: UuidSchema,
208
+ });
209
+
115
210
  export const FlowSchema = Schema.Struct({
116
211
  version: Schema.Literal(1),
117
212
  id: Schema.String,
118
213
  chainId: ChainIdSchema,
119
214
  inputs: Schema.Array(FlowInputSchema),
120
215
  nodes: Schema.Array(CallSchema),
216
+ lineage: Schema.optional(LineageSchema),
121
217
  });
122
218
 
123
219
  export type SolType = typeof SolTypeSchema.Type;
@@ -129,4 +225,5 @@ export type LiteralBinding = typeof LiteralBindingSchema.Type;
129
225
  export type BindValue = typeof BindValueSchema.Type;
130
226
  export type AppliedGuard = typeof AppliedGuardSchema.Type;
131
227
  export type Call = typeof CallSchema.Type;
228
+ export type Lineage = typeof LineageSchema.Type;
132
229
  export type Flow = typeof FlowSchema.Type;
@@ -1,9 +1,11 @@
1
- // Shared hex-string patterns for the compose wire format. Zero-dependency leaf
2
- // so both the Effect-schema side (`descriptor.ts`) and the standalone Zod
3
- // mirror (`zodSchemas.ts`) consume one source of truth without importing across
1
+ // Shared string patterns and bounds for the compose wire format.
2
+ // Zero-dependency leaf so both the Effect-schema side (`flowSchema.ts`,
3
+ // `continuation.ts`, `descriptor.ts`) and the standalone Zod mirror
4
+ // (`zodSchemas.ts`) consume one source of truth without importing across
4
5
  // layers. compose-spec is the wire-format leaf and may not import `@lifi/utils`
5
- // (enforced by `scripts/check-compose-boundaries.mjs`), so the equivalent of
6
- // `makeHexStringRegex(32, { lowercase: true })` is inlined here.
6
+ // (enforced by `scripts/check-compose-boundaries.mjs`), so the equivalents of
7
+ // `makeHexStringRegex(32, { lowercase: true })` and `MaxUint256` are inlined
8
+ // here.
7
9
 
8
10
  // A `0x`-prefixed, exactly-32-byte, STRICTLY lowercase hex string. Validated
9
11
  // strictly — deliberately overriding compose-spec's lenient `0x`-prefix-only
@@ -14,3 +16,22 @@
14
16
  // poison determinism and the byte-identity fixture discipline. A zero hash
15
17
  // `0x00…00` (64 zeros) remains valid under the strict rule.
16
18
  export const BYTES32_LOWER_HEX = /^0x[0-9a-f]{64}$/;
19
+
20
+ // A `0x`-prefixed 20-byte EVM address, hex digits in either case (EIP-55
21
+ // checksums are mixed-case); the prefix itself must be lowercase.
22
+ export const EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/;
23
+
24
+ // `0x` followed by whole bytes. Calldata is decoded by `hexToBytes`, which
25
+ // silently drops a trailing odd nibble, so odd-length input is rejected here
26
+ // rather than compiled into a different call.
27
+ export const HEX_BYTES = /^0x(?:[0-9a-fA-F]{2})*$/;
28
+
29
+ // A decimal integer string with no sign, fraction, exponent or hex prefix.
30
+ export const DECIMAL_UINT = /^[0-9]+$/;
31
+
32
+ // eslint-disable-next-line @lifi/prefer-utils-constants -- see the header: compose-spec may not import @lifi/utils
33
+ export const MAX_UINT256 = 2n ** 256n - 1n;
34
+
35
+ // The largest epoch-millisecond magnitude a JS `Date` holds (ECMA-262
36
+ // §21.4.1.1); an expiry outside it has no ISO-8601 form to register.
37
+ export const MAX_DATE_MS = 8.64e15;
package/src/index.ts CHANGED
@@ -9,8 +9,11 @@ export type {
9
9
  AppliedGuard,
10
10
  Call,
11
11
  Flow,
12
+ Lineage,
12
13
  } from './flowSchema.js';
13
14
  export {
15
+ EVMAddressString,
16
+ IntegerString,
14
17
  FlowSchema,
15
18
  ResourceSchema,
16
19
  SolTypeSchema,
@@ -22,6 +25,8 @@ export {
22
25
  BindValueSchema,
23
26
  AppliedGuardSchema,
24
27
  CallSchema,
28
+ LineageSchema,
29
+ UuidSchema,
25
30
  } from './flowSchema.js';
26
31
 
27
32
  export type {
@@ -153,6 +158,14 @@ export {
153
158
  resourceOutput,
154
159
  } from './constructors.js';
155
160
 
161
+ export type { OutputFamilyPort } from './outputFamilies.js';
162
+ export {
163
+ expandOutputPorts,
164
+ familySize,
165
+ instancePortName,
166
+ isOutputFamily,
167
+ } from './outputFamilies.js';
168
+
156
169
  export type {
157
170
  ParsedRef,
158
171
  RefScope,
@@ -292,7 +305,7 @@ export {
292
305
  ComposeManifestZod,
293
306
  GuardSelectorZod,
294
307
  GuardCompatibilityZod,
295
- Phase1ArtifactZod,
308
+ SettlementZod,
296
309
  CheckZod,
297
310
  AssertionSpecZod,
298
311
  AssertedPredicateZod,
@@ -302,7 +315,8 @@ export {
302
315
  export type {
303
316
  HandleUnits,
304
317
  StaticSolType,
305
- Phase1ArtifactWire,
318
+ SettlementWire,
319
+ SettlementEscrowWire,
306
320
  AssertionSpecWire,
307
321
  AssertedPredicateWire,
308
322
  VerificationDescriptorWire,
@@ -0,0 +1,68 @@
1
+ import type { Call } from './flowSchema.js';
2
+ import type { OpOutputPort, ResourceOutputPort } from './zodSchemas.js';
3
+
4
+ // An output *family* is a declared resource output carrying `countFrom`. When a
5
+ // call's config is bound, the family expands into one ordinary port per
6
+ // instance. `config[countFrom]` sets the instance count: an array gives one
7
+ // instance per element, and a non-negative integer gives that many instances.
8
+ // This module is the single definition of that expansion and of instance
9
+ // naming, shared by the compiler and the SDK so the two cannot disagree on
10
+ // port names.
11
+
12
+ // A family is marked by the `countFrom` field itself, which is also how it
13
+ // reaches SDK clients in the manifest JSON, so `isOutputFamily` narrows any
14
+ // port, whether built by `resourceOutput` or parsed from the wire.
15
+ export type OutputFamilyPort = ResourceOutputPort & {
16
+ readonly countFrom: string;
17
+ };
18
+
19
+ export const isOutputFamily = (port: OpOutputPort): port is OutputFamilyPort =>
20
+ port.kind === 'resource_output' && port.countFrom !== undefined;
21
+
22
+ // `parseRef` splits a ref at its first dot, so `node.parts.1` addresses port
23
+ // `parts.1` of node `node`. Declared port names never contain a dot, so an
24
+ // instance name cannot equal a fixed port name.
25
+ export const instancePortName = (family: string, index: number): string =>
26
+ `${family}.${index}`;
27
+
28
+ // The number of instances a family has under a call's config: the length of
29
+ // an array, or the value of a non-negative integer. The compiler decodes the
30
+ // config before expansion, so there any other value is an op-definition bug;
31
+ // the SDK sizes handles from the undecoded config the author wrote.
32
+ export const familySize = (
33
+ family: Pick<OutputFamilyPort, 'name' | 'countFrom'>,
34
+ config: Call['config'],
35
+ ): number => {
36
+ const source = config[family.countFrom];
37
+ if (Array.isArray(source)) return source.length;
38
+ if (Number.isSafeInteger(source) && (source as number) >= 0) {
39
+ return source as number;
40
+ }
41
+ throw new Error(
42
+ `Output family '${family.name}' counts from config '${family.countFrom}', which is neither an array nor a non-negative integer`,
43
+ );
44
+ };
45
+
46
+ const expandFamily = (
47
+ port: OutputFamilyPort,
48
+ config: Call['config'],
49
+ ): ResourceOutputPort[] => {
50
+ const { countFrom: _countFrom, ...instance } = port;
51
+ return Array.from({ length: familySize(port, config) }, (_, index) => ({
52
+ ...instance,
53
+ name: instancePortName(port.name, index),
54
+ }));
55
+ };
56
+
57
+ // Expand a declared output list against a call's decoded config. Fixed ports
58
+ // pass through unchanged; each family becomes its instances, in index order,
59
+ // at the family's position. A list without a family is returned as is.
60
+ export const expandOutputPorts = (
61
+ declared: readonly OpOutputPort[],
62
+ config: Call['config'],
63
+ ): readonly OpOutputPort[] =>
64
+ declared.some(isOutputFamily)
65
+ ? declared.flatMap((port) =>
66
+ isOutputFamily(port) ? expandFamily(port, config) : [port],
67
+ )
68
+ : declared;