@lifi/compose-spec 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,174 @@
1
+ import type { Resource } from './resource.js';
2
+
3
+ /**
4
+ * Per-chain native-asset semantics.
5
+ *
6
+ * Most EVM chains have an ETH-style native gas coin sent via `msg.value` (the
7
+ * `evm-native` policy). A small number — currently only Tempo — express their
8
+ * "native" coin as an ERC-20 token (the `as-erc20` policy). Code that needs to
9
+ * lower or simulate a `Resource` of kind `"native"` should consult
10
+ * `getChainCapabilities(chainId)` rather than hardcoding chain IDs.
11
+ *
12
+ * The compose compiler uses this registry to transparently normalise native
13
+ * resources into ERC-20 resources on `as-erc20` chains at schema-decode time
14
+ * (see `normalizeResource` below and the `ResourceSchema` transform in
15
+ * `flowSchema.ts`).
16
+ *
17
+ * This union is the extension point for future native-asset policies. A chain
18
+ * with no canonical native asset would get a `reject-native` arm, under which a
19
+ * `{ kind: "native" }` resource becomes a validation error rather than being
20
+ * rewritten. No such chain exists yet, so the arm is not defined here.
21
+ */
22
+ export type ChainCapabilities =
23
+ | { readonly kind: 'evm-native'; readonly chainId: number }
24
+ | {
25
+ readonly kind: 'as-erc20';
26
+ readonly chainId: number;
27
+ readonly nativeErc20: NativeErc20;
28
+ };
29
+
30
+ export interface NativeErc20 {
31
+ readonly token: `0x${string}`;
32
+ readonly symbol: string;
33
+ readonly decimals: number;
34
+ }
35
+
36
+ /**
37
+ * The zero-address sentinel that represents the native gas coin on
38
+ * EVM-native chains. Exported so tests and call-sites can reference it
39
+ * by name rather than inlining 40 zeros.
40
+ *
41
+ * Inlined as a literal rather than imported from `@lifi/utils`: `compose-spec`
42
+ * is the wire-format leaf package and carries no `@lifi/*` dependencies
43
+ * (enforced by `scripts/check-compose-boundaries.mjs`).
44
+ */
45
+ export const EVM_NATIVE_SENTINEL: `0x${string}` =
46
+ // eslint-disable-next-line @lifi/prefer-utils-constants -- compose-spec is the wire-format leaf and must not import @lifi/utils (enforced by scripts/check-compose-boundaries.mjs); the literal is intentional here
47
+ '0x0000000000000000000000000000000000000000';
48
+
49
+ /**
50
+ * Whether `address` is the EVM-native zero-address sentinel, compared
51
+ * case-insensitively. Module-local: the two call-sites below share this exact
52
+ * comparison; it is not part of the package's public surface.
53
+ */
54
+ const isNativeSentinel = (address: string): boolean =>
55
+ address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase();
56
+
57
+ export const TEMPO_CHAIN_ID = 4217;
58
+
59
+ export const TEMPO_NATIVE_ERC20: NativeErc20 = {
60
+ token: '0x20C0000000000000000000000000000000000000',
61
+ symbol: 'pathUSD',
62
+ decimals: 6,
63
+ };
64
+
65
+ const REGISTRY: ReadonlyMap<number, ChainCapabilities> = new Map<
66
+ number,
67
+ ChainCapabilities
68
+ >([
69
+ [
70
+ TEMPO_CHAIN_ID,
71
+ {
72
+ kind: 'as-erc20',
73
+ chainId: TEMPO_CHAIN_ID,
74
+ nativeErc20: TEMPO_NATIVE_ERC20,
75
+ },
76
+ ],
77
+ ]);
78
+
79
+ export const getChainCapabilities = (chainId: number): ChainCapabilities =>
80
+ REGISTRY.get(chainId) ?? { kind: 'evm-native', chainId };
81
+
82
+ export const isAsErc20Chain = (chainId: number): boolean =>
83
+ getChainCapabilities(chainId).kind === 'as-erc20';
84
+
85
+ /**
86
+ * The address that represents the chain's native asset.
87
+ *
88
+ * On EVM-native chains this is the zero-address sentinel `0x0…0`. On
89
+ * `as-erc20` chains it is the chain's stand-in ERC-20 (e.g. PathUSD on Tempo).
90
+ */
91
+ export const canonicalNativeAddress = (chainId: number): `0x${string}` => {
92
+ const caps = getChainCapabilities(chainId);
93
+ return caps.kind === 'as-erc20'
94
+ ? caps.nativeErc20.token
95
+ : EVM_NATIVE_SENTINEL;
96
+ };
97
+
98
+ /**
99
+ * Whether `address` represents the native asset of `chainId`.
100
+ *
101
+ * On EVM-native chains, this is the case-insensitive zero-address check. On
102
+ * `as-erc20` chains, the literal zero address returns `false` — only the
103
+ * chain's stand-in ERC-20 address matches.
104
+ */
105
+ export const isNativeAddressForChain = (
106
+ chainId: number,
107
+ address: string,
108
+ ): boolean => {
109
+ const caps = getChainCapabilities(chainId);
110
+ const target =
111
+ caps.kind === 'as-erc20' ? caps.nativeErc20.token : EVM_NATIVE_SENTINEL;
112
+ return address.toLowerCase() === target.toLowerCase();
113
+ };
114
+
115
+ /**
116
+ * Whether `address` on `chainId` is the genuine `msg.value`-style native coin:
117
+ * an `evm-native` chain's zero-address sentinel.
118
+ *
119
+ * This is the single predicate that gates `msg.value` semantics — choosing a
120
+ * `NativeBalance` over an `Erc20Balance` simulation requirement, and skipping
121
+ * the ERC-20 approval a native input would otherwise need. It returns `false`
122
+ * for every address on an `as-erc20` chain (including the zero sentinel),
123
+ * because there the "native" coin is a real ERC-20 moved via `transferFrom`,
124
+ * never `msg.value`. Use this rather than re-deriving
125
+ * `!isAsErc20Chain(chainId) && address === EVM_NATIVE_SENTINEL` at call sites,
126
+ * and rather than `isNativeAddressForChain`, which returns `true` for the
127
+ * stand-in ERC-20 (PathUSD) on `as-erc20` chains and would wrongly route it to
128
+ * `msg.value`.
129
+ */
130
+ export const isMsgValueNative = (chainId: number, address: string): boolean =>
131
+ !isAsErc20Chain(chainId) && isNativeSentinel(address);
132
+
133
+ /**
134
+ * Rewrite a single `Resource` according to its chain's capabilities.
135
+ *
136
+ * On chains with the default `evm-native` policy, every resource is returned
137
+ * unchanged. On `as-erc20` chains (currently only Tempo, chainId 4217), a
138
+ * resource of kind `"native"` is rewritten into the equivalent ERC-20
139
+ * resource pointing at the chain's stand-in token (PathUSD for Tempo).
140
+ *
141
+ * This is the rewrite primitive behind the `ResourceSchema` decode transform
142
+ * (see `flowSchema.ts`), which is THE chokepoint: it runs every time a
143
+ * `Resource` is parsed — flow inputs via `FlowSchema`, op configs via
144
+ * `decodeConfig` — so every downstream pass (`normalizeFlow`, `resolve`,
145
+ * `lower`, `simulate`) sees only ERC-20 resources on `as-erc20` chains.
146
+ *
147
+ * The function preserves referential identity when nothing changes (returns the
148
+ * input `r` unchanged on evm-native chains and for ERC-20 resources) and is
149
+ * idempotent: running it on an already-rewritten resource is a no-op.
150
+ */
151
+ export const normalizeResource = (r: Resource): Resource => {
152
+ if (r.kind !== 'native') return r;
153
+ const caps = getChainCapabilities(r.chainId);
154
+ if (caps.kind !== 'as-erc20') return r;
155
+ return {
156
+ kind: 'erc20',
157
+ chainId: r.chainId,
158
+ token: caps.nativeErc20.token,
159
+ };
160
+ };
161
+
162
+ /**
163
+ * Address-level counterpart of `normalizeResource` for wire fields that carry a
164
+ * native asset as a bare token string (a continuation outcome's `token`). On
165
+ * `as-erc20` chains the native sentinel is rewritten to the chain's stand-in
166
+ * ERC-20; every other address passes through.
167
+ */
168
+ export const normalizeNativeTokenAddress = (
169
+ token: string,
170
+ chainId: number,
171
+ ): string =>
172
+ isAsErc20Chain(chainId) && isNativeSentinel(token)
173
+ ? canonicalNativeAddress(chainId)
174
+ : token;
package/src/compile.ts CHANGED
@@ -1,8 +1,10 @@
1
- import type { InputSpec, Precondition } from "./flow.js";
2
- import type { Flow } from "./flowSchema.js";
3
- import type { ProducedResource } from "./resource.js";
1
+ import type { VerificationDescriptor } from './descriptor.js';
2
+ import type { InputSpec, Precondition } from './flow.js';
3
+ import type { Flow } from './flowSchema.js';
4
+ import type { ProducedResource } from './resource.js';
5
+ import type { ContinuationPlanWire, Phase1ArtifactWire } from './zodSchemas.js';
4
6
 
