UNPKG

@lifi/compose-spec

Version:

Public wire-format types and schemas for Compose flows

1,106 lines (1,105 loc) • 44.5 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); //#region \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion let effect = require("effect"); let zod = require("zod"); zod = __toESM(zod, 1); //#region src/chainCapabilities.ts /** * The zero-address sentinel that represents the native gas coin on * EVM-native chains. Exported so tests and call-sites can reference it * by name rather than inlining 40 zeros. * * Inlined as a literal rather than imported from `@lifi/utils`: `compose-spec` * is the wire-format leaf package and carries no `@lifi/*` dependencies * (enforced by `scripts/check-compose-boundaries.mjs`). */ const EVM_NATIVE_SENTINEL = "0x0000000000000000000000000000000000000000"; /** * Whether `address` is the EVM zero address (the native sentinel), compared * case-insensitively. Inlined comparison: `compose-spec` cannot import * `toAddress` from `@lifi/utils` (see `EVM_NATIVE_SENTINEL`). */ const isZeroAddress = (address) => address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase(); const TEMPO_CHAIN_ID = 4217; const TEMPO_NATIVE_ERC20 = { token: "0x20C0000000000000000000000000000000000000", symbol: "pathUSD", decimals: 6 }; const ARC_CHAIN_ID = 5042; /** * Arc's native gas coin is USDC (18-decimal wei at the EVM level). The USDC * ERC-20 at this address is a view over native balances: `balanceOf` returns * `native wei / 1e12` and has no balance storage slot; allowances live in * regular storage. The composer interacts with USDC exclusively through this * facade, never via `msg.value`. */ const ARC_NATIVE_ERC20 = { token: "0x3600000000000000000000000000000000000000", symbol: "USDC", decimals: 6 }; const ARC_NATIVE_SCALE = 10n ** BigInt(18 - ARC_NATIVE_ERC20.decimals); const ARC_TESTNET_CHAIN_ID = 5042002; const REGISTRY = /* @__PURE__ */ new Map([ [TEMPO_CHAIN_ID, { kind: "as-erc20", chainId: TEMPO_CHAIN_ID, nativeErc20: TEMPO_NATIVE_ERC20 }], [ARC_CHAIN_ID, { kind: "native-mirrored-erc20", chainId: ARC_CHAIN_ID, nativeErc20: ARC_NATIVE_ERC20, nativeScale: ARC_NATIVE_SCALE }], [ARC_TESTNET_CHAIN_ID, { kind: "native-mirrored-erc20", chainId: ARC_TESTNET_CHAIN_ID, nativeErc20: ARC_NATIVE_ERC20, nativeScale: ARC_NATIVE_SCALE }] ]); const getChainCapabilities = (chainId) => REGISTRY.get(chainId) ?? { kind: "evm-native", chainId }; /** * Structural fold over the `ChainCapabilities` union — the capabilities * counterpart of `foldResource`/`foldRef`. Dispatches on `kind` and hands each * case its narrowed fields, so consumers that must branch on the native-asset * policy (e.g. compose-core's `rewritePreconditions`) do so through one * combinator whose exhaustiveness the compiler enforces: adding a new arm to * the union above turns every `foldChainCapabilities` call into a type error * until it handles the new case. */ const foldChainCapabilities = (caps, cases) => { switch (caps.kind) { case "evm-native": return cases.evmNative(caps.chainId); case "as-erc20": return cases.asErc20(caps.nativeErc20, caps.chainId); case "native-mirrored-erc20": return cases.nativeMirroredErc20(caps.nativeErc20, caps.nativeScale, caps.chainId); } }; const nativeCheckPolicy = (chainId) => foldChainCapabilities(getChainCapabilities(chainId), { evmNative: () => ({ kind: "keep" }), asErc20: (nativeErc20) => ({ kind: "rewrite", token: nativeErc20.token }), nativeMirroredErc20: (nativeErc20) => ({ kind: "reject", reason: `nativeBalanceGte is not accepted on chain ${chainId}: its canonical native asset is an ERC-20 facade whose units differ from native wei — author the check as erc20BalanceGte of ${nativeErc20.token}` }) }); /** * Exact-kind check for `as-erc20` (currently Tempo only) — the rare case that * genuinely means "no `msg.value` coin exists on this chain". Most consumers * want `hasErc20CanonicalNative` instead, which also covers * `native-mirrored-erc20` chains (Arc), where the composer's ERC-20-only * policy applies even though `msg.value` works. Code that must treat the two * ERC-20-native kinds differently goes through `foldChainCapabilities` or * `nativeCheckPolicy`, never a second exact-kind predicate. */ const isAsErc20Chain = (chainId) => getChainCapabilities(chainId).kind === "as-erc20"; /** * The chain's stand-in native ERC-20 when its canonical native asset is an * ERC-20 (`as-erc20` and `native-mirrored-erc20`), `undefined` on plain * `evm-native` chains. Module-local narrowing helper behind the exported * predicates and rewrites below. */ const erc20CanonicalNative = (caps) => caps.kind === "as-erc20" || caps.kind === "native-mirrored-erc20" ? caps.nativeErc20 : void 0; /** * Whether the chain's canonical native asset is an ERC-20 — true for both * `as-erc20` chains (Tempo: no `msg.value` coin exists) and * `native-mirrored-erc20` chains (Arc: `msg.value` exists but is never used). * This is the predicate for the shared resource-level behaviour: native * resources are rewritten to the ERC-20, native routing edges are dropped, and * a surviving native resource is a compile error. */ const hasErc20CanonicalNative = (chainId) => erc20CanonicalNative(getChainCapabilities(chainId)) !== void 0; /** * The address that represents the chain's native asset. * * On EVM-native chains this is the zero-address sentinel `0x0…0`. On chains * whose canonical native asset is an ERC-20 it is the chain's stand-in token * (PathUSD on Tempo, the USDC facade on Arc). */ const canonicalNativeAddress = (chainId) => erc20CanonicalNative(getChainCapabilities(chainId))?.token ?? "0x0000000000000000000000000000000000000000"; /** * Whether `address` represents the native asset of `chainId`. * * On EVM-native chains, this is the case-insensitive zero-address check. On * chains whose canonical native asset is an ERC-20, the literal zero address * returns `false` — only the chain's stand-in ERC-20 address matches. */ const isNativeAddressForChain = (chainId, address) => { const target = canonicalNativeAddress(chainId); return address.toLowerCase() === target.toLowerCase(); }; /** * Whether `address` on `chainId` is the genuine `msg.value`-style native coin: * an `evm-native` chain's zero-address sentinel. * * This is the single predicate that gates `msg.value` semantics — choosing a * `NativeBalance` over an `Erc20Balance` simulation requirement, and skipping * the ERC-20 approval a native input would otherwise need. It returns `false` * for every address on a chain whose canonical native asset is an ERC-20 * (including the zero sentinel): on `as-erc20` chains the "native" coin is a * real ERC-20 moved via `transferFrom`, never `msg.value`, and on * `native-mirrored-erc20` chains `msg.value` works but the composer's policy * is to move the coin exclusively through the ERC-20 facade. Use this rather * than re-deriving the check at call sites, and rather than * `isNativeAddressForChain`, which returns `true` for the stand-in ERC-20 * (PathUSD on Tempo) and would wrongly route it to `msg.value`. */ const isMsgValueNative = (chainId, address) => !hasErc20CanonicalNative(chainId) && isZeroAddress(address); /** * Rewrite a single `Resource` according to its chain's capabilities. * * On chains with the default `evm-native` policy, every resource is returned * unchanged. On chains whose canonical native asset is an ERC-20 (`as-erc20` * Tempo, `native-mirrored-erc20` Arc), a resource of kind `"native"` is * rewritten into the equivalent ERC-20 resource pointing at the chain's * stand-in token (PathUSD on Tempo, the USDC facade on Arc). * * This is the rewrite primitive behind the `ResourceSchema` decode transform * (see `flowSchema.ts`), which is THE chokepoint: it runs every time a * `Resource` is parsed — flow inputs via `FlowSchema`, op configs via * `decodeConfig` — so every downstream pass (`normalizeFlow`, `resolve`, * `lower`, `simulate`) sees only ERC-20 resources on those chains. * * The function preserves referential identity when nothing changes (returns the * input `r` unchanged on evm-native chains and for ERC-20 resources) and is * idempotent: running it on an already-rewritten resource is a no-op. */ const normalizeResource = (r) => { if (r.kind !== "native") return r; const erc20 = erc20CanonicalNative(getChainCapabilities(r.chainId)); if (erc20 === void 0) return r; return { kind: "erc20", chainId: r.chainId, token: erc20.token }; }; /** * Address-level counterpart of `normalizeResource` for wire fields that carry a * native asset as a bare token string (a continuation outcome's `token`). On * chains whose canonical native asset is an ERC-20, the native sentinel is * rewritten to the chain's stand-in ERC-20; every other address passes through. */ const normalizeNativeTokenAddress = (token, chainId) => hasErc20CanonicalNative(chainId) && isZeroAddress(token) ? canonicalNativeAddress(chainId) : token; //#endregion //#region src/hexPatterns.ts const BYTES32_LOWER_HEX = /^0x[0-9a-f]{64}$/; const EVM_ADDRESS_HEX = /^0x[0-9a-fA-F]{40}$/; const DECIMAL_UINT = /^[0-9]+$/; const MAX_UINT256 = 2n ** 256n - 1n; const MAX_DATE_MS = 864e13; //#endregion //#region src/flowSchema.ts const SolTypeSchema = effect.Schema.Literal("uint8", "uint16", "uint32", "uint64", "uint128", "uint256", "int128", "int256", "address", "bool", "bytes", "bytes4", "bytes32", "string"); const ChainIdSchema = effect.Schema.Number.pipe(effect.Schema.int(), effect.Schema.positive()); const EVMAddressString = effect.Schema.String.pipe(effect.Schema.pattern(EVM_ADDRESS_HEX, { message: () => "expected a 0x-prefixed 20-byte EVM address" })).annotations({ description: "EVM address: 0x followed by 40 hex characters" }); const EpochMsSchema = effect.Schema.Number.pipe(effect.Schema.int(), effect.Schema.between(-864e13, MAX_DATE_MS)); const IntegerString = effect.Schema.String.pipe(effect.Schema.filter((value) => { if (!DECIMAL_UINT.test(value)) return "amount must be a decimal integer string"; if (BigInt(value) > MAX_UINT256) return "amount must not exceed uint256 max"; })); const RawResourceSchema = effect.Schema.Union(effect.Schema.Struct({ kind: effect.Schema.Literal("native"), chainId: ChainIdSchema }), effect.Schema.Struct({ kind: effect.Schema.Literal("erc20"), token: EVMAddressString, chainId: ChainIdSchema })); /** * THE chain-capabilities chokepoint. * * `ResourceSchema` is a decode transform: it parses the plain `native | erc20` * wire union (`RawResourceSchema`) and then runs `normalizeResource`, so on * `as-erc20` chains (e.g. Tempo) a `{ kind: "native", chainId }` resource is * rewritten to its ERC-20 form (PathUSD) before any application code sees it. * Because every Resource-bearing schema embeds this one — `FlowSchema` for flow * inputs, op `configSchema`s for op configs — making the schema itself * chain-aware covers every parsed entry point in one place. * * The `encode` direction is the identity: the ERC-20 form is itself valid wire * format, and the rewrite is deliberately not reversible (we never want to * re-introduce a `native` resource when serialising). `JSONSchema.make` derives * the published wire format from the encoded (`from`) side, so the manifest * keeps advertising the plain union with both arms. */ const ResourceSchema = effect.Schema.transform(RawResourceSchema, effect.Schema.typeSchema(RawResourceSchema), { strict: true, decode: (raw) => normalizeResource(raw), encode: (resource) => resource }); const ResourceInputSchema = effect.Schema.Struct({ name: effect.Schema.String, resource: ResourceSchema }); const HandleInputSchema = effect.Schema.Struct({ name: effect.Schema.String, type: SolTypeSchema }); const FlowInputSchema = effect.Schema.Union(ResourceInputSchema, HandleInputSchema); const RefSchema = effect.Schema.Struct({ $ref: effect.Schema.String.pipe(effect.Schema.filter((s) => s.indexOf(".") > 0, { message: () => "$ref must be a dotpath like \"input.name\" or \"nodeId.port\"" })) }); const LiteralBindingSchema = effect.Schema.Struct({ kind: SolTypeSchema, value: effect.Schema.String }); const BindValueSchema = effect.Schema.Union(RefSchema, LiteralBindingSchema); const AppliedGuardSchema = effect.Schema.Struct({ kind: effect.Schema.String }, { key: effect.Schema.String, value: effect.Schema.Unknown }); const NodeIdSchema = effect.Schema.String.pipe(effect.Schema.filter((id) => id !== "__proto__", { message: () => "node id \"__proto__\" is reserved; choose another node id" }), effect.Schema.filter((id) => id.length > 0, { message: () => "node id must not be empty" })); const CallSchema = effect.Schema.Struct({ id: NodeIdSchema, op: effect.Schema.String, bind: effect.Schema.optionalWith(effect.Schema.Record({ key: effect.Schema.String, value: BindValueSchema }), { default: () => ({}) }), config: effect.Schema.optionalWith(effect.Schema.Record({ key: effect.Schema.String, value: effect.Schema.Unknown }), { default: () => ({}) }), guards: effect.Schema.optional(effect.Schema.Array(AppliedGuardSchema)) }); const UuidSchema = effect.Schema.String.pipe(effect.Schema.pattern(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/)); const LineageSchema = effect.Schema.Struct({ journeyId: UuidSchema, parentRequestId: UuidSchema }); const ForwardToSchema = effect.Schema.Union(EVMAddressString, RefSchema); const EpilogueForwardSchema = effect.Schema.Struct({ resource: ResourceSchema, to: ForwardToSchema }); const EpilogueSchema = effect.Schema.Struct({ forwards: effect.Schema.optional(effect.Schema.NonEmptyArray(EpilogueForwardSchema)), remainder: effect.Schema.optional(ForwardToSchema) }).pipe(effect.Schema.filter((e) => e.forwards !== void 0 || e.remainder !== void 0, { message: () => "epilogue needs forwards, a remainder, or both" })); const FlowSchema = effect.Schema.Struct({ version: effect.Schema.Literal(1), id: effect.Schema.String, chainId: ChainIdSchema, inputs: effect.Schema.Array(FlowInputSchema), nodes: effect.Schema.Array(CallSchema), lineage: effect.Schema.optional(LineageSchema), epilogue: effect.Schema.optional(EpilogueSchema) }); //#endregion //#region src/continuation.ts const CONTINUATION_COMMITMENT_OP_ID = "continuation.commitment"; const outcomeFields = (minAmount) => ({ token: EVMAddressString, minAmount, destination: EVMAddressString, chainId: ChainIdSchema }); const normalizingOutcome = (raw) => effect.Schema.transform(raw, effect.Schema.typeSchema(raw), { strict: true, decode: (outcome) => ({ ...outcome, token: normalizeNativeTokenAddress(outcome.token, outcome.chainId) }), encode: (outcome) => outcome }); const ContinuationOutcomeSchema = normalizingOutcome(effect.Schema.Struct(outcomeFields(effect.Schema.optional(IntegerString)))); const CommittedOutcomeSchema = normalizingOutcome(effect.Schema.Struct(outcomeFields(IntegerString))); const ContinuationIntentSchema = effect.Schema.Struct({ outcomes: effect.Schema.Array(ContinuationOutcomeSchema), continuationFlow: effect.Schema.optional(FlowSchema), validity: effect.Schema.Struct({ expiresAtMs: EpochMsSchema }), provider: effect.Schema.optional(effect.Schema.String), funding: effect.Schema.optional(effect.Schema.Literal("inline", "external")), refund: effect.Schema.optional(EVMAddressString.pipe(effect.Schema.filter((address) => !isZeroAddress(address), { message: () => "refund must not be the zero address" }))), exact: effect.Schema.optional(effect.Schema.Boolean) }); const HexStringSchema = effect.Schema.String.pipe(effect.Schema.startsWith("0x")); const Phase1EscrowSchema = effect.Schema.Struct({ chainId: ChainIdSchema, address: HexStringSchema, token: HexStringSchema, amount: effect.Schema.String, cap: effect.Schema.String, floor: effect.Schema.String, owner: HexStringSchema, refund: HexStringSchema, expiresAtMs: effect.Schema.Number.pipe(effect.Schema.int(), effect.Schema.positive()) }); const Phase1BindingSchema = effect.Schema.Struct({ executionTarget: HexStringSchema, payload: HexStringSchema, payloadHash: HexStringSchema, calldata: HexStringSchema, approvals: effect.Schema.Array(effect.Schema.Struct({ token: HexStringSchema, spender: HexStringSchema })) }); const Phase1ArtifactSchema = effect.Schema.Union(effect.Schema.Struct({ kind: effect.Schema.Literal("transaction"), funding: effect.Schema.Literal("inline", "external", "delivered"), transactionRequest: effect.Schema.optional(effect.Schema.Struct({ to: effect.Schema.String, data: effect.Schema.String, value: effect.Schema.String, chainId: effect.Schema.Number })), escrow: effect.Schema.optional(Phase1EscrowSchema), binding: effect.Schema.optional(Phase1BindingSchema) }), effect.Schema.Struct({ kind: effect.Schema.Literal("signables"), typedData: effect.Schema.Array(effect.Schema.Unknown) }), effect.Schema.Struct({ kind: effect.Schema.Literal("none") })); const AssertionOwnerSchema = effect.Schema.Union(EVMAddressString, effect.Schema.Literal("escrow", "delivery")); const Erc20BalanceGteSpecSchema = effect.Schema.Struct({ kind: effect.Schema.Literal("erc20BalanceGte"), chainId: ChainIdSchema, token: EVMAddressString, owner: AssertionOwnerSchema, minAmount: IntegerString }); const NativeBalanceGteSpecSchema = effect.Schema.Struct({ kind: effect.Schema.Literal("nativeBalanceGte"), chainId: ChainIdSchema, owner: AssertionOwnerSchema, minAmount: IntegerString }); const CallCheckSpecSchema = effect.Schema.Struct({ kind: effect.Schema.Literal("call"), chainId: ChainIdSchema, to: EVMAddressString, signature: effect.Schema.String, args: effect.Schema.Array(effect.Schema.String), comparator: effect.Schema.Literal("gte", "eq", "lte"), threshold: IntegerString }); const asErc20BalanceGteCheck = (check, token) => ({ kind: "erc20BalanceGte", chainId: check.chainId, token, owner: check.owner, minAmount: check.minAmount }); const decodeNativeBalanceGte = (check, ast) => { const policy = nativeCheckPolicy(check.chainId); switch (policy.kind) { case "keep": return effect.ParseResult.succeed(check); case "rewrite": return effect.ParseResult.succeed(asErc20BalanceGteCheck(check, policy.token)); case "reject": return effect.ParseResult.fail(new effect.ParseResult.Type(ast, check, policy.reason)); } }; const AssertionSpecSchema = effect.Schema.Union(Erc20BalanceGteSpecSchema, NativeBalanceGteSpecSchema, CallCheckSpecSchema); const settledOutcome = (intent) => intent.outcomes[0]; //#endregion //#region src/descriptor.ts const Bytes32HexSchema = effect.Schema.String.pipe(effect.Schema.pattern(BYTES32_LOWER_HEX)); const AssertedPredicateSchema = effect.Schema.transformOrFail(AssertionSpecSchema, effect.Schema.typeSchema(AssertionSpecSchema), { strict: true, decode: (pred, _options, ast) => pred.kind === "nativeBalanceGte" ? decodeNativeBalanceGte(pred, ast) : effect.ParseResult.succeed(pred), encode: (pred) => effect.ParseResult.succeed(pred) }); const VerificationDescriptorSchema = effect.Schema.Struct({ validationProgramHash: Bytes32HexSchema, paramsHash: Bytes32HexSchema, assertedPredicate: effect.Schema.Array(AssertedPredicateSchema) }); const canonicalJson = (value) => { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (value !== null && typeof value === "object") { const record = value; return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`; } return JSON.stringify(value); }; const canonicalAssertedPredicate = (specs) => canonicalJson(specs); //#endregion //#region src/flow.ts const isResourceInput = (input) => "resource" in input; const flowInputType = (input) => isResourceInput(input) ? "uint256" : input.type; const flowInputMode = (input) => isResourceInput(input) ? "linear" : "copy"; const flowInputResource = (input) => isResourceInput(input) ? input.resource : void 0; const isResourcePort = (port) => port.kind === "resource"; const isHandlePort = (port) => port.kind === "handle"; const isResourceOutputPort = (port) => port.kind === "resource_output"; const isFutureResourceOutput = (port) => isResourceOutputPort(port) && port.availability === "future"; const isMaterialiserInput = (s) => typeof s === "object" && s !== null && "kind" in s; //#endregion //#region src/resource.ts const erc20Resource = (token, chainId) => ({ kind: "erc20", token, chainId }); const nativeResource = (chainId) => ({ kind: "native", chainId }); const isERC20Resource = (r) => r.kind === "erc20"; const isNativeResource = (r) => r.kind === "native"; const resourcesEqual = (a, b) => { switch (a.kind) { case "native": return b.kind === "native" && a.chainId === b.chainId; case "erc20": return b.kind === "erc20" && a.chainId === b.chainId && a.token.toLowerCase() === b.token.toLowerCase(); } }; const foldResource = (r, cases) => { switch (r.kind) { case "native": return cases.native(r); case "erc20": return cases.erc20(r); } }; const resourceToken = (r) => foldResource(r, { native: () => EVM_NATIVE_SENTINEL, erc20: ({ token }) => token }); const resourceKey = (r) => foldResource(r, { native: ({ chainId }) => `native:${chainId}`, erc20: ({ token, chainId }) => `erc20:${token.toLowerCase()}:${chainId}` }); const erc20Token = (r) => { if (r.kind !== "erc20") throw new Error(`Expected erc20 resource, got ${r.kind}`); return r.token; }; //#endregion //#region src/flashloan.ts const PROVIDER_KIND = { AAVE_V3: 0, ERC3156: 1, BALANCER_V2: 2, MORPHO_BLUE: 3 }; const providerKindNames = [ "aave-v3", "erc3156", "balancer-v2", "morpho-blue" ]; const providerKindByName = { "aave-v3": PROVIDER_KIND.AAVE_V3, erc3156: PROVIDER_KIND.ERC3156, "balancer-v2": PROVIDER_KIND.BALANCER_V2, "morpho-blue": PROVIDER_KIND.MORPHO_BLUE }; //#endregion //#region src/constructors.ts /** Returns `{ [key]: value }` when `value` is not nullish, else `{}`. */ const optionalProp = (key, value) => value !== void 0 && value !== null ? { [key]: value } : {}; const linear = (name, type) => ({ name, type, mode: "linear", availability: "now" }); const copy = (name, type) => ({ name, type, mode: "copy", availability: "now" }); const handle = (name, type) => ({ name, type }); const native = (name, chainId) => ({ name, resource: nativeResource(chainId) }); const erc20 = (name, token, chainId) => ({ name, resource: erc20Resource(token, chainId) }); const resource = (name, accepts, options) => ({ kind: "resource", name, accepts, mode: "linear", ...optionalProp("optional", options?.optional) }); const readResource = (name, accepts) => ({ kind: "resource", name, accepts, mode: "copy" }); const opHandle = (name, type, options) => ({ kind: "handle", name, type, mode: "copy", ...optionalProp("expose", options?.expose), ...optionalProp("units", options?.units), ...optionalProp("optional", options?.optional) }); const resourceOutput = (name, options) => { const raw = options; const opts = typeof raw === "string" ? { availability: raw } : raw; return { kind: "resource_output", name, mode: "linear", ...optionalProp("availability", opts?.availability), ...optionalProp("providesMinimum", opts?.providesMinimum), ...optionalProp("omitIfZero", opts?.omitIfZero), ...optionalProp("deliveryAddressInput", opts?.deliveryAddressInput), ...optionalProp("countFrom", opts?.countFrom) }; }; //#endregion //#region src/outputFamilies.ts const isOutputFamily = (port) => port.kind === "resource_output" && port.countFrom !== void 0; const instancePortName = (family, index) => `${family}.${index}`; const familySize = (family, config) => { const source = config[family.countFrom]; if (Array.isArray(source)) return source.length; if (Number.isSafeInteger(source) && source >= 0) return source; throw new Error(`Output family '${family.name}' counts from config '${family.countFrom}', which is neither an array nor a non-negative integer`); }; const expandFamily = (port, config) => { const { countFrom: _countFrom, ...instance } = port; return Array.from({ length: familySize(port, config) }, (_, index) => ({ ...instance, name: instancePortName(port.name, index) })); }; const expandOutputPorts = (declared, config) => declared.some(isOutputFamily) ? declared.flatMap((port) => isOutputFamily(port) ? expandFamily(port, config) : [port]) : declared; //#endregion //#region src/ref.ts const isContextKey = (key) => key === "sender" || key === "executionAddress"; /** * Ref prefixes that parseRef intercepts before the fallback `output` scope. * A node whose id matches one of these would produce ambiguous refs * (e.g. `context.sender` could be a context ref or node-output ref). * Validation must reject these as node ids. */ const RESERVED_REF_SCOPES = /* @__PURE__ */ new Set([ "input", "context", "literal" ]); const isRef = (v) => typeof v === "object" && v !== null && "$ref" in v && typeof v.$ref === "string"; const parseRef = (ref) => { const dot = ref.$ref.indexOf("."); if (dot === -1) throw new Error(`Invalid ref: "${ref.$ref}" (must contain a dot)`); const prefix = ref.$ref.slice(0, dot); const suffix = ref.$ref.slice(dot + 1); if (prefix === "input") return { scope: "input", port: suffix }; if (prefix === "context") { if (!isContextKey(suffix)) throw new Error(`Unknown context key: "${suffix}"`); return { scope: "context", key: suffix }; } return { scope: "output", node: prefix, port: suffix }; }; const buildRef = (path) => { if (path.indexOf(".") < 1) throw new Error(`Invalid ref: "${path}" (must be a dotpath like "input.name" or "nodeId.port")`); const built = { $ref: path }; parseRef(built); return built; }; const ref = Object.assign(buildRef, { input: (port) => buildRef(`input.${port}`), context: { sender: buildRef("context.sender"), executionAddress: buildRef("context.executionAddress") } }); const foldRef = (ref, cases) => { if (ref.scope === "input") return cases.input(ref.port); if (ref.scope === "context") return cases.context(ref.key); return cases.output(ref.node, ref.port); }; const refKey = (ref) => foldRef(parseRef(ref), { input: (port) => `input:${port}`, context: (key) => `context:${key}`, output: (node, port) => `output:${node}:${port}` }); //#endregion //#region src/preconditions.ts const erc20Balance = (config) => ({ type: "Erc20Balance", ...config }); const nativeBalance = (config) => ({ type: "NativeBalance", ...config }); const erc20Allowance = (config) => ({ type: "Erc20Allowance", ...config }); const isErc20BalancePrecondition = (p) => p.type === "Erc20Balance"; const isErc20AllowancePrecondition = (p) => p.type === "Erc20Allowance"; const isNativeBalancePrecondition = (p) => p.type === "NativeBalance"; //#endregion //#region src/simulate.ts /** * Maximum number of watched `(token, owner)` pairs accepted by `POST /simulate`. * * The limit comes from the VM's hard register budget (~123 usable registers, * checked on the final ISA layout). Each pair costs two result registers — a * before-read and an after-read — that are both live at the closing abi-encode, * so the compiler cannot coalesce them; that `2 × N` is the cost that scales. * Token and owner address literals do not scale it, since constant-propagation * merges identical-valued literals into one register. The cap leaves headroom * for the inner-call / gas-measurement / abi-encode scaffolding. */ const SIMULATE_MAX_TRACKED_BALANCES = 40; /** * Maximum number of funding `requirements` accepted by `POST /simulate`. * * Each requirement triggers a slot-discovery cycle (access-list probe + sentinel * verification + RPC round trips) in slot-finder, so an unbounded array lets a * single request amplify into arbitrary upstream RPC work. Bounded here at the * trust boundary and re-enforced server-side in `rawSimulation.ts`. */ const SIMULATE_MAX_REQUIREMENTS = 40; //#endregion //#region src/headers.ts /** * HTTP header names on the compose wire. * * Both the SDK (which sends the request header) and the backend (which reads it * and answers with the response header) are part of the same handshake, so the * names belong to the wire format rather than to either side of it. */ /** Compose contract version the client was built against. Sent on every request. */ const COMPOSER_SDK_VERSION_HEADER = "x-lifi-composer-sdk"; /** Compose contract version the backend serves. Returned on every compose response. */ const COMPOSE_VERSION_HEADER = "x-lifi-composer-version"; //#endregion //#region src/version.ts const SEMANTIC_VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; /** * Parses the numeric triple of a semantic version. Prerelease and build * suffixes are accepted and ignored: `0.5.1-staging.3` compares as `0.5.1`. * Returns `undefined` for anything that is not a complete semver string, * including the `dev` sentinel the SDK sends when it runs unbundled. */ const parseVersion = (version) => { const match = SEMANTIC_VERSION_PATTERN.exec(version); if (!match) return void 0; const major = Number(match[1]); const minor = Number(match[2]); const patch = Number(match[3]); if (![ major, minor, patch ].every(Number.isSafeInteger)) return void 0; return { major, minor, patch }; }; const compareVersions = (a, b) => a.major !== b.major ? a.major - b.major : a.minor !== b.minor ? a.minor - b.minor : a.patch - b.patch; /** * Decides whether a client built against `client` may talk to a server that * serves `server` and accepts clients down to `minimum`. * * - A client ahead of the server in any component is `server_outdated`. Even * a patch-ahead client may send a field the server has never seen, and the * guarantee must not depend on every server schema staying strict. This is * the rollout window between an npm publish and the prod image bump. * - A client below `minimum` is `sdk_outdated`: the server no longer serves * the contract that client speaks. * - Anything in between is compatible. Patch releases only add, so a client * at or behind the server's patch never emits anything the server lacks; * a client on an older minor is served because the server still emits the * shapes that minor reads. * * `minimum` defaults to the server's own `major.minor.0`, which makes every * minor bump a hard cutover. The backend passes its explicit floor so a minor * bump can ship with the previous line still accepted; the SDK passes no floor * because the server, not the client, decides how far back it serves. */ const checkCompatibility = (client, server, minimum = { major: server.major, minor: server.minor, patch: 0 }) => { if (compareVersions(client, server) > 0) return "server_outdated"; if (compareVersions(client, minimum) < 0) return "sdk_outdated"; return "compatible"; }; //#endregion //#region src/materialiserMetadata.ts const foldMaterialiserMetadata = (meta, cases) => { if (meta.kind === "exact") return cases.exact(meta.amount); if (meta.kind === "exact-native") return cases.exactNative(meta.amount); if (meta.kind === "capped") return cases.capped(meta.amount, meta.min); return cases.runtime(meta.min); }; //#endregion //#region src/zodSchemas.ts const chainIdZod = zod.default.number().int().positive(); const evmAddressZod = zod.default.string().regex(EVM_ADDRESS_HEX); const uintStringZod = zod.default.string().refine((value) => DECIMAL_UINT.test(value) && BigInt(value) <= MAX_UINT256, { message: "expected a uint256 decimal integer string" }); const SolTypeZod = zod.default.enum([ "uint8", "uint16", "uint32", "uint64", "uint128", "uint256", "int128", "int256", "address", "bool", "bytes", "bytes4", "bytes32", "string" ]); const ResourcePortZod = zod.default.object({ kind: zod.default.literal("resource"), name: zod.default.string(), accepts: zod.default.enum([ "erc20", "native", "any" ]), mode: zod.default.enum(["linear", "copy"]), optional: zod.default.boolean().optional() }); const HANDLE_UNITS = [ "raw", "wad", "ray", "bps", "token-decimals" ]; const STATIC_SOL_TYPES = [ "uint256", "uint128", "uint64", "uint32", "uint16", "uint8", "address", "bool", "bytes32" ]; const HandleUnitsZod = zod.default.enum(HANDLE_UNITS); const StaticSolTypeZod = zod.default.enum(STATIC_SOL_TYPES); const STATIC_SOL_TYPE_SET = new Set(STATIC_SOL_TYPES); const isStaticSolType = (value) => STATIC_SOL_TYPE_SET.has(value); const HandlePortZod = zod.default.object({ kind: zod.default.literal("handle"), name: zod.default.string(), type: SolTypeZod, mode: zod.default.enum(["linear", "copy"]), expose: zod.default.boolean().optional(), units: HandleUnitsZod.optional(), optional: zod.default.boolean().optional() }); const InputPortZod = zod.default.discriminatedUnion("kind", [ResourcePortZod, HandlePortZod]); const ResourceOutputPortZod = zod.default.object({ kind: zod.default.literal("resource_output"), name: zod.default.string(), mode: zod.default.enum(["linear", "copy"]), availability: zod.default.enum(["now", "future"]).optional(), providesMinimum: zod.default.boolean().optional(), omitIfZero: zod.default.boolean().optional(), deliveryAddressInput: zod.default.string().optional(), countFrom: zod.default.string().optional() }); const OutputPortZod = zod.default.discriminatedUnion("kind", [ResourceOutputPortZod, HandlePortZod]); const ManifestOperationZod = zod.default.object({ id: zod.default.string(), description: zod.default.string().optional(), inputs: zod.default.array(InputPortZod), outputs: zod.default.array(OutputPortZod), configSchema: zod.default.unknown().optional() }); const PortKindEnum = zod.default.enum([ "resource", "resource_output", "handle" ]); const SelectorMatchZod = zod.default.object({ kind: zod.default.union([PortKindEnum, zod.default.array(PortKindEnum)]), mode: zod.default.enum(["linear", "copy"]).optional(), type: zod.default.enum([ "erc20", "native", "any" ]).optional() }); const ConfigSelectionZod = zod.default.object({ kind: zod.default.literal("config"), configKey: zod.default.string(), cardinality: zod.default.enum(["one", "many"]) }); const AllMatchingSelectionZod = zod.default.object({ kind: zod.default.literal("all_matching") }); const SelectorSelectionZod = zod.default.discriminatedUnion("kind", [ConfigSelectionZod, AllMatchingSelectionZod]); const GuardSelectorZod = zod.default.object({ binding: zod.default.string(), source: zod.default.enum(["inputs", "outputs"]), match: SelectorMatchZod, selection: SelectorSelectionZod }); const GuardCompatibilityZod = zod.default.object({ selectors: zod.default.array(GuardSelectorZod) }); const ManifestGuardZod = zod.default.object({ kind: zod.default.string(), description: zod.default.string().optional(), configSchema: zod.default.unknown().optional(), compatibility: GuardCompatibilityZod.optional() }); const ManifestMaterialiserZod = zod.default.object({ kind: zod.default.string(), description: zod.default.string().optional(), accepts: zod.default.enum([ "resource", "handle", "any" ]), configSchema: zod.default.unknown().optional() }); const ManifestPreconditionZod = zod.default.object({ type: zod.default.string(), description: zod.default.string().optional(), configSchema: zod.default.unknown().optional() }); const ManifestRoutingZod = zod.default.object({ maxRouteHops: zod.default.number().int().min(1), swapHops: zod.default.enum(["head", "none"]) }); const ComposeManifestZod = zod.default.object({ manifestVersion: zod.default.number(), manifestHash: zod.default.string(), flowSchema: zod.default.object({}).passthrough(), operations: zod.default.array(ManifestOperationZod), guards: zod.default.array(ManifestGuardZod), materialisers: zod.default.array(ManifestMaterialiserZod), preconditions: zod.default.array(ManifestPreconditionZod).optional(), routing: ManifestRoutingZod.optional() }); const hexStringZod = zod.default.string().startsWith("0x"); const SettlementEscrowZod = zod.default.object({ chainId: chainIdZod, address: hexStringZod, token: hexStringZod, amount: zod.default.string(), cap: zod.default.string(), floor: zod.default.string(), owner: hexStringZod, refund: hexStringZod, expiresAtMs: zod.default.number().int().positive() }); const SettlementBindingZod = zod.default.object({ executionTarget: hexStringZod, payload: hexStringZod, payloadHash: hexStringZod, calldata: hexStringZod, approvals: zod.default.array(zod.default.object({ token: hexStringZod, spender: hexStringZod })).readonly() }); const assertionOwnerZod = zod.default.union([evmAddressZod, zod.default.enum(["escrow", "delivery"])]); const AssertionSpecZod = zod.default.discriminatedUnion("kind", [ zod.default.object({ kind: zod.default.literal("erc20BalanceGte"), chainId: chainIdZod, token: evmAddressZod, owner: assertionOwnerZod, minAmount: uintStringZod }), zod.default.object({ kind: zod.default.literal("nativeBalanceGte"), chainId: chainIdZod, owner: assertionOwnerZod, minAmount: uintStringZod }), zod.default.object({ kind: zod.default.literal("call"), chainId: chainIdZod, to: evmAddressZod, signature: zod.default.string(), args: zod.default.array(zod.default.string()).readonly(), comparator: zod.default.enum([ "gte", "eq", "lte" ]), threshold: uintStringZod }) ]); const VerificationDescriptorZod = zod.default.object({ validationProgramHash: zod.default.string().regex(BYTES32_LOWER_HEX), paramsHash: zod.default.string().regex(BYTES32_LOWER_HEX), assertedPredicate: zod.default.array(AssertionSpecZod).readonly() }); const SettlementZod = zod.default.object({ escrow: SettlementEscrowZod.optional(), binding: SettlementBindingZod.optional() }); const ShortfallZod = zod.default.object({ required: zod.default.string(), available: zod.default.string() }); //#endregion exports.ARC_CHAIN_ID = ARC_CHAIN_ID; exports.ARC_NATIVE_ERC20 = ARC_NATIVE_ERC20; exports.ARC_NATIVE_SCALE = ARC_NATIVE_SCALE; exports.AppliedGuardSchema = AppliedGuardSchema; exports.AssertedPredicateSchema = AssertedPredicateSchema; exports.AssertionOwnerSchema = AssertionOwnerSchema; exports.AssertionSpecSchema = AssertionSpecSchema; exports.AssertionSpecZod = AssertionSpecZod; exports.BindValueSchema = BindValueSchema; exports.Bytes32HexSchema = Bytes32HexSchema; exports.COMPOSER_SDK_VERSION_HEADER = COMPOSER_SDK_VERSION_HEADER; exports.COMPOSE_VERSION_HEADER = COMPOSE_VERSION_HEADER; exports.CONTINUATION_COMMITMENT_OP_ID = CONTINUATION_COMMITMENT_OP_ID; exports.CallCheckSpecSchema = CallCheckSpecSchema; exports.CallSchema = CallSchema; exports.CommittedOutcomeSchema = CommittedOutcomeSchema; exports.ComposeManifestZod = ComposeManifestZod; exports.ContinuationIntentSchema = ContinuationIntentSchema; exports.ContinuationOutcomeSchema = ContinuationOutcomeSchema; exports.EVMAddressString = EVMAddressString; exports.EVM_NATIVE_SENTINEL = EVM_NATIVE_SENTINEL; exports.EpilogueForwardSchema = EpilogueForwardSchema; exports.EpilogueSchema = EpilogueSchema; exports.Erc20BalanceGteSpecSchema = Erc20BalanceGteSpecSchema; exports.FlowInputSchema = FlowInputSchema; exports.FlowSchema = FlowSchema; exports.ForwardToSchema = ForwardToSchema; exports.GuardCompatibilityZod = GuardCompatibilityZod; exports.GuardSelectorZod = GuardSelectorZod; exports.HANDLE_UNITS = HANDLE_UNITS; exports.HandleInputSchema = HandleInputSchema; exports.HandlePortZod = HandlePortZod; exports.HandleUnitsZod = HandleUnitsZod; exports.HexStringSchema = HexStringSchema; exports.InputPortZod = InputPortZod; exports.IntegerString = IntegerString; exports.LineageSchema = LineageSchema; exports.LiteralBindingSchema = LiteralBindingSchema; exports.ManifestGuardZod = ManifestGuardZod; exports.ManifestMaterialiserZod = ManifestMaterialiserZod; exports.ManifestOperationZod = ManifestOperationZod; exports.ManifestPreconditionZod = ManifestPreconditionZod; exports.ManifestRoutingZod = ManifestRoutingZod; exports.NativeBalanceGteSpecSchema = NativeBalanceGteSpecSchema; exports.OutputPortZod = OutputPortZod; exports.PROVIDER_KIND = PROVIDER_KIND; exports.Phase1ArtifactSchema = Phase1ArtifactSchema; exports.RESERVED_REF_SCOPES = RESERVED_REF_SCOPES; exports.RefSchema = RefSchema; exports.ResourceInputSchema = ResourceInputSchema; exports.ResourceOutputPortZod = ResourceOutputPortZod; exports.ResourcePortZod = ResourcePortZod; exports.ResourceSchema = ResourceSchema; exports.SIMULATE_MAX_REQUIREMENTS = SIMULATE_MAX_REQUIREMENTS; exports.SIMULATE_MAX_TRACKED_BALANCES = SIMULATE_MAX_TRACKED_BALANCES; exports.STATIC_SOL_TYPES = STATIC_SOL_TYPES; exports.SettlementZod = SettlementZod; exports.ShortfallZod = ShortfallZod; exports.SolTypeSchema = SolTypeSchema; exports.StaticSolTypeZod = StaticSolTypeZod; exports.TEMPO_CHAIN_ID = TEMPO_CHAIN_ID; exports.TEMPO_NATIVE_ERC20 = TEMPO_NATIVE_ERC20; exports.UuidSchema = UuidSchema; exports.VerificationDescriptorSchema = VerificationDescriptorSchema; exports.VerificationDescriptorZod = VerificationDescriptorZod; exports.canonicalAssertedPredicate = canonicalAssertedPredicate; exports.canonicalNativeAddress = canonicalNativeAddress; exports.checkCompatibility = checkCompatibility; exports.copy = copy; exports.erc20 = erc20; exports.erc20Allowance = erc20Allowance; exports.erc20Balance = erc20Balance; exports.erc20Resource = erc20Resource; exports.erc20Token = erc20Token; exports.expandOutputPorts = expandOutputPorts; exports.familySize = familySize; exports.flowInputMode = flowInputMode; exports.flowInputResource = flowInputResource; exports.flowInputType = flowInputType; exports.foldChainCapabilities = foldChainCapabilities; exports.foldMaterialiserMetadata = foldMaterialiserMetadata; exports.foldRef = foldRef; exports.foldResource = foldResource; exports.getChainCapabilities = getChainCapabilities; exports.handle = handle; exports.hasErc20CanonicalNative = hasErc20CanonicalNative; exports.instancePortName = instancePortName; exports.isAsErc20Chain = isAsErc20Chain; exports.isContextKey = isContextKey; exports.isERC20Resource = isERC20Resource; exports.isErc20AllowancePrecondition = isErc20AllowancePrecondition; exports.isErc20BalancePrecondition = isErc20BalancePrecondition; exports.isFutureResourceOutput = isFutureResourceOutput; exports.isHandlePort = isHandlePort; exports.isMaterialiserInput = isMaterialiserInput; exports.isMsgValueNative = isMsgValueNative; exports.isNativeAddressForChain = isNativeAddressForChain; exports.isNativeBalancePrecondition = isNativeBalancePrecondition; exports.isNativeResource = isNativeResource; exports.isOutputFamily = isOutputFamily; exports.isRef = isRef; exports.isResourceInput = isResourceInput; exports.isResourceOutputPort = isResourceOutputPort; exports.isResourcePort = isResourcePort; exports.isStaticSolType = isStaticSolType; exports.linear = linear; exports.native = native; exports.nativeBalance = nativeBalance; exports.nativeCheckPolicy = nativeCheckPolicy; exports.nativeResource = nativeResource; exports.normalizeNativeTokenAddress = normalizeNativeTokenAddress; exports.normalizeResource = normalizeResource; exports.opHandle = opHandle; exports.parseRef = parseRef; exports.parseVersion = parseVersion; exports.providerKindByName = providerKindByName; exports.providerKindNames = providerKindNames; exports.readResource = readResource; exports.ref = ref; exports.refKey = refKey; exports.resource = resource; exports.resourceKey = resourceKey; exports.resourceOutput = resourceOutput; exports.resourceToken = resourceToken; exports.resourcesEqual = resourcesEqual; exports.settledOutcome = settledOutcome;