UNPKG

@lifi/composer-sdk

Version:

Public Composer SDK for building and submitting flows

547 lines (428 loc) • 32.5 kB
# @lifi/composer-sdk TypeScript SDK for building LI.FI Compose flows and compiling them into submit-ready transactions. Full documentation: [docs.li.fi/composer](https://docs.li.fi/composer/overview). SDK API reference: [SDK API](https://docs.li.fi/composer/composer-api/reference/sdk-api.md). ## Install `@lifi/compose-spec` is a peer dependency. Install it at exactly the same version as the SDK; the two are versioned in lockstep. Node.js 24 or later is required. ```bash npm install @lifi/composer-sdk @lifi/compose-spec ``` `apiKey` is required (create one at [portal.li.fi](https://portal.li.fi)). A missing or blank key throws a `ComposeError` with code `VALIDATION_ERROR` when you call `createComposeSdk()`, including from plain JavaScript that skips the type check. It has been required since 0.3.0. ## Quick start Swap WETH to USDC, then zap the USDC into an Aave lending position, in one transaction. ```ts import { createComposeSdk, resources, guards, materialisers, } from '@lifi/composer-sdk'; const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'; const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'; const A_ETH_USDC = '0x98C23E9d8f34FEFb1B7BD6a91B7FF122F4e16F5c'; // Aave aEthUSDC const OWNER = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; const sdk = createComposeSdk({ baseUrl: 'https://composer.li.quest', apiKey: process.env.LIFI_API_KEY!, }); // A flow on Ethereum mainnet with one token input. const builder = sdk.flow(1, { name: 'swap-and-zap-weth-to-aave', inputs: { amountIn: resources.erc20(WETH, 1), }, }); // Step 1: swap WETH to USDC via LI.FI. const swapOutputs = builder.lifi.swap('swap', { bind: { amountIn: builder.inputs.amountIn }, config: { resourceOut: resources.erc20(USDC, 1), slippage: 0.03, }, }); // Step 2: zap the swapped USDC into Aave. The swap's amountOut handle // feeds the zap's amountIn directly. builder.lifi.zap('zap', { bind: { amountIn: swapOutputs.amountOut }, config: { resourceOut: resources.erc20(A_ETH_USDC, 1), }, guards: [guards.slippage({ port: 'amountOut', bps: 100 })], }); const flow = builder.build(); const request = sdk.request(flow, { signer: OWNER, inputs: { amountIn: materialisers.directDeposit({ amount: '1000000000000000000', }), }, sweepTo: builder.context.sender, // Opt into partial results. Under the default 'strict' policy a simulated // revert throws a ComposeError instead, and the `partial` branch is unreachable. simulationPolicy: 'allow-revert', }); const result = await sdk.client.compile(request); if (result.status === 'success') { // transactionRequest includes gasLimit. console.log(result.transactionRequest); // One entry per output port. Nothing downstream spends the zap's output, so // it is terminal and carries its owner. The swap's output is `consumed` by the zap. const position = result.outputs['zap.amountOut']; if (position?.role === 'terminal') { console.log(position.owner, position.amount.estimate?.value); } } else { // status === 'partial': simulation reverted. The transaction is still // returned, without gasLimit. console.log(result.simulationRevert); } ``` `builder.compile(run)` is shorthand for `sdk.client.compile(sdk.request(builder.build(), run))`. ## Core concepts **Flows and operations**: a flow is an ordered list of on-chain operations. You declare inputs, chain operations, and the backend compiles everything into one transaction. Operations are namespaced, e.g. `builder.lifi.swap` and `builder.core.split`. Each call takes a node id that must be unique in the flow. **Resources**: `resources.erc20(address, chainId)` and `resources.native(chainId)` describe the tokens flowing through the flow. A resource input must be on the flow's chain. **Handles**: operations return typed output handles, e.g. `OutputHandle<'resource'>` or `OutputHandle<'uint256'>`, which you bind to downstream inputs. TypeScript enforces the port types. A resource handle fits a `uint256` slot (resources are amounts), but an `address` handle does not. **Runtime inputs (materialisers)**: a materialiser tells the backend how to fund a flow input when the transaction executes. - `directDeposit({ amount })` pulls exactly `amount`. For a token the compose token registry flags non-exact (stETH, Aave aTokens), a transfer credits a wei or two off, so the deposit instead pulls up to `amount` and asserts it received at least `amount` less 4 wei. - `directDeposit({ amount, allowNonExact: true })` permits a capped ERC-20 deposit of up to `amount`; `directDeposit({ allowNonExact: true })` deposits with no on-chain cap (ERC-20 only). - `balanceOf({ owner })` reads a current balance. - `call({ target, calldata })` measures the balance delta after an arbitrary contract call. **Preconditions**: on-chain state the backend assumes when it simulates, e.g. a balance the signer will hold at execution time. The factories are `erc20Balance`, `nativeBalance`, and `erc20Allowance`. **Guards**: runtime checks on an operation's output, attached through its `guards` field. `guards.slippage({ port, bps })` floors an output at `bps` below its simulated amount. The `port` argument is typed against the ports a guard can protect. For example, `lifi.swap`'s `amountOut` already carries the aggregator's own floor, so it rejects a slippage guard at compile time. **Outputs**: a compile result carries `outputs`, keyed `'<nodeId>.<portName>'`, with one entry per resource output, plus one entry per resource input no node consumes, keyed `'input.<name>'`. An entry is either: - `role: 'terminal'`: delivered to `owner`. `delivery.when` says whether it lands with this transaction (`'now'`) or later (`'future'`). - `role: 'consumed'`: spent by the node named in `consumedBy`. Narrow on `role` before reading those fields. `amount.estimate` and `amount.minimum` are both optional. An absent minimum means no floor is enforced; there is no `0` default. `terminalOutputs(result.outputs)` keeps only the terminal entries. ## API surface **SDK** - `createComposeSdk({ baseUrl, apiKey, fetch? })`: `baseUrl` must be an HTTP(S) URL. A trailing slash is stripped. - `sdk.flow(chainId, { inputs, name? })`: returns a `FlowBuilder`. `name` defaults to a random UUID. - `builder.<namespace>.<operation>(nodeId, { bind, config, guards? })`: adds a node and returns one typed handle per output port. - `builder.untypedOp(nodeId, op, { bind, config, guards? })`: escape hatch for ops without a typed method. Returns `void`; reference its outputs with `raw.ref<T>(path)`. - `builder.build()`: returns the `Flow` document. - `builder.compile(run)`: builds, then compiles. - `sdk.request(flow, run)`: builds a `ComposeCompileRequest` from a flow and a `ComposeRunInput`. - `sdk.route(request)`: compiles a token pair without authoring a flow. See [Routing a token pair](#routing-a-token-pair). - `sdk.simulate(request)`: simulates a raw transaction. See [Simulating a raw transaction](#simulating-a-raw-transaction). - `sdk.getSupportedChains()`: same as `sdk.client.getChains()`. **`sdk.client` (HTTP)** - `compile(request)`: `POST /compose`. Returns a `ComposeCompileResult` with `status: 'success'` or `status: 'partial'`. - `route(request)`: `POST /compose/route`. Returns the same union. - `getManifest()`: `GET /compose/manifest`, the live operation registry. From 0.10.2 the response also carries `routing` (`maxRouteHops`, `swapHops`), the deployment's `POST /compose/route` bounds; an older server omits it. - `getChains()`: `GET /chains`. Returns `readonly ChainSummary[]` (`{ chainId, name }`), ascending by `chainId`. - A chain is listed once the VM contract is confirmed deployed on it. `compile`, `route`, and `simulate` validate against the same condition, so they reject an unlisted chain. A listed chain can still have no routing edge for a given pair. - `name` is a display label that can change, so key on `chainId`. A chain with no configured label reports `Chain <id>`. - `getZapPacks(options?)`: `GET /compose/zap-packs`. Returns the routing edges grouped by protocol as `ZapPackOverview[]`. Filter with `{ protocols: 'aave' }` or an array. See [Discovering routable pairs](#discovering-routable-pairs). - `simulate(request)`: `POST /simulate`. The SDK caches none of these responses. **Helpers** - `resources.erc20(address, chainId)` / `resources.native(chainId)`. - `guards.slippage`, `guards.coreNumericInvariant`. - `materialisers.directDeposit`, `materialisers.balanceOf`, `materialisers.call`. - `preconditions.erc20Balance`, `preconditions.nativeBalance`, `preconditions.erc20Allowance`. - `raw.ref<T>(path)`, `raw.literal(kind, value)`, `raw.guard(kind, config?)`, `raw.materialiser(kind, config?)`: low-level constructors for cases the typed helpers do not cover. - `routeAmount.exact(amount)` / `routeAmount.all(simAmount)`: amount constructors for `route`. - `buildReachability(packs, { maxHops?, allowAsyncRoutes? })`: the pairs `route` can connect (pure, no I/O). - `buildSimulateRequest(...)`: turns a compile result into a `SimulateRequest` (pure, no I/O). - `terminalOutputs(outputs)`. - `isComposeError`, `isComposePreparationError`, `isComposeSdkOutdatedError`, `isComposeServerOutdatedError`: type guards. `ComposeError` is exported as a type only, so narrow with these rather than `instanceof`. ## Routing a token pair `sdk.route(...)` is the shortcut for when the backend can choose the operations. You pass a from/to token pair on one chain, an amount, and a signer. It returns the same `ComposeCompileResult` that `compile()` does. The backend plans the shortest chain of routing-catalog edges for the pair: entering or exiting a protocol position, a wrap or unwrap, a mint or burn. The route can be up to the server's hop ceiling (2 by default). The chain may open with one `lifi.swap` when the input has to be sold first; the swap counts as a hop, so at the default ceiling it precedes at most one catalog edge. That swap only targets a hub token or the underlying of the next deposit, so `route` is not a general swap aggregator. - Node ids are `hop0`, `hop1`, … and the last node is always `zap`, so the delivered output is `result.outputs['zap.amountOut']`. - Every intermediate step settles inside the proxy in the same transaction. Only the last step may pay out to a recipient, or land after settlement (only with `allowAsyncRoutes`). - A route that opens with a swap requires `sweepTo`, because the swap can leave unspent input in the proxy. Omitting it fails with `validation_error`. ```ts import { createComposeSdk, routeAmount } from '@lifi/composer-sdk'; const sdk = createComposeSdk({ baseUrl: 'https://composer.li.quest', apiKey: process.env.LIFI_API_KEY!, }); const result = await sdk.route({ chainId: 1, fromToken: '0x0000000000000000000000000000000000000000', // native ETH toToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH, a `wrap` edge amount: routeAmount.exact(100_000_000_000_000_000n), // 0.1 ETH signer: '0xYourAddress...', slippageBps: 100, }); if (result.status === 'success') { console.log(result.transactionRequest); // to, chainId, data, value, gasLimit } ``` ### Discovering routable pairs The catalog changes as protocols, chains, and token blacklists move, so discover pairs instead of hardcoding them. `getZapPacks` lists single edges; `route` chains them. `buildReachability` computes the chained closure locally, using the planner's rule: ```ts import { buildReachability } from '@lifi/composer-sdk'; const packs = await sdk.client.getZapPacks(); const reach = buildReachability(packs); reach.canRoute(aUsdc, yvUsdc); // aUSDC -> USDC -> yvUSDC: true for (const pair of reach.routableFrom(aUsdc)) { console.log(pair.in.address, '->', pair.out.address, `(${pair.hops} hops)`); } ``` `pair.in` and `pair.out` are the `fromToken` and `toToken` of a `route` call on `pair.in.chainId`. The rule the helper applies, and the server enforces: - Every edge except the last must leave its output in the proxy for the next edge to consume. An edge with `recipient: 'required'` or `availability: 'future'` can only be the last hop. - The last edge must be synchronous, unless you pass `allowAsyncRoutes: true` to both `buildReachability` and `route`. - A route never visits the same token twice and never exceeds `maxHops`. The helper can overstate or miss what `route` accepts in a few ways: - `maxHops` defaults to 2, the deployment default. The server reports its effective value in `no_route_error` `details.maxHops`; pass that value if it differs. - The helper cannot check `inAmountMin` / `inAmountMax` on an intermediate hop without an amount. A reported pair is routable structurally, just as a listed edge is. - The server drops blacklisted tokens as intermediates, so a reported pair can still return `no_route_error`. - Routes that open with a `lifi.swap` depend on what the aggregator can sell, so the helper does not report them. Two edge fields change how you call `route`: - **`recipient: 'required'`**: the protocol mints to a named receiver. Set `sweepTo` when the output should not land with the signer. - **`availability: 'future'`**: the output only exists once the transaction settles, and `route` uses such an edge only with `allowAsyncRoutes: true`. Once opted in: - `sweepTo` names the future output's owner. - No slippage floor applies. - You must track settlement. - A synchronous route still wins whenever one exists, so read each terminal output's `delivery.when`. A future output still reports `amount.estimate` (`basis: 'simulated'`, the in-transaction estimate). The catalog carries no settlement time. The compile result carries it as `delivery.etaSeconds` on a future terminal output; that field is absent when the protocol publishes no estimate, and absence means unknown, not zero. ### Amounts - **`routeAmount.exact(amount)`**: spend exactly `amount` of `fromToken`, in its smallest unit. - **`routeAmount.all(simAmount)`**: spend the signer's whole `fromToken` balance, read on-chain at execution time. - The quote, price impact, and returned approvals are computed against `simAmount`. The transaction moves the real balance, so pass a realistic estimate. - Not supported for a native `fromToken`: a gas coin arrives via `msg.value`, so there is no balance to sweep. Both accept a `bigint` or a decimal string. ### Options The SDK sends only the fields you set. The server applies the defaults. - **`slippageBps`**: default `100` (1%). An end-to-end tolerance on the route's final output, not a per-hop one. - **`maxPriceImpactBps`**: reject the route when its priced impact exceeds this. Default `500`; `0` disables the check. - **`referrer`**: opaque tag forwarded to the underlying quote provider. - **`sweepTo`**: owner of everything the route leaves behind. An address or `{ $ref: 'context.sender' }`; `context.executionAddress` is rejected. Defaults to the signer, except that a route with a swap requires it. - **`checkOnChainAllowances`**: omit approvals that current allowances already cover. Default `false`. - **`simulationPolicy`**: `'strict'` (default) or `'allow-revert'`. See [Simulation policy and partial results](#simulation-policy-and-partial-results). - **`simulateUserProgram`**: also simulate the final user-facing transaction after the structured simulation succeeds. Default `false`. - **`allowAsyncRoutes`**: accept a route whose output arrives after the transaction settles. Default `false`, which guarantees every terminal output is `delivery.when: 'now'`. ### When to author a flow instead Use `sdk.flow(...)` for anything `route` cannot express: - a chain you choose yourself, or one longer than the hop ceiling - one input split across several destinations - guards on intermediate outputs - explicit preconditions or arithmetic - funding from proxy-held balances - combining an asynchronous position with other steps For example, swapping WETH to USDC and depositing the USDC into Aave is a route when the planner can connect it, and a flow when you want to control the swap or add steps. ### Errors `route` maps failures like `compile` does (see [Error handling](#error-handling)). Two outcomes are specific to it: - **`NOT_FOUND`** with `kind: 'no_route_error'`: the planner cannot connect the pair within `details.maxHops` edges. `details.searchTruncated` reports whether the search hit its work bound. - **`VALIDATION_ERROR`**: the pair connects but the request is rejected. Examples: price impact above `maxPriceImpactBps`, or a simulated revert under `'strict'`. ## Simulation policy and partial results The backend simulates every compiled transaction. Under the default `simulationPolicy: 'strict'`, a revert throws a `ComposeError` with code `VALIDATION_ERROR` (HTTP 422). With `'allow-revert'` you get a **partial result** (HTTP 206) instead: ```ts const result = await builder.compile({ signer: OWNER, inputs: { amountIn: materialisers.balanceOf({ owner: OWNER }) }, simulationPolicy: 'allow-revert', }); if (result.status === 'success') { console.log(result.transactionRequest?.gasLimit); // string } else { // status === 'partial': the transaction is returned without gasLimit; // estimate gas yourself. console.log(result.error.kind); // 'simulation_revert' console.log(result.error.message); const revert = result.simulationRevert; console.log(revert.code, revert.rawErrorBytes); for (const c of revert.decodeResult?.errorCandidates ?? []) { console.log(c.decodedErrorSignature, c.decodedParams); } const tx = result.transactionRequest; console.log(tx.to, tx.data, tx.value); } ``` Pass `checkOnChainAllowances: true` to have the server drop entries from `approvals` that current on-chain allowances already cover. ## Simulating a raw transaction `sdk.client.simulate(...)` (and `sdk.simulate(...)`) answers a question compile does not: if I send this exact transaction, how do specific balances change, and how much gas does it burn? It takes a pre-encoded transaction (`to`, hex `data`, optional `value`). It funds the sender as `requirements` describe, runs the transaction in one `eth_call`, and reports the watched balances before and after, their signed deltas, and the inner-call gas. ```ts import { createComposeSdk } from '@lifi/composer-sdk'; const sdk = createComposeSdk({ baseUrl: 'https://composer.li.quest', apiKey: process.env.LIFI_API_KEY!, }); const result = await sdk.client.simulate({ chainId: 1, from: '0x1111111111111111111111111111111111111111', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC data: '0xa9059cbb...', // pre-encoded transfer calldata value: 0n, requirements: [ { type: 'Erc20Balance', wallet: '0x1111111111111111111111111111111111111111', token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', balance: 1_000_000n, }, ], trackedBalances: [ { token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', owner: '0x1111111111111111111111111111111111111111', }, { token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', owner: '0x2222222222222222222222222222222222222222', }, ], }); switch (result.status) { case 'ok': console.log(result.gasUsed, result.deltas); break; case 'revert': // The simulation ran and the transaction reverted. Not an error. console.log(result.revertReason, result.decodeResult); break; case 'error': // Well-formed request, but the simulation could not be set up or run. console.log(result.message); break; } ``` - `requirements` entries are `Erc20Balance`, `NativeBalance`, `Erc20Allowance`, or `Permit2Allowance`. Use the zero address as a `trackedBalances` token to watch the native balance. - `Permit2Allowance` (`owner`, `token`, `spender`, `amount`) lets `spender` pull `token` from `owner` through Uniswap Permit2's `transferFrom`. The simulation also grants the ERC-20 allowance `owner` → Permit2, but not the owner's balance: fund it with an `Erc20Balance`. Only the canonical Permit2 address `0x000000000022D473030F116dDEE9F6B43aC78BA3` is supported; on a chain without it, `simulate` returns `status: 'error'` with a message that names Permit2 and the chain. - Amount fields accept `bigint` or decimal strings. - `SIMULATE_MAX_TRACKED_BALANCES` and `SIMULATE_MAX_REQUIREMENTS` (both `40`) are exported. - A `revert` is returned, not thrown. Only transport failures and HTTP 400/401/403/404/429/5xx throw `ComposeError`. - `gasUsed` is inner-call execution gas only; it excludes the 21000 base cost and calldata gas. - EOA-only behaviour, such as `msg.sender == tx.origin` checks, is not simulated faithfully, because the call runs through injected VM bytecode rather than a real EOA. To simulate a transaction you just compiled, `buildSimulateRequest(...)` fills in the transaction fields from the compile result. A compile result carries neither `chainId` nor `signer`, so pass both. Nothing in a flow says which balances to watch, so pass `trackedBalances` and any `requirements` too. It throws when the result has no single `transactionRequest` (a flow funded by an external action); submit that result's `actions` instead. ```ts import { buildSimulateRequest } from '@lifi/composer-sdk'; const compiled = await builder.compile({ inputs: { ... }, signer: '0x1111...' }); const req = buildSimulateRequest({ result: compiled, chainId: 1, signer: '0x1111111111111111111111111111111111111111', trackedBalances: [ { token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', owner: '0x1111111111111111111111111111111111111111', }, ], }); const sim = await sdk.client.simulate(req); ``` Runnable versions: [`src/examples/simulateRawTransaction.ts`](src/examples/simulateRawTransaction.ts) and [`src/examples/simulateCompiledSwap.ts`](src/examples/simulateCompiledSwap.ts). ## Deferred settlement (continuations) `builder.continuation.settle(id, { bind: { input }, config })` escrows a resource and commits to an outcome that an off-chain executor settles later by running the node's `continuationFlow` (the *leg*) from the escrow. The leg is an ordinary flow built with `sdk.flow(...)`, with one input, the funding resource, on the escrow chain: ```ts // The leg supplies the escrowed WETH to Aave; the aBasWETH it mints stays in // the leg's proxy, and the compiler's epilogue forwards it at commit. const leg = sdk.flow(8453, { inputs: { funding: resources.erc20(WETH, 8453) } }); leg.lifi.zap('supply', { bind: { amountIn: leg.inputs.funding }, config: { resourceOut: resources.erc20(A_BAS_WETH, 8453) }, guards: [guards.slippage({ port: 'amountOut', bps: 50 })], }); builder.continuation.settle('settle', { bind: { input: swap.amountOut }, config: { outcomes: [{ token: A_BAS_WETH, destination: owner, chainId: 8453 }], continuationFlow: leg.build(), validity: { expiresAtMs: Date.now() + 60 * 60 * 1000 }, }, }); ``` Three rules decide whether a settlement can ever fill, and the compiler rejects a flow that breaks them: - The leg leaves each outcome token in its own proxy: a leg that only delivers its funding has no nodes, and a node that needs a receiver binds `leg.context.executionAddress`. Never name `destination` or any payee. At commit the compiler writes the leg's epilogue, which forwards the outcome to the settlement contract (it verifies the committed floor and pays `destination`) and the residual to `refund`. A leg that carries its own `epilogue` is rejected. - The leg must not reference `context.sender`: inside the leg it is the solver's executor, not the user. - The leg declares exactly one input, the funding resource. The compile response carries the escrow terms in `settlements[id].escrow` and any `fundEscrow` action in `actions`. The leg contract, funding modes (inline, external, bridge-delivered), expiry and refund, and monitoring are in [`docs/continuations.md`](docs/continuations.md). ## Error handling HTTP and transport failures are thrown as a `ComposeError`. Builder mistakes (a duplicate node id, a missing output port) throw a plain `Error` at the call site. Narrow with `isComposeError`: ```ts import { isComposeError } from '@lifi/composer-sdk'; try { const result = await sdk.client.compile(request); } catch (err) { if (isComposeError(err)) { console.error(err.code, err.status, err.kind, err.message); console.error(err.path, err.port, err.fix); // when the server names a location or a fix } } ``` | `code` | HTTP status | Typical cause | | ------------------ | ----------- | --------------------------------------------------------------- | | `VALIDATION_ERROR` | 400, 422 | Malformed or rejected flow or request, simulated revert, guard | | `UNAUTHENTICATED` | 401 | Missing or invalid API key | | `FORBIDDEN` | 403 | The server refuses the request | | `NOT_FOUND` | 404 | `no_route_error` | | `RATE_LIMITED` | 429 | Too many requests | | `SERVER_ERROR` | 5xx | Backend failure or a dependency temporarily unavailable | | `NETWORK_ERROR` | none | The request never got a response | | `UNKNOWN_ERROR` | other | Unexpected status | `kind` is the backend's finer-grained classification, e.g. `simulation_revert`, `guard_error`, or `price_impact_exceeded`. When `kind` is `simulation_revert`, `err.details` has the same shape as `result.simulationRevert`. A `preparation_error` (HTTP 422) means some prepared ops (ops that fetch external quotes at compile time, such as `lifi.swap`) failed while others succeeded, e.g. a mixed basket with one unroutable leg. A `failedOps` entry whose `kind` is `resolution_error` hit an upstream outage rather than a dead route, so keep that node when resubmitting. When every failed op hit an outage, the error is a 503 `resolution_error` instead: retry the same flow. Narrow with `isComposePreparationError`, drop the other failed node ids from the flow, and resubmit: ```ts import { isComposePreparationError } from '@lifi/composer-sdk'; try { const result = await sdk.client.compile(request); } catch (err) { if (isComposePreparationError(err)) { for (const op of err.failedOps) { console.error(op.callId, op.op, op.kind, op.message); } // Only the prepared ops that succeeded, not the rest of the flow. To retry, // remove the failedOps callIds from the original flow, keeping any whose // kind is 'resolution_error'. console.error('prepared ok:', err.succeededOps); } } ``` **Version mismatch.** `compile` and `route` fail with `kind: 'sdk_outdated'` when this SDK is older than the oldest version the backend serves. They fail with `kind: 'server_outdated'` when the SDK is newer than the backend in any version component, which happens between an npm release and the backend rollout. Both come back as `VALIDATION_ERROR`. `isComposeSdkOutdatedError(err)` exposes `err.sdkOutdated.minimumSdkVersion`; `isComposeServerOutdatedError(err)` exposes `err.serverOutdated.serverVersion`. On `server_outdated`, pin both packages to the server's version or wait for the rollout. ## Examples Each file in `src/examples/` is a complete flow: - **lifiSwap**: single token swap (WETH to USDC) - **lifiZap**: swap into a DeFi position - **lifiZapAsync**: zap into a position whose output settles after the initiating transaction - **swapAndZap**: swap, then deposit - **splitAndZap**: split a resource and zap each part into a different vault - **splitWithArithmetic**: split, then check with add/subtract/assertEqual - **dustSweep**: split, use part of the tokens, sweep the rest back to the sender - **depositFromProxy**: spend tokens already on the proxy via `balanceOf`, with a precondition - **approveAndDeposit**: approve a vault, deposit, and turn the shares into a resource via `asResource` - **consolidateToUsdc** / **consolidateToEth**: consolidate several tokens into one - **swapToRecipient**: swap and send to another address - **swapWithBalanceCheck**: swap with a balance precondition - **swapWithOutputValidation**: swap with computed bounds via bpsDown/bpsUp/assertInRange - **invariantChecks**: swap, then assert the output with `invariant.gte` and an allowance with `invariant.allowanceAtLeast` - **rawCallWithArithmetic**: query a contract with pre-encoded calldata, then scale the result - **readContractState**: compare `peek` (compile time), `staticCall` (execution time), and `balanceOf` (resource) - **emitCustomEvent**: emit a custom event with `core.emitEvent2`; `bytes32` ports accept any static 32-byte handle - **swapWithAllowRevert**: handle both branches of `ComposeCompileResult` under `'allow-revert'` - **transferTokens**: transfer ERC-20 tokens from the proxy to any recipient - **callContract**: call an arbitrary contract (ERC-4626 redeem, reward claim) without a typed op - **flySwap**: on Base, exit a Pendle PT via `lifi.zap`, then swap all proceeds to WETH with `fly.swap` - **aaveBorrow**: supply USDC to Aave v3, borrow USDC against it, and guard the health factor with `aave.getHealthFactor` - **aaveHealthFactorExplode**: read the Aave v3 health factor and assert it stays above 1.0 - **aaveRepay**: repay Aave v3 variable debt and sweep the unspent residual to the sender - **aaveRepayWithATokens**: repay Aave v3 debt by burning aTokens held by the proxy - **aaveClaimRewards**: claim Aave rewards and forward them to a recipient - **aaveSetEMode**: switch the proxy's Aave v3 eMode category - **morphoBlueBorrow**: supply WETH collateral to a Morpho Blue market and borrow USDC - **morphoBlueRepay**: open, repay and close a Morpho Blue position with `morphoBlue.repay` in `max` mode - **uniswapV2AddLiquidity**: split USDC, swap half to WETH, and deposit both into the Uniswap V2 USDC/WETH pair with a `band` guard on the pool price - **uniswapV3Mint**: mint a full-range Uniswap V3 USDC/WETH position with `band` and `slippage` guards - **untypedOpWithTypedRef**: add a node with `untypedOp`, then use its output in typed ops via `raw.ref<T>()` - **routeTokenPair**: `sdk.route(...)` with both the `exact` and `all` amount variants - **supportedChains**: cache `sdk.getSupportedChains()`, then fail an unsupported chain locally with a message naming the alternatives - **simulateRawTransaction** / **simulateCompiledSwap**: raw and compiled simulation - **continuationSettle**: swap USDC to WETH on Base, then escrow the WETH for a deferred settlement whose leg supplies it to Aave and delivers the aBasWETH position - **continuationBridgeSettle**: bridge USDC from Arbitrum into a settle escrow on Base; when the delivery lands, the leg supplies it to Aave and delivers the aBasUSDC position - **continuationExactInvoice**: escrow USDC on Base for an exact leg (`exact: true`) that pays a Request Network invoice through `core.call` and returns the surplus; a second builder funds the same leg from a WETH-to-USDC swap, and a third from Arbitrum ETH swapped to USDC and delivered by an exact-output `lifiIntents.order` (`exactAmountOut`) into the escrow at exactly the invoice total, with no outcome (`outcomes: []`) ## Staging channel Some operations run on the backend but are held back from the default SDK, for example because their contract changes are not live in production yet. These **staged** operations are published on the `staging` npm dist-tag: ```bash npm install @lifi/composer-sdk@staging @lifi/compose-spec@staging ``` The `staging` build types the staged operations (e.g. `lifi.flashloanRepay`). The default install never exposes them. A staged operation only runs on a backend that has it enabled, so point `baseUrl` at one: ```ts const sdk = createComposeSdk({ baseUrl: '<staging-backend-url>', apiKey: process.env.LIFI_API_KEY!, }); ``` Against a backend without the operation, the call fails at runtime; having the types does not mean the backend supports the operation. The channel is permanent, and its contents rotate as ops graduate to `latest`. The backend URL is a runtime argument, so one staging build can target whichever backend has the ops enabled. ## License Apache-2.0