5
- export type SimulationPolicy = "strict" | "allow-revert";
7
+ export type SimulationPolicy = 'strict' | 'allow-revert';
6
8
 
7
9
  /**
8
10
  * Destination for sweeping proxy-held terminal resources after execution.
@@ -44,7 +46,7 @@ export interface ApprovalEntry {
44
46
  readonly transactionRequest: {
45
47
  readonly to: string;
46
48
  readonly data: string;
47
- readonly value: "0";
49
+ readonly value: '0';
48
50
  };
49
51
  }
50
52
 
@@ -67,32 +69,63 @@ export interface ComposeTransactionRequest {
67
69
  readonly gasLimit?: string;
68
70
  }
69
71
 
72
+ // A single continuation pointer: the node whose `future` output is awaited and
73
+ // the downstream flow that consumes its proceeds. A flow can declare several,
74
+ // carried in the response as `continuations`.
70
75
  export interface ComposeContinuation {
71
76
  readonly awaits: string;
72
77
  readonly flowId: string;
73
78
  }
74
79
 
75
- export interface ComposeCompileSuccessData {
80
+ // Continuation fields shared by the success and partial-error responses, so the
81
+ // two shapes cannot drift. `phase1ByNode` / `continuationPlans` reuse the
82
+ // Zod-inferred wire types from `zodSchemas.ts`, pinning these SDK-facing types
83
+ // to the server contract rather than hand-transcribing them.
84
+ interface ComposeContinuationData {
85
+ // One pointer per `continuation.settle` branch (a flow can fork into several).
86
+ readonly continuations?: readonly ComposeContinuation[];
87
+ // Phase-1 action to sign/fund now, keyed by settle node. Absent for an atomic flow.
88
+ readonly phase1ByNode?: Record<string, Phase1ArtifactWire>;
89
+ // Self-serve second leg to re-submit later, keyed by settle node. Present only
90
+ // for providers that hand the next leg back to the caller (manual-relay).
91
+ readonly continuationPlans?: Record<string, ContinuationPlanWire>;
92
+ }
93
+
94
+ // One funding leg the compiled fill consumes: the resource input's token
95
+ // (native → zero address) and its statically resolved amount as a decimal
96
+ // string (verified continuations, plan GD-8, seam C5).
97
+ export interface SpendEntry {
98
+ readonly token: string;
99
+ readonly amount: string;
100
+ }
101
+
102
+ export interface ComposeCompileSuccessData extends ComposeContinuationData {
76
103
  readonly producedResources: Record<string, ProducedResource>;
77
104
  readonly transactionRequest: ComposeTransactionRequest;
78
105
  readonly userProxy: string;
79
106
  readonly priceImpact?: PriceImpact;
80
107
  readonly approvals?: readonly ApprovalEntry[];
81
- readonly continuation?: ComposeContinuation;
108
+ // GD-8 settlement-fill fields (seam C5), additive on every success response:
109
+ // `spends` (the exact token amounts the fill consumes) and `quote.validUntilMs`
110
+ // (fill freshness bound; the far-future sentinel until quote-expiry plumbing
111
+ // lands). `verificationDescriptor` (the echo) is present only when the flow
112
+ // carried a `continuation.commitment` node.
113
+ readonly spends?: readonly SpendEntry[];
114
+ readonly quote?: { readonly validUntilMs: number };
115
+ readonly verificationDescriptor?: VerificationDescriptor;
82
116
  }
83
117
 
84
- export interface ComposeCompilePartialData {
118
+ export interface ComposeCompilePartialData extends ComposeContinuationData {
85
119
  readonly producedResources: Record<string, ProducedResource>;
86
120
  readonly transactionRequest: ComposeTransactionRequest;
87
121
  readonly userProxy: string;
88
122
  readonly simulationRevert: SimulationRevert;
89
123
  readonly approvals?: readonly ApprovalEntry[];
90
- readonly continuation?: ComposeContinuation;
91
124
  }
92
125
 
93
126
  export type ComposeCompileResult =
94
- | (ComposeCompileSuccessData & { readonly status: "success" })
127
+ | (ComposeCompileSuccessData & { readonly status: 'success' })
95
128
  | (ComposeCompilePartialData & {
96
- readonly status: "partial";
129
+ readonly status: 'partial';
97
130
  readonly error: { readonly kind: string; readonly message: string };
98
131
  });
@@ -1,13 +1,13 @@
1
- import type { HandleInput, Ref, ResourceInput, SolType } from "./flowSchema.js";
2
1
  import type {
3
- Port,
4
- ResourcePort,
5
2
  HandlePort,
3
+ Port,
6
4
  ResourceOutputPort,
7
- } from "./flow.js";
8
- import type { Availability } from "./resource.js";
9
- import { erc20Resource, nativeResource } from "./resource.js";
10
- import type { HandleUnits } from "./zodSchemas.js";
5
+ ResourcePort,
6
+ } from './flow.js';
7
+ import type { HandleInput, Ref, ResourceInput, SolType } from './flowSchema.js';
8
+ import type { Availability } from './resource.js';
9
+ import { erc20Resource, nativeResource } from './resource.js';
10
+ import type { HandleUnits } from './zodSchemas.js';
11
11
 
12
12
  export interface OpHandleOptions {
13
13
  readonly expose?: boolean;
@@ -23,91 +23,93 @@ export const outputRef = (node: string, port: string): Ref => ({
23
23
  /** Returns `{ [key]: value }` when `value` is not nullish, else `{}`. */
