diff --git a/README.md b/README.md index 9b672e5..401c0ce 100644 --- a/README.md +++ b/README.md @@ -101,8 +101,79 @@ account recipient tag (`context` ends in `0x00`). Stellar routes require the exclusivity identities for those orders are commitments, not padded EVM addresses. -Current support is mainnet only. It covers G-account users and recipients, -escrow orders with 1–4 inputs and outputs, and no same-chain Stellar orders. +Builders support G-account users and recipients, escrow orders with 1–4 inputs +and outputs, and no same-chain Stellar orders. Mainnet deployments remain the +defaults. `STELLAR_TESTNET_CHAIN_ID` (`1201081091099711n`) has the testnet +passphrase hash configured, but **no default deployment addresses**. + +Supply validated raw contract ids per `Intent` instance through `IntentDeps`: + +```ts +import { STELLAR_TESTNET_CHAIN_ID, type IntentDeps } from "@lifi/intent"; + +type StellarResolver = NonNullable; +// deployment is the validated public handoff, not credentials or predicted activation data. +const getStellarDeployment: StellarResolver = (chainId) => + chainId === STELLAR_TESTNET_CHAIN_ID + ? { + inputEscrow: stellarStrkeyToBytes32(deployment.stellar.inputEscrow), + outputSettler: stellarStrkeyToBytes32(deployment.stellar.outputSettler), + } + : undefined; +``` + +Pass `{ getOracle, getStellarDeployment }` as the constructor's dependencies. +The same optional resolver is accepted as the second argument of +`inputSettlerForStellar(chainId, resolver)` and +`outputSettlerForStellar(chainId, resolver)`. Explicit values win, `undefined` +falls back to the known mainnet defaults, and an unresolved testnet fails with +`Unsupported Stellar chain id`. No exported registry is mutated. Keep oracle +selection in `getOracle`; this resolver selects only the two settlers. + +`IntentApi.getQuotes` accepts `oracle: { chainId: number | bigint; +namespace?: Namespace; address: string }[]`. Omitted namespaces remain `eip155`. +Set `namespace: "stellar"` for Stellar filters, using a C-StrKey or raw bytes32 +contract id (converted to C-StrKey). G-account oracles and filters conflicting +with a route's namespace are rejected before HTTP. Use `new IntentApi(false)` +for the development API; explicitly allow both corridor oracle deployments. +Stellar testnet USDC has 7 decimals, Base Sepolia USDC 6. + +`GetQuoteOptions` and `GetQuoteResponse` are exported. A selected quote can also +be typed as `Awaited>["quotes"][number]`. +Keep the whole quote, including `quoteId`, optional `validUntil` (Unix seconds), +`metadata.oracle`, `metadata.quoteReference`, allowances, and `openIntentTx`. +The order type is `oif-user-open-v0`. Stellar `data` is base64 **order ScVal +XDR**, not a signed envelope; it has no `gasRequired`. Decode and pass the exact +ScVal to `open` on returned `to`, then simulate/sign on the selected network. +EVM returns calldata, gas and optional native `value`; Solana and Tron retain +their compute-unit and fee-limit fields. Do not reconstruct a nonce or re-encode +API payloads from preview amounts. This SDK returns quote payloads unchanged. + +Order-status/list imports accept G/C-StrKeys as well as existing hex/base58. +Stellar output recipient kinds remain bound to their context tag (`00` account, +`01` contract); conflicting or missing tags fail instead of silently changing +identity. Contract-account users are explicitly unsupported by the G-account +order encoder. Hex claimant commitments remain opaque, never decoded as keys. + +Git dependencies run the normal `prepare` build to generate `_esm`, `_cjs` and +`_types` exports (requires Bun and the package's development build dependencies). +Bun consumers must allow this package's lifecycle explicitly with +`"trustedDependencies": ["@lifi/intent"]` in their package manifest; merge that +entry with any existing audited trust list, not a blanket allow-all. The build +also supports Bun's in-place Git preparation under `node_modules`, while +transforming only this package's `src` tree. +Bun 1.4.2 does not install a Git dependency's own devDependencies for this +in-place build. Bun Git consumers must therefore declare these build tools in +their own devDependencies: `rollup: "^4.61.0"`, +`rollup-plugin-esbuild: "^6.2.1"`, `typescript: "^5.6.3"`, and +`@types/bun: "^1.3.8"` (keep compatible existing entries). Install with dev +dependencies enabled. No additional lifecycle trust was needed for those +tools in the verified install; esbuild's optional platform binary worked with +its postinstall still blocked. npm Git installation prepares in its temporary +checkout with the SDK's devDependencies and needs no consumer build-tool entries. +Consumers can pin the final SDK Git commit before a release; replacing that pin +with an npm version requires a later release/tag publication. No new +EVM/Stellar Axelar transport API or private-relay support is introduced here. ## Axelar (Solana) diff --git a/package.json b/package.json index 1e9aa54..be375b0 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "build:markers": "node ./scripts/write-subdir-markers.mjs", "build:smoke": "node ./scripts/smoke.mjs", "build": "bun run build:js && bun run build:types && bun run build:markers && bun run build:smoke", + "prepare": "bun run build", "lint:staged": "prettier -w", "prepublishOnly": "bun run build && bun run check && bun run test", "test": "bun test", diff --git a/rollup.config.mjs b/rollup.config.mjs index 479062c..66f0f12 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -45,6 +45,10 @@ export default { ], plugins: [ esbuild({ + // Bun prepares Git dependencies inside node_modules. Match only this + // package's sources instead of excluding every node_modules ancestor. + include: "src/**/*.{js,jsx,ts,tsx}", + exclude: "src/**/node_modules/**", // Keep in sync with `target` in tsconfig.base.json. esbuild does NOT read // `target` from a tsconfig (esbuild's `tsconfigRaw` only honours a subset // of options, and `target` is not among them), so it must be set here diff --git a/src/api/intentApi.spec.ts b/src/api/intentApi.spec.ts index b8b5de8..700d053 100644 --- a/src/api/intentApi.spec.ts +++ b/src/api/intentApi.spec.ts @@ -8,6 +8,13 @@ import { bytes32ToSolanaBase58, solanaBase58ToBytes32, } from "../helpers/solana"; +import { + bytes32ToStellarAccount, + bytes32ToStellarContract, + stellarAddressCommitment, + stellarStrkeyToBytes32, +} from "../helpers/stellar"; +import { computeStandardStellarId } from "../intent/stellar/standard.stellar"; import { IntentApi, parseOrderStatusPayload } from "./intentApi"; const BYTES32_ONE = @@ -198,6 +205,100 @@ describe("parseOrderStatusPayload", () => { expect(input[0]).toBe(123n); }); + it("imports Stellar strkeys without changing order identity or recipient kind", () => { + const key = `0x${"12".repeat(32)}` as const; + const contract = bytes32ToStellarContract(key); + const account = bytes32ToStellarAccount(key); + const commitment = stellarAddressCommitment(account); + const rawOrder = { + user: key, + nonce: 123n, + originChainId: STELLAR_MAINNET_CHAIN_ID, + expires: 2_000_000_000, + fillDeadline: 1_999_999_900, + inputOracle: key, + inputs: [[BigInt(key), 10_000_000n]] as [bigint, bigint][], + outputs: [ + { + oracle: key, + settler: key, + chainId: STELLAR_MAINNET_CHAIN_ID, + token: key, + amount: 10_000_000n, + recipient: key, + callbackData: "0x" as const, + context: "0x01" as const, + }, + ], + }; + for (const [recipient, context] of [ + [account, "0x00"], + [contract, "0x01"], + ] as const) { + const payload = { + inputSettler: contract, + order: { + ...rawOrder, + user: account, + inputOracle: contract, + inputs: [[contract, "10000000"]], + outputs: [ + { + ...rawOrder.outputs[0], + oracle: contract, + settler: contract, + token: contract, + recipient, + context, + }, + ], + }, + }; + const parsed = parseOrderStatusPayload(payload); + if (!isStandardOrder(parsed.order)) + throw new Error("Expected standard order"); + expect(parsed.inputSettler).toBe(stellarStrkeyToBytes32(contract)); + expect(parsed.order).toEqual({ + ...rawOrder, + outputs: [{ ...rawOrder.outputs[0]!, context }], + }); + expect(computeStandardStellarId(parsed.inputSettler, parsed.order)).toBe( + computeStandardStellarId(key, { + ...rawOrder, + outputs: [{ ...rawOrder.outputs[0]!, context }], + }), + ); + expect(() => + parseOrderStatusPayload({ + ...payload, + order: { + ...payload.order, + outputs: [ + { + ...payload.order.outputs[0], + context: context === "0x01" ? "0x00" : "0x01", + }, + ], + }, + }), + ).toThrow("recipient kind"); + } + const parsedCommitment = parseOrderStatusPayload({ + inputSettler: contract, + order: { + ...rawOrder, + outputs: [{ ...rawOrder.outputs[0], recipient: commitment }], + }, + }); + expect(parsedCommitment.order.outputs[0]!.recipient).toBe(commitment); + expect(() => + parseOrderStatusPayload({ + inputSettler: contract, + order: { ...rawOrder, user: contract }, + }), + ).toThrow("contract users are not supported"); + }); + it("throws for invalid payload", () => { expect(() => parseOrderStatusPayload({ data: {} })).toThrow(); }); diff --git a/src/api/intentApi.ts b/src/api/intentApi.ts index 0f51b8b..8a5e69f 100644 --- a/src/api/intentApi.ts +++ b/src/api/intentApi.ts @@ -20,6 +20,7 @@ import { bytes32ToStellarContract, isStellarAccount, isStellarContract, + stellarStrkeyToBytes32, } from "../helpers/stellar"; type OrderStatus = "Signed" | "Delivered" | "Settled"; @@ -71,7 +72,7 @@ type GetOrderResponse = { * namespace must be set on any non-EVM input or output — it selects both the * CAIP-2 chain prefix and the address encoding, and they have to agree. */ -type GetQuoteOptions = { +export type GetQuoteOptions = { user: string; userChainId: number | bigint; userNamespace?: Namespace; @@ -92,8 +93,12 @@ type GetQuoteOptions = { swapType?: "exact-input" | "exact-output"; minValidUntil?: number; exclusiveFor?: `0x${string}`[]; - /** Accepted EVM oracle contracts on both sides of a cross-chain route. */ - oracle?: { chainId: number | bigint; address: `0x${string}` }[]; + /** Accepted oracle contracts, encoded in each chain's native namespace. */ + oracle?: { + chainId: number | bigint; + namespace?: Namespace; + address: string; + }[]; /** * Optional integrator key sent as the `X-Integrator-Key` header on the quote * request. Lets an integrator receive integrator-specific quotes. @@ -116,22 +121,49 @@ type QuotePreviewItem = { amount: string; }; -type GetQuoteResponse = { +export type GetQuoteResponse = { quotes: { quoteId: string; provider: string; + validUntil?: number; preview: { inputs: QuotePreviewItem[]; outputs: QuotePreviewItem[]; }; order: { - type: string; - openIntentTx: { - chain: string; - to: string; - data: string; - gasRequired: string; - }; + type: "oif-user-open-v0"; + openIntentTx: + | { + chain: `stellar:${string}`; + to: string; + /** Base64 order ScVal XDR, not a signed transaction envelope. */ + data: string; + gasRequired?: never; + value?: never; + } + | { + chain: `eip155:${string}`; + to: string; + data: string; + gasRequired: string; + value?: string; + } + | { + chain: `solana:${string}`; + to: string; + data: string; + computeUnitsRequired: string; + gasRequired?: never; + value?: never; + } + | { + chain: `tron:${string}`; + to: string; + data: string; + feeLimit: string; + gasRequired?: never; + value?: string; + }; checks: { allowances: { chain: string; @@ -146,8 +178,10 @@ type GetQuoteResponse = { failureHandling: string; metadata: { // Rendered in the INPUT chain's own form: `0x` hex on EVM, `T...` on - // Tron, base58 on Solana — not necessarily hex. - exclusiveFor: string | string[] | null; + // Tron, base58 on Solana, a commitment on Stellar — not necessarily hex. + exclusiveFor: string | null; + oracle: { input: string; output: string }; + quoteReference: string; }; }[]; }; @@ -306,12 +340,15 @@ function toBigIntValue(value: unknown, field: string): bigint { * `inputSettler`, mints and recipients as raw base58. Left unconverted they * fail `toHexString` and the import dies on the first such field. * - * The two encodings cannot collide: base58's alphabet excludes `0`, so no - * base58 address can begin with `0x`. Hex is passed through byte-for-byte, - * which leaves EVM and Tron orders parsed exactly as before. + * Valid Stellar strkeys must be recognized before Solana base58. The internal + * representation keeps their raw keys; Stellar recipient kinds remain in the + * output context. Hex (including claimant commitments) passes through unchanged. */ function toAddress(value: unknown, field: string): `0x${string}` { if (typeof value === "string" && !value.startsWith("0x")) { + const address = value.trim(); + if (isStellarAccount(address) || isStellarContract(address)) + return stellarStrkeyToBytes32(address); try { return solanaBase58ToBytes32(value.trim()); } catch { @@ -341,6 +378,12 @@ function toAssetId(value: unknown, field: string): bigint { return toBigIntValue(value, field); } +function toOrderUser(value: unknown): `0x${string}` { + if (typeof value === "string" && isStellarContract(value.trim())) + throw new Error("Order payload invalid: contract users are not supported"); + return toAddress(value, "order.user"); +} + function toNumberValue(value: unknown, field: string): number { const parsed = typeof value === "number" @@ -369,6 +412,17 @@ function normalizeOutputs(value: unknown) { throw new Error(`Order payload invalid: outputs[${index}]`); } const o = output as Record; + const context = toHexString(o.context ?? "0x", `outputs[${index}].context`); + if ( + typeof o.recipient === "string" && + (isStellarAccount(o.recipient) || isStellarContract(o.recipient)) + ) { + const tag = isStellarContract(o.recipient) ? "01" : "00"; + if (context === "0x" || context.slice(-2) !== tag) + throw new Error( + `Order payload invalid: outputs[${index}].recipient kind does not match context`, + ); + } return { oracle: toAddress(o.oracle, `outputs[${index}].oracle`), settler: toAddress(o.settler, `outputs[${index}].settler`), @@ -380,7 +434,7 @@ function normalizeOutputs(value: unknown) { o.callbackData ?? "0x", `outputs[${index}].callbackData`, ), - context: toHexString(o.context ?? "0x", `outputs[${index}].context`), + context, }; }); } @@ -389,7 +443,9 @@ function normalizeStandardOrder(order: Record): StandardOrder { if (!Array.isArray(order.inputs)) throw new Error("Order payload invalid: inputs"); return { - user: toAddress(order.user, "order.user"), + // The Stellar encoder supports G-account users, not contract accounts. + // Reject rather than silently re-encoding a C-address as an ed25519 key. + user: toOrderUser(order.user), nonce: toBigIntValue(order.nonce, "order.nonce"), originChainId: toBigIntValue(order.originChainId, "order.originChainId"), expires: toNumberValue(order.expires, "order.expires"), @@ -414,7 +470,7 @@ function normalizeMultichainOrder( if (!Array.isArray(order.inputs)) throw new Error("Order payload invalid: inputs"); return { - user: toAddress(order.user, "order.user"), + user: toOrderUser(order.user), nonce: toBigIntValue(order.nonce, "order.nonce"), expires: toNumberValue(order.expires, "order.expires"), fillDeadline: toNumberValue(order.fillDeadline, "order.fillDeadline"), @@ -634,28 +690,49 @@ export class IntentApi { ); } if (oracle !== undefined) { - metadata.oracle = oracle.map(({ chainId, address }) => { - if ( - (typeof chainId === "number" && !Number.isSafeInteger(chainId)) || - chainId <= 0 - ) { - throw new Error("Oracle chain ID must be a positive EVM integer"); - } - if (!/^0x[0-9a-fA-F]{40}$/.test(address)) { - throw new Error("Oracle contract must be a 20-byte EVM address"); - } - if ( - [...inputs, ...outputs].some( - (item) => - BigInt(item.chainId) === BigInt(chainId) && - item.namespace !== undefined && - item.namespace !== "eip155", - ) - ) { - throw new Error("Oracle filters support EVM chains only"); - } - return { chain: toCaip2Chain(chainId, "eip155"), address }; - }); + metadata.oracle = oracle.map( + ({ chainId, namespace = "eip155", address }) => { + if ( + (typeof chainId === "number" && !Number.isSafeInteger(chainId)) || + chainId <= 0 + ) { + throw new Error("Oracle chain ID must be a positive safe integer"); + } + if ( + [...inputs, ...outputs].some( + (item) => + BigInt(item.chainId) === BigInt(chainId) && + (item.namespace ?? "eip155") !== namespace, + ) + ) { + throw new Error( + "Oracle namespace conflicts with route chain namespace", + ); + } + let nativeAddress: string; + if (namespace === "stellar") { + if (isStellarContract(address)) nativeAddress = address; + else if (/^0x[0-9a-fA-F]{64}$/.test(address)) + nativeAddress = bytes32ToStellarContract( + address as `0x${string}`, + ); + else + throw new Error( + "Oracle contract must be a Stellar C-address or 32-byte contract ID", + ); + } else if (namespace === "solana") { + nativeAddress = toQuoteAddress(address, "asset", namespace); + } else { + if (!/^0x[0-9a-fA-F]{40}$/.test(address)) + throw new Error("Oracle contract must be a 20-byte EVM address"); + nativeAddress = address; + } + return { + chain: toCaip2Chain(chainId, namespace), + address: nativeAddress, + }; + }, + ); } if (Object.keys(metadata).length > 0) intent.metadata = metadata; @@ -763,35 +840,6 @@ export class IntentApi { */ async getAndParseOrders(): Promise { const response = await this.getOrders(); - return response.data.map((instance) => { - const order: StandardOrder = { - ...instance.order, - nonce: BigInt(instance.order.nonce), - originChainId: BigInt(instance.order.originChainId), - inputs: instance.order.inputs.map(([tokenId, amount]) => [ - BigInt(tokenId), - BigInt(amount), - ]), - outputs: instance.order.outputs.map((output) => ({ - ...output, - chainId: BigInt(output.chainId), - amount: BigInt(output.amount), - })), - }; - const allocatorSignature: Signature | NoSignature = - instance.allocatorSignature - ? { type: "ECDSA", payload: instance.allocatorSignature } - : { type: "None", payload: "0x" }; - const sponsorSignature: Signature | NoSignature = - instance.sponsorSignature - ? { type: "ECDSA", payload: instance.sponsorSignature } - : { type: "None", payload: "0x" }; - return { - inputSettler: instance.inputSettler, - order, - sponsorSignature, - allocatorSignature, - }; - }); + return response.data.map((instance) => parseOrderStatusPayload(instance)); } } diff --git a/src/api/oracle-quotes.spec.ts b/src/api/oracle-quotes.spec.ts index d697810..7dfc38f 100644 --- a/src/api/oracle-quotes.spec.ts +++ b/src/api/oracle-quotes.spec.ts @@ -1,5 +1,10 @@ import { afterEach, describe, expect, it } from "bun:test"; import { IntentApi } from "./intentApi"; +import { STELLAR_TESTNET_CHAIN_ID } from "../constants"; +import { + bytes32ToStellarAccount, + bytes32ToStellarContract, +} from "../helpers/stellar"; const originalFetch = globalThis.fetch; afterEach(() => { @@ -58,7 +63,7 @@ describe("EVM oracle quote filters", () => { expect(bodies[1].intent.metadata).toEqual({ oracle: [] }); }); - it("rejects invalid chain IDs, malformed addresses, and non-EVM route entries before fetch", async () => { + it("rejects invalid chain IDs, malformed addresses, and conflicting namespaces before fetch", async () => { globalThis.fetch = Object.assign( async () => { throw new Error("unexpected fetch"); @@ -66,10 +71,19 @@ describe("EVM oracle quote filters", () => { { preconnect: originalFetch.preconnect }, ); const api = new IntentApi(false); - for (const chainId of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) { + for (const chainId of [ + 0, + -1, + 0n, + -1n, + 1.5, + NaN, + Infinity, + Number.MAX_SAFE_INTEGER + 1, + ]) { await expect( api.getQuotes({ ...options, oracle: [{ chainId, address }] }), - ).rejects.toThrow("positive EVM integer"); + ).rejects.toThrow("positive safe integer"); } await expect( api.getQuotes({ ...options, oracle: [{ chainId: 1, address: "0x123" }] }), @@ -80,6 +94,85 @@ describe("EVM oracle quote filters", () => { inputs: [{ ...options.inputs[0]!, namespace: "tron" }], oracle: [{ chainId: 1, address }], }), - ).rejects.toThrow("EVM chains only"); + ).rejects.toThrow("namespace conflicts"); + }); + + it("normalizes Stellar contracts and preserves both route namespaces", async () => { + const key = `0x${"12".repeat(32)}` as const; + const contract = bytes32ToStellarContract(key); + const stellarOptions = { + ...options, + outputs: [ + { + receiver: bytes32ToStellarAccount(key), + asset: contract, + chainId: STELLAR_TESTNET_CHAIN_ID, + namespace: "stellar" as const, + }, + ], + }; + let captured: unknown; + globalThis.fetch = (async (input, init) => { + const request = + input instanceof Request ? input : new Request(input.toString(), init); + captured = await request.json(); + return Response.json({ quotes: [] }); + }) as typeof fetch; + for (const stellarOracle of [key, contract]) { + await new IntentApi(false).getQuotes({ + ...stellarOptions, + oracle: [ + { chainId: 1, address }, + { + chainId: STELLAR_TESTNET_CHAIN_ID, + namespace: "stellar", + address: stellarOracle, + }, + ], + }); + expect(captured).toMatchObject({ + intent: { + metadata: { + oracle: [ + { chain: "eip155:1", address }, + { + chain: `stellar:${STELLAR_TESTNET_CHAIN_ID}`, + address: contract, + }, + ], + }, + }, + }); + } + for (const invalid of [ + bytes32ToStellarAccount(key), + "0x12", + contract.slice(0, -1) + "A", + ]) { + await expect( + new IntentApi(false).getQuotes({ + ...stellarOptions, + oracle: [ + { + chainId: STELLAR_TESTNET_CHAIN_ID, + namespace: "stellar", + address: invalid, + }, + ], + }), + ).rejects.toThrow("Stellar C-address"); + } + await expect( + new IntentApi(false).getQuotes({ + ...stellarOptions, + oracle: [{ chainId: STELLAR_TESTNET_CHAIN_ID, address }], + }), + ).rejects.toThrow("namespace conflicts"); + await expect( + new IntentApi(false).getQuotes({ + ...options, + oracle: [{ chainId: 1, namespace: "stellar", address: contract }], + }), + ).rejects.toThrow("namespace conflicts"); }); }); diff --git a/src/constants.ts b/src/constants.ts index d6edadc..e9a595a 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -234,12 +234,18 @@ export const TRON_LEGACY_POLYMER_ORACLES: Record< /** OIF chain id of Stellar mainnet (intent-soroban deployment). */ export const STELLAR_MAINNET_CHAIN_ID = 1201081091099710n; +/** OIF chain id of Stellar testnet. Deployment addresses must be supplied explicitly. */ +export const STELLAR_TESTNET_CHAIN_ID = 1201081091099711n; + // Stellar mainnet deployment (contracts/DEPLOYMENTS.md), as raw 32-byte // contract ids. Do NOT use these directly — go through // inputSettlerForStellar / outputSettlerForStellar / networkIdForStellar. // sha256("Public Global Stellar Network ; September 2015") const STELLAR_MAINNET_NETWORK_ID = "0x7ac33997544e3175d266bd022439b22cdb16508c01163f26e5cb2a3e1045a979" as const; +// sha256("Test SDF Network ; September 2015") +const STELLAR_TESTNET_NETWORK_ID = + "0xcee0302d59844d32bdca915c8203dd44b33fbb7edc19051ea37abedf28ecd472" as const; // InputEscrow: CA5GTK5U5LYGWIJSAG6LD724NUDFONHVEHYOHOH5KWCKCX5I442QYLUN const STELLAR_MAINNET_INPUT_ESCROW = "0x3a69abb4eaf06b213201bcb1ff5c6d065734f521f0e3b8fd5584a15fa8e7350c" as const; @@ -249,6 +255,7 @@ const STELLAR_MAINNET_OUTPUT_SETTLER = export const STELLAR_NETWORK_IDS: Record = { [STELLAR_MAINNET_CHAIN_ID.toString()]: STELLAR_MAINNET_NETWORK_ID, + [STELLAR_TESTNET_CHAIN_ID.toString()]: STELLAR_TESTNET_NETWORK_ID, }; export const STELLAR_INPUT_ESCROWS: Record = diff --git a/src/deps.ts b/src/deps.ts index f3540cf..8eb48a5 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -5,6 +5,10 @@ export type IntentDeps = { verifier: CoreVerifier, chainId: bigint, ) => `0x${string}` | undefined; + /** Explicit raw Stellar contract ids override known-network defaults. */ + getStellarDeployment?: ( + chainId: bigint, + ) => { inputEscrow: `0x${string}`; outputSettler: `0x${string}` } | undefined; }; export type StandardOrderValidationDeps = { diff --git a/src/intent/create.ts b/src/intent/create.ts index a1ec01d..219acfd 100644 --- a/src/intent/create.ts +++ b/src/intent/create.ts @@ -39,6 +39,7 @@ export class Intent { private inputs: TokenContext[]; private outputs: TokenContext[]; private getOracle: IntentDeps["getOracle"]; + private getStellarDeployment: IntentDeps["getStellarDeployment"]; private verifier: string; private exclusiveFor?: `0x${string}`; private outputRecipient?: `0x${string}`; @@ -58,6 +59,7 @@ export class Intent { this.outputs = opts.outputTokens; this.verifier = opts.verifier; this.getOracle = deps.getOracle; + this.getStellarDeployment = deps.getStellarDeployment; this.exclusiveFor = opts.exclusiveFor; this.outputRecipient = opts.outputRecipient; if (opts.expiry !== undefined) this.expiry = opts.expiry; @@ -204,6 +206,7 @@ export class Intent { exclusiveFor: this.exclusiveFor, outputTokens: this.outputs, getOracle: this.getOracle, + getStellarDeployment: this.getStellarDeployment, verifier: this.verifier, inputChainId: inputChain, inputNamespace, @@ -248,6 +251,7 @@ export class Intent { exclusiveFor: this.exclusiveFor, outputTokens: this.outputs, getOracle: this.getOracle, + getStellarDeployment: this.getStellarDeployment, verifier: this.verifier, inputChainId: inputChain, inputNamespace, @@ -301,6 +305,7 @@ export class Intent { exclusiveFor: this.exclusiveFor, outputTokens: this.outputs, getOracle: this.getOracle, + getStellarDeployment: this.getStellarDeployment, verifier: this.verifier, inputChainId: inputChain, inputNamespace, @@ -311,7 +316,7 @@ export class Intent { }), }; return new StandardStellarIntent( - inputSettlerForStellar(inputChain), + inputSettlerForStellar(inputChain, this.getStellarDeployment), stellarOrder, ); } @@ -354,6 +359,7 @@ export class Intent { exclusiveFor: this.exclusiveFor, outputTokens: this.outputs, getOracle: this.getOracle, + getStellarDeployment: this.getStellarDeployment, verifier: this.verifier, inputChainId: inputChain, inputNamespace, @@ -425,6 +431,7 @@ export class Intent { exclusiveFor: this.exclusiveFor, outputTokens: this.outputs, getOracle: this.getOracle, + getStellarDeployment: this.getStellarDeployment, verifier: this.verifier, inputChainId: firstInput.token.chainId, // Multichain orders are EVM-only: a Solana or Tron input is rejected diff --git a/src/intent/helpers/output-encoding.spec.ts b/src/intent/helpers/output-encoding.spec.ts index 421b1ea..4335071 100644 --- a/src/intent/helpers/output-encoding.spec.ts +++ b/src/intent/helpers/output-encoding.spec.ts @@ -6,6 +6,7 @@ import { SOLANA_DEVNET_OUTPUT_SETTLER_PDA, SOLANA_MAINNET_CHAIN_ID, SOLANA_MAINNET_OUTPUT_SETTLER_PDA, + STELLAR_TESTNET_CHAIN_ID, TRON_MAINNET_CHAIN_ID, TRON_MAINNET_OUTPUT_SETTLER, } from "../../constants"; @@ -416,4 +417,47 @@ describe("output encoding helpers", () => { expect(first.oracle).toBe(addressToBytes32(tronInputOracle)); expect(first.settler).toBe(addressToBytes32(COIN_FILLER)); }); + + it("uses the explicit Stellar output deployment and never borrows mainnet settlers", () => { + const settler = `0x${"12".repeat(32)}` as const; + const oracle = `0x${"34".repeat(32)}` as const; + const options = { + outputTokens: [ + { + token: { + address: `0x${"56".repeat(32)}` as const, + name: "USDC", + chainId: STELLAR_TESTNET_CHAIN_ID, + decimals: 7, + chainNamespace: "stellar" as const, + }, + amount: 10_000_000n, + }, + ], + getOracle: () => oracle, + verifier: "axelar", + inputChainId: 84532n, + inputNamespace: "eip155" as const, + sameChain: false, + recipient: `0x${"78".repeat(32)}` as const, + currentTime: 1_700_000_000, + }; + const [output] = buildMandateOutputs({ + ...options, + getStellarDeployment: (chainId) => + chainId === STELLAR_TESTNET_CHAIN_ID + ? { inputEscrow: `0x${"90".repeat(32)}`, outputSettler: settler } + : undefined, + }); + expect(output).toMatchObject({ + settler, + oracle, + chainId: STELLAR_TESTNET_CHAIN_ID, + amount: 10_000_000n, + context: "0x00", + }); + expect(() => buildMandateOutputs(options)).toThrow( + `Unsupported Stellar chain id: ${STELLAR_TESTNET_CHAIN_ID}`, + ); + }); }); diff --git a/src/intent/helpers/output-encoding.ts b/src/intent/helpers/output-encoding.ts index 4f44396..64424fe 100644 --- a/src/intent/helpers/output-encoding.ts +++ b/src/intent/helpers/output-encoding.ts @@ -81,6 +81,7 @@ export function buildMandateOutputs(options: { exclusiveFor?: `0x${string}`; outputTokens: TokenContext[]; getOracle: IntentDeps["getOracle"]; + getStellarDeployment?: IntentDeps["getStellarDeployment"]; verifier: CoreVerifier; inputChainId: bigint; inputNamespace: Namespace; @@ -94,6 +95,7 @@ export function buildMandateOutputs(options: { exclusiveFor, outputTokens, getOracle, + getStellarDeployment, verifier, inputChainId, inputNamespace, @@ -122,7 +124,10 @@ export function buildMandateOutputs(options: { } else if (token.chainNamespace === "tron") { outputSettler = outputSettlerForTron(token.chainId); } else if (token.chainNamespace === "stellar") { - outputSettler = outputSettlerForStellar(token.chainId); + outputSettler = outputSettlerForStellar( + token.chainId, + getStellarDeployment, + ); } else { outputSettler = COIN_FILLER; } diff --git a/src/intent/helpers/shared.ts b/src/intent/helpers/shared.ts index 0026dfa..80380c1 100644 --- a/src/intent/helpers/shared.ts +++ b/src/intent/helpers/shared.ts @@ -14,6 +14,7 @@ import { TRON_INPUT_SETTLER_PROGRAMS, TRON_OUTPUT_SETTLERS, } from "../../constants"; +import type { IntentDeps } from "../../deps"; import type { CompactLock, EscrowLock } from "../../types"; export const ONE_MINUTE = 60; @@ -83,21 +84,31 @@ export function outputSettlerForTron(chainId: bigint): `0x${string}` { return settler; } -/** Returns the raw InputEscrow contract id for the given Stellar chain ID. Throws for undeployed networks. */ -export function inputSettlerForStellar(chainId: bigint): `0x${string}` { - const settler = STELLAR_INPUT_ESCROWS[chainId.toString()]; +/** Returns the raw InputEscrow contract id; explicit deployments take priority over defaults. */ +export function inputSettlerForStellar( + chainId: bigint, + getStellarDeployment?: IntentDeps["getStellarDeployment"], +): `0x${string}` { + const settler = + getStellarDeployment?.(chainId)?.inputEscrow ?? + STELLAR_INPUT_ESCROWS[chainId.toString()]; if (!settler) throw new Error(`Unsupported Stellar chain id: ${chainId}`); return settler; } -/** Returns the raw OutputSettler contract id — the value `MandateOutput.settler` must hold. Throws for undeployed networks. */ -export function outputSettlerForStellar(chainId: bigint): `0x${string}` { - const settler = STELLAR_OUTPUT_SETTLERS[chainId.toString()]; +/** Returns the raw OutputSettler contract id; explicit deployments take priority over defaults. */ +export function outputSettlerForStellar( + chainId: bigint, + getStellarDeployment?: IntentDeps["getStellarDeployment"], +): `0x${string}` { + const settler = + getStellarDeployment?.(chainId)?.outputSettler ?? + STELLAR_OUTPUT_SETTLERS[chainId.toString()]; if (!settler) throw new Error(`Unsupported Stellar chain id: ${chainId}`); return settler; } -/** Returns the network id (sha256 of the passphrase) bound into Stellar order ids. Throws for undeployed networks. */ +/** Returns the network id (sha256 of the passphrase) bound into Stellar order ids. Throws for unknown networks. */ export function networkIdForStellar(chainId: bigint): `0x${string}` { const networkId = STELLAR_NETWORK_IDS[chainId.toString()]; if (!networkId) throw new Error(`Unsupported Stellar chain id: ${chainId}`); diff --git a/src/intent/stellar/standard.stellar.spec.ts b/src/intent/stellar/standard.stellar.spec.ts index 856bca5..0755cdb 100644 --- a/src/intent/stellar/standard.stellar.spec.ts +++ b/src/intent/stellar/standard.stellar.spec.ts @@ -1,9 +1,18 @@ import { describe, expect, it } from "bun:test"; -import { bytesToHex } from "viem"; +import { bytesToHex, sha256, toBytes } from "viem"; import fixture from "../../../tests/vectors/stellarClientOrder.json"; import { stellarStrkeyToBytes32 } from "../../helpers/stellar"; import type { StandardStellar } from "../../types"; -import { STELLAR_MAINNET_CHAIN_ID } from "../../constants"; +import { + STELLAR_MAINNET_CHAIN_ID, + STELLAR_TESTNET_CHAIN_ID, +} from "../../constants"; +import { Intent } from "../create"; +import { + inputSettlerForStellar, + outputSettlerForStellar, +} from "../helpers/shared"; +import type { CoreToken, IntentDeps } from "../../index"; import { orderToIntent } from "../fromOrder"; import { StandardStellarIntent, @@ -99,6 +108,28 @@ describe("Stellar order encoding", () => { ); }); + it("binds testnet order ids to the testnet passphrase", () => { + const escrow = stellarStrkeyToBytes32(fixture.escrow); + const order = { + ...fixtureOrder(), + originChainId: STELLAR_TESTNET_CHAIN_ID, + }; + expect(computeStandardStellarId(escrow, order)).toBe( + stellarOrderId( + sha256(toBytes("Test SDF Network ; September 2015")), + escrow, + order, + ), + ); + expect(computeStandardStellarId(escrow, order)).not.toBe( + stellarOrderId( + sha256(toBytes("Public Global Stellar Network ; September 2015")), + escrow, + order, + ), + ); + }); + it("rejects orders the escrow would reject", () => { const order = fixtureOrder(); expect(() => encodeStellarOrder({ ...order, inputs: [] })).toThrow( @@ -170,3 +201,73 @@ describe("orderToIntent", () => { expect(intent.orderId()).toBe(computeStandardStellarId(escrow, order)); }); }); + +describe("explicit Stellar deployments", () => { + // Synthetic contract ids, not deployment records. + const inputEscrow = `0x${"12".repeat(32)}` as const; + const outputSettler = `0x${"34".repeat(32)}` as const; + const stellarToken: CoreToken = { + address: word("02"), + name: "USDC", + chainId: STELLAR_TESTNET_CHAIN_ID, + decimals: 7, + chainNamespace: "stellar", + }; + const evmToken: CoreToken = { + address: "0x1111111111111111111111111111111111111111", + name: "USDC", + chainId: 84532n, + decimals: 6, + chainNamespace: "eip155", + }; + const deps: IntentDeps = { + getOracle: (_, chainId) => + chainId === STELLAR_TESTNET_CHAIN_ID ? word("03") : evmToken.address, + getStellarDeployment: (chainId) => + chainId === STELLAR_TESTNET_CHAIN_ID + ? { inputEscrow, outputSettler } + : undefined, + }; + const options = { + account: fixtureOrder().user, + inputTokens: [{ token: stellarToken, amount: 10_000_000n }], + outputTokens: [{ token: evmToken, amount: 1_000_000n }], + outputRecipient: evmToken.address, + lock: { type: "escrow" as const }, + verifier: "axelar", + }; + + it("uses the instance deployment for Stellar issuance and fails closed without one", () => { + const intent = new Intent(options, deps).singlechain(); + expect(intent.inputSettler).toBe(inputEscrow); + expect(intent.asOrder().inputs).toEqual([ + [BigInt(stellarToken.address), 10_000_000n], + ]); + expect(intent.asOrder().outputs[0]!.amount).toBe(1_000_000n); + expect(intent.orderId()).toBe( + computeStandardStellarId(inputEscrow, intent.asOrder()), + ); + expect(() => + new Intent(options, { getOracle: deps.getOracle }).singlechain(), + ).toThrow(`Unsupported Stellar chain id: ${STELLAR_TESTNET_CHAIN_ID}`); + }); + + it("overrides mainnet defaults locally without mutating them", () => { + const defaultInput = inputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID); + const defaultOutput = outputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID); + const resolve = () => ({ inputEscrow, outputSettler }); + expect(inputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID, resolve)).toBe( + inputEscrow, + ); + expect(outputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID, resolve)).toBe( + outputSettler, + ); + expect(inputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID)).toBe(defaultInput); + expect(outputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID)).toBe( + defaultOutput, + ); + expect( + inputSettlerForStellar(STELLAR_MAINNET_CHAIN_ID, () => undefined), + ).toBe(defaultInput); + }); +});