@lifi/composer-sdk 0.2.0-staging.4 → 0.2.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.
- package/README.md +81 -0
- package/dist/authoring/handles.cjs.map +1 -1
- package/dist/authoring/handles.d.cts +13 -6
- package/dist/authoring/handles.d.ts +13 -6
- package/dist/authoring/handles.js.map +1 -1
- package/dist/client.cjs +38 -6
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +25 -1
- package/dist/client.d.ts +25 -1
- package/dist/client.js +41 -6
- package/dist/client.js.map +1 -1
- package/dist/errors.cjs +4 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.js +6 -1
- package/dist/errors.js.map +1 -1
- package/dist/generated/config.generated.cjs.map +1 -1
- package/dist/generated/config.generated.d.cts +82 -7
- package/dist/generated/config.generated.d.ts +82 -7
- package/dist/generated/materialisers.generated.cjs +2 -8
- package/dist/generated/materialisers.generated.cjs.map +1 -1
- package/dist/generated/materialisers.generated.d.cts +1 -1
- package/dist/generated/materialisers.generated.d.ts +1 -1
- package/dist/generated/materialisers.generated.js +1 -6
- package/dist/generated/materialisers.generated.js.map +1 -1
- package/dist/generated/operations.generated.cjs +56 -31
- package/dist/generated/operations.generated.cjs.map +1 -1
- package/dist/generated/operations.generated.d.cts +204 -94
- package/dist/generated/operations.generated.d.ts +204 -94
- package/dist/generated/operations.generated.js +56 -31
- package/dist/generated/operations.generated.js.map +1 -1
- package/dist/index.cjs +8 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/{materialisers.generated-BfWJ-g7t.d.ts → materialisers.generated-BMkBQgWZ.d.ts} +3 -8
- package/dist/{materialisers.generated-DaJRwiRe.d.cts → materialisers.generated-BWq5oePO.d.cts} +3 -8
- package/dist/responseSchemas.cjs +110 -0
- package/dist/responseSchemas.cjs.map +1 -0
- package/dist/responseSchemas.d.cts +36 -0
- package/dist/responseSchemas.d.ts +36 -0
- package/dist/responseSchemas.js +74 -0
- package/dist/responseSchemas.js.map +1 -0
- package/dist/run/simulate.cjs +41 -0
- package/dist/run/simulate.cjs.map +1 -0
- package/dist/run/simulate.d.cts +59 -0
- package/dist/run/simulate.d.ts +59 -0
- package/dist/run/simulate.js +17 -0
- package/dist/run/simulate.js.map +1 -0
- package/dist/sdk.cjs +6 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.d.cts +13 -1
- package/dist/sdk.d.ts +13 -1
- package/dist/sdk.js +6 -1
- package/dist/sdk.js.map +1 -1
- package/package.json +7 -5
- package/src/authoring/handles.ts +19 -10
- package/src/client.ts +86 -11
- package/src/errors.ts +8 -10
- package/src/examples/aaveRepay.ts +55 -16
- package/src/examples/aaveRepayWithATokens.ts +41 -30
- package/src/examples/aaveRounding.ts +42 -0
- package/src/examples/aaveSetEMode.ts +0 -1
- package/src/examples/config.ts +1 -1
- package/src/examples/emitCustomEvent.ts +75 -0
- package/src/examples/invariantChecks.ts +96 -0
- package/src/examples/run.ts +20 -18
- package/src/examples/simulateCompiledSwap.ts +76 -0
- package/src/examples/simulateRawTransaction.ts +39 -0
- package/src/examples/untypedOpWithTypedRef.ts +26 -20
- package/src/generated/config.generated.ts +229 -6
- package/src/generated/materialisers.generated.ts +0 -12
- package/src/generated/operations.generated.ts +330 -177
- package/src/index.ts +19 -0
- package/src/responseSchemas.ts +143 -0
- package/src/run/simulate.ts +78 -0
- package/src/sdk.ts +20 -1
- package/src/examples/staged/aaveBorrow.ts +0 -104
- package/src/examples/staged/aaveDebtRebalanceExactOut.ts +0 -301
- package/src/examples/staged/aaveHealthFactorExplode.ts +0 -70
- package/src/examples/staged/aaveToMorphoDebtMigration.ts +0 -190
- package/src/examples/staged/aaveToMorphoDebtMigrationWithSwap.ts +0 -221
- package/src/examples/staged/aaveToMorphoDebtMigrationWithSwapExactOut.ts +0 -302
- package/src/examples/staged/flashloanRepay.ts +0 -138
- package/src/examples/staged/morphoBlueBorrow.ts +0 -89
- package/src/examples/staged/morphoBlueRepay.ts +0 -91
- package/src/examples/staged/registry.ts +0 -78
package/README.md
CHANGED
|
@@ -119,6 +119,7 @@ if (result.status === 'success') {
|
|
|
119
119
|
- `sdk.client.compile(request)` — sends the flow to the backend and returns a `ComposeCompileResult` (discriminated union: `status: 'success'` or `status: 'partial'`)
|
|
120
120
|
- `sdk.client.getManifest()` — fetches the operation manifest
|
|
121
121
|
- `sdk.client.getZapPacks(options?)` — fetches the available routing edges grouped by protocol, returning `ZapPackOverview[]`. The catalog is dynamic (reflects the backend's current routing snapshot) and is not cached by the SDK. Filter to specific protocols via `GetZapPacksOptions`; each entry's edges are typed as `ZapPackEdge`.
|
|
122
|
+
- `sdk.client.simulate(request)` / `sdk.simulate(request)` — simulates a raw, pre-encoded transaction and returns a `SimulateResult` (discriminated union: `status: 'ok' | 'revert' | 'error'`). See [Simulating a raw transaction](#simulating-a-raw-transaction).
|
|
122
123
|
|
|
123
124
|
**Helpers**
|
|
124
125
|
- `resources.erc20(address, chainId)` / `resources.native(chainId)` — resource constructors
|
|
@@ -127,6 +128,7 @@ if (result.status === 'success') {
|
|
|
127
128
|
- `preconditions.*` — precondition factories (erc20Balance, nativeBalance, erc20Allowance)
|
|
128
129
|
- `raw.ref<T>(path)` — create a typed `$ref` pointer for use in bind slots (escape hatch for `untypedOp` outputs)
|
|
129
130
|
- `raw.guard(kind, config?)` / `raw.materialiser(kind, config?)` — low-level factories for guards and materialisers
|
|
131
|
+
- `buildSimulateRequest({ result, chainId, signer, trackedBalances, requirements?, block?, value? })` — assembles a `SimulateRequest` from a compile result (pure, no I/O)
|
|
130
132
|
|
|
131
133
|
## Simulation policy and partial results
|
|
132
134
|
|
|
@@ -181,6 +183,85 @@ const result = await builder.compile({
|
|
|
181
183
|
});
|
|
182
184
|
```
|
|
183
185
|
|
|
186
|
+
## Simulating a raw transaction
|
|
187
|
+
|
|
188
|
+
`sdk.client.simulate(...)` (and the `sdk.simulate(...)` pass-through) answer a question the compile pipeline does not: *if I send this exact transaction, how do specific token balances change and how much gas does it burn?* It takes a raw, pre-encoded transaction (a `to`, hex `data`, optional native `value`), funds a sender, runs it in one `eth_call`, and reports the watched balances before/after, their signed deltas, and the inner-call gas.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import { createComposeSdk } from '@lifi/composer-sdk';
|
|
192
|
+
|
|
193
|
+
const sdk = createComposeSdk({ baseUrl: 'https://li.quest' });
|
|
194
|
+
|
|
195
|
+
const result = await sdk.client.simulate({
|
|
196
|
+
chainId: 1,
|
|
197
|
+
from: '0x1111111111111111111111111111111111111111',
|
|
198
|
+
to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
|
|
199
|
+
data: '0xa9059cbb...', // pre-encoded transfer calldata
|
|
200
|
+
value: 0n, // bigint accepted; serialised to "0"
|
|
201
|
+
requirements: [
|
|
202
|
+
{
|
|
203
|
+
type: 'Erc20Balance',
|
|
204
|
+
wallet: '0x1111111111111111111111111111111111111111',
|
|
205
|
+
token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
|
|
206
|
+
balance: 1_000_000n, // bigint accepted
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
trackedBalances: [
|
|
210
|
+
{
|
|
211
|
+
token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
|
|
212
|
+
owner: '0x1111111111111111111111111111111111111111',
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
|
|
216
|
+
owner: '0x2222222222222222222222222222222222222222',
|
|
217
|
+
},
|
|
218
|
+
],
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
switch (result.status) {
|
|
222
|
+
case 'ok':
|
|
223
|
+
// Successful simulation.
|
|
224
|
+
console.log(result.gasUsed, result.deltas);
|
|
225
|
+
break;
|
|
226
|
+
case 'revert':
|
|
227
|
+
// The simulation ran but the transaction reverted on-chain — NOT an error.
|
|
228
|
+
console.log(result.revertReason, result.decodeResult);
|
|
229
|
+
break;
|
|
230
|
+
case 'error':
|
|
231
|
+
// The request was well-formed but the simulation could not be set up/run.
|
|
232
|
+
console.log(result.message);
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`requirements` is the funding-instruction union (`Erc20Balance`, `NativeBalance`, `Erc20Allowance`); use the zero address as a `trackedBalances` `token` to watch native balance. Amount fields accept `bigint` (serialised to decimal strings) or strings. The caps `SIMULATE_MAX_TRACKED_BALANCES` and `SIMULATE_MAX_REQUIREMENTS` (both `40`) are exported for reference.
|
|
238
|
+
|
|
239
|
+
Unlike `compile`, a `revert` is returned (not thrown): a revert is a *successful simulation* whose execution reverted. Only transport failures and HTTP 400/401/403/404/429/5xx throw `ComposeError`.
|
|
240
|
+
|
|
241
|
+
To simulate a transaction you just compiled, `buildSimulateRequest(...)` assembles the request without re-typing the transaction fields. `chainId` and `signer` are required (a compile result carries neither), and `trackedBalances`/`requirements` cannot be inferred from a flow:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
import { buildSimulateRequest } from '@lifi/composer-sdk';
|
|
245
|
+
|
|
246
|
+
const compiled = await builder.compile({ inputs: { ... }, signer: '0x1111...' });
|
|
247
|
+
const req = buildSimulateRequest({
|
|
248
|
+
result: compiled,
|
|
249
|
+
chainId: 1,
|
|
250
|
+
signer: '0x1111111111111111111111111111111111111111',
|
|
251
|
+
trackedBalances: [
|
|
252
|
+
{
|
|
253
|
+
token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
|
|
254
|
+
owner: '0x1111111111111111111111111111111111111111',
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
});
|
|
258
|
+
const sim = await sdk.client.simulate(req);
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
Two caveats from the endpoint: `gasUsed` is the inner-call execution gas only (it excludes the 21000 base tx cost and calldata gas), and EOA-only behaviour (e.g. `msg.sender == tx.origin` checks) is not faithfully simulated because the call runs through injected VM bytecode rather than a real EOA. See [`docs/references/simulate-endpoint.md`](../../../docs/references/simulate-endpoint.md) for the full contract.
|
|
262
|
+
|
|
263
|
+
Two runnable examples cover both paths: [`src/examples/simulateRawTransaction.ts`](src/examples/simulateRawTransaction.ts) builds a raw `SimulateRequest` directly, and [`src/examples/simulateCompiledSwap.ts`](src/examples/simulateCompiledSwap.ts) shows the end-to-end compile → `buildSimulateRequest` → `simulate` arc.
|
|
264
|
+
|
|
184
265
|
## Error handling
|
|
185
266
|
|
|
186
267
|
All SDK errors are thrown as `ComposeError` with a `code` property:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/authoring/handles.ts"],"sourcesContent":["import type { Resource } from '@lifi/compose-spec';\n\nimport type { OutputKind, TypedRef } from '../types.js';\n\n/**\n * A handle referencing a flow input declared in the flow's input schema.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface InputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'input';\n readonly inputName: string;\n readonly __outputKind?: T;\n}\n\n/**\n * An input handle for a resource (token) input, carrying the resource\n * declaration alongside the reference.\n */\nexport interface ResourceInputHandle extends InputHandle<'resource'> {\n readonly resource: Resource;\n}\n\n/**\n * A handle referencing an output port of a previously declared operation node.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface OutputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'output';\n readonly nodeId: string;\n readonly portName: string;\n readonly __outputKind?: T;\n}\n\n/** Discriminated union of all handle types that can be bound to operation arguments. */\nexport type AnyHandle = InputHandle | OutputHandle;\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link InputHandle}. */\nexport const isInputHandle = (h: AnyHandle): h is InputHandle =>\n h._tag === 'input';\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link OutputHandle}. */\nexport const isOutputHandle = (h: AnyHandle): h is OutputHandle =>\n h._tag === 'output';\n\n/**\n * Converts a handle to a JSON `$ref` pointer used in the flow document.\n * Input handles become `\"input.<name>\"`; output handles become `\"<nodeId>.<port>\"`.\n */\nexport const handleToRef = (h: AnyHandle): { $ref: string } => {\n if (h._tag === 'input') {\n if (!h.inputName) throw new Error('InputHandle has empty inputName');\n return { $ref: `input.${h.inputName}` };\n }\n if (!h.nodeId) throw new Error('OutputHandle has empty nodeId');\n if (!h.portName) throw new Error('OutputHandle has empty portName');\n return { $ref: `${h.nodeId}.${h.portName}` };\n};\n\n/**\n * For a bind slot expecting type T,
|
|
1
|
+
{"version":3,"sources":["../../src/authoring/handles.ts"],"sourcesContent":["import type { Resource, StaticSolType } from '@lifi/compose-spec';\n\nimport type { OutputKind, TypedRef } from '../types.js';\n\n/**\n * A handle referencing a flow input declared in the flow's input schema.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface InputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'input';\n readonly inputName: string;\n readonly __outputKind?: T;\n}\n\n/**\n * An input handle for a resource (token) input, carrying the resource\n * declaration alongside the reference.\n */\nexport interface ResourceInputHandle extends InputHandle<'resource'> {\n readonly resource: Resource;\n}\n\n/**\n * A handle referencing an output port of a previously declared operation node.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface OutputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'output';\n readonly nodeId: string;\n readonly portName: string;\n readonly __outputKind?: T;\n}\n\n/** Discriminated union of all handle types that can be bound to operation arguments. */\nexport type AnyHandle = InputHandle | OutputHandle;\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link InputHandle}. */\nexport const isInputHandle = (h: AnyHandle): h is InputHandle =>\n h._tag === 'input';\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link OutputHandle}. */\nexport const isOutputHandle = (h: AnyHandle): h is OutputHandle =>\n h._tag === 'output';\n\n/**\n * Converts a handle to a JSON `$ref` pointer used in the flow document.\n * Input handles become `\"input.<name>\"`; output handles become `\"<nodeId>.<port>\"`.\n */\nexport const handleToRef = (h: AnyHandle): { $ref: string } => {\n if (h._tag === 'input') {\n if (!h.inputName) throw new Error('InputHandle has empty inputName');\n return { $ref: `input.${h.inputName}` };\n }\n if (!h.nodeId) throw new Error('OutputHandle has empty nodeId');\n if (!h.portName) throw new Error('OutputHandle has empty portName');\n return { $ref: `${h.nodeId}.${h.portName}` };\n};\n\n/**\n * For a bind slot expecting type T, widen the set of accepted handle types:\n * - `'bytes32'` is the raw 32-byte word type: accept any static-32-byte handle\n * (`uint256`/`uintN`/`address`/`bool`/`bytes32`) plus `'resource'` (a uint256\n * amount). At the IR1 boundary every value is a type-erased word, so any\n * static-32-byte handle is a sound bind for a `bytes32` payload port.\n * - `'uint256'` keeps its existing widening to also accept `'resource'`-tagged\n * handles (resources are uint256 amounts).\n * - every other type keeps exact-SolType matching.\n */\ntype SlotAssignable<T extends OutputKind> = T extends 'bytes32'\n ? StaticSolType | 'resource'\n : T extends 'uint256'\n ? T | 'resource'\n : T;\n\n/**\n * The set of values accepted by a typed bind slot.\n * - `OutputHandle<T>` / `InputHandle<T>` (same type)\n * - For `'uint256'` slots, also `'resource'`-tagged handles\n * - For `'bytes32'` slots, any static-32-byte handle (and `'resource'`)\n * - `TypedRef<T>` (typed context refs, subject to `SlotAssignable`)\n *\n * Plain `{ $ref: '...' }` objects are **not** accepted — use `raw.ref<T>()`\n * to create a typed ref when you need to reference a raw path.\n */\nexport type Bindable<T extends OutputKind> =\n | OutputHandle<SlotAssignable<T>>\n | InputHandle<SlotAssignable<T>>\n | TypedRef<SlotAssignable<T>>;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCO,MAAM,gBAAgB,CAAC,MAC5B,EAAE,SAAS;AAGN,MAAM,iBAAiB,CAAC,MAC7B,EAAE,SAAS;AAMN,MAAM,cAAc,CAAC,MAAmC;AAC7D,MAAI,EAAE,SAAS,SAAS;AACtB,QAAI,CAAC,EAAE,UAAW,OAAM,IAAI,MAAM,iCAAiC;AACnE,WAAO,EAAE,MAAM,SAAS,EAAE,SAAS,GAAG;AAAA,EACxC;AACA,MAAI,CAAC,EAAE,OAAQ,OAAM,IAAI,MAAM,+BAA+B;AAC9D,MAAI,CAAC,EAAE,SAAU,OAAM,IAAI,MAAM,iCAAiC;AAClE,SAAO,EAAE,MAAM,GAAG,EAAE,MAAM,IAAI,EAAE,QAAQ,GAAG;AAC7C;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Resource } from '@lifi/compose-spec';
|
|
1
|
+
import { StaticSolType, Resource } from '@lifi/compose-spec';
|
|
2
2
|
import { OutputKind, TypedRef } from '../types.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -43,19 +43,26 @@ declare const handleToRef: (h: AnyHandle) => {
|
|
|
43
43
|
$ref: string;
|
|
44
44
|
};
|
|
45
45
|
/**
|
|
46
|
-
* For a bind slot expecting type T,
|
|
47
|
-
*
|
|
46
|
+
* For a bind slot expecting type T, widen the set of accepted handle types:
|
|
47
|
+
* - `'bytes32'` is the raw 32-byte word type: accept any static-32-byte handle
|
|
48
|
+
* (`uint256`/`uintN`/`address`/`bool`/`bytes32`) plus `'resource'` (a uint256
|
|
49
|
+
* amount). At the IR1 boundary every value is a type-erased word, so any
|
|
50
|
+
* static-32-byte handle is a sound bind for a `bytes32` payload port.
|
|
51
|
+
* - `'uint256'` keeps its existing widening to also accept `'resource'`-tagged
|
|
52
|
+
* handles (resources are uint256 amounts).
|
|
53
|
+
* - every other type keeps exact-SolType matching.
|
|
48
54
|
*/
|
|
49
|
-
type
|
|
55
|
+
type SlotAssignable<T extends OutputKind> = T extends 'bytes32' ? StaticSolType | 'resource' : T extends 'uint256' ? T | 'resource' : T;
|
|
50
56
|
/**
|
|
51
57
|
* The set of values accepted by a typed bind slot.
|
|
52
58
|
* - `OutputHandle<T>` / `InputHandle<T>` (same type)
|
|
53
59
|
* - For `'uint256'` slots, also `'resource'`-tagged handles
|
|
54
|
-
* - `
|
|
60
|
+
* - For `'bytes32'` slots, any static-32-byte handle (and `'resource'`)
|
|
61
|
+
* - `TypedRef<T>` (typed context refs, subject to `SlotAssignable`)
|
|
55
62
|
*
|
|
56
63
|
* Plain `{ $ref: '...' }` objects are **not** accepted — use `raw.ref<T>()`
|
|
57
64
|
* to create a typed ref when you need to reference a raw path.
|
|
58
65
|
*/
|
|
59
|
-
type Bindable<T extends OutputKind> = OutputHandle<
|
|
66
|
+
type Bindable<T extends OutputKind> = OutputHandle<SlotAssignable<T>> | InputHandle<SlotAssignable<T>> | TypedRef<SlotAssignable<T>>;
|
|
60
67
|
|
|
61
68
|
export { type AnyHandle, type Bindable, type InputHandle, type OutputHandle, type ResourceInputHandle, handleToRef, isInputHandle, isOutputHandle };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Resource } from '@lifi/compose-spec';
|
|
1
|
+
import { StaticSolType, Resource } from '@lifi/compose-spec';
|
|
2
2
|
import { OutputKind, TypedRef } from '../types.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -43,19 +43,26 @@ declare const handleToRef: (h: AnyHandle) => {
|
|
|
43
43
|
$ref: string;
|
|
44
44
|
};
|
|
45
45
|
/**
|
|
46
|
-
* For a bind slot expecting type T,
|
|
47
|
-
*
|
|
46
|
+
* For a bind slot expecting type T, widen the set of accepted handle types:
|
|
47
|
+
* - `'bytes32'` is the raw 32-byte word type: accept any static-32-byte handle
|
|
48
|
+
* (`uint256`/`uintN`/`address`/`bool`/`bytes32`) plus `'resource'` (a uint256
|
|
49
|
+
* amount). At the IR1 boundary every value is a type-erased word, so any
|
|
50
|
+
* static-32-byte handle is a sound bind for a `bytes32` payload port.
|
|
51
|
+
* - `'uint256'` keeps its existing widening to also accept `'resource'`-tagged
|
|
52
|
+
* handles (resources are uint256 amounts).
|
|
53
|
+
* - every other type keeps exact-SolType matching.
|
|
48
54
|
*/
|
|
49
|
-
type
|
|
55
|
+
type SlotAssignable<T extends OutputKind> = T extends 'bytes32' ? StaticSolType | 'resource' : T extends 'uint256' ? T | 'resource' : T;
|
|
50
56
|
/**
|
|
51
57
|
* The set of values accepted by a typed bind slot.
|
|
52
58
|
* - `OutputHandle<T>` / `InputHandle<T>` (same type)
|
|
53
59
|
* - For `'uint256'` slots, also `'resource'`-tagged handles
|
|
54
|
-
* - `
|
|
60
|
+
* - For `'bytes32'` slots, any static-32-byte handle (and `'resource'`)
|
|
61
|
+
* - `TypedRef<T>` (typed context refs, subject to `SlotAssignable`)
|
|
55
62
|
*
|
|
56
63
|
* Plain `{ $ref: '...' }` objects are **not** accepted — use `raw.ref<T>()`
|
|
57
64
|
* to create a typed ref when you need to reference a raw path.
|
|
58
65
|
*/
|
|
59
|
-
type Bindable<T extends OutputKind> = OutputHandle<
|
|
66
|
+
type Bindable<T extends OutputKind> = OutputHandle<SlotAssignable<T>> | InputHandle<SlotAssignable<T>> | TypedRef<SlotAssignable<T>>;
|
|
60
67
|
|
|
61
68
|
export { type AnyHandle, type Bindable, type InputHandle, type OutputHandle, type ResourceInputHandle, handleToRef, isInputHandle, isOutputHandle };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/authoring/handles.ts"],"sourcesContent":["import type { Resource } from '@lifi/compose-spec';\n\nimport type { OutputKind, TypedRef } from '../types.js';\n\n/**\n * A handle referencing a flow input declared in the flow's input schema.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface InputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'input';\n readonly inputName: string;\n readonly __outputKind?: T;\n}\n\n/**\n * An input handle for a resource (token) input, carrying the resource\n * declaration alongside the reference.\n */\nexport interface ResourceInputHandle extends InputHandle<'resource'> {\n readonly resource: Resource;\n}\n\n/**\n * A handle referencing an output port of a previously declared operation node.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface OutputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'output';\n readonly nodeId: string;\n readonly portName: string;\n readonly __outputKind?: T;\n}\n\n/** Discriminated union of all handle types that can be bound to operation arguments. */\nexport type AnyHandle = InputHandle | OutputHandle;\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link InputHandle}. */\nexport const isInputHandle = (h: AnyHandle): h is InputHandle =>\n h._tag === 'input';\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link OutputHandle}. */\nexport const isOutputHandle = (h: AnyHandle): h is OutputHandle =>\n h._tag === 'output';\n\n/**\n * Converts a handle to a JSON `$ref` pointer used in the flow document.\n * Input handles become `\"input.<name>\"`; output handles become `\"<nodeId>.<port>\"`.\n */\nexport const handleToRef = (h: AnyHandle): { $ref: string } => {\n if (h._tag === 'input') {\n if (!h.inputName) throw new Error('InputHandle has empty inputName');\n return { $ref: `input.${h.inputName}` };\n }\n if (!h.nodeId) throw new Error('OutputHandle has empty nodeId');\n if (!h.portName) throw new Error('OutputHandle has empty portName');\n return { $ref: `${h.nodeId}.${h.portName}` };\n};\n\n/**\n * For a bind slot expecting type T,
|
|
1
|
+
{"version":3,"sources":["../../src/authoring/handles.ts"],"sourcesContent":["import type { Resource, StaticSolType } from '@lifi/compose-spec';\n\nimport type { OutputKind, TypedRef } from '../types.js';\n\n/**\n * A handle referencing a flow input declared in the flow's input schema.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface InputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'input';\n readonly inputName: string;\n readonly __outputKind?: T;\n}\n\n/**\n * An input handle for a resource (token) input, carrying the resource\n * declaration alongside the reference.\n */\nexport interface ResourceInputHandle extends InputHandle<'resource'> {\n readonly resource: Resource;\n}\n\n/**\n * A handle referencing an output port of a previously declared operation node.\n * The phantom `__outputKind` field carries the type parameter through\n * TypeScript's structural type system without affecting runtime shape.\n */\nexport interface OutputHandle<T extends OutputKind = OutputKind> {\n readonly _tag: 'output';\n readonly nodeId: string;\n readonly portName: string;\n readonly __outputKind?: T;\n}\n\n/** Discriminated union of all handle types that can be bound to operation arguments. */\nexport type AnyHandle = InputHandle | OutputHandle;\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link InputHandle}. */\nexport const isInputHandle = (h: AnyHandle): h is InputHandle =>\n h._tag === 'input';\n\n/** Type guard that narrows an {@link AnyHandle} to an {@link OutputHandle}. */\nexport const isOutputHandle = (h: AnyHandle): h is OutputHandle =>\n h._tag === 'output';\n\n/**\n * Converts a handle to a JSON `$ref` pointer used in the flow document.\n * Input handles become `\"input.<name>\"`; output handles become `\"<nodeId>.<port>\"`.\n */\nexport const handleToRef = (h: AnyHandle): { $ref: string } => {\n if (h._tag === 'input') {\n if (!h.inputName) throw new Error('InputHandle has empty inputName');\n return { $ref: `input.${h.inputName}` };\n }\n if (!h.nodeId) throw new Error('OutputHandle has empty nodeId');\n if (!h.portName) throw new Error('OutputHandle has empty portName');\n return { $ref: `${h.nodeId}.${h.portName}` };\n};\n\n/**\n * For a bind slot expecting type T, widen the set of accepted handle types:\n * - `'bytes32'` is the raw 32-byte word type: accept any static-32-byte handle\n * (`uint256`/`uintN`/`address`/`bool`/`bytes32`) plus `'resource'` (a uint256\n * amount). At the IR1 boundary every value is a type-erased word, so any\n * static-32-byte handle is a sound bind for a `bytes32` payload port.\n * - `'uint256'` keeps its existing widening to also accept `'resource'`-tagged\n * handles (resources are uint256 amounts).\n * - every other type keeps exact-SolType matching.\n */\ntype SlotAssignable<T extends OutputKind> = T extends 'bytes32'\n ? StaticSolType | 'resource'\n : T extends 'uint256'\n ? T | 'resource'\n : T;\n\n/**\n * The set of values accepted by a typed bind slot.\n * - `OutputHandle<T>` / `InputHandle<T>` (same type)\n * - For `'uint256'` slots, also `'resource'`-tagged handles\n * - For `'bytes32'` slots, any static-32-byte handle (and `'resource'`)\n * - `TypedRef<T>` (typed context refs, subject to `SlotAssignable`)\n *\n * Plain `{ $ref: '...' }` objects are **not** accepted — use `raw.ref<T>()`\n * to create a typed ref when you need to reference a raw path.\n */\nexport type Bindable<T extends OutputKind> =\n | OutputHandle<SlotAssignable<T>>\n | InputHandle<SlotAssignable<T>>\n | TypedRef<SlotAssignable<T>>;\n"],"mappings":"AAuCO,MAAM,gBAAgB,CAAC,MAC5B,EAAE,SAAS;AAGN,MAAM,iBAAiB,CAAC,MAC7B,EAAE,SAAS;AAMN,MAAM,cAAc,CAAC,MAAmC;AAC7D,MAAI,EAAE,SAAS,SAAS;AACtB,QAAI,CAAC,EAAE,UAAW,OAAM,IAAI,MAAM,iCAAiC;AACnE,WAAO,EAAE,MAAM,SAAS,EAAE,SAAS,GAAG;AAAA,EACxC;AACA,MAAI,CAAC,EAAE,OAAQ,OAAM,IAAI,MAAM,+BAA+B;AAC9D,MAAI,CAAC,EAAE,SAAU,OAAM,IAAI,MAAM,iCAAiC;AAClE,SAAO,EAAE,MAAM,GAAG,EAAE,MAAM,IAAI,EAAE,QAAQ,GAAG;AAC7C;","names":[]}
|
package/dist/client.cjs
CHANGED
|
@@ -22,7 +22,8 @@ __export(client_exports, {
|
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(client_exports);
|
|
24
24
|
var import_errors = require("./errors.js");
|
|
25
|
-
|
|
25
|
+
var import_responseSchemas = require("./responseSchemas.js");
|
|
26
|
+
const SDK_VERSION = true ? "0.2.0" : "dev";
|
|
26
27
|
const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
27
28
|
const isNonNullObject = (v) => typeof v === "object" && v !== null;
|
|
28
29
|
const parseBody = async (res, url) => {
|
|
@@ -40,16 +41,28 @@ const parseCompileSuccessBody = async (res, url) => {
|
|
|
40
41
|
};
|
|
41
42
|
const parsePartialBody = async (res, url) => {
|
|
42
43
|
const body = await res.json().catch((_) => null);
|
|
43
|
-
|
|
44
|
+
const envelope = (0, import_responseSchemas.parseCompilePartialEnvelope)(body);
|
|
45
|
+
if (envelope === null) {
|
|
44
46
|
throw new import_errors.ComposeError(
|
|
45
47
|
"UNKNOWN_ERROR",
|
|
46
48
|
"Unexpected partial response format",
|
|
47
49
|
{ url }
|
|
48
50
|
);
|
|
49
51
|
}
|
|
50
|
-
const data =
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
const data = envelope.data;
|
|
53
|
+
return { ...data, status: "partial", error: envelope.error };
|
|
54
|
+
};
|
|
55
|
+
const parseSimulateBody = async (res, url) => {
|
|
56
|
+
const body = await res.json().catch((_) => null);
|
|
57
|
+
const result = (0, import_responseSchemas.parseSimulateResult)(body);
|
|
58
|
+
if (result === null) {
|
|
59
|
+
throw new import_errors.ComposeError(
|
|
60
|
+
"UNKNOWN_ERROR",
|
|
61
|
+
"Unexpected simulate response format",
|
|
62
|
+
{ url }
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
53
66
|
};
|
|
54
67
|
const createComposeClient = (options) => {
|
|
55
68
|
if (!options.baseUrl || !/^https?:\/\//i.test(options.baseUrl)) {
|
|
@@ -131,7 +144,26 @@ const createComposeClient = (options) => {
|
|
|
131
144
|
}
|
|
132
145
|
return await parseBody(res, url);
|
|
133
146
|
};
|
|
134
|
-
|
|
147
|
+
const simulate = async (request) => {
|
|
148
|
+
const url = `${base}/simulate`;
|
|
149
|
+
let res;
|
|
150
|
+
try {
|
|
151
|
+
res = await fetchFn(url, {
|
|
152
|
+
method: "POST",
|
|
153
|
+
headers: { ...baseHeaders, "Content-Type": "application/json" },
|
|
154
|
+
body: JSON.stringify(request, bigintReplacer)
|
|
155
|
+
});
|
|
156
|
+
} catch (err) {
|
|
157
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
158
|
+
throw new import_errors.ComposeError("NETWORK_ERROR", message, { cause: err });
|
|
159
|
+
}
|
|
160
|
+
if (res.status === 200 || res.status === 422) {
|
|
161
|
+
return await parseSimulateBody(res, url);
|
|
162
|
+
}
|
|
163
|
+
const body = await res.text();
|
|
164
|
+
throw (0, import_errors.errorFromHttpResponse)(res.status, body, url);
|
|
165
|
+
};
|
|
166
|
+
return { getManifest, compile, getZapPacks, simulate };
|
|
135
167
|
};
|
|
136
168
|
// Annotate the CommonJS export names for ESM import in node:
|
|
137
169
|
0 && (module.exports = {
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n} from '@lifi/compose-spec';\n\nimport type { GetZapPacksOptions, ZapPackOverview } from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `x-lifi-composer-sdk` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** Optional LI.FI API key. When set, sent as the `x-lifi-api-key` header on every request. */\n readonly apiKey?: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n}\n\nconst bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n if (\n !isNonNullObject(body) ||\n !('data' in body) ||\n !isNonNullObject(body.data) ||\n !('error' in body) ||\n !isNonNullObject(body.error)\n ) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n const data = body.data as unknown as ComposeCompilePartialData;\n const error = body.error as unknown as { kind: string; message: string };\n return { ...data, status: 'partial' as const, error };\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n 'x-lifi-composer-sdk': SDK_VERSION,\n ...(trimmedApiKey ? { 'x-lifi-api-key': trimmedApiKey } : {}),\n };\n\n const getManifest = async (): Promise<ComposeManifest> => {\n const url = `${base}/compose/manifest`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<ComposeManifest>(res, url);\n };\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> => {\n const url = `${base}/compose`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n };\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n const url = `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<readonly ZapPackOverview[]>(res, url);\n };\n\n return { getManifest, compile, getZapPacks };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,oBAAoD;AASpD,MAAM,cACJ,OAAyC,oBAAkB;AA+D7D,MAAM,iBAAiB,CAAC,MAAc,UACpC,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAEjC,MAAM,YAAY,OAAU,KAAe,QAA4B;AACrE,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI;AAC/C,MAAI,CAAC,gBAAgB,IAAI,KAAK,EAAE,UAAU,OAAO;AAC/C,UAAM,IAAI,2BAAa,iBAAiB,8BAA8B;AAAA,MACpE;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,KAAK;AACd;AAEA,MAAM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I,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAC1D,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,YAAY;AAAA,MAC5B,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,2BAAa,iBAAiB,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IACjE;AACA,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,gBAAM,qCAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,IACnD;AACA,WAAO,MAAM,UAAsC,KAAK,GAAG;AAAA,EAC7D;AAEA,SAAO,EAAE,aAAa,SAAS,YAAY;AAC7C;","names":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\n\nimport type { GetZapPacksOptions, ZapPackOverview } from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `x-lifi-composer-sdk` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** Optional LI.FI API key. When set, sent as the `x-lifi-api-key` header on every request. */\n readonly apiKey?: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\nconst bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as unknown as ComposeCompilePartialData;\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n 'x-lifi-composer-sdk': SDK_VERSION,\n ...(trimmedApiKey ? { 'x-lifi-api-key': trimmedApiKey } : {}),\n };\n\n const getManifest = async (): Promise<ComposeManifest> => {\n const url = `${base}/compose/manifest`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<ComposeManifest>(res, url);\n };\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> => {\n const url = `${base}/compose`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n };\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n const url = `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<readonly ZapPackOverview[]>(res, url);\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status,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AAA,EAC7D;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,mBAAmB;AAAA,QAC9D,MAAM,KAAK,UAAU,SAAS,cAAc;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,2BAAa,iBAAiB,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IACjE;AAOA,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAC5C,aAAO,MAAM,kBAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,cAAM,qCAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,SAAS,aAAa,SAAS;AACvD;","names":["options"]}
|
package/dist/client.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ComposeManifest, ComposeCompileRequest, ComposeCompileResult } from '@lifi/compose-spec';
|
|
1
|
+
import { ComposeManifest, ComposeCompileRequest, ComposeCompileResult, SimulateRequest, SimulateResult } from '@lifi/compose-spec';
|
|
2
2
|
import { GetZapPacksOptions, ZapPackOverview } from './discovery.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -55,6 +55,30 @@ interface ComposeClient {
|
|
|
55
55
|
* routing catalog is not yet initialized).
|
|
56
56
|
*/
|
|
57
57
|
readonly getZapPacks: (options?: GetZapPacksOptions) => Promise<readonly ZapPackOverview[]>;
|
|
58
|
+
/**
|
|
59
|
+
* Simulates a raw, pre-encoded transaction against `POST /simulate` and
|
|
60
|
+
* reports how the watched balances change and how much inner-call gas it
|
|
61
|
+
* burns.
|
|
62
|
+
*
|
|
63
|
+
* The result is a discriminated union on `status`:
|
|
64
|
+
* - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.
|
|
65
|
+
* - `'revert'` — the simulation ran but the transaction reverted on-chain. A
|
|
66
|
+
* revert is a *successful simulation*, not a transport error, so it is
|
|
67
|
+
* returned (HTTP 200) rather than thrown — mirroring how {@link compile}
|
|
68
|
+
* returns `status: 'partial'` on a simulated revert.
|
|
69
|
+
* - `'error'` — the request was well-formed but the simulation could not be
|
|
70
|
+
* set up or run (HTTP 422); `message` is intentionally generic.
|
|
71
|
+
*
|
|
72
|
+
* `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)
|
|
73
|
+
* are serialised to decimal strings automatically.
|
|
74
|
+
*
|
|
75
|
+
* @param request - The raw transaction plus funding `requirements` and the
|
|
76
|
+
* `trackedBalances` to watch.
|
|
77
|
+
* @returns A {@link SimulateResult} (`ok` / `revert` / `error`).
|
|
78
|
+
* @throws {@link ComposeError} on network failures, HTTP 400 (malformed
|
|
79
|
+
* input), 401/403 (auth), 404, 429, and 5xx.
|
|
80
|
+
*/
|
|
81
|
+
readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;
|
|
58
82
|
}
|
|
59
83
|
/**
|
|
60
84
|
* Creates a low-level Compose API client.
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ComposeManifest, ComposeCompileRequest, ComposeCompileResult } from '@lifi/compose-spec';
|
|
1
|
+
import { ComposeManifest, ComposeCompileRequest, ComposeCompileResult, SimulateRequest, SimulateResult } from '@lifi/compose-spec';
|
|
2
2
|
import { GetZapPacksOptions, ZapPackOverview } from './discovery.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -55,6 +55,30 @@ interface ComposeClient {
|
|
|
55
55
|
* routing catalog is not yet initialized).
|
|
56
56
|
*/
|
|
57
57
|
readonly getZapPacks: (options?: GetZapPacksOptions) => Promise<readonly ZapPackOverview[]>;
|
|
58
|
+
/**
|
|
59
|
+
* Simulates a raw, pre-encoded transaction against `POST /simulate` and
|
|
60
|
+
* reports how the watched balances change and how much inner-call gas it
|
|
61
|
+
* burns.
|
|
62
|
+
*
|
|
63
|
+
* The result is a discriminated union on `status`:
|
|
64
|
+
* - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.
|
|
65
|
+
* - `'revert'` — the simulation ran but the transaction reverted on-chain. A
|
|
66
|
+
* revert is a *successful simulation*, not a transport error, so it is
|
|
67
|
+
* returned (HTTP 200) rather than thrown — mirroring how {@link compile}
|
|
68
|
+
* returns `status: 'partial'` on a simulated revert.
|
|
69
|
+
* - `'error'` — the request was well-formed but the simulation could not be
|
|
70
|
+
* set up or run (HTTP 422); `message` is intentionally generic.
|
|
71
|
+
*
|
|
72
|
+
* `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)
|
|
73
|
+
* are serialised to decimal strings automatically.
|
|
74
|
+
*
|
|
75
|
+
* @param request - The raw transaction plus funding `requirements` and the
|
|
76
|
+
* `trackedBalances` to watch.
|
|
77
|
+
* @returns A {@link SimulateResult} (`ok` / `revert` / `error`).
|
|
78
|
+
* @throws {@link ComposeError} on network failures, HTTP 400 (malformed
|
|
79
|
+
* input), 401/403 (auth), 404, 429, and 5xx.
|
|
80
|
+
*/
|
|
81
|
+
readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;
|
|
58
82
|
}
|
|
59
83
|
/**
|
|
60
84
|
* Creates a low-level Compose API client.
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { ComposeError, errorFromHttpResponse } from "./errors.js";
|
|
2
|
-
|
|
2
|
+
import {
|
|
3
|
+
parseCompilePartialEnvelope,
|
|
4
|
+
parseSimulateResult
|
|
5
|
+
} from "./responseSchemas.js";
|
|
6
|
+
const SDK_VERSION = true ? "0.2.0" : "dev";
|
|
3
7
|
const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
4
8
|
const isNonNullObject = (v) => typeof v === "object" && v !== null;
|
|
5
9
|
const parseBody = async (res, url) => {
|
|
@@ -17,16 +21,28 @@ const parseCompileSuccessBody = async (res, url) => {
|
|
|
17
21
|
};
|
|
18
22
|
const parsePartialBody = async (res, url) => {
|
|
19
23
|
const body = await res.json().catch((_) => null);
|
|
20
|
-
|
|
24
|
+
const envelope = parseCompilePartialEnvelope(body);
|
|
25
|
+
if (envelope === null) {
|
|
21
26
|
throw new ComposeError(
|
|
22
27
|
"UNKNOWN_ERROR",
|
|
23
28
|
"Unexpected partial response format",
|
|
24
29
|
{ url }
|
|
25
30
|
);
|
|
26
31
|
}
|
|
27
|
-
const data =
|
|
28
|
-
|
|
29
|
-
|
|
32
|
+
const data = envelope.data;
|
|
33
|
+
return { ...data, status: "partial", error: envelope.error };
|
|
34
|
+
};
|
|
35
|
+
const parseSimulateBody = async (res, url) => {
|
|
36
|
+
const body = await res.json().catch((_) => null);
|
|
37
|
+
const result = parseSimulateResult(body);
|
|
38
|
+
if (result === null) {
|
|
39
|
+
throw new ComposeError(
|
|
40
|
+
"UNKNOWN_ERROR",
|
|
41
|
+
"Unexpected simulate response format",
|
|
42
|
+
{ url }
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
30
46
|
};
|
|
31
47
|
const createComposeClient = (options) => {
|
|
32
48
|
if (!options.baseUrl || !/^https?:\/\//i.test(options.baseUrl)) {
|
|
@@ -108,7 +124,26 @@ const createComposeClient = (options) => {
|
|
|
108
124
|
}
|
|
109
125
|
return await parseBody(res, url);
|
|
110
126
|
};
|
|
111
|
-
|
|
127
|
+
const simulate = async (request) => {
|
|
128
|
+
const url = `${base}/simulate`;
|
|
129
|
+
let res;
|
|
130
|
+
try {
|
|
131
|
+
res = await fetchFn(url, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { ...baseHeaders, "Content-Type": "application/json" },
|
|
134
|
+
body: JSON.stringify(request, bigintReplacer)
|
|
135
|
+
});
|
|
136
|
+
} catch (err) {
|
|
137
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
138
|
+
throw new ComposeError("NETWORK_ERROR", message, { cause: err });
|
|
139
|
+
}
|
|
140
|
+
if (res.status === 200 || res.status === 422) {
|
|
141
|
+
return await parseSimulateBody(res, url);
|
|
142
|
+
}
|
|
143
|
+
const body = await res.text();
|
|
144
|
+
throw errorFromHttpResponse(res.status, body, url);
|
|
145
|
+
};
|
|
146
|
+
return { getManifest, compile, getZapPacks, simulate };
|
|
112
147
|
};
|
|
113
148
|
export {
|
|
114
149
|
createComposeClient
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n} from '@lifi/compose-spec';\n\nimport type { GetZapPacksOptions, ZapPackOverview } from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `x-lifi-composer-sdk` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** Optional LI.FI API key. When set, sent as the `x-lifi-api-key` header on every request. */\n readonly apiKey?: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n}\n\nconst bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n if (\n !isNonNullObject(body) ||\n !('data' in body) ||\n !isNonNullObject(body.data) ||\n !('error' in body) ||\n !isNonNullObject(body.error)\n ) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n const data = body.data as unknown as ComposeCompilePartialData;\n const error = body.error as unknown as { kind: string; message: string };\n return { ...data, status: 'partial' as const, error };\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n 'x-lifi-composer-sdk': SDK_VERSION,\n ...(trimmedApiKey ? { 'x-lifi-api-key': trimmedApiKey } : {}),\n };\n\n const getManifest = async (): Promise<ComposeManifest> => {\n const url = `${base}/compose/manifest`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<ComposeManifest>(res, url);\n };\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> => {\n const url = `${base}/compose`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n };\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n const url = `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<readonly ZapPackOverview[]>(res, url);\n };\n\n return { getManifest, compile, getZapPacks };\n};\n"],"mappings":"AASA,SAAS,cAAc,6BAA6B;AASpD,MAAM,cACJ,OAAyC,oBAAkB;AA+D7D,MAAM,iBAAiB,CAAC,MAAc,UACpC,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAEjC,MAAM,YAAY,OAAU,KAAe,QAA4B;AACrE,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI;AAC/C,MAAI,CAAC,gBAAgB,IAAI,KAAK,EAAE,UAAU,OAAO;AAC/C,UAAM,IAAI,aAAa,iBAAiB,8BAA8B;AAAA,MACpE;AAAA,IACF,CAAC;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AO,SAAS;AAC3B,UAAM,MAAM,GAAG,IAAI,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAC1D,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,YAAY;AAAA,MAC5B,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,aAAa,iBAAiB,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IACjE;AACA,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,YAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,IACnD;AACA,WAAO,MAAM,UAAsC,KAAK,GAAG;AAAA,EAC7D;AAEA,SAAO,EAAE,aAAa,SAAS,YAAY;AAC7C;","names":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\n\nimport type { GetZapPacksOptions, ZapPackOverview } from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `x-lifi-composer-sdk` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** Optional LI.FI API key. When set, sent as the `x-lifi-api-key` header on every request. */\n readonly apiKey?: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\nconst bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as unknown as ComposeCompilePartialData;\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n 'x-lifi-composer-sdk': SDK_VERSION,\n ...(trimmedApiKey ? { 'x-lifi-api-key': trimmedApiKey } : {}),\n };\n\n const getManifest = async (): Promise<ComposeManifest> => {\n const url = `${base}/compose/manifest`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<ComposeManifest>(res, url);\n };\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> => {\n const url = `${base}/compose`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n };\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n const url = `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'GET',\n headers: { ...baseHeaders },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<readonly ZapPackOverview[]>(res, url);\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n let res: Response;\n try {\n res = await fetchFn(url, {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(request, bigintReplacer),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, compile, getZapPacks, simulate };\n};\n"],"mappings":"AAWA,SAAS,cAAc,6BAA6B;AACpD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,cACJ,OAAyC,UAAkB;AAuF7D,MAAM,iBAAiB,CAAC,MAAc,UACpC,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAEjC,MAAM,YAAY,OAAU,KAAe,QAA4B;AACrE,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI;AAC/C,MAAI,CAAC,gBAAgB,IAAI,KAAK,EAAE,UAAU,OAAO;AAC/C,UAAM,IAAI,aAAa,iBAAiB,8BAA8B;AAAA,MACpE;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,KAAK;AACd;AAEA,MAAM,0BAA0B,OAC9B,KACA,QACkC;AAClC,QAAM,OAAO,MAAM,UAAqC,KAAK,GAAG;AAChE,SAAO,EAAE,GAAG,MAAM,QAAQ,UAAmB;AAC/C;AAEA,MAAM,mBAAmB,OACvB,KACA,QACkC;AAClC,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI;AAC/C,QAAM,WAAW,4BAA4B,IAAI;AACjD,MAAI,aAAa,MAAM;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AAIA,QAAM,OAAO,SAAS;AACtB,SAAO,EAAE,GAAG,MAAM,QAAQ,WAAoB,OAAO,SAAS,MAAM;AACtE;AAMA,MAAM,oBAAoB,OACxB,KACA,QAC4B;AAC5B,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI;AAC/C,QAAM,SAAS,oBAAoB,IAAI;AACvC,MAAI,WAAW,MAAM;AACnB,UAA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,KAAK,GAAG;AAAA,EAC7D;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,mBAAmB;AAAA,QAC9D,MAAM,KAAK,UAAU,SAAS,cAAc;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,aAAa,iBAAiB,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IACjE;AAOA,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAC5C,aAAO,MAAM,kBAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,SAAS,aAAa,SAAS;AACvD;","names":["options"]}
|
package/dist/errors.cjs
CHANGED
|
@@ -23,6 +23,7 @@ __export(errors_exports, {
|
|
|
23
23
|
isComposeError: () => isComposeError
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(errors_exports);
|
|
26
|
+
var import_responseSchemas = require("./responseSchemas.js");
|
|
26
27
|
class ComposeError extends Error {
|
|
27
28
|
name = "ComposeError";
|
|
28
29
|
/** Machine-readable error category. */
|
|
@@ -61,11 +62,13 @@ const STATUS_TO_CODE = /* @__PURE__ */ new Map([
|
|
|
61
62
|
[429, "RATE_LIMITED"]
|
|
62
63
|
]);
|
|
63
64
|
const tryParseErrorBody = (body) => {
|
|
65
|
+
let json;
|
|
64
66
|
try {
|
|
65
|
-
|
|
67
|
+
json = JSON.parse(body);
|
|
66
68
|
} catch {
|
|
67
69
|
return null;
|
|
68
70
|
}
|
|
71
|
+
return (0, import_responseSchemas.parseServerErrorBody)(json);
|
|
69
72
|
};
|
|
70
73
|
const errorFromHttpResponse = (status, body, url) => {
|
|
71
74
|
const parsed = tryParseErrorBody(body);
|