24
24
  const optionalProp = <K extends string, V>(
25
25
  key: K,
26
- value: V | undefined | null
26
+ value: V | undefined | null,
27
27
  ): Partial<Record<K, V>> =>
28
- value != null ? ({ [key]: value } as Partial<Record<K, V>>) : {};
28
+ value !== undefined && value !== null
29
+ ? ({ [key]: value } as Partial<Record<K, V>>)
30
+ : {};
29
31
 
30
32
  export const linear = <N extends string, T extends SolType>(
31
33
  name: N,
32
- type: T
33
- ): Port & { readonly name: N; readonly type: T; readonly mode: "linear" } =>
34
- ({ name, type, mode: "linear", availability: "now" } as Port & {
34
+ type: T,
35
+ ): Port & { readonly name: N; readonly type: T; readonly mode: 'linear' } =>
36
+ ({ name, type, mode: 'linear', availability: 'now' }) as Port & {
35
37
  readonly name: N;
36
38
  readonly type: T;
37
- readonly mode: "linear";
38
- });
39
+ readonly mode: 'linear';
40
+ };
39
41
 
40
42
  export const copy = <N extends string, T extends SolType>(
41
43
  name: N,
42
- type: T
43
- ): Port & { readonly name: N; readonly type: T; readonly mode: "copy" } =>
44
- ({ name, type, mode: "copy", availability: "now" } as Port & {
44
+ type: T,
45
+ ): Port & { readonly name: N; readonly type: T; readonly mode: 'copy' } =>
46
+ ({ name, type, mode: 'copy', availability: 'now' }) as Port & {
45
47
  readonly name: N;
46
48
  readonly type: T;
47
- readonly mode: "copy";
48
- });
49
+ readonly mode: 'copy';
50
+ };
49
51
 
