@lifi/composer-sdk 0.5.1 → 0.6.1

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.
Files changed (62) hide show
  1. package/README.md +13 -3
  2. package/dist/authoring/FlowBuilderCore.cjs.map +1 -1
  3. package/dist/authoring/FlowBuilderCore.d.cts +11 -4
  4. package/dist/authoring/FlowBuilderCore.d.ts +11 -4
  5. package/dist/authoring/FlowBuilderCore.js.map +1 -1
  6. package/dist/authoring/handles.cjs.map +1 -1
  7. package/dist/authoring/handles.d.cts +2 -2
  8. package/dist/authoring/handles.d.ts +2 -2
  9. package/dist/authoring/handles.js.map +1 -1
  10. package/dist/authoring/raw.cjs +5 -3
  11. package/dist/authoring/raw.cjs.map +1 -1
  12. package/dist/authoring/raw.js +5 -3
  13. package/dist/authoring/raw.js.map +1 -1
  14. package/dist/client.cjs +41 -30
  15. package/dist/client.cjs.map +1 -1
  16. package/dist/client.d.cts +3 -3
  17. package/dist/client.d.ts +3 -3
  18. package/dist/client.js +41 -30
  19. package/dist/client.js.map +1 -1
  20. package/dist/generated/config.generated.cjs.map +1 -1
  21. package/dist/generated/config.generated.d.cts +46 -5
  22. package/dist/generated/config.generated.d.ts +46 -5
  23. package/dist/generated/operations.generated.cjs +4 -0
  24. package/dist/generated/operations.generated.cjs.map +1 -1
  25. package/dist/generated/operations.generated.d.cts +16 -2
  26. package/dist/generated/operations.generated.d.ts +16 -2
  27. package/dist/generated/operations.generated.js +4 -0
  28. package/dist/generated/operations.generated.js.map +1 -1
  29. package/dist/index.cjs +4 -1
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +3 -2
  32. package/dist/index.d.ts +3 -2
  33. package/dist/index.js +3 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/outputs.cjs +33 -0
  36. package/dist/outputs.cjs.map +1 -0
  37. package/dist/outputs.d.cts +10 -0
  38. package/dist/outputs.d.ts +10 -0
  39. package/dist/outputs.js +9 -0
  40. package/dist/outputs.js.map +1 -0
  41. package/dist/responseSchemas.cjs.map +1 -1
  42. package/dist/responseSchemas.d.cts +4 -4
  43. package/dist/responseSchemas.d.ts +4 -4
  44. package/dist/responseSchemas.js.map +1 -1
  45. package/dist/types.cjs.map +1 -1
  46. package/dist/types.d.cts +16 -5
  47. package/dist/types.d.ts +16 -5
  48. package/package.json +4 -3
  49. package/src/authoring/FlowBuilderCore.ts +12 -3
  50. package/src/authoring/handles.ts +2 -1
  51. package/src/authoring/raw.ts +4 -3
  52. package/src/client.ts +77 -45
  53. package/src/examples/flySwap.ts +3 -3
  54. package/src/examples/lifiZapAsync.ts +8 -7
  55. package/src/examples/swapAndZap.ts +7 -0
  56. package/src/examples/swapWithAllowRevert.ts +13 -3
  57. package/src/generated/config.generated.ts +49 -4
  58. package/src/generated/operations.generated.ts +25 -0
  59. package/src/index.ts +13 -2
  60. package/src/outputs.ts +16 -0
  61. package/src/responseSchemas.ts +4 -4
  62. package/src/types.ts +16 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} 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 `COMPOSER_SDK_VERSION_HEADER` 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// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\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 /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\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 * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\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 * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every produced resource comes back\n * `availability: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `producedResources[*].availability` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\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\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const 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\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (\n value: unknown,\n key: string,\n field: 'amountOut' | 'amountOutMin',\n url: string,\n): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: producedResources.${key}.simulated.${field} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// `simulated.amountOut` / `.amountOutMin` are declared `bigint` on\n// `SimulatedAmounts` (the domain truth: `compose-core` produces real bigints)\n// but arrive as decimal strings on the wire (the backend stringifies them).\n// Decode at this seam so a consumer reading the declared type gets the value\n// the type promises. A resource without `simulated` is left untouched; a\n// `simulated` claiming a missing or non-numeric amount is a contract violation\n// and surfaces as a `ComposeError` rather than `NaN` / `BigInt(undefined)`.\nconst decodeSimulatedAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n const resources = data.producedResources;\n if (!isNonNullObject(resources)) return;\n for (const key of Object.keys(resources)) {\n const resource = resources[key];\n if (!isNonNullObject(resource)) continue;\n const simulated = resource.simulated;\n if (simulated === undefined) continue;\n if (!isNonNullObject(simulated)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: producedResources.${key}.simulated is not an object`,\n { url },\n );\n }\n simulated.amountOut = decodeAmount(\n simulated.amountOut,\n key,\n 'amountOut',\n url,\n );\n if (simulated.amountOutMin !== undefined) {\n simulated.amountOutMin = decodeAmount(\n simulated.amountOutMin,\n key,\n 'amountOutMin',\n url,\n );\n }\n }\n};\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 decodeSimulatedAmounts(data, 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 decodeSimulatedAmounts(data, url);\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// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\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// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\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 trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\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 return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\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, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAKO;AAOP,oBAAoD;AACpD,6BAGO;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,yBAAqB,kCAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,C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Q,WAAW,MAAM,IAAI,KAAK,GAAG;AACzD,aAAO,IAAI,aAAa,IAAI;AAAA,IAC9B;AACA,UAAM,KAAK,OAAO,SAAS;AAC3B,WAAO;AAAA,MACL;AAAA,MACA,GAAG,IAAI,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,UAAM,MAAM,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ,QAAQ,MAAM,QAAQ,CAAC;AAOxE,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,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} 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 `COMPOSER_SDK_VERSION_HEADER` 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// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\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 /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\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 * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\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 * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\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\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const 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\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\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 decodeWireAmounts(data, 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 ComposeCompilePartialData;\n decodeWireAmounts(data, url);\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// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\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// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\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 trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\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 return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\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, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAKO;AAOP,oBAAoD;AACpD,6BAGO;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,yBAAqB,kCAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CAAC,OAAgB,MAAc,QAAwB;AAC1E,MAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR;AAAA,MACA,+BAA+B,IAAI,OACjC,UAAU,SAAY,WAAW,uBACnC;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AACA,SAAO,OAAO,KAAK;AACrB;AAgBA,MAAM,YAAY,CAAC,MAAc,MAAc,QAC7C,IAAI;AAAA,EACF;AAAA,EACA,+BAA+B,IAAI,IAAI,IAAI;AAAA,EAC3C,EAAE,IAAI;AACR;AAIF,MAAM,mBAAmB,CACvB,QACA,OACA,MACA,QACS;AACT,QAAM,OAAO,OAAO,KAAK;AACzB,MAAI,SAAS,OAAW;AACxB,MAAI,CAAC,gBAAgB,IAAI,GAAG;AAC1B,UAAM,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,oBAAoB,GAAG;AAAA,EAC7D;AACA,OAAK,QAAQ,aAAa,KAAK,OAAO,GAAG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AO;AAAA,MACL;AAAA,MACA,GAAG,IAAI,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,UAAM,MAAM,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ,QAAQ,MAAM,QAAQ,CAAC;AAOxE,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,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
