@lifi/compose-spec 0.10.0 → 0.11.3

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.
package/dist/index.js CHANGED
@@ -12,11 +12,11 @@ import z from "zod";
12
12
  */
13
13
  const EVM_NATIVE_SENTINEL = "0x0000000000000000000000000000000000000000";
14
14
  /**
15
- * Whether `address` is the EVM-native zero-address sentinel, compared
16
- * case-insensitively. Module-local: the two call-sites below share this exact
17
- * comparison; it is not part of the package's public surface.
15
+ * Whether `address` is the EVM zero address (the native sentinel), compared
16
+ * case-insensitively. Inlined comparison: `compose-spec` cannot import
17
+ * `toAddress` from `@lifi/utils` (see `EVM_NATIVE_SENTINEL`).
18
18
  */
19
- const isNativeSentinel = (address) => address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase();
19
+ const isZeroAddress = (address) => address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase();
20
20
  const TEMPO_CHAIN_ID = 4217;
21
21
  const TEMPO_NATIVE_ERC20 = {
22
22
  token: "0x20C0000000000000000000000000000000000000",
@@ -139,7 +139,7 @@ const isNativeAddressForChain = (chainId, address) => {
139
139
  * `isNativeAddressForChain`, which returns `true` for the stand-in ERC-20
140
140
  * (PathUSD on Tempo) and would wrongly route it to `msg.value`.
141
141
  */
142
- const isMsgValueNative = (chainId, address) => !hasErc20CanonicalNative(chainId) && isNativeSentinel(address);
142
+ const isMsgValueNative = (chainId, address) => !hasErc20CanonicalNative(chainId) && isZeroAddress(address);
143
143
  /**
144
144
  * Rewrite a single `Resource` according to its chain's capabilities.
145
145
  *
@@ -175,7 +175,7 @@ const normalizeResource = (r) => {
175
175
  * chains whose canonical native asset is an ERC-20, the native sentinel is
176
176
  * rewritten to the chain's stand-in ERC-20; every other address passes through.
177
177
  */
178
- const normalizeNativeTokenAddress = (token, chainId) => hasErc20CanonicalNative(chainId) && isNativeSentinel(token) ? canonicalNativeAddress(chainId) : token;
178
+ const normalizeNativeTokenAddress = (token, chainId) => hasErc20CanonicalNative(chainId) && isZeroAddress(token) ? canonicalNativeAddress(chainId) : token;
179
179
  //#endregion
180
180
  //#region src/hexPatterns.ts
181
181
  const BYTES32_LOWER_HEX = /^0x[0-9a-f]{64}$/;
@@ -263,38 +263,51 @@ const LineageSchema = Schema.Struct({
263
263
  journeyId: UuidSchema,
264
264
  parentRequestId: UuidSchema
265
265
  });
266
+ const ForwardToSchema = Schema.Union(EVMAddressString, RefSchema);
267
+ const EpilogueForwardSchema = Schema.Struct({
268
+ resource: ResourceSchema,
269
+ to: ForwardToSchema
270
+ });
271
+ const EpilogueSchema = Schema.Struct({
272
+ forwards: Schema.optional(Schema.NonEmptyArray(EpilogueForwardSchema)),
273
+ remainder: Schema.optional(ForwardToSchema)
274
+ }).pipe(Schema.filter((e) => e.forwards !== void 0 || e.remainder !== void 0, { message: () => "epilogue needs forwards, a remainder, or both" }));
266
275
  const FlowSchema = Schema.Struct({
267
276
  version: Schema.Literal(1),
268
277
  id: Schema.String,
269
278
  chainId: ChainIdSchema,
270
279
  inputs: Schema.Array(FlowInputSchema),
271
280
  nodes: Schema.Array(CallSchema),
272
- lineage: Schema.optional(LineageSchema)
281
+ lineage: Schema.optional(LineageSchema),
282
+ epilogue: Schema.optional(EpilogueSchema)
273
283
  });
274
284
  //#endregion
275
285
  //#region src/continuation.ts
276
286
  const CONTINUATION_COMMITMENT_OP_ID = "continuation.commitment";
277
- const RawContinuationOutcomeSchema = Schema.Struct({
287
+ const outcomeFields = (minAmount) => ({
278
288
  token: EVMAddressString,
279
- minAmount: IntegerString,
289
+ minAmount,
280
290
  destination: EVMAddressString,
281
291
  chainId: ChainIdSchema
282
292
  });
283
- const ContinuationOutcomeSchema = Schema.transform(RawContinuationOutcomeSchema, Schema.typeSchema(RawContinuationOutcomeSchema), {
293
+ const normalizingOutcome = (raw) => Schema.transform(raw, Schema.typeSchema(raw), {
284
294
  strict: true,
285
- decode: (raw) => ({
286
- ...raw,
287
- token: normalizeNativeTokenAddress(raw.token, raw.chainId)
295
+ decode: (outcome) => ({
296
+ ...outcome,
297
+ token: normalizeNativeTokenAddress(outcome.token, outcome.chainId)
288
298
  }),
289
299
  encode: (outcome) => outcome
290
300
  });
301
+ const ContinuationOutcomeSchema = normalizingOutcome(Schema.Struct(outcomeFields(Schema.optional(IntegerString))));
302
+ const CommittedOutcomeSchema = normalizingOutcome(Schema.Struct(outcomeFields(IntegerString)));
291
303
  const ContinuationIntentSchema = Schema.Struct({
292
304
  outcomes: Schema.NonEmptyArray(ContinuationOutcomeSchema),
293
305
  continuationFlow: Schema.optional(FlowSchema),
294
306
  validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
295
307
  perpetual: Schema.optional(Schema.Boolean),
296
308
  provider: Schema.optional(Schema.String),
297
- funding: Schema.optional(Schema.Literal("inline", "external"))
309
+ funding: Schema.optional(Schema.Literal("inline", "external")),
310
+ refund: Schema.optional(EVMAddressString.pipe(Schema.filter((address) => !isZeroAddress(address), { message: () => "refund must not be the zero address" })))
298
311
  });
299
312
  const HexStringSchema = Schema.String.pipe(Schema.startsWith("0x"));
300
313
  const Phase1EscrowSchema = Schema.Struct({
@@ -303,13 +316,14 @@ const Phase1EscrowSchema = Schema.Struct({
303
316
  token: HexStringSchema,
304
317
  amount: Schema.String,
305
318
  cap: Schema.String,
319
+ floor: Schema.String,
306
320
  owner: HexStringSchema,
307
321
  refund: HexStringSchema,
308
322
  expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive())
309
323
  });
310
324
  const Phase1ArtifactSchema = Schema.Union(Schema.Struct({
311
325
  kind: Schema.Literal("transaction"),
312
- funding: Schema.Literal("inline", "external"),
326
+ funding: Schema.Literal("inline", "external", "delivered"),
313
327
  transactionRequest: Schema.optional(Schema.Struct({
314
328
  to: Schema.String,
315
329
  data: Schema.String,
@@ -434,18 +448,24 @@ const nativeResource = (chainId) => ({
434
448
  const isERC20Resource = (r) => r.kind === "erc20";
435
449
  const isNativeResource = (r) => r.kind === "native";
436
450
  const resourcesEqual = (a, b) => {
437
- if (isNativeResource(a) && isNativeResource(b)) return a.chainId === b.chainId;
438
- if (isERC20Resource(a) && isERC20Resource(b)) return a.chainId === b.chainId && a.token.toLowerCase() === b.token.toLowerCase();
439
- return false;
451
+ switch (a.kind) {
452
+ case "native": return b.kind === "native" && a.chainId === b.chainId;
453
+ case "erc20": return b.kind === "erc20" && a.chainId === b.chainId && a.token.toLowerCase() === b.token.toLowerCase();
454
+ }
455
+ };
456
+ const foldResource = (r, cases) => {
457
+ switch (r.kind) {
458
+ case "native": return cases.native(r);
459
+ case "erc20": return cases.erc20(r);
460
+ }
440
461
  };
441
- const foldResource = (r, cases) => r.kind === "native" ? cases.native(r.chainId) : cases.erc20(r.token, r.chainId);
442
462
  const resourceToken = (r) => foldResource(r, {
443
463
  native: () => EVM_NATIVE_SENTINEL,
444
- erc20: (token) => token
464
+ erc20: ({ token }) => token
445
465
  });
446
466
  const resourceKey = (r) => foldResource(r, {
447
- native: (chainId) => `native:${chainId}`,
448
- erc20: (token, chainId) => `erc20:${token.toLowerCase()}:${chainId}`
467
+ native: ({ chainId }) => `native:${chainId}`,
468
+ erc20: ({ token, chainId }) => `erc20:${token.toLowerCase()}:${chainId}`
449
469
  });
450
470
  const erc20Token = (r) => {
451
471
  if (r.kind !== "erc20") throw new Error(`Expected erc20 resource, got ${r.kind}`);
@@ -862,6 +882,10 @@ const ManifestPreconditionZod = z.object({
862
882
  description: z.string().optional(),
863
883
  configSchema: z.unknown().optional()
864
884
  });
885
+ const ManifestRoutingZod = z.object({
886
+ maxRouteHops: z.number().int().min(1),
887
+ swapHops: z.enum(["head", "none"])
888
+ });
865
889
  const ComposeManifestZod = z.object({
866
890
  manifestVersion: z.number(),
867
891
  manifestHash: z.string(),
@@ -869,7 +893,8 @@ const ComposeManifestZod = z.object({
869
893
  operations: z.array(ManifestOperationZod),
870
894
  guards: z.array(ManifestGuardZod),
871
895
  materialisers: z.array(ManifestMaterialiserZod),
872
- preconditions: z.array(ManifestPreconditionZod).optional()
896
+ preconditions: z.array(ManifestPreconditionZod).optional(),
897
+ routing: ManifestRoutingZod.optional()
873
898
  });
874
899
  const hexStringZod = z.string().startsWith("0x");
875
900
  const SettlementEscrowZod = z.object({
@@ -878,6 +903,7 @@ const SettlementEscrowZod = z.object({
878
903
  token: hexStringZod,
879
904
  amount: z.string(),
880
905
  cap: z.string(),
906
+ floor: z.string(),
881
907
  owner: hexStringZod,
882
908
  refund: hexStringZod,
883
909
  expiresAtMs: z.number().int().positive()
@@ -953,4 +979,4 @@ const VerificationDescriptorZod = z.object({
953
979
  });
954
980
  const SettlementZod = z.object({ escrow: SettlementEscrowZod.optional() });
955
981
  //#endregion
956
- export { ARC_CHAIN_ID, ARC_NATIVE_ERC20, ARC_NATIVE_SCALE, AppliedGuardSchema, AssertedErc20BalanceGteSpecSchema, AssertedNativeBalanceGteSpecSchema, AssertedPredicateSchema, AssertedPredicateZod, AssertionOwnerSchema, AssertionSpecSchema, AssertionSpecZod, BindValueSchema, Bytes32HexSchema, COMPOSER_SDK_VERSION_HEADER, COMPOSE_VERSION_HEADER, CONTINUATION_COMMITMENT_OP_ID, CallCheckSpecSchema, CallSchema, ComposeManifestZod, ContinuationIntentSchema, ContinuationOutcomeSchema, EVMAddressString, EVM_NATIVE_SENTINEL, Erc20BalanceDeltaGteSpecSchema, Erc20BalanceGteSpecSchema, FlowInputSchema, FlowSchema, GuardCompatibilityZod, GuardSelectorZod, HANDLE_UNITS, HandleInputSchema, HandlePortZod, HandleUnitsZod, HexStringSchema, InputPortZod, IntegerString, LineageSchema, LiteralBindingSchema, ManifestGuardZod, ManifestMaterialiserZod, ManifestOperationZod, ManifestPreconditionZod, NativeBalanceDeltaGteSpecSchema, NativeBalanceGteSpecSchema, OutputPortZod, PROVIDER_KIND, Phase1ArtifactSchema, RESERVED_REF_SCOPES, RefSchema, ResourceInputSchema, ResourceOutputPortZod, ResourcePortZod, ResourceSchema, SIMULATE_MAX_REQUIREMENTS, SIMULATE_MAX_TRACKED_BALANCES, STATIC_SOL_TYPES, SettlementZod, SolTypeSchema, StaticSolTypeZod, TEMPO_CHAIN_ID, TEMPO_NATIVE_ERC20, UuidSchema, VerificationDescriptorSchema, VerificationDescriptorZod, canonicalAssertedPredicate, canonicalNativeAddress, checkCompatibility, copy, erc20, erc20Allowance, erc20Balance, erc20Resource, erc20Token, expandOutputPorts, familySize, flowInputMode, flowInputResource, flowInputType, foldChainCapabilities, foldMaterialiserMetadata, foldRef, foldResource, getChainCapabilities, handle, hasErc20CanonicalNative, instancePortName, isAsErc20Chain, isContextKey, isERC20Resource, isErc20AllowancePrecondition, isErc20BalancePrecondition, isFutureResourceOutput, isHandlePort, isMaterialiserInput, isMsgValueNative, isNativeAddressForChain, isNativeBalancePrecondition, isNativeResource, isOutputFamily, isRef, isResourceInput, isResourceOutputPort, isResourcePort, isStaticSolType, linear, native, nativeBalance, nativeCheckPolicy, nativeResource, normalizeNativeTokenAddress, normalizeResource, opHandle, parseRef, parseVersion, providerKindByName, providerKindNames, readResource, ref, refKey, resource, resourceKey, resourceOutput, resourceToken, resourcesEqual, settledOutcome };
982
+ export { ARC_CHAIN_ID, ARC_NATIVE_ERC20, ARC_NATIVE_SCALE, AppliedGuardSchema, AssertedErc20BalanceGteSpecSchema, AssertedNativeBalanceGteSpecSchema, AssertedPredicateSchema, AssertedPredicateZod, AssertionOwnerSchema, AssertionSpecSchema, AssertionSpecZod, BindValueSchema, Bytes32HexSchema, COMPOSER_SDK_VERSION_HEADER, COMPOSE_VERSION_HEADER, CONTINUATION_COMMITMENT_OP_ID, CallCheckSpecSchema, CallSchema, CommittedOutcomeSchema, ComposeManifestZod, ContinuationIntentSchema, ContinuationOutcomeSchema, EVMAddressString, EVM_NATIVE_SENTINEL, EpilogueForwardSchema, EpilogueSchema, Erc20BalanceDeltaGteSpecSchema, Erc20BalanceGteSpecSchema, FlowInputSchema, FlowSchema, ForwardToSchema, GuardCompatibilityZod, GuardSelectorZod, HANDLE_UNITS, HandleInputSchema, HandlePortZod, HandleUnitsZod, HexStringSchema, InputPortZod, IntegerString, LineageSchema, LiteralBindingSchema, ManifestGuardZod, ManifestMaterialiserZod, ManifestOperationZod, ManifestPreconditionZod, ManifestRoutingZod, NativeBalanceDeltaGteSpecSchema, NativeBalanceGteSpecSchema, OutputPortZod, PROVIDER_KIND, Phase1ArtifactSchema, RESERVED_REF_SCOPES, RefSchema, ResourceInputSchema, ResourceOutputPortZod, ResourcePortZod, ResourceSchema, SIMULATE_MAX_REQUIREMENTS, SIMULATE_MAX_TRACKED_BALANCES, STATIC_SOL_TYPES, SettlementZod, SolTypeSchema, StaticSolTypeZod, TEMPO_CHAIN_ID, TEMPO_NATIVE_ERC20, UuidSchema, VerificationDescriptorSchema, VerificationDescriptorZod, canonicalAssertedPredicate, canonicalNativeAddress, checkCompatibility, copy, erc20, erc20Allowance, erc20Balance, erc20Resource, erc20Token, expandOutputPorts, familySize, flowInputMode, flowInputResource, flowInputType, foldChainCapabilities, foldMaterialiserMetadata, foldRef, foldResource, getChainCapabilities, handle, hasErc20CanonicalNative, instancePortName, isAsErc20Chain, isContextKey, isERC20Resource, isErc20AllowancePrecondition, isErc20BalancePrecondition, isFutureResourceOutput, isHandlePort, isMaterialiserInput, isMsgValueNative, isNativeAddressForChain, isNativeBalancePrecondition, isNativeResource, isOutputFamily, isRef, isResourceInput, isResourceOutputPort, isResourcePort, isStaticSolType, linear, native, nativeBalance, nativeCheckPolicy, nativeResource, normalizeNativeTokenAddress, normalizeResource, opHandle, parseRef, parseVersion, providerKindByName, providerKindNames, readResource, ref, refKey, resource, resourceKey, resourceOutput, resourceToken, resourcesEqual, settledOutcome };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/compose-spec",
3
- "version": "0.10.0",
3
+ "version": "0.11.3",
4
4
  "description": "Public wire-format types and schemas for Compose flows",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,11 +65,11 @@ export const EVM_NATIVE_SENTINEL: `0x${string}` =
65
65
  '0x0000000000000000000000000000000000000000';
66
66
 
67
67
  /**
68
- * Whether `address` is the EVM-native zero-address sentinel, compared
69
- * case-insensitively. Module-local: the two call-sites below share this exact
70
- * comparison; it is not part of the package's public surface.
68
+ * Whether `address` is the EVM zero address (the native sentinel), compared
69
+ * case-insensitively. Inlined comparison: `compose-spec` cannot import
70
+ * `toAddress` from `@lifi/utils` (see `EVM_NATIVE_SENTINEL`).
71
71
  */
72
- const isNativeSentinel = (address: string): boolean =>
72
+ export const isZeroAddress = (address: string): boolean =>
73
73
  address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase();
74
74
 
75
75
  export const TEMPO_CHAIN_ID = 4217;
@@ -291,7 +291,7 @@ export const isNativeAddressForChain = (
291
291
  * (PathUSD on Tempo) and would wrongly route it to `msg.value`.
292
292
  */
293
293
  export const isMsgValueNative = (chainId: number, address: string): boolean =>
294
- !hasErc20CanonicalNative(chainId) && isNativeSentinel(address);
294
+ !hasErc20CanonicalNative(chainId) && isZeroAddress(address);
295
295
 
296
296
  /**
297
297
  * Rewrite a single `Resource` according to its chain's capabilities.
@@ -333,6 +333,6 @@ export const normalizeNativeTokenAddress = (
333
333
  token: string,
334
334
  chainId: number,
335
335
  ): string =>
336
- hasErc20CanonicalNative(chainId) && isNativeSentinel(token)
336
+ hasErc20CanonicalNative(chainId) && isZeroAddress(token)
337
337
  ? canonicalNativeAddress(chainId)
338
338
  : token;
package/src/compile.ts CHANGED
@@ -1,18 +1,12 @@
1
1
  import type { VerificationDescriptor } from './descriptor.js';
2
2
  import type { InputSpec, Precondition } from './flow.js';
3
- import type { Flow } from './flowSchema.js';
3
+ import type { Flow, ForwardTo } from './flowSchema.js';
4
4
  import type { Outputs } from './output.js';
5
+ import type { Resource } from './resource.js';
5
6
  import type { SettlementWire } from './zodSchemas.js';
6
7
 
7
8
  export type SimulationPolicy = 'strict' | 'allow-revert';
8
9
 
9
- /**
10
- * Destination for sweeping proxy-held terminal resources after execution.
11
- * Either a literal EVM address or a `{ $ref }` context reference
12
- * (e.g. `{ $ref: "context.sender" }`).
13
- */
14
- export type SweepTo = string | { readonly $ref: string };
15
-
16
10
  export interface ComposeRun {
17
11
  readonly inputs: Record<string, InputSpec>;
18
12
  readonly preconditions?: readonly Precondition[];
@@ -21,7 +15,9 @@ export interface ComposeRun {
21
15
  readonly referrer?: string;
22
16
  readonly integratorFeeBps?: number;
23
17
  readonly maxPriceImpactBps?: number;
24
- readonly sweepTo?: SweepTo;
18
+ // Sugar for `flow.epilogue.remainder`; zap-backend desugars it before the
19
+ // compile.
20
+ readonly sweepTo?: ForwardTo;
25
21
  readonly simulationPolicy?: SimulationPolicy;
26
22
  /**
27
23
  * Also simulate the final user-facing transaction. Defaults to `false`;
@@ -149,6 +145,19 @@ export interface ComposeUserProgramSimulation {
149
145
  readonly returnData: string;
150
146
  }
151
147
 
148
+ // One advisory finding the compiler raised without failing the compile, e.g. a
149
+ // tight slippage bound on a highly volatile token. Hand-mirrored from
150
+ // api-schemas' `ComposeWarningSchema`. `path`, `port`, and `fix` mean what they
151
+ // mean on a compile error. `kind` is an open set: a new kind ships in a patch
152
+ // release, so a reader must tolerate a kind it does not know.
153
+ export interface ComposeWarning {
154
+ readonly kind: string;
155
+ readonly message: string;
156
+ readonly path?: string;
157
+ readonly port?: string;
158
+ readonly fix?: string;
159
+ }
160
+
152
161
  // The solver-extractable fill (verified continuations, GD-8/GD-6, seam C5),
153
162
  // present on every compiled success. Hand-mirrored to api-schemas' `fill`
154
163
  // object (the OpenAPI source of truth; this package cannot depend on it).
@@ -163,12 +172,32 @@ export interface ComposeFill {
163
172
  readonly validUntilMs?: number;
164
173
  }
165
174
 
175
+ // One named epilogue forward as executed: the proxy's whole balance of
176
+ // `resource`, moved to `to`, as the simulation measured it. Hand-mirrored from
177
+ // api-schemas' `ExecutedForwardSchema`; the SDK decodes `amount` to `bigint`.
178
+ export interface ExecutedForward {
179
+ readonly resource: Resource;
180
+ readonly to: string;
181
+ readonly amount: bigint;
182
+ }
183
+
184
+ // The flow's epilogue as executed. The remainder is not measured: it reports
185
+ // its resolved address only, and its effect on `outputs` is a re-owned
186
+ // `owner`. Absent when the flow has no epilogue (and never on a partial
187
+ // result, which measured nothing).
188
+ export interface ExecutedEpilogue {
189
+ readonly forwards: readonly ExecutedForward[];
190
+ readonly remainder?: string;
191
+ }
192
+
166
193
  export interface ComposeCompileSuccessData extends ComposeContinuationData {
167
194
  // Every linear resource output port, consumed or terminal, keyed
168
- // `<nodeId>.<portName>`. See `Output` for the per-entry rules. Hand-mirrored
195
+ // `<nodeId>.<portName>`, and every resource input no node spends, keyed
196
+ // `input.<name>`. See `Output` for the per-entry rules. Hand-mirrored
169
197
  // from api-schemas' `OutputSchema` (the OpenAPI source of truth; this
170
198
  // package cannot depend on it); the SDK decodes the wire strings to `bigint`.
171
199
  readonly outputs: Outputs;
200
+ readonly epilogue?: ExecutedEpilogue;
172
201
  // The OpenAPI source of truth documents the optionality and funding modes.
173
202
  readonly transactionRequest?: ComposeTransactionRequest;
174
203
  readonly actions?: readonly ComposeAction[];
@@ -192,6 +221,9 @@ export interface ComposeCompileSuccessData extends ComposeContinuationData {
192
221
  // committed a validation program; one entry per committing node, so a
193
222
  // fan-out across committed settles carries several.
194
223
  readonly verificationByNode?: Record<string, VerificationDescriptor>;
224
+ // Advisory findings in the order the compiler raised them. Absent when it
225
+ // raised none; never an empty array.
226
+ readonly warnings?: readonly ComposeWarning[];
195
227
  }
196
228
 
197
229
  export interface ComposeCompilePartialData extends ComposeContinuationData {
@@ -209,6 +241,9 @@ export interface ComposeCompilePartialData extends ComposeContinuationData {
209
241
  // The optional user-program simulation echo, present only when the request
210
242
  // opted in via `run.simulateUserProgram` and the simulation succeeded.
211
243
  readonly userProgramSimulation?: ComposeUserProgramSimulation;
244
+ // Mirrors `ComposeCompileSuccessData.warnings`: a reverted compile keeps the
245
+ // warnings its compile raised.
246
+ readonly warnings?: readonly ComposeWarning[];
212
247
  }
213
248
 
214
249
  export type ComposeCompileResult =
@@ -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';
@@ -22,37 +23,61 @@ import {
22
23
  // settlement fill answered as an ordinary flow with no descriptor).
23
24
  export const CONTINUATION_COMMITMENT_OP_ID = 'continuation.commitment';
24
25
 
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({
26
+ // A single outcome of a deferred settlement: `token` must be delivered to
27
+ // `destination` on `chainId`. Amounts are decimal strings on the wire because
28
+ // JSON has no bigint; `chainId` reuses the shared `ChainIdSchema` from
29
+ // `flowSchema.ts`. `token` becomes a `Resource` in `continuation.settle`'s
30
+ // output and `destination` its owner, so both take the address rule.
31
+ //
32
+ // `minAmount` is the floor the author commits to. An author may omit it: a
33
+ // committed provider proves the floor from the settle's `continuationFlow`,
34
+ // and an authored value can only raise what the proof delivers. A provider
35
+ // that proves nothing requires it. A zero `minAmount` decodes (`IntegerString`
36
+ // admits 0) and the pipeline reads it as omitted: the committed floor is the
37
+ // larger of the authored and the proven floor, and a floor of 0 is rejected.
38
+ //
39
+ // The decode transform mirrors `ResourceSchema`: `token` never flows through
40
+ // `ResourceSchema`, so on `as-erc20` chains the native sentinel is rewritten to
41
+ // the chain's ERC-20 here — otherwise downstream would treat the delivery asset
42
+ // as native. Encode is the identity (the ERC-20 form is valid wire input).
43
+ // Field order is wire-visible: a committed action serializes the decoded
44
+ // struct, so both structs below keep `minAmount` second.
45
+ const outcomeFields = <
46
+ M extends Schema.Schema.All | Schema.PropertySignature.All,
47
+ >(
48
+ minAmount: M,
49
+ ) => ({
34
50
  token: EVMAddressString,
35
- minAmount: IntegerString,
51
+ minAmount,
36
52
  destination: EVMAddressString,
37
53
  chainId: ChainIdSchema,
38
54
  });
39
55
 
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
- {
56
+ const normalizingOutcome = <
57
+ A extends { readonly token: string; readonly chainId: number },
58
+ I,
59
+ >(
60
+ raw: Schema.Schema<A, I>,
61
+ ) =>
62
+ Schema.transform(raw, Schema.typeSchema(raw), {
49
63
  strict: true,
50
- decode: (raw) => ({
51
- ...raw,
52
- token: normalizeNativeTokenAddress(raw.token, raw.chainId),
64
+ decode: (outcome) => ({
65
+ ...outcome,
66
+ token: normalizeNativeTokenAddress(outcome.token, outcome.chainId),
53
67
  }),
54
68
  encode: (outcome) => outcome,
55
- },
69
+ });
70
+
71
+ // The authored outcome: `minAmount` optional.
72
+ export const ContinuationOutcomeSchema = normalizingOutcome(
73
+ Schema.Struct(outcomeFields(Schema.optional(IntegerString))),
74
+ );
75
+
76
+ // The committed outcome: the floor the provider registered, always present.
77
+ // The `continuation.commitment` node and every provider's `prepare()` read
78
+ // this shape.
79
+ export const CommittedOutcomeSchema = normalizingOutcome(
80
+ Schema.Struct(outcomeFields(IntegerString)),
56
81
  );
57
82
 
58
83
  // Backend-neutral config for the `continuation.settle` op. Note: the funding
@@ -74,8 +99,19 @@ export const ContinuationIntentSchema = Schema.Struct({
74
99
  perpetual: Schema.optional(Schema.Boolean),
75
100
  provider: Schema.optional(Schema.String),
76
101
  // Funding-path mode. The HTTP wire contract is documented by
77
- // `ComposeActionsSchema` in `@lifi/api-schemas`.
102
+ // `ComposeActionsSchema` in `@lifi/api-schemas`. A settle funded by a
103
+ // bridge delivery (`'delivered'` on the artifact) is inferred from its
104
+ // binding and never authored.
78
105
  funding: Schema.optional(Schema.Literal('inline', 'external')),
106
+ // The address on the escrow's chain that receives the escrow balance on
107
+ // expiry; defaults to the signer. The zero address would burn that balance.
108
+ refund: Schema.optional(
109
+ EVMAddressString.pipe(
110
+ Schema.filter((address) => !isZeroAddress(address), {
111
+ message: () => 'refund must not be the zero address',
112
+ }),
113
+ ),
114
+ ),
79
115
  });
80
116
 
81
117
  // A `0x`-prefixed string, prefix checked only. Continuation vocabulary no
@@ -99,6 +135,8 @@ export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));
99
135
  // supplies the funding.
100
136
  // - `cap` — the committed funding allocation: the most a fill may spend from
101
137
  // the escrow. A balance above it stays in the escrow.
138
+ // - `floor` — the registered funding floor: the least balance that arms a
139
+ // fill. A smaller balance waits for expiry and is refunded.
102
140
  // - `owner` — the account that controls the escrow and can sweep it.
103
141
  // - `refund` — where the escrow balance returns when the settlement expires.
104
142
  // - `expiresAtMs` — when the settlement expires: the effective expiry the
@@ -112,6 +150,7 @@ const Phase1EscrowSchema = Schema.Struct({
112
150
  token: HexStringSchema,
113
151
  amount: Schema.String,
114
152
  cap: Schema.String,
153
+ floor: Schema.String,
115
154
  owner: HexStringSchema,
116
155
  refund: HexStringSchema,
117
156
  expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive()),
@@ -120,11 +159,13 @@ const Phase1EscrowSchema = Schema.Struct({
120
159
  // Internal phase-1 artifact. The HTTP layer projects its `escrow` onto
121
160
  // `settlements` and publishes external-funding calldata and typed data through
122
161
  // `ComposeActionsSchema`. The internal `transactionRequest` remains optional
123
- // because inline funding does not produce a submittable transfer.
162
+ // because inline funding does not produce a submittable transfer, and
163
+ // `delivered` funding (a bridge delivers into the escrow) produces none
164
+ // either.
124
165
  export const Phase1ArtifactSchema = Schema.Union(
125
166
  Schema.Struct({
126
167
  kind: Schema.Literal('transaction'),
127
- funding: Schema.Literal('inline', 'external'),
168
+ funding: Schema.Literal('inline', 'external', 'delivered'),
128
169
  transactionRequest: Schema.optional(
129
170
  Schema.Struct({
130
171
  to: Schema.String,
@@ -283,6 +324,7 @@ export const AssertionSpecSchema = Schema.Union(
283
324
  );
284
325
 
285
326
  export type ContinuationOutcome = typeof ContinuationOutcomeSchema.Type;
327
+ export type CommittedOutcome = typeof CommittedOutcomeSchema.Type;
286
328
  export type ContinuationIntent = typeof ContinuationIntentSchema.Type;
287
329
  export type Phase1Artifact = typeof Phase1ArtifactSchema.Type;
288
330
  export type AssertionSpec = typeof AssertionSpecSchema.Type;
@@ -293,6 +335,9 @@ export type AssertionSpec = typeof AssertionSpecSchema.Type;
293
335
  // intent, so the first outcome is the settled one everywhere. `NonEmptyArray`
294
336
  // makes `[0]` present by construction. Keep this the only place that picks
295
337
  // 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];
338
+ // Generic over the intent so a `CommittedIntent` yields a `CommittedOutcome`.
339
+ export const settledOutcome = <
340
+ I extends { readonly outcomes: readonly [unknown, ...unknown[]] },
341
+ >(
342
+ intent: I,
343
+ ): I['outcomes'][0] => intent.outcomes[0];
package/src/flow.ts CHANGED
@@ -84,6 +84,8 @@ export type ComposeErrorKind =
84
84
  | 'fee_resolution_error'
85
85
  | 'fee_resolution_unavailable'
86
86
  | 'flashloan_unauthorized'
87
+ // A delivery tranche's failure; reasons in `DeliveryErrorReason`.
88
+ | 'delivery_error'
87
89
  // The request exceeded its wall-clock budget and was cancelled mid-flight.
88
90
  | 'deadline_exceeded';
89
91
 
@@ -103,7 +105,7 @@ export type ComposeRouteErrorKind =
103
105
 
104
106
  export type GenericComposeErrorKind = Exclude<
105
107
  ComposeErrorKind,
106
- 'preparation_error' | 'simulation_revert'
108
+ 'preparation_error' | 'simulation_revert' | 'delivery_error'
107
109
  >;
108
110
 
109
111
  export interface FailedPreparedOp {
@@ -140,13 +142,49 @@ export interface SimulationRevertComposeError extends ComposeErrorBase {
140
142
  readonly details?: SimulationRevert;
141
143
  }
142
144
 
145
+ // Why a delivery tranche failed:
146
+ // - `floor_drift`: the second quote's `min` fell below the registered floor;
147
+ // - `eta_exceeds_expiry`: the escrow expires before the delivery's ETA rule
148
+ // allows;
149
+ // - `quote_failed`: the second quote (to the registered escrow) failed;
150
+ // `cause` is the kind of that failure and `quoted` is the first quote.
151
+ export type DeliveryErrorReason =
152
+ 'floor_drift' | 'eta_exceeds_expiry' | 'quote_failed';
153
+
154
+ // `escrow` is present only when the failure came after the escrow was
155
+ // registered: the escrow is then abandoned and expires unfunded, and this
156
+ // record is its only trace.
157
+ export interface DeliveryErrorDetails {
158
+ readonly reason: DeliveryErrorReason;
159
+ readonly cause?: ComposeErrorKind;
160
+ readonly quoted: {
161
+ readonly min: string;
162
+ readonly expected: string;
163
+ readonly etaSeconds?: number;
164
+ };
165
+ readonly escrow?: {
166
+ readonly chainId: number;
167
+ readonly address: string;
168
+ readonly floor: string;
169
+ readonly expiresAtMs: number;
170
+ };
171
+ }
172
+
173
+ export interface DeliveryComposeError extends ComposeErrorBase {
174
+ readonly kind: 'delivery_error';
175
+ readonly details: DeliveryErrorDetails;
176
+ }
177
+
143
178
  export interface GenericComposeError extends ComposeErrorBase {
144
179
  readonly kind: GenericComposeErrorKind;
145
180
  readonly [key: string]: unknown;
146
181
  }
147
182
 
148
183
  export type ComposeError =
149
- PreparationComposeError | SimulationRevertComposeError | GenericComposeError;
184
+ | PreparationComposeError
185
+ | SimulationRevertComposeError
186
+ | DeliveryComposeError
187
+ | GenericComposeError;
150
188
 
151
189
  export interface MaterialiserInputBase {
152
190
  readonly kind: string;
package/src/flowSchema.ts CHANGED
@@ -215,6 +215,28 @@ export const LineageSchema = Schema.Struct({
215
215
  parentRequestId: UuidSchema,
216
216
  });
217
217
 
218
+ // Where a post-graph forward sends a balance: a literal address or a ref the
219
+ // compiler resolves. The compiler admits `context.sender` only.
220
+ export const ForwardToSchema = Schema.Union(EVMAddressString, RefSchema);
221
+
222
+ export const EpilogueForwardSchema = Schema.Struct({
223
+ resource: ResourceSchema,
224
+ to: ForwardToSchema,
225
+ });
226
+
227
+ // The flow's post-graph forwards, run after the last node. A named forward
228
+ // moves the proxy's whole balance of one resource to one address; the
229
+ // remainder moves every other proxy-held terminal resource to one address.
230
+ // `run.sweepTo: X` is sugar for `{ remainder: X }`.
231
+ export const EpilogueSchema = Schema.Struct({
232
+ forwards: Schema.optional(Schema.NonEmptyArray(EpilogueForwardSchema)),
233
+ remainder: Schema.optional(ForwardToSchema),
234
+ }).pipe(
235
+ Schema.filter((e) => e.forwards !== undefined || e.remainder !== undefined, {
236
+ message: () => 'epilogue needs forwards, a remainder, or both',
237
+ }),
238
+ );
239
+
218
240
  export const FlowSchema = Schema.Struct({
219
241
  version: Schema.Literal(1),
220
242
  id: Schema.String,
@@ -222,6 +244,7 @@ export const FlowSchema = Schema.Struct({
222
244
  inputs: Schema.Array(FlowInputSchema),
223
245
  nodes: Schema.Array(CallSchema),
224
246
  lineage: Schema.optional(LineageSchema),
247
+ epilogue: Schema.optional(EpilogueSchema),
225
248
  });
226
249
 
227
250
  export type SolType = typeof SolTypeSchema.Type;
@@ -234,4 +257,7 @@ export type BindValue = typeof BindValueSchema.Type;
234
257
  export type AppliedGuard = typeof AppliedGuardSchema.Type;
235
258
  export type Call = typeof CallSchema.Type;
236
259
  export type Lineage = typeof LineageSchema.Type;
260
+ export type ForwardTo = typeof ForwardToSchema.Type;
261
+ export type EpilogueForward = typeof EpilogueForwardSchema.Type;
262
+ export type Epilogue = typeof EpilogueSchema.Type;
237
263
  export type Flow = typeof FlowSchema.Type;