50
52
  export const handle = <N extends string, T extends SolType>(
51
53
  name: N,
52
- type: T
54
+ type: T,
53
55
  ): HandleInput & { readonly name: N; readonly type: T } =>
54
- ({ name, type } as HandleInput & { readonly name: N; readonly type: T });
56
+ ({ name, type }) as HandleInput & { readonly name: N; readonly type: T };
55
57
 
56
58
  export const native = <N extends string>(
57
59
  name: N,
58
- chainId: number
60
+ chainId: number,
59
61
  ): ResourceInput & { readonly name: N } =>
60
- ({ name, resource: nativeResource(chainId) } as ResourceInput & {
62
+ ({ name, resource: nativeResource(chainId) }) as ResourceInput & {
61
63
  readonly name: N;
62
- });
64
+ };
63
65
 
64
66
  export const erc20 = <N extends string>(
65
67
  name: N,
66
68
  token: string,
67
- chainId: number
69
+ chainId: number,
68
70
  ): ResourceInput & { readonly name: N } =>
69
- ({ name, resource: erc20Resource(token, chainId) } as ResourceInput & {
71
+ ({ name, resource: erc20Resource(token, chainId) }) as ResourceInput & {
70
72
  readonly name: N;
71
- });
73
+ };
72
74
 
73
75
  export const resource = <N extends string, Opt extends boolean = false>(
74
76
  name: N,
75
- accepts: "erc20" | "native" | "any",
76
- options?: { optional?: Opt }
77
+ accepts: 'erc20' | 'native' | 'any',
78
+ options?: { optional?: Opt },
77
79
  ): ResourcePort & { readonly name: N; readonly optional: Opt } =>