package/dist/client.d.cts CHANGED
@@ -83,11 +83,11 @@ interface ComposeClient {
83
83
  * the server, not the shape of this contract.
84
84
  *
85
85
  * Only synchronous edges are considered unless the request sets
86
- * `allowAsyncRoutes: true`, so by default every produced resource comes back
87
- * `availability: 'now'` and a pair reachable only after settlement is a
86
+ * `allowAsyncRoutes: true`, so by default every terminal output comes back
87
+ * `delivery.when: 'now'` and a pair reachable only after settlement is a
88
88
  * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still
89
89
  * loses to a synchronous edge when the pair has one; read
90
- * `producedResources[*].availability` to see which representation you got.
90
+ * `outputs[*].delivery.when` to see which representation you got.
91
91
  *
92
92
  * Use {@link compile} for what the server does not author for you: several
93
93
  * chained operations, splits, explicit preconditions, or per-op guards.
package/dist/client.d.ts CHANGED
@@ -83,11 +83,11 @@ interface ComposeClient {
83
83
  * the server, not the shape of this contract.
84
84
  *
85
85
  * Only synchronous edges are considered unless the request sets
86
- * `allowAsyncRoutes: true`, so by default every produced resource comes back
87
- * `availability: 'now'` and a pair reachable only after settlement is a
86
+ * `allowAsyncRoutes: true`, so by default every terminal output comes back
87
+ * `delivery.when: 'now'` and a pair reachable only after settlement is a
88
88
  * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still
89
89
  * loses to a synchronous edge when the pair has one; read
90
- * `producedResources[*].availability` to see which representation you got.
90
+ * `outputs[*].delivery.when` to see which representation you got.
91
91
  *
92
92
  * Use {@link compile} for what the server does not author for you: several
93
93
  * chained operations, splits, explicit preconditions, or per-op guards.
package/dist/client.js CHANGED
@@ -9,53 +9,64 @@ import {
9
9
  parseCompilePartialEnvelope,
10
10
  parseSimulateResult
11
11
  } from "./responseSchemas.js";
12
- const SDK_VERSION = true ? "0.5.1" : "dev";
12
+ const SDK_VERSION = true ? "0.6.1" : "dev";
13
13
  const SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);
14
14
  const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
15
15
  const isNonNullObject = (v) => typeof v === "object" && v !== null;
16
16
  const INTEGER_STRING = /^\d+$/;
17
- const decodeAmount = (value, key, field, url) => {
17
+ const decodeAmount = (value, path, url) => {
18
18
  if (typeof value !== "string" || !INTEGER_STRING.test(value)) {
19
19
  throw new ComposeError(
20
20
  "UNKNOWN_ERROR",
21
- `Malformed compose response: producedResources.${key}.simulated.${field} is ${value === void 0 ? "absent" : "not an integer string"}`,
21
+ `Malformed compose response: ${path} is ${value === void 0 ? "absent" : "not an integer string"}`,
22
22
  { url }
23
23
  );
24
24
  }
25
25
  return BigInt(value);
26
26
  };
27
- const decodeSimulatedAmounts = (data, url) => {
28
- if (!isNonNullObject(data)) return;
29
- const resources = data.producedResources;
30
- if (!isNonNullObject(resources)) return;
31
- for (const key of Object.keys(resources)) {
32
- const resource = resources[key];
33
- if (!isNonNullObject(resource)) continue;
34
- const simulated = resource.simulated;
35
- if (simulated === void 0) continue;
36
- if (!isNonNullObject(simulated)) {
37
- throw new ComposeError(
38
- "UNKNOWN_ERROR",
39
- `Malformed compose response: producedResources.${key}.simulated is not an object`,
40
- { url }
41
- );
42
- }
43
- simulated.amountOut = decodeAmount(
44
- simulated.amountOut,
45
- key,
46
- "amountOut",
27
+ const malformed = (path, what, url) => new ComposeError(
28
+ "UNKNOWN_ERROR",
29
+ `Malformed compose response: ${path} ${what}`,
30
+ { url }
31
+ );
32
+ const decodeAmountLeaf = (amount, field, path, url) => {
33
+ const leaf = amount[field];
34
+ if (leaf === void 0) return;
35
+ if (!isNonNullObject(leaf)) {
36
+ throw malformed(`${path}.${field}`, "is not an object", url);
37
+ }
38
+ leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);
39
+ };
40
+ const decodeOutputs = (data, url) => {
41
+ const outputs = data.outputs;
42
+ if (!isNonNullObject(outputs)) {
43
+ throw malformed(
44
+ "outputs",
45
+ outputs === void 0 ? "is absent" : "is not an object",
47
46
  url
48
47
  );
49
- if (simulated.amountOutMin !== void 0) {
50
- simulated.amountOutMin = decodeAmount(
51
- simulated.amountOutMin,
52
- key,
53
- "amountOutMin",
48
+ }
49
+ for (const key of Object.keys(outputs)) {
50
+ const entry = outputs[key];
51
+ if (!isNonNullObject(entry)) {
52
+ throw malformed(`outputs.${key}`, "is not an object", url);
53
+ }
54
+ const amount = entry.amount;
55
+ if (!isNonNullObject(amount)) {
56
+ throw malformed(
57
+ `outputs.${key}.amount`,
58
+ amount === void 0 ? "is absent" : "is not an object",
54
59
  url
55
60
  );
56
61
  }
62
+ decodeAmountLeaf(amount, "estimate", `outputs.${key}.amount`, url);
63
+ decodeAmountLeaf(amount, "minimum", `outputs.${key}.amount`, url);
57
64
  }
58
65
  };
66
+ const decodeWireAmounts = (data, url) => {
67
+ if (!isNonNullObject(data)) return;
68
+ decodeOutputs(data, url);
69
+ };
59
70
  const parseBody = async (res, url) => {
60
71
  const body = await res.json().catch((_) => null);
61
72
  if (!isNonNullObject(body) || !("data" in body)) {
@@ -67,7 +78,7 @@ const parseBody = async (res, url) => {
67
78
  };
68
79
  const parseCompileSuccessBody = async (res, url) => {
69
80
  const data = await parseBody(res, url);
70
- decodeSimulatedAmounts(data, url);
81
+ decodeWireAmounts(data, url);
71
82
  return { ...data, status: "success" };
72
83
  };
73
84
  const parsePartialBody = async (res, url) => {
@@ -81,7 +92,7 @@ const parsePartialBody = async (res, url) => {
81
92
  );
82
93
  }
83
94
  const data = envelope.data;
84
- decodeSimulatedAmounts(data, url);
95
+ decodeWireAmounts(data, url);
85
96
  return { ...data, status: "partial", error: envelope.error };
86
97
  };
87
98
  const parseSimulateBody = async (res, url) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} 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 `COMPOSER_SDK_VERSION_HEADER` 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// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\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 /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\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 * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\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 * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every produced resource comes back\n * `availability: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `producedResources[*].availability` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\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\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const 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\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (\n value: unknown,\n key: string,\n field: 'amountOut' | 'amountOutMin',\n url: string,\n): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: producedResources.${key}.simulated.${field} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// `simulated.amountOut` / `.amountOutMin` are declared `bigint` on\n// `SimulatedAmounts` (the domain truth: `compose-core` produces real bigints)\n// but arrive as decimal strings on the wire (the backend stringifies them).\n// Decode at this seam so a consumer reading the declared type gets the value\n// the type promises. A resource without `simulated` is left untouched; a\n// `simulated` claiming a missing or non-numeric amount is a contract violation\n// and surfaces as a `ComposeError` rather than `NaN` / `BigInt(undefined)`.\nconst decodeSimulatedAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n const resources = data.producedResources;\n if (!isNonNullObject(resources)) return;\n for (const key of Object.keys(resources)) {\n const resource = resources[key];\n if (!isNonNullObject(resource)) continue;\n const simulated = resource.simulated;\n if (simulated === undefined) continue;\n if (!isNonNullObject(simulated)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: producedResources.${key}.simulated is not an object`,\n { url },\n );\n }\n simulated.amountOut = decodeAmount(\n simulated.amountOut,\n key,\n 'amountOut',\n url,\n );\n if (simulated.amountOutMin !== undefined) {\n simulated.amountOutMin = decodeAmount(\n simulated.amountOutMin,\n key,\n 'amountOutMin',\n url,\n );\n }\n }\n};\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 decodeSimulatedAmounts(data, 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 decodeSimulatedAmounts(data, url);\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// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\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// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\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 trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\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 return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\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, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,6BAA6B;AACpD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,qBAAqB,aAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CACnB,OACA,KACA,OACA,QACW;AACX,MAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR;AAAA,MACA,iDAAiD,GAAG,cAAc,KAAK,OACrE,UAAU,SAAY,WAAW,uBACnC;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AACA,SAAO,OAAO,KAAK;AACrB;AASA,MAAM,yBAAyB,CAAC,MAAe,QAAsB;AACnE,MAAI,CAAC,gBAAgB,IAAI,EA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AQ,MAAM,QAAQ,CAAC;AAOxE,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,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} 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 `COMPOSER_SDK_VERSION_HEADER` 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// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\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 /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\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 * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\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 * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\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\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const 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\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\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 decodeWireAmounts(data, 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 ComposeCompilePartialData;\n decodeWireAmounts(data, url);\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// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\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// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\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 trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\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 return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\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, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,c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BAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/generated/config.generated.ts"],"sourcesContent":["// AUTO-GENERATED from manifest.json — do not edit by hand.\n// Regenerate with: yarn workspace @lifi/composer-sdk generate\n\nimport type { Address, IntegerStringInput } from '../types.js';\n\n/**\n * a number between 0 and 10000\n */\nexport type Between010000 = number;\n\nexport interface CoreSplitConfig {\n bps: Between010000;\n}\n\n/**\n * a positive number\n */\nexport type Positive = number;\n/**\n * a string at most 64 character(s) long\n */\nexport type MaxLength64 = string;\n/**\n * an array of at most 50 item(s)\n *\n * @maxItems 50\n */\nexport type MaxItems50 = MaxLength64[];\n\nexport interface LifiSwapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n slippage?: number;\n timing?: {\n swapStepTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n routeTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n };\n exchanges?: {\n allow?: MaxItems50;\n deny?: MaxItems50;\n prefer?: MaxItems50;\n };\n}\n\nexport interface InvariantNumericConfig {\n op: 'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq';\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantNumericInRangeConfig {\n min: IntegerStringInput;\n max: IntegerStringInput;\n}\n\nexport interface InvariantGteConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantGtConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantLteConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantLtConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantEqConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantNeqConfig {\n threshold: IntegerStringInput;\n}\n\n/**\n * a non-negative number\n */\nexport type NonNegative = number;\n\nexport interface CoreBpsDownConfig {\n bps: NonNegative;\n}\n\nexport interface CoreBpsUpConfig {\n bps: NonNegative;\n}\n\nexport interface CoreApproveConfig {\n spender: Address;\n}\n\nexport interface CoreBalanceOfConfig {\n token: Address;\n owner?: Address;\n}\n\nexport interface CoreTransferConfig {\n amount?: IntegerStringInput;\n}\n\nexport interface CoreEmitEvent1Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent2Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent3Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent4Config {\n signature: string;\n}\n\n/**\n * a string at most 65536 character(s) long\n */\nexport type MaxLength65536 = string;\n\nexport interface CoreCallConfig {\n target: Address;\n functionSignature: string;\n callType?: 'Call' | 'ValueCall';\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n approvals?: (\n | {\n spender: Address;\n }\n | {\n from: 'sender';\n }\n )[];\n}\n\nexport interface CoreStaticCallConfig {\n target: Address;\n functionSignature: string;\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n}\n\nexport interface CoreRawCallConfig {\n target: Address;\n calldata: string;\n callType?: 'Call' | 'StaticCall' | 'ValueCall' | 'DelegateCall';\n resultType?: string;\n}\n\nexport interface CoreInvokeConfig {\n target: Address;\n functionSignature: string;\n callType?: 'Call' | 'ValueCall';\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n}\n\nexport interface CoreAsResourceConfig {\n resource:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface AaveBorrowConfig {\n pool: string;\n asset: string;\n variableDebtToken: string;\n amount: IntegerStringInput;\n referralId?: number;\n}\n\nexport type AaveRepayConfig =\n | {\n pool: string;\n mode: 'exact';\n }\n | {\n pool: string;\n mode: 'max';\n };\n\nexport interface AaveRepayWithATokensConfig {\n pool: string;\n asset: string;\n}\n\nexport interface AaveClaimRewardsConfig {\n rewardsController: string;\n assets: string[];\n reward: string;\n amount?: IntegerStringInput;\n to?: string;\n}\n\n/**\n * a number between 0 and 255\n */\nexport type Between0255 = number;\n\nexport interface AaveSetEModeConfig {\n pool: string;\n category: Between0255;\n}\n\nexport interface AaveGetHealthFactorConfig {\n pool: string;\n user?: string;\n}\n\nexport type MorphoBlueSupplyCollateralConfig =\n | (\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'exact';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'exact';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'all';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'all';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueWithdrawCollateralConfig =\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueBorrowConfig =\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueRepayConfig =\n | (\n | {\n morpho?: string;\n mode: 'exact';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'exact';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n mode: 'max';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'max';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueSupplyConfig =\n | {\n morpho?: string;\n onBehalfOf?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueWithdrawConfig =\n | (\n | {\n morpho?: string;\n mode: 'exact';\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'exact';\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n mode: 'max';\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'max';\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueGetPositionConfig =\n | {\n morpho?: string;\n user?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n user?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport interface LifiFlashloanRepayConfig {\n leg: string;\n fee?: string;\n}\n\nexport type ContinuationAssertReadyConfig =\n | {\n kind: 'erc20BalanceGte';\n chainId: Positive;\n token: StartsWith0X;\n owner: StartsWith0X;\n minAmount: string;\n }\n | {\n kind: 'nativeBalanceGte';\n chainId: Positive;\n owner: StartsWith0X;\n minAmount: string;\n }\n | {\n kind: 'call';\n chainId: Positive;\n to: StartsWith0X;\n calldata: StartsWith0X;\n comparator: 'gte' | 'eq' | 'lte';\n value: string;\n };\n/**\n * a string starting with \"0x\"\n */\nexport type StartsWith0X = string;\n\nexport interface LifiZapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface LifiZapAsyncConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface ParaswapBuyConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n exactAmountOut: string;\n srcDecimals: NonNegative;\n destDecimals: NonNegative;\n maxSlippageBps?: Between010000;\n partner?: string;\n partnerAddress?: string;\n /**\n * Integrator fee in basis points; non-negative integer string capped at 9000.\n */\n partnerFeeBps?: string;\n}\n\nexport interface CorePeekConfig {\n target: Address;\n functionSignature: string;\n args?: string[];\n}\n\n/**\n * a number between 0 and 3318\n */\nexport type Between03318 = number;\n/**\n * a number between 0 and 5000\n */\nexport type Between05000 = number;\n\nexport interface FlySwapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n inputVarianceBps?: Between03318;\n maxSlippageBps?: Between05000;\n}\n\nexport interface SlippageGuardConfig {\n port: string;\n bps: Between010000;\n}\n\nexport interface CoreNumericInvariantGuardConfig {\n port: string;\n op: 'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq';\n threshold: IntegerStringInput;\n}\n\nexport interface BalanceOfMaterialiserConfig {\n owner: Address;\n}\n\nexport type DirectDepositMaterialiserConfig =\n | {\n amount: IntegerStringInput;\n allowNonExact?: false;\n }\n | {\n amount: IntegerStringInput;\n allowNonExact: true;\n }\n | {\n allowNonExact: true;\n simAmount?: string;\n };\n\nexport interface CallMaterialiserConfig {\n target: Address;\n calldata: string;\n}\n\nexport interface FlashloanMaterialiserConfig {\n providerKind: 'aave-v3' | 'erc3156' | 'balancer-v2' | 'morpho-blue';\n amount: IntegerStringInput;\n}\n\nexport interface Erc20BalancePreconditionConfig {\n wallet: Address;\n token: Address;\n balance: IntegerStringInput;\n}\n\nexport interface NativeBalancePreconditionConfig {\n wallet: Address;\n balance: IntegerStringInput;\n}\n\nexport interface Erc20AllowancePreconditionConfig {\n owner: Address;\n spender: Address;\n token: Address;\n allowance: IntegerStringInput;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../src/generated/config.generated.ts"],"sourcesContent":["// AUTO-GENERATED from manifest.json — do not edit by hand.\n// Regenerate with: yarn workspace @lifi/composer-sdk generate\n\nimport type { Address, IntegerStringInput } from '../types.js';\n\n/**\n * a number between 0 and 10000\n */\nexport type Between010000 = number;\n\nexport interface CoreSplitConfig {\n bps: Between010000;\n}\n\n/**\n * a positive number\n */\nexport type Positive = number;\n/**\n * a string at most 64 character(s) long\n */\nexport type MaxLength64 = string;\n/**\n * an array of at most 50 item(s)\n *\n * @maxItems 50\n */\nexport type MaxItems50 = MaxLength64[];\n\nexport interface LifiSwapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n slippage?: number;\n timing?: {\n swapStepTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n routeTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n };\n exchanges?: {\n allow?: MaxItems50;\n deny?: MaxItems50;\n prefer?: MaxItems50;\n };\n}\n\n/**\n * a string starting with \"0x\"\n */\nexport type StartsWith0X = string;\n/**\n * a number between 0 and 1\n */\nexport type Between01 = number;\n\nexport interface LifiBridgeConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n destination: StartsWith0X;\n slippage?: Between01;\n timing?: {\n swapStepTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n routeTimingStrategies?: {\n strategy: 'minWaitTime';\n minWaitTimeMs: number;\n startingExpectedResults: number;\n reduceEveryMs: number;\n }[];\n };\n bridges?: {\n allow?: MaxItems50;\n deny?: MaxItems50;\n prefer?: MaxItems50;\n };\n exchanges?: {\n allow?: MaxItems50;\n deny?: MaxItems50;\n prefer?: MaxItems50;\n };\n order?: 'FASTEST' | 'CHEAPEST';\n}\n\nexport interface InvariantNumericConfig {\n op: 'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq';\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantNumericInRangeConfig {\n min: IntegerStringInput;\n max: IntegerStringInput;\n}\n\nexport interface InvariantGteConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantGtConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantLteConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantLtConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantEqConfig {\n threshold: IntegerStringInput;\n}\n\nexport interface InvariantNeqConfig {\n threshold: IntegerStringInput;\n}\n\n/**\n * a non-negative number\n */\nexport type NonNegative = number;\n\nexport interface CoreBpsDownConfig {\n bps: NonNegative;\n}\n\nexport interface CoreBpsUpConfig {\n bps: NonNegative;\n}\n\nexport interface CoreApproveConfig {\n spender: Address;\n}\n\nexport interface CoreBalanceOfConfig {\n token: Address;\n owner?: Address;\n}\n\nexport interface CoreTransferConfig {\n amount?: IntegerStringInput;\n}\n\nexport interface CoreEmitEvent1Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent2Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent3Config {\n signature: string;\n}\n\nexport interface CoreEmitEvent4Config {\n signature: string;\n}\n\n/**\n * a string at most 65536 character(s) long\n */\nexport type MaxLength65536 = string;\n\nexport interface CoreCallConfig {\n target: Address;\n functionSignature: string;\n callType?: 'Call' | 'ValueCall';\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n approvals?: (\n | {\n spender: Address;\n }\n | {\n from: 'sender';\n }\n )[];\n}\n\nexport interface CoreStaticCallConfig {\n target: Address;\n functionSignature: string;\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n}\n\nexport interface CoreRawCallConfig {\n target: Address;\n calldata: string;\n callType?: 'Call' | 'StaticCall' | 'ValueCall' | 'DelegateCall';\n resultType?: string;\n}\n\nexport interface CoreInvokeConfig {\n target: Address;\n functionSignature: string;\n callType?: 'Call' | 'ValueCall';\n args?: (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )\n | (\n | MaxLength65536\n | number\n | boolean\n | {\n $ref: string;\n }\n )[]\n )[]\n )[]\n )[]\n )[]\n )[];\n}\n\nexport interface CoreAsResourceConfig {\n resource:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface AaveBorrowConfig {\n pool: string;\n asset: string;\n variableDebtToken: string;\n amount: IntegerStringInput;\n referralId?: number;\n}\n\nexport type AaveRepayConfig =\n | {\n pool: string;\n mode: 'exact';\n }\n | {\n pool: string;\n mode: 'max';\n };\n\nexport interface AaveRepayWithATokensConfig {\n pool: string;\n asset: string;\n}\n\nexport interface AaveClaimRewardsConfig {\n rewardsController: string;\n assets: string[];\n reward: string;\n amount?: IntegerStringInput;\n to?: string;\n}\n\n/**\n * a number between 0 and 255\n */\nexport type Between0255 = number;\n\nexport interface AaveSetEModeConfig {\n pool: string;\n category: Between0255;\n}\n\nexport interface AaveGetHealthFactorConfig {\n pool: string;\n user?: string;\n}\n\nexport type MorphoBlueSupplyCollateralConfig =\n | (\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'exact';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'exact';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'all';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n mode: 'all';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueWithdrawCollateralConfig =\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueBorrowConfig =\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueRepayConfig =\n | (\n | {\n morpho?: string;\n mode: 'exact';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'exact';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n mode: 'max';\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'max';\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueSupplyConfig =\n | {\n morpho?: string;\n onBehalfOf?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n onBehalfOf?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport type MorphoBlueWithdrawConfig =\n | (\n | {\n morpho?: string;\n mode: 'exact';\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'exact';\n amount: IntegerStringInput;\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n )\n | (\n | {\n morpho?: string;\n mode: 'max';\n onBehalfOf?: string;\n receiver?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n mode: 'max';\n onBehalfOf?: string;\n receiver?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n }\n );\n\nexport type MorphoBlueGetPositionConfig =\n | {\n morpho?: string;\n user?: string;\n /**\n * a string matching the pattern ^0x[0-9a-fA-F]{64}$\n */\n marketId: string;\n }\n | {\n morpho?: string;\n user?: string;\n marketParams: {\n loanToken: string;\n collateralToken: string;\n oracle: string;\n irm: string;\n lltv: string;\n };\n };\n\nexport interface LifiFlashloanRepayConfig {\n leg: string;\n fee?: string;\n}\n\nexport type ContinuationAssertReadyConfig =\n | {\n kind: 'erc20BalanceGte';\n chainId: Positive;\n token: StartsWith0X;\n owner: StartsWith0X;\n minAmount: string;\n }\n | {\n kind: 'nativeBalanceGte';\n chainId: Positive;\n owner: StartsWith0X;\n minAmount: string;\n }\n | {\n kind: 'call';\n chainId: Positive;\n to: StartsWith0X;\n calldata: StartsWith0X;\n comparator: 'gte' | 'eq' | 'lte';\n value: string;\n };\n\nexport interface LifiZapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface LifiZapAsyncConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n}\n\nexport interface ParaswapBuyConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n exactAmountOut: string;\n srcDecimals: NonNegative;\n destDecimals: NonNegative;\n maxSlippageBps?: Between010000;\n partner?: string;\n partnerAddress?: string;\n /**\n * Integrator fee in basis points; non-negative integer string capped at 9000.\n */\n partnerFeeBps?: string;\n}\n\nexport interface CorePeekConfig {\n target: Address;\n functionSignature: string;\n args?: string[];\n}\n\n/**\n * a number between 0 and 3318\n */\nexport type Between03318 = number;\n/**\n * a number between 0 and 5000\n */\nexport type Between05000 = number;\n\nexport interface FlySwapConfig {\n resourceOut:\n | {\n kind: 'native';\n chainId: Positive;\n }\n | {\n kind: 'erc20';\n token: Address;\n chainId: Positive;\n };\n inputVarianceBps?: Between03318;\n maxSlippageBps?: Between05000;\n}\n\nexport interface SlippageGuardConfig {\n port: string;\n bps: Between010000;\n}\n\nexport interface CoreNumericInvariantGuardConfig {\n port: string;\n op: 'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq';\n threshold: IntegerStringInput;\n}\n\nexport interface BalanceOfMaterialiserConfig {\n owner: Address;\n}\n\nexport type DirectDepositMaterialiserConfig =\n | {\n amount: IntegerStringInput;\n allowNonExact?: false;\n }\n | {\n amount: IntegerStringInput;\n allowNonExact: true;\n }\n | {\n allowNonExact: true;\n simAmount?: string;\n };\n\nexport interface CallMaterialiserConfig {\n target: Address;\n calldata: string;\n}\n\nexport interface FlashloanMaterialiserConfig {\n providerKind: 'aave-v3' | 'erc3156' | 'balancer-v2' | 'morpho-blue';\n amount: IntegerStringInput;\n}\n\nexport interface Erc20BalancePreconditionConfig {\n wallet: Address;\n token: Address;\n balance: IntegerStringInput;\n}\n\nexport interface NativeBalancePreconditionConfig {\n wallet: Address;\n balance: IntegerStringInput;\n}\n\nexport interface Erc20AllowancePreconditionConfig {\n owner: Address;\n spender: Address;\n token: Address;\n allowance: IntegerStringInput;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -52,6 +52,51 @@ interface LifiSwapConfig {
52
52
  prefer?: MaxItems50;
53
53
  };
54
54
  }
55
+ /**
56
+ * a string starting with "0x"
57
+ */
58
+ type StartsWith0X = string;
59
+ /**
60
+ * a number between 0 and 1
61
+ */
62
+ type Between01 = number;
63
+ interface LifiBridgeConfig {
64
+ resourceOut: {
65
+ kind: 'native';
66
+ chainId: Positive;
67
+ } | {
68
+ kind: 'erc20';
69
+ token: Address;
70
+ chainId: Positive;
71
+ };
72
+ destination: StartsWith0X;
73
+ slippage?: Between01;
74
+ timing?: {
75
+ swapStepTimingStrategies?: {
76
+ strategy: 'minWaitTime';
77
+ minWaitTimeMs: number;
78
+ startingExpectedResults: number;
79
+ reduceEveryMs: number;
80
+ }[];
81
+ routeTimingStrategies?: {
82
+ strategy: 'minWaitTime';
83
+ minWaitTimeMs: number;
84
+ startingExpectedResults: number;
85
+ reduceEveryMs: number;
86
+ }[];
87
+ };
88
+ bridges?: {
89
+ allow?: MaxItems50;
90
+ deny?: MaxItems50;
91
+ prefer?: MaxItems50;
92
+ };
93
+ exchanges?: {
94
+ allow?: MaxItems50;
95
+ deny?: MaxItems50;
96
+ prefer?: MaxItems50;
97
+ };
98
+ order?: 'FASTEST' | 'CHEAPEST';
99
+ }
55
100
  interface InvariantNumericConfig {
56
101
  op: 'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq';
57
102
  threshold: IntegerStringInput;
@@ -447,10 +492,6 @@ type ContinuationAssertReadyConfig = {
447
492
  comparator: 'gte' | 'eq' | 'lte';
448
493
  value: string;
449
494
  };
450
- /**
451
- * a string starting with "0x"
452
- */
453
- type StartsWith0X = string;
454
495
  interface LifiZapConfig {
455
496
  resourceOut: {
456
497
  kind: 'native';
@@ -562,4 +603,4 @@ interface Erc20AllowancePreconditionConfig {
562
603
  allowance: IntegerStringInput;
563
604
  }
564
605
 
565
- export type { AaveBorrowConfig, AaveClaimRewardsConfig, AaveGetHealthFactorConfig, AaveRepayConfig, AaveRepayWithATokensConfig, AaveSetEModeConfig, BalanceOfMaterialiserConfig, Between010000, Between0255, Between03318, Between05000, CallMaterialiserConfig, ContinuationAssertReadyConfig, CoreApproveConfig, CoreAsResourceConfig, CoreBalanceOfConfig, CoreBpsDownConfig, CoreBpsUpConfig, CoreCallConfig, CoreEmitEvent1Config, CoreEmitEvent2Config, CoreEmitEvent3Config, CoreEmitEvent4Config, CoreInvokeConfig, CoreNumericInvariantGuardConfig, CorePeekConfig, CoreRawCallConfig, CoreSplitConfig, CoreStaticCallConfig, CoreTransferConfig, DirectDepositMaterialiserConfig, Erc20AllowancePreconditionConfig, Erc20BalancePreconditionConfig, FlashloanMaterialiserConfig, FlySwapConfig, InvariantEqConfig, InvariantGtConfig, InvariantGteConfig, InvariantLtConfig, InvariantLteConfig, InvariantNeqConfig, InvariantNumericConfig, InvariantNumericInRangeConfig, LifiFlashloanRepayConfig, LifiSwapConfig, LifiZapAsyncConfig, LifiZapConfig, MaxItems50, MaxLength64, MaxLength65536, MorphoBlueBorrowConfig, MorphoBlueGetPositionConfig, MorphoBlueRepayConfig, MorphoBlueSupplyCollateralConfig, MorphoBlueSupplyConfig, MorphoBlueWithdrawCollateralConfig, MorphoBlueWithdrawConfig, NativeBalancePreconditionConfig, NonNegative, ParaswapBuyConfig, Positive, SlippageGuardConfig, StartsWith0X };
606
+ export type { AaveBorrowConfig, AaveClaimRewardsConfig, AaveGetHealthFactorConfig, AaveRepayConfig, AaveRepayWithATokensConfig, AaveSetEModeConfig, BalanceOfMaterialiserConfig, Between01, Between010000, Between0255, Between03318, Between05000, CallMaterialiserConfig, ContinuationAssertReadyConfig, CoreApproveConfig, CoreAsResourceConfig, CoreBalanceOfConfig, CoreBpsDownConfig, CoreBpsUpConfig, CoreCallConfig, CoreEmitEvent1Config, CoreEmitEvent2Config, CoreEmitEvent3Config, CoreEmitEvent4Config, CoreInvokeConfig, CoreNumericInvariantGuardConfig, CorePeekConfig, CoreRawCallConfig, CoreSplitConfig, CoreStaticCallConfig, CoreTransferConfig, DirectDepositMaterialiserConfig, Erc20AllowancePreconditionConfig, Erc20BalancePreconditionConfig, FlashloanMaterialiserConfig, FlySwapConfig, InvariantEqConfig, InvariantGtConfig, InvariantGteConfig, InvariantLtConfig, InvariantLteConfig, InvariantNeqConfig, InvariantNumericConfig, InvariantNumericInRangeConfig, LifiBridgeConfig, LifiFlashloanRepayConfig, LifiSwapConfig, LifiZapAsyncConfig, LifiZapConfig, MaxItems50, MaxLength64, MaxLength65536, MorphoBlueBorrowConfig, MorphoBlueGetPositionConfig, MorphoBlueRepayConfig, MorphoBlueSupplyCollateralConfig, MorphoBlueSupplyConfig, MorphoBlueWithdrawCollateralConfig, MorphoBlueWithdrawConfig, NativeBalancePreconditionConfig, NonNegative, ParaswapBuyConfig, Positive, SlippageGuardConfig, StartsWith0X };