@lifi/compose-spec
Version:
Public wire-format types and schemas for Compose flows
947 lines (946 loc) • 38.2 kB
JavaScript
import { ParseResult, Schema } from "effect";
import z from "zod";
// 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;
// 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;
// src/flowSchema.ts
const SolTypeSchema = Schema.Literal("uint8", "uint16", "uint32", "uint64", "uint128", "uint256", "int128", "int256", "address", "bool", "bytes", "bytes4", "bytes32", "string");
const ChainIdSchema = Schema.Number.pipe(Schema.int(), Schema.positive());
const EVMAddressString = Schema.String.pipe(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 = Schema.Number.pipe(Schema.int(), Schema.between(-864e13, MAX_DATE_MS));
const IntegerString = Schema.String.pipe(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 = Schema.Union(Schema.Struct({
kind: Schema.Literal("native"),
chainId: ChainIdSchema
}), Schema.Struct({
kind: 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 = Schema.transform(RawResourceSchema, Schema.typeSchema(RawResourceSchema), {
strict: true,
decode: (raw) => normalizeResource(raw),
encode: (resource) => resource
});
const ResourceInputSchema = Schema.Struct({
name: Schema.String,
resource: ResourceSchema
});
const HandleInputSchema = Schema.Struct({
name: Schema.String,
type: SolTypeSchema
});
const FlowInputSchema = Schema.Union(ResourceInputSchema, HandleInputSchema);
const RefSchema = Schema.Struct({ $ref: Schema.String.pipe(Schema.filter((s) => s.indexOf(".") > 0, { message: () => "$ref must be a dotpath like \"input.name\" or \"nodeId.port\"" })) });
const LiteralBindingSchema = Schema.Struct({
kind: SolTypeSchema,
value: Schema.String
});
const BindValueSchema = Schema.Union(RefSchema, LiteralBindingSchema);
const AppliedGuardSchema = Schema.Struct({ kind: Schema.String }, {
key: Schema.String,
value: Schema.Unknown
});
const NodeIdSchema = Schema.String.pipe(Schema.filter((id) => id !== "__proto__", { message: () => "node id \"__proto__\" is reserved; choose another node id" }), Schema.filter((id) => id.length > 0, { message: () => "node id must not be empty" }));
const CallSchema = Schema.Struct({
id: NodeIdSchema,
op: Schema.String,
bind: Schema.optionalWith(Schema.Record({
key: Schema.String,
value: BindValueSchema
}), { default: () => ({}) }),
config: Schema.optionalWith(Schema.Record({
key: Schema.String,
value: Schema.Unknown
}), { default: () => ({}) }),
guards: Schema.optional(Schema.Array(AppliedGuardSchema))
});
const UuidSchema = Schema.String.pipe(Schema.pattern(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/));
const LineageSchema = Schema.Struct({
journeyId: UuidSchema,
parentRequestId: UuidSchema
});
const ForwardToSchema = Schema.Union(EVMAddressString, RefSchema);
const EpilogueForwardSchema = Schema.Struct({
resource: ResourceSchema,
to: ForwardToSchema
});
const EpilogueSchema = Schema.Struct({
forwards: Schema.optional(Schema.NonEmptyArray(EpilogueForwardSchema)),
remainder: Schema.optional(ForwardToSchema)
}).pipe(Schema.filter((e) => e.forwards !== void 0 || e.remainder !== void 0, { message: () => "epilogue needs forwards, a remainder, or both" }));
const FlowSchema = Schema.Struct({
version: Schema.Literal(1),
id: Schema.String,
chainId: ChainIdSchema,
inputs: Schema.Array(FlowInputSchema),
nodes: Schema.Array(CallSchema),
lineage: Schema.optional(LineageSchema),
epilogue: Schema.optional(EpilogueSchema)
});
// src/continuation.ts
const CONTINUATION_COMMITMENT_OP_ID = "continuation.commitment";
const outcomeFields = (minAmount) => ({
token: EVMAddressString,
minAmount,
destination: EVMAddressString,
chainId: ChainIdSchema
});
const normalizingOutcome = (raw) => Schema.transform(raw, Schema.typeSchema(raw), {
strict: true,
decode: (outcome) => ({
...outcome,
token: normalizeNativeTokenAddress(outcome.token, outcome.chainId)
}),
encode: (outcome) => outcome
});
const ContinuationOutcomeSchema = normalizingOutcome(Schema.Struct(outcomeFields(Schema.optional(IntegerString))));
const CommittedOutcomeSchema = normalizingOutcome(Schema.Struct(outcomeFields(IntegerString)));
const ContinuationIntentSchema = Schema.Struct({
outcomes: Schema.Array(ContinuationOutcomeSchema),
continuationFlow: Schema.optional(FlowSchema),
validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
provider: Schema.optional(Schema.String),
funding: Schema.optional(Schema.Literal("inline", "external")),
refund: Schema.optional(EVMAddressString.pipe(Schema.filter((address) => !isZeroAddress(address), { message: () => "refund must not be the zero address" }))),
exact: Schema.optional(Schema.Boolean)
});
const HexStringSchema = Schema.String.pipe(Schema.startsWith("0x"));
const Phase1EscrowSchema = Schema.Struct({
chainId: ChainIdSchema,
address: HexStringSchema,
token: HexStringSchema,
amount: Schema.String,
cap: Schema.String,
floor: Schema.String,
owner: HexStringSchema,
refund: HexStringSchema,
expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive())
});
const Phase1BindingSchema = Schema.Struct({
executionTarget: HexStringSchema,
payload: HexStringSchema,
payloadHash: HexStringSchema,
calldata: HexStringSchema,
approvals: Schema.Array(Schema.Struct({
token: HexStringSchema,
spender: HexStringSchema
}))
});
const Phase1ArtifactSchema = Schema.Union(Schema.Struct({
kind: Schema.Literal("transaction"),
funding: Schema.Literal("inline", "external", "delivered"),
transactionRequest: Schema.optional(Schema.Struct({
to: Schema.String,
data: Schema.String,
value: Schema.String,
chainId: Schema.Number
})),
escrow: Schema.optional(Phase1EscrowSchema),
binding: Schema.optional(Phase1BindingSchema)
}), Schema.Struct({
kind: Schema.Literal("signables"),
typedData: Schema.Array(Schema.Unknown)
}), Schema.Struct({ kind: Schema.Literal("none") }));
const AssertionOwnerSchema = Schema.Union(EVMAddressString, Schema.Literal("escrow", "delivery"));
const Erc20BalanceGteSpecSchema = Schema.Struct({
kind: Schema.Literal("erc20BalanceGte"),
chainId: ChainIdSchema,
token: EVMAddressString,
owner: AssertionOwnerSchema,
minAmount: IntegerString
});
const NativeBalanceGteSpecSchema = Schema.Struct({
kind: Schema.Literal("nativeBalanceGte"),
chainId: ChainIdSchema,
owner: AssertionOwnerSchema,
minAmount: IntegerString
});
const CallCheckSpecSchema = Schema.Struct({
kind: Schema.Literal("call"),
chainId: ChainIdSchema,
to: EVMAddressString,
signature: Schema.String,
args: Schema.Array(Schema.String),
comparator: 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 ParseResult.succeed(check);
case "rewrite": return ParseResult.succeed(asErc20BalanceGteCheck(check, policy.token));
case "reject": return ParseResult.fail(new ParseResult.Type(ast, check, policy.reason));
}
};
const AssertionSpecSchema = Schema.Union(Erc20BalanceGteSpecSchema, NativeBalanceGteSpecSchema, CallCheckSpecSchema);
// src/descriptor.ts
const Bytes32HexSchema = Schema.String.pipe(Schema.pattern(BYTES32_LOWER_HEX));
const AssertedPredicateSchema = Schema.transformOrFail(AssertionSpecSchema, Schema.typeSchema(AssertionSpecSchema), {
strict: true,
decode: (pred, _options, ast) => pred.kind === "nativeBalanceGte" ? decodeNativeBalanceGte(pred, ast) : ParseResult.succeed(pred),
encode: (pred) => ParseResult.succeed(pred)
});
const VerificationDescriptorSchema = Schema.Struct({
validationProgramHash: Bytes32HexSchema,
paramsHash: Bytes32HexSchema,
assertedPredicate: 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);
// 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;
// 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 describeResource = (r) => foldResource(r, {
native: ({ chainId }) => `native coin on chain ${chainId}`,
erc20: ({ token, chainId }) => `${token} on chain ${chainId}`
});
const erc20Token = (r) => {
if (r.kind !== "erc20") throw new Error(`Expected erc20 resource, got ${r.kind}`);
return r.token;
};
// src/flashloan.ts
const providerKindNames = [
"aave-v3",
"balancer-v2",
"morpho-blue"
];
const FlashloanConfigSchema = Schema.Struct({
providerKind: Schema.Literal(...providerKindNames),
amount: IntegerString,
maxFee: Schema.optional(IntegerString)
});
const FlashloanMaterialiserInputSchema = Schema.Struct({
kind: Schema.Literal("flashloan"),
...FlashloanConfigSchema.fields
});
const isFlashloanMaterialiserInput = Schema.is(FlashloanMaterialiserInputSchema);
const FLASHLOAN_FEE_BPS = {
"aave-v3": 5n,
"balancer-v2": 0n,
"morpho-blue": 0n
};
const BPS_DENOMINATOR = 10000n;
const flashloanMaxFee = ({ providerKind, amount, maxFee }) => maxFee !== void 0 ? BigInt(maxFee) : (BigInt(amount) * FLASHLOAN_FEE_BPS[providerKind] + BPS_DENOMINATOR - 1n) / BPS_DENOMINATOR;
// 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)
};
};
// 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;
// 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}`
});
// 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";
// 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;
// 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";
// 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";
};
// 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);
};
// src/zodSchemas.ts
const chainIdZod = z.number().int().positive();
const evmAddressZod = z.string().regex(EVM_ADDRESS_HEX);
const uintStringZod = z.string().refine((value) => DECIMAL_UINT.test(value) && BigInt(value) <= MAX_UINT256, { message: "expected a uint256 decimal integer string" });
const SolTypeZod = z.enum([
"uint8",
"uint16",
"uint32",
"uint64",
"uint128",
"uint256",
"int128",
"int256",
"address",
"bool",
"bytes",
"bytes4",
"bytes32",
"string"
]);
const ResourcePortZod = z.object({
kind: z.literal("resource"),
name: z.string(),
accepts: z.enum([
"erc20",
"native",
"any"
]),
mode: z.enum(["linear", "copy"]),
optional: z.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 = z.enum(HANDLE_UNITS);
const StaticSolTypeZod = z.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 = z.object({
kind: z.literal("handle"),
name: z.string(),
type: SolTypeZod,
mode: z.enum(["linear", "copy"]),
expose: z.boolean().optional(),
units: HandleUnitsZod.optional(),
optional: z.boolean().optional()
});
const InputPortZod = z.discriminatedUnion("kind", [ResourcePortZod, HandlePortZod]);
const ResourceOutputPortZod = z.object({
kind: z.literal("resource_output"),
name: z.string(),
mode: z.enum(["linear", "copy"]),
availability: z.enum(["now", "future"]).optional(),
providesMinimum: z.boolean().optional(),
omitIfZero: z.boolean().optional(),
deliveryAddressInput: z.string().optional(),
countFrom: z.string().optional()
});
const OutputPortZod = z.discriminatedUnion("kind", [ResourceOutputPortZod, HandlePortZod]);
const ManifestOperationZod = z.object({
id: z.string(),
description: z.string().optional(),
inputs: z.array(InputPortZod),
outputs: z.array(OutputPortZod),
configSchema: z.unknown().optional()
});
const PortKindEnum = z.enum([
"resource",
"resource_output",
"handle"
]);
const SelectorMatchZod = z.object({
kind: z.union([PortKindEnum, z.array(PortKindEnum)]),
mode: z.enum(["linear", "copy"]).optional(),
type: z.enum([
"erc20",
"native",
"any"
]).optional()
});
const ConfigSelectionZod = z.object({
kind: z.literal("config"),
configKey: z.string(),
cardinality: z.enum(["one", "many"])
});
const AllMatchingSelectionZod = z.object({ kind: z.literal("all_matching") });
const SelectorSelectionZod = z.discriminatedUnion("kind", [ConfigSelectionZod, AllMatchingSelectionZod]);
const GuardSelectorZod = z.object({
binding: z.string(),
source: z.enum(["inputs", "outputs"]),
match: SelectorMatchZod,
selection: SelectorSelectionZod
});
const GuardCompatibilityZod = z.object({ selectors: z.array(GuardSelectorZod) });
const ManifestGuardZod = z.object({
kind: z.string(),
description: z.string().optional(),
configSchema: z.unknown().optional(),
compatibility: GuardCompatibilityZod.optional()
});
const ManifestMaterialiserZod = z.object({
kind: z.string(),
description: z.string().optional(),
accepts: z.enum([
"resource",
"handle",
"any"
]),
configSchema: z.unknown().optional()
});
const ManifestPreconditionZod = z.object({
type: z.string(),
description: z.string().optional(),
configSchema: z.unknown().optional()
});
const ManifestRoutingZod = z.object({
maxRouteHops: z.number().int().min(1),
swapHops: z.enum(["head", "none"])
});
const ComposeManifestZod = z.object({
manifestVersion: z.number(),
manifestHash: z.string(),
flowSchema: z.object({}).passthrough(),
operations: z.array(ManifestOperationZod),
guards: z.array(ManifestGuardZod),
materialisers: z.array(ManifestMaterialiserZod),
preconditions: z.array(ManifestPreconditionZod).optional(),
routing: ManifestRoutingZod.optional()
});
const hexStringZod = z.string().startsWith("0x");
const SettlementEscrowZod = z.object({
chainId: chainIdZod,
address: hexStringZod,
token: hexStringZod,
amount: z.string(),
cap: z.string(),
floor: z.string(),
owner: hexStringZod,
refund: hexStringZod,
expiresAtMs: z.number().int().positive()
});
const SettlementBindingZod = z.object({
executionTarget: hexStringZod,
payload: hexStringZod,
payloadHash: hexStringZod,
calldata: hexStringZod,
approvals: z.array(z.object({
token: hexStringZod,
spender: hexStringZod
})).readonly()
});
const assertionOwnerZod = z.union([evmAddressZod, z.enum(["escrow", "delivery"])]);
const AssertionSpecZod = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("erc20BalanceGte"),
chainId: chainIdZod,
token: evmAddressZod,
owner: assertionOwnerZod,
minAmount: uintStringZod
}),
z.object({
kind: z.literal("nativeBalanceGte"),
chainId: chainIdZod,
owner: assertionOwnerZod,
minAmount: uintStringZod
}),
z.object({
kind: z.literal("call"),
chainId: chainIdZod,
to: evmAddressZod,
signature: z.string(),
args: z.array(z.string()).readonly(),
comparator: z.enum([
"gte",
"eq",
"lte"
]),
threshold: uintStringZod
})
]);
const VerificationDescriptorZod = z.object({
validationProgramHash: z.string().regex(BYTES32_LOWER_HEX),
paramsHash: z.string().regex(BYTES32_LOWER_HEX),
assertedPredicate: z.array(AssertionSpecZod).readonly()
});
const SettlementZod = z.object({
escrow: SettlementEscrowZod.optional(),
binding: SettlementBindingZod.optional()
});
const ShortfallZod = z.object({
required: z.string(),
available: z.string()
});
export { ARC_CHAIN_ID, ARC_NATIVE_ERC20, ARC_NATIVE_SCALE, AppliedGuardSchema, AssertedPredicateSchema, AssertionOwnerSchema, AssertionSpecSchema, AssertionSpecZod, BindValueSchema, Bytes32HexSchema, COMPOSER_SDK_VERSION_HEADER, COMPOSE_VERSION_HEADER, CONTINUATION_COMMITMENT_OP_ID, CallCheckSpecSchema, CallSchema, CommittedOutcomeSchema, ComposeManifestZod, ContinuationIntentSchema, ContinuationOutcomeSchema, EVMAddressString, EVM_NATIVE_SENTINEL, EpilogueForwardSchema, EpilogueSchema, Erc20BalanceGteSpecSchema, FlashloanConfigSchema, FlashloanMaterialiserInputSchema, FlowInputSchema, FlowSchema, ForwardToSchema, GuardCompatibilityZod, GuardSelectorZod, HANDLE_UNITS, HandleInputSchema, HandlePortZod, HandleUnitsZod, HexStringSchema, InputPortZod, IntegerString, LineageSchema, LiteralBindingSchema, ManifestGuardZod, ManifestMaterialiserZod, ManifestOperationZod, ManifestPreconditionZod, ManifestRoutingZod, NativeBalanceGteSpecSchema, OutputPortZod, Phase1ArtifactSchema, RESERVED_REF_SCOPES, RefSchema, ResourceInputSchema, ResourceOutputPortZod, ResourcePortZod, ResourceSchema, SIMULATE_MAX_REQUIREMENTS, SIMULATE_MAX_TRACKED_BALANCES, STATIC_SOL_TYPES, SettlementZod, ShortfallZod, SolTypeSchema, StaticSolTypeZod, TEMPO_CHAIN_ID, TEMPO_NATIVE_ERC20, UuidSchema, VerificationDescriptorSchema, VerificationDescriptorZod, canonicalAssertedPredicate, canonicalNativeAddress, checkCompatibility, copy, describeResource, erc20, erc20Allowance, erc20Balance, erc20Resource, erc20Token, expandOutputPorts, familySize, flashloanMaxFee, flowInputMode, flowInputResource, flowInputType, foldChainCapabilities, foldMaterialiserMetadata, foldRef, foldResource, getChainCapabilities, handle, hasErc20CanonicalNative, instancePortName, isAsErc20Chain, isContextKey, isERC20Resource, isErc20AllowancePrecondition, isErc20BalancePrecondition, isFlashloanMaterialiserInput, isFutureResourceOutput, isHandlePort, isMaterialiserInput, isMsgValueNative, isNativeAddressForChain, isNativeBalancePrecondition, isNativeResource, isOutputFamily, isRef, isResourceInput, isResourceOutputPort, isResourcePort, isStaticSolType, linear, native, nativeBalance, nativeCheckPolicy, nativeResource, normalizeNativeTokenAddress, normalizeResource, opHandle, parseRef, parseVersion, providerKindNames, readResource, ref, refKey, resource, resourceKey, resourceOutput, resourceToken, resourcesEqual };