78
80
  ({
79
- kind: "resource",
81
+ kind: 'resource',
80
82
  name,
81
83
  accepts,
82
- mode: "linear",
83
- ...optionalProp("optional", options?.optional),
84
- } as ResourcePort & { readonly name: N; readonly optional: Opt });
84
+ mode: 'linear',
85
+ ...optionalProp('optional', options?.optional),
86
+ }) as ResourcePort & { readonly name: N; readonly optional: Opt };
85
87
 
86
88
  export const readResource = <N extends string>(
87
89
  name: N,
88
- accepts: "erc20" | "native" | "any"
89
- ): ResourcePort & { readonly name: N; readonly mode: "copy" } =>
90
- ({ kind: "resource", name, accepts, mode: "copy" } as ResourcePort & {
90
+ accepts: 'erc20' | 'native' | 'any',
91
+ ): ResourcePort & { readonly name: N; readonly mode: 'copy' } =>
92
+ ({ kind: 'resource', name, accepts, mode: 'copy' }) as ResourcePort & {
91
93
  readonly name: N;
92
- readonly mode: "copy";
93
- });
94
+ readonly mode: 'copy';
95
+ };
94
96
 
95
97
  export const opHandle = <N extends string, T extends SolType>(
96
98
  name: N,
97
99
  type: T,
98
- options?: OpHandleOptions
100
+ options?: OpHandleOptions,
99
101
  ): HandlePort & { readonly name: N; readonly type: T } =>
100
102
  ({
101
- kind: "handle",
103
+ kind: 'handle',
102
104
  name,
103
105
  type,
104
- mode: "copy",
105
- ...optionalProp("expose", options?.expose),
106
- ...optionalProp("units", options?.units),
107
- } as HandlePort & {
106
+ mode: 'copy',
107
+ ...optionalProp('expose', options?.expose),
108
+ ...optionalProp('units', options?.units),
109
+ }) as HandlePort & {
108
110
  readonly name: N;
109
111
  readonly type: T;
110
- });
112
+ };
111
113
 
112
114
  export const resourceOutput = <N extends string>(
113
115
  name: N,
@@ -118,17 +120,17 @@ export const resourceOutput = <N extends string>(
118
120
  providesMinimum?: boolean;
119
121
  omitIfZero?: boolean;
120
122
  deliveryAddressInput?: string;
121
- }
123
+ },
122
124
  ): ResourceOutputPort & { readonly name: N } => {
123
125
  const opts =
124
- typeof options === "string" ? { availability: options } : options;
126
+ typeof options === 'string' ? { availability: options } : options;
125
127
  return {
126
- kind: "resource_output",
128
+ kind: 'resource_output',
127
129
  name,
128
- mode: "linear",
129
- ...optionalProp("availability", opts?.availability),
130
- ...optionalProp("providesMinimum", opts?.providesMinimum),
131
- ...optionalProp("omitIfZero", opts?.omitIfZero),
132
- ...optionalProp("deliveryAddressInput", opts?.deliveryAddressInput),
130
+ mode: 'linear',
131
+ ...optionalProp('availability', opts?.availability),
132
+ ...optionalProp('providesMinimum', opts?.providesMinimum),
133
+ ...optionalProp('omitIfZero', opts?.omitIfZero),
134
+ ...optionalProp('deliveryAddressInput', opts?.deliveryAddressInput),
133
135
  } as ResourceOutputPort & { readonly name: N };
134
136
  };