@lifi/compose-spec 0.10.0 → 0.12.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.
@@ -1,6 +1,7 @@
1
1
  import { type Effect, ParseResult, Schema, type SchemaAST } from 'effect';
2
2
 
3
3
  import {
4
+ isZeroAddress,
4
5
  nativeCheckPolicy,
5
6
  normalizeNativeTokenAddress,
6
7
  } from './chainCapabilities.js';
@@ -9,7 +10,6 @@ import {
9
10
  EpochMsSchema,
10
11
  EVMAddressString,
11
12
  FlowSchema,
12
- HexBytesString,
13
13
  IntegerString,
14
14
  } from './flowSchema.js';
15
15
 
@@ -22,43 +22,67 @@ import {
22
22
  // settlement fill answered as an ordinary flow with no descriptor).
23
23
  export const CONTINUATION_COMMITMENT_OP_ID = 'continuation.commitment';
24
24
 
25
- // A single committed outcome of a deferred settlement: at least `minAmount` of
26
- // `token` must be delivered to `destination` on `chainId`. Amounts are decimal
27
- // strings on the wire because JSON has no bigint; `chainId` reuses the shared
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.
33
- const RawContinuationOutcomeSchema = Schema.Struct({
25
+ // A single outcome of a deferred settlement: `token` must be delivered to
26
+ // `destination` on `chainId`. Amounts are decimal strings on the wire because
27
+ // JSON has no bigint; `chainId` reuses the shared `ChainIdSchema` from
28
+ // `flowSchema.ts`. `token` becomes a `Resource` in `continuation.settle`'s
29
+ // output and `destination` its owner, so both take the address rule.
30
+ //
31
+ // `minAmount` is the floor the author commits to. An author may omit it: a
32
+ // committed provider proves the floor from the settle's `continuationFlow`,
33
+ // and an authored value can only raise what the proof delivers. A provider
34
+ // that proves nothing requires it. A zero `minAmount` decodes (`IntegerString`
35
+ // admits 0) and the pipeline reads it as omitted: the committed floor is the
36
+ // larger of the authored and the proven floor, and a floor of 0 is rejected.
37
+ //
38
+ // The decode transform mirrors `ResourceSchema`: `token` never flows through
39
+ // `ResourceSchema`, so on `as-erc20` chains the native sentinel is rewritten to
40
+ // the chain's ERC-20 here — otherwise downstream would treat the delivery asset
41
+ // as native. Encode is the identity (the ERC-20 form is valid wire input).
42
+ // Field order is wire-visible: a committed action serializes the decoded
43
+ // struct, so both structs below keep `minAmount` second.
44
+ const outcomeFields = <
45
+ M extends Schema.Schema.All | Schema.PropertySignature.All,
46
+ >(
47
+ minAmount: M,
48
+ ) => ({
34
49
  token: EVMAddressString,
35
- minAmount: IntegerString,
50
+ minAmount,
36
51
  destination: EVMAddressString,
37
52
  chainId: ChainIdSchema,
38
53
  });
39
54
 
40
- // Decode transform mirroring `ResourceSchema`: `token` never flows through
41
- // `ResourceSchema`, so on `as-erc20` chains the native
42
- // sentinel is rewritten to the chain's ERC-20 here — otherwise downstream would
43
- // treat the delivery asset as native. Encode is the identity (the ERC-20 form
44
- // is valid wire input).
45
- export const ContinuationOutcomeSchema = Schema.transform(
46
- RawContinuationOutcomeSchema,
47
- Schema.typeSchema(RawContinuationOutcomeSchema),
48
- {
55
+ const normalizingOutcome = <
56
+ A extends { readonly token: string; readonly chainId: number },
57
+ I,
58
+ >(
59
+ raw: Schema.Schema<A, I>,
60
+ ) =>
61
+ Schema.transform(raw, Schema.typeSchema(raw), {
49
62
  strict: true,
50
- decode: (raw) => ({
51
- ...raw,
52
- token: normalizeNativeTokenAddress(raw.token, raw.chainId),
63
+ decode: (outcome) => ({
64
+ ...outcome,
65
+ token: normalizeNativeTokenAddress(outcome.token, outcome.chainId),
53
66
  }),
54
67
  encode: (outcome) => outcome,
55
- },
68
+ });
69
+
70
+ // The authored outcome: `minAmount` optional.
71
+ export const ContinuationOutcomeSchema = normalizingOutcome(
72
+ Schema.Struct(outcomeFields(Schema.optional(IntegerString))),
73
+ );
74
+
75
+ // The committed outcome: the floor the provider registered, always present.
76
+ // The `continuation.commitment` node and every provider's `prepare()` read
77
+ // this shape.
78
+ export const CommittedOutcomeSchema = normalizingOutcome(
79
+ Schema.Struct(outcomeFields(IntegerString)),
56
80
  );
57
81
 
58
82
  // Backend-neutral config for the `continuation.settle` op. Note: the funding
59
83
  // input is NOT a config field — the deferred step's funding resource/amount is
60
84
  // wired via the node's `bind.input` (see M3b). Only the committed terms below
61
- // (`outcomes`/`continuationFlow`/`validity`/`perpetual`/`provider`) are the
85
+ // (`outcomes`/`continuationFlow`/`validity`/`provider`) are the
62
86
  // node's `config`.
63
87
  //
64
88
  // `continuationFlow` is an inlined Flow document that the settlement backend
@@ -71,17 +95,32 @@ export const ContinuationIntentSchema = Schema.Struct({
71
95
  outcomes: Schema.NonEmptyArray(ContinuationOutcomeSchema),
72
96
  continuationFlow: Schema.optional(FlowSchema),
73
97
  validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
74
- perpetual: Schema.optional(Schema.Boolean),
75
98
  provider: Schema.optional(Schema.String),
76
99
  // Funding-path mode. The HTTP wire contract is documented by
77
- // `ComposeActionsSchema` in `@lifi/api-schemas`.
100
+ // `ComposeActionsSchema` in `@lifi/api-schemas`. A settle funded by a
101
+ // bridge delivery (`'delivered'` on the artifact) is inferred from its
102
+ // binding and never authored.
78
103
  funding: Schema.optional(Schema.Literal('inline', 'external')),
104
+ // The address on the escrow's chain that receives the escrow balance on
105
+ // expiry; defaults to the signer. The zero address would burn that balance.
106
+ refund: Schema.optional(
107
+ EVMAddressString.pipe(
108
+ Schema.filter((address) => !isZeroAddress(address), {
109
+ message: () => 'refund must not be the zero address',
110
+ }),
111
+ ),
112
+ ),
113
+ // Bind the settlement to the leg's compiled bytes: the fill runs exactly the
114
+ // calldata the compile proved, so the solver chooses nothing. Needs a
115
+ // `continuationFlow` and a provider that advertises the capability.
116
+ exact: Schema.optional(Schema.Boolean),
79
117
  });
80
118
 
81
119
  // A `0x`-prefixed string, prefix checked only. Continuation vocabulary no
82
120
  // 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`.
121
+ // for the escrow and binding records below, which the settlement service
122
+ // returns, and for op configs not yet tightened. `zodSchemas.ts` mirrors it
123
+ // as `hexStringZod`.
85
124
  export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
86
125
 
87
126
  // The escrow a settlement provider registered for a settle node, disclosed on
@@ -90,41 +129,67 @@ export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
90
129
  // providers that fund no escrow never set it. Every field is present whenever
91
130
  // the record is. Mirrored by `SettlementEscrowZod`.
92
131
  //
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.
132
+ // - `chainId` + `address` — the escrow and its chain. Every registration gets
133
+ // a fresh escrow, so the pair identifies this one settlement; never fund it
134
+ // for another.
96
135
  // - `token` + `amount` — the funding asset (native → `EVM_NATIVE_SENTINEL`)
97
136
  // and the raw amount the escrow was sized from. The program transfers the
98
137
  // amount realised at execution, which can differ when an upstream op
99
138
  // supplies the funding.
100
139
  // - `cap` — the committed funding allocation: the most a fill may spend from
101
140
  // the escrow. A balance above it stays in the escrow.
141
+ // - `floor` — the registered funding floor: the least balance that arms a
142
+ // fill. A smaller balance waits for expiry and is refunded.
102
143
  // - `owner` — the account that controls the escrow and can sweep it.
103
144
  // - `refund` — where the escrow balance returns when the settlement expires.
104
145
  // - `expiresAtMs` — when the settlement expires: the effective expiry the
105
146
  // settlement service stores, which can be earlier than the authored
106
- // `validity.expiresAtMs` or, for a re-registered perpetual escrow, the
107
- // existing escrow's expiry (later, or already past); after it the escrow is
108
- // never filled and its balance is refunded.
147
+ // `validity.expiresAtMs`; after it the escrow is never filled and its
148
+ // balance is refunded.
109
149
  const Phase1EscrowSchema = Schema.Struct({
110
150
  chainId: ChainIdSchema,
111
151
  address: HexStringSchema,
112
152
  token: HexStringSchema,
113
153
  amount: Schema.String,
114
154
  cap: Schema.String,
155
+ floor: Schema.String,
115
156
  owner: HexStringSchema,
116
157
  refund: HexStringSchema,
117
158
  expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive()),
118
159
  });
119
160
 
120
- // Internal phase-1 artifact. The HTTP layer projects its `escrow` onto
121
- // `settlements` and publishes external-funding calldata and typed data through
122
- // `ComposeActionsSchema`. The internal `transactionRequest` remains optional
123
- // because inline funding does not produce a submittable transfer.
161
+ // The executor binding of an `exact` settle, disclosed on the `transaction`
162
+ // artifact and projected onto the wire as `settlements[nodeId].binding`.
163
+ // Absent unless the settle is `exact`. Every field is present whenever the
164
+ // record is. Mirrored by `SettlementBindingZod`.
165
+ //
166
+ // - `executionTarget` — the executor that runs the fill.
167
+ // - `payload` — the executor call the settlement service hashed into the
168
+ // escrow's execute constraint; a fill that runs anything else is rejected.
169
+ // - `payloadHash` — `keccak256(payload)`, the committed hash.
170
+ // - `calldata` — what the executor's proxy runs: the leg's compiled bytes.
171
+ // - `approvals` — the allowances the executor grants before it runs
172
+ // `calldata`.
173
+ const Phase1BindingSchema = Schema.Struct({
174
+ executionTarget: HexStringSchema,
175
+ payload: HexStringSchema,
176
+ payloadHash: HexStringSchema,
177
+ calldata: HexStringSchema,
178
+ approvals: Schema.Array(
179
+ Schema.Struct({ token: HexStringSchema, spender: HexStringSchema }),
180
+ ),
181
+ });
182
+
183
+ // Internal phase-1 artifact. The HTTP layer projects its `escrow` and
184
+ // `binding` onto `settlements` and publishes external-funding calldata and
185
+ // typed data through `ComposeActionsSchema`. The internal `transactionRequest`
186
+ // remains optional because inline funding does not produce a submittable
187
+ // transfer, and `delivered` funding (a bridge delivers into the escrow)
188
+ // produces none either.
124
189
  export const Phase1ArtifactSchema = Schema.Union(
125
190
  Schema.Struct({
126
191
  kind: Schema.Literal('transaction'),
127
- funding: Schema.Literal('inline', 'external'),
192
+ funding: Schema.Literal('inline', 'external', 'delivered'),
128
193
  transactionRequest: Schema.optional(
129
194
  Schema.Struct({
130
195
  to: Schema.String,
@@ -134,6 +199,7 @@ export const Phase1ArtifactSchema = Schema.Union(
134
199
  }),
135
200
  ),
136
201
  escrow: Schema.optional(Phase1EscrowSchema),
202
+ binding: Schema.optional(Phase1BindingSchema),
137
203
  }),
138
204
  Schema.Struct({
139
205
  kind: Schema.Literal('signables'),
@@ -142,29 +208,36 @@ export const Phase1ArtifactSchema = Schema.Union(
142
208
  Schema.Struct({ kind: Schema.Literal('none') }),
143
209
  );
144
210
 
145
- // The absolute assertion members of `AssertionSpec` below: each is a predicate
146
- // over on-chain state that a derived validation program enforces. Amounts are
147
- // decimal strings on the wire because JSON has no bigint.
211
+ // The members of `AssertionSpec` below: each is an absolute predicate over
212
+ // on-chain state that a derived validation program enforces at settlement.
213
+ // Every register operand of a member (an owner, a call argument, a threshold)
214
+ // becomes a committed validation param; the constants a member bakes into the
215
+ // program (a token, a call target, a function signature) are committed by the
216
+ // program hash. Amounts are decimal strings on the wire because JSON has no
217
+ // bigint.
148
218
  //
149
219
  // - `erc20BalanceGte` — `owner`'s balance of `token` on `chainId` is at least
150
220
  // `minAmount`.
151
221
  // - `nativeBalanceGte` — `owner`'s native balance on `chainId` is at least
152
222
  // `minAmount`.
153
- // - `call` — a generic `eth_call` to `to` with `calldata`, comparing the
154
- // returned value against `value` using `comparator`.
223
+ // - `call` — a static call to `to` on `chainId` of `signature` with `args`,
224
+ // whose `uint256` return compares against `threshold` using `comparator`.
155
225
  //
156
- // Addresses (`token`/`owner`/`to`) take `EVMAddressString`, `calldata` takes
157
- // `HexBytesString`, and amounts (`minAmount`/`value`, and `minDelta` below)
158
- // take `IntegerString`, so a malformed value fails at decode instead of in
159
- // lowering. Amounts are not positive-only: a persisted descriptor re-decodes
160
- // these members, and a zero threshold is well-formed (just vacuous).
226
+ // Addresses (`token`/`to`) take `EVMAddressString`, `owner` takes
227
+ // `AssertionOwnerSchema` (below), and amounts
228
+ // (`minAmount`/`threshold`) take `IntegerString`, so a malformed value fails at
229
+ // decode instead of in lowering. Amounts are not positive-only: a persisted
230
+ // descriptor re-decodes these members, and a zero threshold is well-formed
231
+ // (just vacuous).
161
232
 
162
- // A balance owner in a derivation-only assertion spec. Concrete addresses stay
163
- // hex; the two symbolic owners `"escrow"` / `"delivery"` are resolved to
164
- // validator-injected register handles at settlement time (see the
165
- // verified-continuations derivation). This widening applies ONLY to the
166
- // derivation-only delta members below — never to the three absolute members,
167
- // whose owner is always a concrete address once an invariant is captured.
233
+ // A balance owner: a concrete address, or one of the two symbolic owners
234
+ // `"escrow"` / `"delivery"`. The symbolic owners are thunk terms: a committed
235
+ // thunk carries one when it is assembled by hand (the uc1 fixtures) or echoed
236
+ // back from the commitment, and the derivation resolves each to a
237
+ // validator-injected register (see the verified-continuations derivation). An
238
+ // op's `asserts` hook cannot emit one: in compose-core its spec type is
239
+ // `AssertionSpecOf<H>`, so an owner is always an operand the hook received.
240
+ // The descriptor discloses the same values the program derives from.
168
241
  export const AssertionOwnerSchema = Schema.Union(
169
242
  EVMAddressString,
170
243
  Schema.Literal('escrow', 'delivery'),
@@ -172,51 +245,49 @@ export const AssertionOwnerSchema = Schema.Union(
172
245
  export type AssertionOwner = typeof AssertionOwnerSchema.Type;
173
246
 
174
247
  // The three absolute members are exported by name so `AssertionSpecSchema` and
175
- // the descriptor's predicate union can reuse them without re-declaring their
176
- // shape. Their `owner` is hex-only: a captured invariant always resolves to a
177
- // concrete address.
248
+ // the descriptor's predicate union share one declaration.
178
249
  export const Erc20BalanceGteSpecSchema = Schema.Struct({
179
250
  kind: Schema.Literal('erc20BalanceGte'),
180
251
  chainId: ChainIdSchema,
181
252
  token: EVMAddressString,
182
- owner: EVMAddressString,
253
+ owner: AssertionOwnerSchema,
183
254
  minAmount: IntegerString,
184
255
  });
185
256
 
186
257
  export const NativeBalanceGteSpecSchema = Schema.Struct({
187
258
  kind: Schema.Literal('nativeBalanceGte'),
188
259
  chainId: ChainIdSchema,
189
- owner: EVMAddressString,
260
+ owner: AssertionOwnerSchema,
190
261
  minAmount: IntegerString,
191
262
  });
192
263
 
264
+ // `signature` is the ethers human-readable form, e.g.
265
+ // `function balanceOf(address) returns (uint256)`, with exactly one `uint256`
266
+ // return and only `address` / `uint256` parameters. `args` has one entry per
267
+ // parameter, each written as that parameter's canonical string (a 20-byte hex
268
+ // address, a decimal integer). The derivation parses the signature once and
269
+ // rejects anything else; this schema is a shape check only.
193
270
  export const CallCheckSpecSchema = Schema.Struct({
194
271
  kind: Schema.Literal('call'),
195
272
  chainId: ChainIdSchema,
196
273
  to: EVMAddressString,
197
- calldata: HexBytesString,
274
+ signature: Schema.String,
275
+ args: Schema.Array(Schema.String),
198
276
  comparator: Schema.Literal('gte', 'eq', 'lte'),
199
- value: IntegerString,
277
+ threshold: IntegerString,
200
278
  });
201
279
 
202
- // The shape shared by the hex-owner `nativeBalanceGte` spec and the
203
- // descriptor's symbolic-owner variant. `owner` is `string` for both
204
- // (`AssertionOwnerSchema.Type` collapses to `string`).
205
- interface NativeBalanceGteLike {
206
- readonly kind: 'nativeBalanceGte';
207
- readonly chainId: number;
208
- readonly owner: string;
209
- readonly minAmount: string;
210
- }
280
+ type Erc20BalanceGteSpec = typeof Erc20BalanceGteSpecSchema.Type;
281
+ type NativeBalanceGteSpec = typeof NativeBalanceGteSpecSchema.Type;
211
282
 
212
283
  // The equivalent `erc20BalanceGte` of a `nativeBalanceGte` spec: `token` is
213
284
  // the chain's stand-in ERC-20 (PathUSD on Tempo), every other field carried
214
285
  // through.
215
286
  const asErc20BalanceGteCheck = (
216
- check: NativeBalanceGteLike,
287
+ check: NativeBalanceGteSpec,
217
288
  token: `0x${string}`,
218
- ) => ({
219
- kind: 'erc20BalanceGte' as const,
289
+ ): Erc20BalanceGteSpec => ({
290
+ kind: 'erc20BalanceGte',
220
291
  chainId: check.chainId,
221
292
  token,
222
293
  owner: check.owner,
@@ -229,11 +300,11 @@ const asErc20BalanceGteCheck = (
229
300
  // chain, and rejected on a `native-mirrored-erc20` chain. Used by the
230
301
  // descriptor's `AssertedPredicateSchema` so the disclosed and the committed
231
302
  // predicate derive the same program (authoring↔settlement hash parity).
232
- export const decodeNativeBalanceGte = <C extends NativeBalanceGteLike>(
233
- check: C,
303
+ export const decodeNativeBalanceGte = (
304
+ check: NativeBalanceGteSpec,
234
305
  ast: SchemaAST.AST,
235
306
  ): Effect.Effect<
236
- C | ReturnType<typeof asErc20BalanceGteCheck>,
307
+ NativeBalanceGteSpec | Erc20BalanceGteSpec,
237
308
  ParseResult.ParseIssue
238
309
  > => {
239
310
  const policy = nativeCheckPolicy(check.chainId);
@@ -250,42 +321,19 @@ export const decodeNativeBalanceGte = <C extends NativeBalanceGteLike>(
250
321
  // The derivation vocabulary (verified continuations, plan GD-1). An
251
322
  // `AssertionSpec` is the structured, backend-neutral form of one invariant a
252
323
  // derived validation program must enforce against the executor's re-quoted
253
- // fill. It extends the three absolute members above (reused verbatim) with two
254
- // derivation-only members. Amounts stay decimal strings on the wire.
255
- //
256
- // - `erc20BalanceDeltaGte` / `nativeBalanceDeltaGte` — `owner`'s post-fill
257
- // balance of `token` (native) on `chainId` must exceed its pre-fill balance
258
- // by at least `minDelta`. The settlement validator already checks each
259
- // committed outcome's floor itself, so the derivation lowers neither kind
260
- // into a program and rejects them as an authored invariant; they stay in
261
- // the vocabulary so a descriptor that carries one still decodes.
262
- export const Erc20BalanceDeltaGteSpecSchema = Schema.Struct({
263
- kind: Schema.Literal('erc20BalanceDeltaGte'),
264
- chainId: ChainIdSchema,
265
- token: EVMAddressString,
266
- owner: AssertionOwnerSchema,
267
- minDelta: IntegerString,
268
- });
269
-
270
- export const NativeBalanceDeltaGteSpecSchema = Schema.Struct({
271
- kind: Schema.Literal('nativeBalanceDeltaGte'),
272
- chainId: ChainIdSchema,
273
- owner: AssertionOwnerSchema,
274
- minDelta: IntegerString,
275
- });
276
-
324
+ // fill: one of the three members above, reused verbatim.
277
325
  export const AssertionSpecSchema = Schema.Union(
278
326
  Erc20BalanceGteSpecSchema,
279
327
  NativeBalanceGteSpecSchema,
280
328
  CallCheckSpecSchema,
281
- Erc20BalanceDeltaGteSpecSchema,
282
- NativeBalanceDeltaGteSpecSchema,
283
329
  );
284
330
 
285
331
  export type ContinuationOutcome = typeof ContinuationOutcomeSchema.Type;
332
+ export type CommittedOutcome = typeof CommittedOutcomeSchema.Type;
286
333
  export type ContinuationIntent = typeof ContinuationIntentSchema.Type;
287
334
  export type Phase1Artifact = typeof Phase1ArtifactSchema.Type;
288
335
  export type AssertionSpec = typeof AssertionSpecSchema.Type;
336
+ export type CallCheckSpec = typeof CallCheckSpecSchema.Type;
289
337
 
290
338
  // The outcome a `continuation.settle` node's single `output` port stands for.
291
339
  // The wire format admits several outcomes, but the op produces one resource,
@@ -293,6 +341,9 @@ export type AssertionSpec = typeof AssertionSpecSchema.Type;
293
341
  // intent, so the first outcome is the settled one everywhere. `NonEmptyArray`
294
342
  // makes `[0]` present by construction. Keep this the only place that picks
295
343
  // it: a multi-outcome design changes one accessor, not a scatter of `[0]`s.
296
- export const settledOutcome = (
297
- intent: ContinuationIntent,
298
- ): ContinuationOutcome => intent.outcomes[0];
344
+ // Generic over the intent so a `CommittedIntent` yields a `CommittedOutcome`.
345
+ export const settledOutcome = <
346
+ I extends { readonly outcomes: readonly [unknown, ...unknown[]] },
347
+ >(
348
+ intent: I,
349
+ ): I['outcomes'][0] => intent.outcomes[0];
package/src/descriptor.ts CHANGED
@@ -1,18 +1,7 @@
1
1
  import { ParseResult, Schema } from 'effect';
2
2
 
3
- import {
4
- AssertionOwnerSchema,
5
- CallCheckSpecSchema,
6
- decodeNativeBalanceGte,
7
- Erc20BalanceDeltaGteSpecSchema,
8
- NativeBalanceDeltaGteSpecSchema,
9
- } from './continuation.js';
3
+ import { AssertionSpecSchema, decodeNativeBalanceGte } from './continuation.js';
10
4
  import type { AssertionSpec } from './continuation.js';
11
- import {
12
- ChainIdSchema,
13
- EVMAddressString,
14
- IntegerString,
15
- } from './flowSchema.js';
16
5
  import { BYTES32_LOWER_HEX } from './hexPatterns.js';
17
6
 
18
7
  // The neutral per-leg verification descriptor (verified continuations, plan
@@ -20,18 +9,14 @@ import { BYTES32_LOWER_HEX } from './hexPatterns.js';
20
9
  // validation program enforces, so a user funding phase 1 can give informed
21
10
  // consent (PRD goal G8). It is backend-neutral (G7): no validator address, no
22
11
  // constraint, no settlement-backend vocabulary — the only escrow-ish term is the
23
- // symbolic owner `"escrow"`, explicitly allowlisted by the boundary check.
12
+ // symbolic owner `"escrow"` (`AssertionOwnerSchema`), explicitly allowlisted by
13
+ // the boundary check.
24
14
  //
25
15
  // The design trick that makes disclosure trustworthy-by-construction:
26
16
  // `assertedPredicate[]` is NOT a new DSL. It is the canonical JSON serialization
27
17
  // of the same `AssertionSpec[]` the validation program is derived from, so
28
18
  // disclosure cannot drift from enforcement — both are projections of one array.
29
19
 
30
- // `ChainIdSchema`, `EVMAddressString` and `IntegerString` (from
31
- // `flowSchema.ts`) are reused directly, so the widened members below differ
32
- // from their `AssertionSpec` counterparts in exactly one field (`owner`) with
33
- // no risk of a drifting re-declaration.
34
-
35
20
  // The `validationProgramHash` (GD-2, seam C1): `keccak256` over the canonical
36
21
  // program body. Strict 32-byte lowercase hex (`BYTES32_LOWER_HEX`) — see the
37
22
  // rationale in `hexPatterns.ts`.
@@ -39,48 +24,13 @@ export const Bytes32HexSchema = Schema.String.pipe(
39
24
  Schema.pattern(BYTES32_LOWER_HEX),
40
25
  );
41
26
 
42
- // The disclosure-path widening of the two balance-`Gte` assertion members: same
43
- // fields as their `continuation.ts` counterparts, but `owner` accepts a symbolic
44
- // `"escrow"`/`"delivery"` too. The derivation genuinely produces such values —
45
- // a captured invariant can carry a symbolic owner, which `resolveOwner` maps to
46
- // a validator-injected slot at settlement (see the `uc1` invariant). The
47
- // `AssertionSpec` members stay hex-only, so this widening lives in the
48
- // descriptor union only.
49
- export const AssertedErc20BalanceGteSpecSchema = Schema.Struct({
50
- kind: Schema.Literal('erc20BalanceGte'),
51
- chainId: ChainIdSchema,
52
- token: EVMAddressString,
53
- owner: AssertionOwnerSchema,
54
- minAmount: IntegerString,
55
- });
56
-
57
- export const AssertedNativeBalanceGteSpecSchema = Schema.Struct({
58
- kind: Schema.Literal('nativeBalanceGte'),
59
- chainId: ChainIdSchema,
60
- owner: AssertionOwnerSchema,
61
- minAmount: IntegerString,
62
- });
63
-
64
- // The disclosed predicate: the five `AssertionSpec` kinds, with symbolic owners
65
- // admitted on the two balance-`Gte` members. The `call` member and the two
66
- // derivation-only delta members are reused verbatim from `continuation.ts` (the
67
- // delta members already carry `AssertionOwnerSchema`).
68
- const RawAssertedPredicateSchema = Schema.Union(
69
- AssertedErc20BalanceGteSpecSchema,
70
- AssertedNativeBalanceGteSpecSchema,
71
- CallCheckSpecSchema,
72
- Erc20BalanceDeltaGteSpecSchema,
73
- NativeBalanceDeltaGteSpecSchema,
74
- );
75
-
76
- // `nativeBalanceGte` handling via `decodeNativeBalanceGte`, applied to the
77
- // disclosed/committed predicate so settlement derives the identical program.
78
- // Idempotent on already-normalized predicates; normalizes or refuses a
79
- // hand-forged committed action that embeds a raw native check. The delta
80
- // members are untouched — they derive from already-normalized outcomes.
27
+ // The disclosed/committed predicate: an `AssertionSpec` with `nativeBalanceGte`
28
+ // handled via `decodeNativeBalanceGte`, so settlement derives the identical
29
+ // program. Idempotent on already-normalized predicates; normalizes or refuses a
30
+ // hand-forged committed action that embeds a raw native check.
81
31
  export const AssertedPredicateSchema = Schema.transformOrFail(
82
- RawAssertedPredicateSchema,
83
- Schema.typeSchema(RawAssertedPredicateSchema),
32
+ AssertionSpecSchema,
33
+ Schema.typeSchema(AssertionSpecSchema),
84
34
  {
85
35
  strict: true,
86
36
  decode: (pred, _options, ast) =>
@@ -107,16 +57,17 @@ export const VerificationDescriptorSchema = Schema.Struct({
107
57
  // Deterministic, key-order-pinned JSON serialization of an `AssertionSpec[]`.
108
58
  // Canonicalization rules:
109
59
  // - Object keys are emitted in recursive lexicographic order (sorted).
110
- // - Compact separators — no whitespace anywhere.
60
+ // - Compact separators — no whitespace between tokens (a string value such as
61
+ // a `call` signature keeps its own spaces).
111
62
  // - Array element order is PRESERVED, never sorted: it is semantic (derivation
112
- // order — deltas, then invariants) and is a faithful projection of the
113
- // program's assertion order.
63
+ // order, and a `call` member's `args` are positional) and is a faithful
64
+ // projection of the program's assertion order.
114
65
  //
115
- // All `AssertionSpec` leaf values are JSON-safe (decimal strings, `0x` hex
116
- // strings, positive-int `chainId`), so lexicographic key sorting is total and
117
- // stable with no number-canonicalization edge cases, and is self-maintaining
118
- // when members gain fields. Embedding this string per fixture vector pins the
119
- // serialization cross-repo (GD-5's consumer asserts it reproduces the string).
66
+ // All `AssertionSpec` leaf values are JSON-safe (strings, positive-int
67
+ // `chainId`), so lexicographic key sorting is total and stable with no
68
+ // number-canonicalization edge cases, and is self-maintaining when members
69
+ // gain fields. Embedding this string per fixture vector pins the serialization
70
+ // cross-repo (GD-5's consumer asserts it reproduces the string).
120
71
  //
121
72
  // Boundary-forced local mirror of `@lifi/utils`'s `canonicalJson`: compose-spec
122
73
  // is the wire-format leaf and may not import `@lifi/utils` (enforced by the
@@ -142,9 +93,6 @@ export const canonicalAssertedPredicate = (
142
93
 
143
94
  export type VerificationDescriptor = typeof VerificationDescriptorSchema.Type;
144
95
 
145
- // `AssertedPredicate` is structurally identical to `AssertionSpec` at the TS
146
- // type level — `AssertionOwner` is a subtype of `string`, so widening `owner`
147
- // changes only schema *decode* behaviour, not the static type. It is therefore
148
- // exported as a plain alias, keeping `canonicalAssertedPredicate` and the
149
- // derivation's `specs` array interchangeable without casts.
96
+ // The disclosed predicate is an `AssertionSpec`; the alias names its role in
97
+ // the descriptor.
150
98
  export type AssertedPredicate = AssertionSpec;
package/src/flow.ts CHANGED
@@ -81,9 +81,9 @@ export type ComposeErrorKind =
81
81
  | 'compilation_error'
82
82
  | 'verification_error'
83
83
  | 'price_impact_exceeded'
84
- | 'fee_resolution_error'
85
- | 'fee_resolution_unavailable'
86
84
  | 'flashloan_unauthorized'
85
+ // A delivery tranche's failure; reasons in `DeliveryErrorReason`.
86
+ | 'delivery_error'
87
87
  // The request exceeded its wall-clock budget and was cancelled mid-flight.
88
88
  | 'deadline_exceeded';
89
89
 
@@ -103,7 +103,7 @@ export type ComposeRouteErrorKind =
103
103
 
104
104
  export type GenericComposeErrorKind = Exclude<
105
105
  ComposeErrorKind,
106
- 'preparation_error' | 'simulation_revert'
106
+ 'preparation_error' | 'simulation_revert' | 'delivery_error'
107
107
  >;
108
108
 
109
109
  export interface FailedPreparedOp {
@@ -140,13 +140,49 @@ export interface SimulationRevertComposeError extends ComposeErrorBase {
140
140
  readonly details?: SimulationRevert;
141
141
  }
142
142
 
143
+ // Why a delivery tranche failed:
144
+ // - `floor_drift`: the second quote's `min` fell below the registered floor;
145
+ // - `eta_exceeds_expiry`: the escrow expires before the delivery's ETA rule
146
+ // allows;
147
+ // - `quote_failed`: the second quote (to the registered escrow) failed;
148
+ // `cause` is the kind of that failure and `quoted` is the first quote.
149
+ export type DeliveryErrorReason =
150
+ 'floor_drift' | 'eta_exceeds_expiry' | 'quote_failed';
151
+
152
+ // `escrow` is present only when the failure came after the escrow was
153
+ // registered: the escrow is then abandoned and expires unfunded, and this
154
+ // record is its only trace.
155
+ export interface DeliveryErrorDetails {
156
+ readonly reason: DeliveryErrorReason;
157
+ readonly cause?: ComposeErrorKind;
158
+ readonly quoted: {
159
+ readonly min: string;
160
+ readonly expected: string;
161
+ readonly etaSeconds?: number;
162
+ };
163
+ readonly escrow?: {
164
+ readonly chainId: number;
165
+ readonly address: string;
166
+ readonly floor: string;
167
+ readonly expiresAtMs: number;
168
+ };
169
+ }
170
+
171
+ export interface DeliveryComposeError extends ComposeErrorBase {
172
+ readonly kind: 'delivery_error';
173
+ readonly details: DeliveryErrorDetails;
174
+ }
175
+
143
176
  export interface GenericComposeError extends ComposeErrorBase {
144
177
  readonly kind: GenericComposeErrorKind;
145
178
  readonly [key: string]: unknown;
146
179
  }
147
180
 
148
181
  export type ComposeError =
149
- PreparationComposeError | SimulationRevertComposeError | GenericComposeError;
182
+ | PreparationComposeError
183
+ | SimulationRevertComposeError
184
+ | DeliveryComposeError
185
+ | GenericComposeError;
150
186
 
151
187
  export interface MaterialiserInputBase {
152
188
  readonly kind: string;