> ## Documentation Index
> Fetch the complete documentation index at: https://docs.li.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> Public surface of @lifi/composer-sdk 0.14.0: the SDK factory, the FlowBuilder, compile results, helper namespaces, handles and errors.

`@lifi/composer-sdk` builds a **Flow** in TypeScript, sends it to the Composer API and returns typed results. This page lists its public surface for version 0.14.0. The authoritative types are the package's [type declarations](https://app.unpkg.com/@lifi/composer-sdk@0.14.0/files/dist/index.d.ts) and the wire types in [`@lifi/compose-spec`](https://app.unpkg.com/@lifi/compose-spec@0.14.0/files/dist/index.d.ts).

## Install

```bash theme={"system"}
npm install @lifi/composer-sdk @lifi/compose-spec
```

Install both packages on the same version. For the supported version, runtime and API key, see [Before you start](https://docs.li.fi/composer/composer-api/overview.md#before-you-start).

> [!NOTE]
>
> **There is no `sdk.compile()`.** Compile lives on the builder: `builder.compile(run)`. `sdk.request(flow, run)` builds the same request without sending it.

## `createComposeSdk(options)`

```ts theme={"system"}
import { createComposeSdk } from '@lifi/composer-sdk';

const sdk = createComposeSdk({
  baseUrl: 'https://composer.li.quest',
  apiKey: process.env.LIFI_API_KEY!,
});
```

Later snippets on this page use this `sdk` and add their own imports.

### `ComposeSdkOptions`

| Field | Type | Notes |
| - | - | - |
| `baseUrl` | `string` | Required, no default. Use `https://composer.li.quest`. Must start with `http://` or `https://`. |
| `apiKey` | `string` | Required. Sent as the `x-lifi-api-key` header on every request. Keep it server-side. |
| `fetch` | `typeof globalThis.fetch` | Optional. Defaults to the global `fetch`. |

`createComposeSdk` throws a `ComposeError` with code `VALIDATION_ERROR` when `baseUrl` is not an HTTP(S) URL or `apiKey` is empty. Every request also sends the SDK version in `x-lifi-composer-sdk` for the [version check](#errors).

### `ComposeSdk`

| Member | Signature | Notes |
| - | - | - |
| `flow` | `<T>(chainId: number, options: FlowOptions<T>) => FlowBuilder<T>` | Creates a flow builder. Described below. |
| `request` | `<T>(flow: TypedFlow<T>, run: ComposeRunInput<T>) => ComposeCompileRequest` | Builds a compile request without sending it. |
| `route` | `(request: ComposeRouteRequest) => Promise<ComposeCompileResult>` | Compiles a token pair without authoring a Flow. |
| `simulate` | `(request: SimulateRequest) => Promise<SimulateResult>` | Simulates a raw transaction. |
| `getSupportedChains` | `() => Promise<readonly ChainSummary[]>` | `GET /chains`: `{ chainId, name }[]`, ascending by `chainId`. Key on `chainId`; `name` is a display label. |
| `client` | `ComposeClient` | The HTTP client the members above use. |

## `sdk.flow(chainId, options)`

```ts theme={"system"}
const builder = sdk.flow(1, {
  name: 'my-flow', // optional; defaults to a random UUID
  inputs: {
    amountIn: resources.erc20('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 1),
    deadline: 'uint256',
  },
});
```

### `FlowOptions<T>`

| Field | Type | Notes |
| - | - | - |
| `name` | `string?` | Becomes the Flow `id`. Defaults to a random UUID. |
| `inputs` | `T extends InputSchema` | Input name → `Resource` (a resource input) or `SolType` (a handle input). |

`sdk.flow` throws when a resource input's `chainId` differs from the flow's `chainId`. The type `T` carries through to typed handles at `builder.inputs.<name>` and to the `run.inputs` keys `compile` accepts.

## `FlowBuilder<T>`

A `FlowBuilder` combines the core members below, one typed method per op, and `compile`.

| Member | Signature | Notes |
| - | - | - |
| `inputs` | `InputHandles<T>` | One handle per declared input: `ResourceInputHandle` for a resource input, `InputHandle<SolType>` for a handle input. |
| `context` | `{ sender, executionAddress }` | Typed refs to `context.sender` (the signer) and `context.executionAddress` (the execution proxy). |
| `untypedOp` | `(id, op, { bind, config, guards? }) => void` | Appends a node for an op that has no typed method. Reference its outputs with `raw.ref`. Throws on a duplicate `id`. |
| `build` | `() => TypedFlow<T>` | Serialises the builder to a Flow: `version`, `id`, `chainId`, `inputs`, `nodes`. |
| `compile` | `(run: ComposeRunInput<T>) => Promise<ComposeCompileResult>` | Calls `build()`, then `sdk.request()`, then `POST /compose`. Described below. |

`build()` never emits `epilogue` or `lineage`. Use `run.sweepTo` for the remainder; for named forwards, add `epilogue` to the built Flow and send it with `sdk.client.compile()`. See [Flow Schema: Epilogue](https://docs.li.fi/composer/composer-api/reference/flow-wire-format.md#epilogue).

### Op methods

Each op method takes `(id, { bind, config, guards? })` and returns the node's output handles, keyed by port name: `const { amountOut } = builder.lifi.swap('swap', …)`. An op with no config takes no `config` key. Every op in the [op catalog](https://docs.li.fi/composer/composer-api/ops.md) is a method named after its id: `lifi.swap` is `builder.lifi.swap`, `core.splitAt` is `builder.core.splitAt`. Config types are exported by name, for example `LifiSwapConfig` and `ContinuationSettleConfig`.

## `builder.compile(run)`

`compile` sends the Flow to `POST /compose` and returns a `ComposeCompileResult`.

```ts theme={"system"}
import { materialisers, resources } from '@lifi/composer-sdk';

const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';

const builder = sdk.flow(1, {
  name: 'weth-to-usdc', // optional; defaults to a random UUID
  inputs: {
    amountIn: resources.erc20(WETH, 1),
  },
});

builder.lifi.swap('swap', {
  bind: { amountIn: builder.inputs.amountIn },
  config: { resourceOut: resources.erc20(USDC, 1), slippage: 0.005 },
});

const result = await builder.compile({
  signer: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  inputs: {
    amountIn: materialisers.directDeposit({ amount: '1000000000000000000' }),
  },
  sweepTo: builder.context.sender,
});

if (result.status === 'partial') {
  // Only with simulationPolicy: 'allow-revert'. Do not submit.
  console.error(result.error.kind, result.error.message, result.simulationRevert);
} else {
  for (const action of result.actions ?? []) {
    if (action.kind === 'transaction') {
      console.log(action.purpose, action.transactionRequest.chainId, action.transactionRequest.to);
    }
  }
  const out = result.outputs['swap.amountOut'];
  console.log(out?.amount.minimum?.value); // bigint
}
```

`compile` throws a `ComposeError` on a network failure or any error response. See [Errors](#errors).

### `ComposeRunInput<T>`

| Field | Type | Notes |
| - | - | - |
| `signer` | `` `0x${string}` `` | Required. The wallet that signs the execution transaction. |
| `inputs` | `{ [K in keyof T]: InputSpecOf<T[K]> }` | Required. A resource input takes a materialiser (`materialisers.directDeposit(…)`) or an amount (`bigint` or decimal string). An integer handle input takes a `bigint` or decimal string, an `address` input an address, a `bytes*` input a hex string. |
| `preconditions` | `readonly Precondition[]?` | On-chain state the simulation assumes. Build them with [`preconditions`](#helper-namespaces). |
| `assumptions` | `{ [K in keyof T]?: bigint }?` | Amounts the compiler plans with when a materialiser resolves an input only at execution time. |
| `referrer` | `string?` | Your referrer tag. |
| `maxPriceImpactBps` | `number?` | 0–10000. Reject the compile above this aggregate USD price impact. |
| `sweepTo` | `ForwardTo?` | Receives every terminal resource the proxy holds after the last node. An address or `builder.context.sender`. |
| `simulationPolicy` | `'strict' \| 'allow-revert'?` | Default `'strict'`. `'allow-revert'` returns a `partial` result instead of throwing on a revert. |
| `simulateUserProgram` | `boolean?` | Default `false`. Also simulate the final user transaction, including the proxy deployment wrap. |
| `checkOnChainAllowances` | `boolean?` | Default `false`. Omit approvals already satisfied on chain. |

## `ComposeCompileResult`

The result is a union on `status`. Check it before you read shape-specific fields.

* `status: 'success'`: the compile and its simulation succeeded.
* `status: 'partial'`: returned only under `simulationPolicy: 'allow-revert'` when the simulation reverted. It carries `error: { kind, message }` and `simulationRevert: { code, rawErrorBytes, decodeResult? }`. Never submit it, and never fund an escrow it registered.

| Field | On `success` | On `partial` | Notes |
| - | - | - | - |
| `outputs` | yes | yes | `Record<key, Output>` keyed `<nodeId>.<port>` or `input.<name>`. Amounts are `bigint`. See [outputs](https://docs.li.fi/composer/composer-api/reference/flow-wire-format.md#outputs). |
| `actions` | optional | optional | Everything to submit, in order. See [the compile response](https://docs.li.fi/composer/composer-api/concepts/execution-model.md#the-compile-response). |
| `transactionRequest` | optional | yes | `{ to, chainId, data, value, gasLimit? }`. Absent on `success` when the compiled program is empty. |
| `userProxy` | yes | yes | The signer's execution proxy. |
| `approvals` | optional | optional | `{ token, spender, amount, transactionRequest }[]`; the same approvals are in `actions`. |
| `settlements` | optional | optional | Per settle node: `{ escrow?, binding? }`. See [settlements](https://docs.li.fi/composer/composer-api/reference/flow-wire-format.md#settlements). |
| `fill` | optional | — | `{ spends, validUntilMs? }`. Always present on a `success` from `builder.compile()`. |
| `epilogue` | optional | — | `{ forwards: { resource, to, amount: bigint }[], remainder? }`. |
| `priceImpact` | optional | — | `{ inputValueUsd, outputValueUsd, impactBps, unpricedInputs, unpricedOutputs }`. |
| `verificationByNode` | optional | — | Per settle node: `{ validationProgramHash, paramsHash, assertedPredicate }`. |
| `warnings` | optional | optional | `{ kind, message, path?, port?, fix? }[]`. Tolerate unknown kinds. |
| `userProgramSimulation` | optional | — | `{ status: 'ok', returnData }` when `simulateUserProgram` succeeded. Success only. |

`terminalOutputs(result.outputs)` keeps only the entries nothing in the flow spends: what the caller actually receives. The wire-only fields `producedHandles` and `producedResources` are not part of this type; see [Flow Schema: 200 response](https://docs.li.fi/composer/composer-api/reference/flow-wire-format.md#200-response).

## `sdk.request(flow, run)`

`sdk.request` returns the exact `{ flow, run }` body `compile` would send. Use it to queue a request, send it through your own backend, or inspect it in tests.

`bigint` values have no JSON form, so a plain `JSON.stringify(request)` throws a `TypeError`. Serialise them as decimal strings, as the SDK does. Continuing with the `builder` above:

```ts theme={"system"}
const request = sdk.request(builder.build(), {
  signer: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  inputs: { amountIn: materialisers.directDeposit({ amount: 10n ** 18n }) }, // a bigint amount
  sweepTo: builder.context.sender,
});

const response = await fetch('https://composer.li.quest/compose', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    'x-lifi-api-key': process.env.LIFI_API_KEY!,
    'x-lifi-composer-sdk': '0.14.0', // the SDK version your flow targets
  },
  body: JSON.stringify(request, (_key, value: unknown) =>
    typeof value === 'bigint' ? value.toString() : value,
  ),
});

const body = (await response.json()) as {
  success: boolean;
  data?: Record<string, unknown>;
  error?: { kind?: string; type?: string; message: string };
};

if (response.status === 200) {
  console.log(body.data?.transactionRequest); // amounts are decimal strings here
} else if (response.status === 206) {
  console.warn('simulation reverted', body.error, body.data?.simulationRevert);
} else {
  // `kind` on compose errors, `type` on auth and rate-limit errors
  throw new Error(`${response.status} ${body.error?.kind ?? body.error?.type}: ${body.error?.message}`);
}
```

A raw response keeps amounts as decimal strings. Send the request with `sdk.client.compile(request)` instead to get the typed result with `bigint` amounts.

## `sdk.route(request)`

`sdk.route` compiles a token pair on one chain without a Flow. The server plans a short chain of catalog edges (a position entry or exit, a wrap or unwrap), optionally opened by a `lifi.swap`, and compiles it through the same pipeline as `compile`. Its node ids are `hop0`, `hop1`, …, and the last node is `zap`.

```ts theme={"system"}
import { routeAmount } from '@lifi/composer-sdk';

const routed = await sdk.route({
  chainId: 1,
  fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
  toToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
  amount: routeAmount.exact(1_000_000_000n), // 1,000 USDC
  signer: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  slippageBps: 50,
  sweepTo: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', // required when the route includes an aggregator swap
});
console.log(routed.status, routed.outputs['zap.amountOut']?.amount.minimum?.value);
```

### `ComposeRouteRequest`

| Field | Type | Notes |
| - | - | - |
| `chainId` | `number` | Required. |
| `fromToken`, `toToken` | `string` | Required. Token addresses on `chainId`. |
| `amount` | `RouteAmount` | Required. `routeAmount.exact(amount)` moves that amount; `routeAmount.all(simAmount)` moves the whole balance and quotes with `simAmount`. |
| `signer` | `string` | Required. Funds the route and, by default, owns its output. |
| `slippageBps` | `number?` | 0–10000, default 100. An end-to-end floor on the final output. |
| `maxPriceImpactBps` | `number?` | 0–10000, default 500. `0` disables the check. |
| `sweepTo` | `ForwardTo?` | Receives what the route leaves behind. Required when the route includes an aggregator swap; `context.executionAddress` is rejected. |
| `allowAsyncRoutes` | `boolean?` | Default `false`. `true` also accepts routes whose output lands after the transaction (`delivery.when: 'future'`). |
| `referrer`, `simulationPolicy`, `simulateUserProgram`, `checkOnChainAllowances` | | As on `ComposeRunInput`. |

A pair the planner cannot connect throws a `ComposeError` with `kind: 'no_route_error'` (HTTP 404). To check reachability without a request, fetch the edges with `sdk.client.getZapPacks()` and pass them to `buildReachability(packs, { maxHops?, allowAsyncRoutes? })`, which returns `{ canRoute(from, to), routableFrom(from), pairs() }`.

## `sdk.simulate(request)`

`sdk.simulate` runs a raw transaction against `POST /simulate` and reports balance changes. `buildSimulateRequest({ result, chainId, signer, trackedBalances, requirements?, block?, value? })` builds the request from a compile result; it throws when the result has no `transactionRequest`.

The result is a union on `status`: `'ok'` (with `balancesBefore`, `balancesAfter`, `deltas`, `gasUsed`), `'revert'` (with `revertReason?`, `code?`, `rawErrorBytes?`, `decodeResult?`) or `'error'` (the simulation could not run). A revert is returned, not thrown.

## `sdk.client`

The low-level client behind every member above. Reach for it to send a request you built with `sdk.request()`, or for discovery.

| Method | Endpoint | Notes |
| - | - | - |
| `compile(request)` | `POST /compose` | What `builder.compile()` calls. Returns `ComposeCompileResult`. |
| `route(request)` | `POST /compose/route` | What `sdk.route()` calls. |
| `simulate(request)` | `POST /simulate` | What `sdk.simulate()` calls. |
| `getManifest()` | `GET /compose/manifest` | The live catalog of ops, guards, materialisers, preconditions and routing, plus the Flow JSON Schema. The [Ops](https://docs.li.fi/composer/composer-api/ops.md), [Materialisers](https://docs.li.fi/composer/composer-api/materialisers.md) and [Guards](https://docs.li.fi/composer/composer-api/guards.md) pages render it. |
| `getChains()` | `GET /chains` | What `sdk.getSupportedChains()` calls. |
| `getZapPacks(options?)` | `GET /compose/zap-packs` | Routing edges grouped by protocol: `{ protocol, edges: { type, in, out, … }[] }[]`. `options.protocols` filters by one name or a list. |

Discover which tokens route into Aave positions:

```ts theme={"system"}
const packs = await sdk.client.getZapPacks({ protocols: 'aave' });
for (const pack of packs) {
  for (const edge of pack.edges) {
    console.log(pack.protocol, edge.type, edge.in.address, '->', edge.out.address);
  }
}
```

The SDK caches nothing; cache discovery results as your refresh needs dictate. See the [routing edges catalog](https://docs.li.fi/composer/protocols-and-chains.md) for the rendered live view.

## Helper namespaces

| Namespace | Members | Notes |
| - | - | - |
| `resources` | `erc20(token, chainId)`, `native(chainId)` | Declare resource inputs and op `resourceOut` values. |
| `materialisers` | `directDeposit(config)`, `balanceOf({ owner })`, `call({ target, calldata })` | Resource input values for `run.inputs`. `directDeposit` takes `{ amount, allowNonExact? }`, or `{ allowNonExact: true, simAmount?, minAmount? }` to pull a balance known only at execution time. See [Materialisers](https://docs.li.fi/composer/composer-api/materialisers.md). |
| `guards` | `slippage({ port, bps })`, `band({ port, bps })`, `coreNumericInvariant({ port, op, threshold })` | Entries for an op's `guards` array. `port` is typed to the op's output ports. See [Guards](https://docs.li.fi/composer/composer-api/guards.md). |
| `preconditions` | `erc20Balance({ wallet, token, balance })`, `nativeBalance({ wallet, balance })`, `erc20Allowance({ owner, spender, token, allowance })` | Entries for `run.preconditions`. |
| `routeAmount` | `exact(amount)`, `all(simAmount)` | The `amount` of a `ComposeRouteRequest`. |
| `raw` | `ref<T>(path)`, `literal(kind, value)`, `guard(kind, config?)`, `materialiser(kind, config?)` | Escape hatches for refs, literal binds, and guard or materialiser kinds without a typed helper. `ref` and `materialiser` are also top-level exports. |

## Handles

An op method binds handles, not ref strings. A **handle** points at a flow input or a node's output port, and the SDK turns it into a `{ "$ref": … }` when it builds the Flow.

* `InputHandle<T>`: a flow input, from `builder.inputs.<name>`.
* `ResourceInputHandle`: an `InputHandle<'resource'>` that also carries its `resource`.
* `OutputHandle<T>`: a node's output port, from an op method's return value.
* `TypedRef<T>`: a ref built with `raw.ref<T>(path)` or read from `builder.context`.

A typed bind slot accepts a handle or `TypedRef` of the matching kind; a `uint256` slot also accepts a resource handle. `isInputHandle` and `isOutputHandle` narrow an `AnyHandle`.

An **output family** returns several handles from one port name. `core.partition` returns `parts`, one handle per `bps` entry; with a literal array the handles are a tuple, so indexing past the last one is a type error:

```ts theme={"system"}
import { raw, resources, terminalOutputs } from '@lifi/composer-sdk';

const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';

const builder = sdk.flow(1, { inputs: { usdc: resources.erc20(USDC, 1) } });

// A literal `bps` array gives a tuple of three handles: `parts[3]` is a type error.
const { parts } = builder.core.partition('split', {
  bind: { source: builder.inputs.usdc },
  config: { bps: [5000, 3000, 2000] },
});

builder.core.transfer('payA', {
  bind: { amount: parts[0], recipient: raw.literal('address', '0x1111111111111111111111111111111111111111') },
  config: {},
});
builder.core.transfer('payB', {
  bind: { amount: raw.ref<'resource'>('split.parts.1'), recipient: builder.context.sender },
  config: {},
});

const result = await builder.compile({
  signer: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  inputs: { usdc: 1_000_000_000n },
  sweepTo: builder.context.sender,
});
for (const [key, out] of Object.entries(terminalOutputs(result.outputs))) {
  console.log(key, out.owner, out.delivery.when, out.amount.minimum?.value);
}
```

`raw.ref('split.parts.1')` addresses the same port as `parts[1]`. Here the unspent third part is swept to the signer by `sweepTo`.

## Continuations

`builder.continuation.settle` adds a **settle node**: the compile registers an escrow, and LI.FI's settlement service later runs the node's **destination flow** (`continuationFlow`) from it. The escrow lives on a bridge's or order's destination chain when one funds it, and on the flow's own chain otherwise. Build the destination flow as an ordinary flow with exactly one resource input and pass `destFlow.build()`. Here a bridge from Arbitrum funds the escrow on Base:

```ts theme={"system"}
import { guards, resources } from '@lifi/composer-sdk';

const ARBITRUM = 42161;
const BASE = 8453;
const ARB_USDC = '0xaf88d065e77c8cC2239327C5EDb3A432268e5831';
const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const A_BAS_USDC = '0x4e65fE4DbA92790696d040ac24Aa414708F5c0AB';
const USER = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';

// The destination flow: an ordinary flow with exactly one resource input.
const destFlow = sdk.flow(BASE, {
  name: 'deposit-on-base',
  inputs: { funding: resources.erc20(BASE_USDC, BASE) },
});
destFlow.lifi.zap('deposit', {
  bind: { amountIn: destFlow.inputs.funding },
  config: { resourceOut: resources.erc20(A_BAS_USDC, BASE) },
  guards: [guards.slippage({ port: 'amountOut', bps: 50 })],
});

const source = sdk.flow(ARBITRUM, {
  name: 'bridge-and-deposit',
  inputs: { amountIn: resources.erc20(ARB_USDC, ARBITRUM) },
});
const bridge = source.lifi.bridge('bridge', {
  bind: { amountIn: source.inputs.amountIn },
  config: { resourceOut: resources.erc20(BASE_USDC, BASE) }, // no destination: delivers into the escrow
});
source.continuation.settle('settle', {
  bind: { input: bridge.amountOut },
  config: {
    outcomes: [{ token: A_BAS_USDC, destination: USER, chainId: BASE }],
    validity: { expiresAtMs: Date.now() + 60 * 60 * 1000 },
    refund: USER,
    continuationFlow: destFlow.build(),
  },
});
```

> [!WARNING]
>
> Every successful compile of a flow with a settle node registers a new escrow. Compile it only when you intend to fund it, and fund only the escrow named in that compile's `settlements[<nodeId>].escrow`.

The settle node returns one handle, `output`, delivered in the future. Its compile result adds `settlements`, a `fundEscrow` action for external funding, and `fill`. Exported types: `ContinuationSettleConfig`, `ContinuationIntent`, `ContinuationOutcome`, `SettlementWire`, `SettlementEscrowWire`, `SettlementBindingWire`, `ComposeAction` and `ComposeFill`. Concepts and rules: [Cross-chain flows](https://docs.li.fi/composer/composer-api/concepts/cross-chain-flows.md), [Build a cross-chain flow](https://docs.li.fi/composer/composer-api/guides/build-a-cross-chain-flow.md) and [`continuation.settle`](https://docs.li.fi/composer/composer-api/ops/continuation-settle).

## Errors

Every SDK failure is a `ComposeError`. The package exports `ComposeError` as a type only, so `instanceof ComposeError` does not compile: narrow with the guards below.

| Field | Type | Notes |
| - | - | - |
| `code` | `ComposeErrorCode` | Transport-level class, from the HTTP status. |
| `status` | `number?` | HTTP status, when there was a response. |
| `url` | `string?` | The request URL. |
| `kind` | `ComposeErrorKind?` | The API's error kind, for example `validation_error`. See [Errors](https://docs.li.fi/composer/composer-api/reference/error-codes.md). |
| `message` | `string` | Human-readable. Do not match on it. |
| `path`, `port`, `fix` | `string?` | Where the error is in the Flow, and a suggested remedy. |
| `shortfall` | `Shortfall?` | `{ required, available }` when an amount cannot cover a step. |
| `details` | `SimulationRevert?` | Revert data for `simulation_revert`. |
| `delivery` | `DeliveryErrorDetails?` | Set on `delivery_error`. |
| `failedOps`, `succeededOps` | arrays? | Set on `preparation_error`. |
| `sdkOutdated`, `serverOutdated` | objects? | Version details on `sdk_outdated` and `server_outdated`. |

`code` maps from the HTTP status: 400 and 422 → `VALIDATION_ERROR`, 401 → `UNAUTHENTICATED`, 403 → `FORBIDDEN`, 404 → `NOT_FOUND`, 429 → `RATE_LIMITED`, 5xx → `SERVER_ERROR`, a transport failure → `NETWORK_ERROR`, anything else → `UNKNOWN_ERROR`.

| Guard | Narrows to |
| - | - |
| `isComposeError(e)` | any `ComposeError` |
| `isComposePreparationError(e)` | `failedOps` and `succeededOps` present |
| `isComposeDeliveryError(e)` | `delivery` present |
| `isComposeSdkOutdatedError(e)` | `sdkOutdated: { sdkVersion, serverVersion, minimumSdkVersion }` |
| `isComposeServerOutdatedError(e)` | `serverOutdated: { sdkVersion, serverVersion }` |

```ts theme={"system"}
import {
  isComposeDeliveryError,
  isComposeError,
  isComposePreparationError,
  isComposeSdkOutdatedError,
} from '@lifi/composer-sdk';

export const reportComposeError = (e: unknown): void => {
  if (isComposePreparationError(e)) {
    for (const op of e.failedOps) console.error(op.callId, op.kind, op.fix ?? op.message);
  } else if (isComposeDeliveryError(e)) {
    console.error(e.delivery.reason, e.delivery.escrow?.address);
  } else if (isComposeSdkOutdatedError(e)) {
    console.error(`Upgrade to at least ${e.sdkOutdated.minimumSdkVersion}`);
  } else if (isComposeError(e)) {
    console.error(e.code, e.status, e.kind, e.path, e.port, e.fix, e.message);
  } else {
    throw e;
  }
};

// Usage: await builder.compile(run).catch(reportComposeError);
```

The SDK also checks versions itself on `compile` and `route`. It reads the API's version from the `x-lifi-composer-version` response header. When the SDK is newer than the API, it throws `server_outdated`; pin the SDK to the API's version or wait for the rollout. When the SDK is older than the API's `major.minor.0`, it throws `sdk_outdated`; upgrade both packages.

## See also

* [Quickstart](https://docs.li.fi/composer/composer-api/quickstart.md) — a first flow in five minutes.
* [Build a same-chain flow](https://docs.li.fi/composer/composer-api/guides/build-a-flow.md) — inputs, ops, materialisers, guards, preconditions and submission.
* [Flow Schema](https://docs.li.fi/composer/composer-api/reference/flow-wire-format.md) — the JSON the SDK sends and receives.
* [Errors](https://docs.li.fi/composer/composer-api/reference/error-codes.md) — every error kind and its HTTP status.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.