import {z} from 'zod' export type CreateApiIntentsRouteArgs = {'x-api-version': '2026-01.alps', 'x-api-key': string, body: {destinationChainId: number, tokenRequests: Array<{tokenAddress: string, amount?: unknown | undefined, balance?: ('spot' | 'perp') | undefined}>, account: {address: string, accountType?: ('smartAccount' | 'GENERIC' | 'EOA' | 'ERC7579') | undefined, setupOps?: Array<{to: string, data: string}> | undefined, mockSignatures?: {[key: string]: string} | undefined, mockSignature: unknown, delegations?: {[key: string]: {contract: string}} | undefined}, destinationExecutions?: Array<{to: string, value: unknown, data: string}> | undefined, preClaimExecutions?: {[key: string]: Array<{to: string, value: unknown, data: string}>} | undefined, destinationGasLimit?: unknown | undefined, accountAccessList?: ({chainIds?: Array | undefined, tokens?: (Array) | undefined, chainTokens?: ({[key: string]: Array}) | undefined, chainTokenAmounts?: {[key: string]: {[key: string]: unknown}} | undefined, exclude?: ({chainIds?: Array | undefined, tokens?: (Array) | undefined, chainTokens?: ({[key: string]: Array}) | undefined}) | undefined}) | undefined, recipient?: ({address: string, accountType?: ('smartAccount' | 'GENERIC' | 'EOA' | 'ERC7579') | undefined, setupOps?: Array<{to: string, data: string}> | undefined, mockSignatures?: {[key: string]: string} | undefined, mockSignature: unknown, delegations?: {[key: string]: {contract: string}} | undefined}) | undefined, options?: ({settlementLayers?: (Array<'ACROSS' | 'ECO' | 'RELAY' | 'OFT' | 'NEAR' | 'RHINO' | 'CCTP'> | {include: Array<'ACROSS' | 'ECO' | 'RELAY' | 'OFT' | 'NEAR' | 'RHINO' | 'CCTP'>} | {exclude: Array<'ACROSS' | 'ECO' | 'RELAY' | 'OFT' | 'NEAR' | 'RHINO' | 'CCTP'>}) | undefined, sponsorSettings?: ({gas?: boolean | undefined, bridgeFees?: boolean | undefined, swapFees?: boolean | undefined}) | undefined, signatureMode?: string | undefined, feeToken?: ('ETH' | 'USDC' | 'WETH' | 'USDT' | 'USDT0' | 'BNB' | 'WBNB' | 'XDAI' | 'WXDAI' | 'POL' | 'WPOL' | 'MON' | 'WMON' | 'S' | 'WS' | 'HYPE' | 'WHYPE' | 'XPL' | 'WXPL' | 'MockUSD' | 'TRX' | 'WTRX' | 'SOL' | 'WSOL') | undefined, appFees?: {feeBps: number} | undefined, executionTokensReceived?: Array | undefined, auxiliaryFunds?: {[key: string]: {[key: string]: unknown}} | undefined, selectionStrategy?: ('cheapest' | 'fastest' | 'best') | undefined}) | undefined}}; export type CreateApiIntentsRouteOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const createApiIntentsRouteResponse = z.object({intentOp: z.object({sponsor: z.string(), nonce: z.string(), targetExecutionNonce: z.string().optional(), expires: z.number().int(), elements: z.array(z.object({arbiter: z.string(), chainId: z.string(), idsAndAmounts: z.array(z.unknown()), spendTokens: z.array(z.unknown()), mandate: z.object({recipient: z.string(), tokenOut: z.array(z.unknown()), destinationChainId: z.string(), fillDeadline: z.number().int(), preClaimOps: z.object({vt: z.string(), ops: z.array(z.object({to: z.string(), value: z.string(), data: z.string()}))}), destinationOps: z.object({vt: z.string(), ops: z.array(z.object({to: z.string(), value: z.string(), data: z.string()}))}), qualifier: z.object({settlementContext: z.discriminatedUnion("settlementLayer", [z.object({settlementLayer: z.literal("INTENT_EXECUTOR"), using7579: z.boolean(), fundingMethod: z.literal("NO_FUNDING"), gasRefund: z.object({overhead: z.string(), exchangeRate: z.string(), token: z.string()}), prefundAmount: z.string().optional(), erc20Prefund: z.array(z.object({token: z.string(), amount: z.string()})).optional(), bridgeFill: z.discriminatedUnion("type", [z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("OFT")}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("RELAY"), requestId: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("NEAR"), depositAddress: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("RHINO"), commitmentId: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("CCTP"), sourceDomainId: z.number(), destinationDomainId: z.number()})]).optional(), bridgeDestinationOps: z.literal(true).optional()}), z.object({settlementLayer: z.literal("SAME_CHAIN"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), bridgeFill: z.discriminatedUnion("type", [z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("OFT")}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("RELAY"), requestId: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("NEAR"), depositAddress: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("RHINO"), commitmentId: z.string()}), z.object({destinationChainId: z.number(), fillExpirationPeriod: z.number().int().gte(0).optional(), type: z.literal("CCTP"), sourceDomainId: z.number(), destinationDomainId: z.number()})]).optional()}), z.object({settlementLayer: z.literal("ACROSS"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"])}), z.object({settlementLayer: z.literal("ECO"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), provingFee: z.string()}), z.object({settlementLayer: z.literal("RELAY"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), requestId: z.string(), orderId: z.string(), subsidizedAmount: z.string().optional(), multicallData: z.string().optional(), executionValidationGas: z.string().optional()}), z.object({settlementLayer: z.literal("NEAR"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), depositAddress: z.string(), correlationId: z.string()}), z.object({settlementLayer: z.literal("RHINO"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), quoteId: z.string()}), z.object({settlementLayer: z.literal("CCTP"), using7579: z.boolean(), fundingMethod: z.enum(["PERMIT2", "NO_FUNDING"]), sourceDomainId: z.number(), destinationDomainId: z.number()})]), encodedVal: z.string()}), minGas: z.string(), swapDestinations: z.array(z.object({tokenIn: z.string(), amountIn: z.string(), amountOut: z.string(), slippage: z.number(), quoter: z.string(), executions: z.array(z.object({to: z.string(), value: z.string(), data: z.string(), senderAddressPlaceholder: z.string().optional(), recipientAddressPlaceholder: z.string().optional()})), outputDecimals: z.number(), outputSymbol: z.string()}).nullable()).optional()}), swapOrigins: z.record(z.string(), z.object({tokenIn: z.string(), tokenOut: z.string(), amountIn: z.string(), amountOut: z.string(), slippage: z.number(), quoter: z.string(), executions: z.array(z.object({to: z.string(), value: z.string(), data: z.string(), senderAddressPlaceholder: z.string().optional(), recipientAddressPlaceholder: z.string().optional()})), inputDecimals: z.number(), inputSymbol: z.string(), price: z.number(), gasEstimate: z.number().optional()})).optional(), bundleId: z.string().optional()})), serverSignature: z.string(), signedMetadata: z.object({strategy: z.enum(["ACROSS", "ECO", "SAME_CHAIN", "TOKENLESS", "RELAY", "OFT", "NEAR", "RHINO", "CCTP_FAST", "CCTP_CHEAP"]).optional(), schemeId: z.string().optional(), tokenPrices: z.record(z.string(), z.number()), gasPrices: z.record(z.string(), z.string()), opGasParams: z.object({estimatedCalldataSize: z.number().optional()}).and(z.record(z.string(), z.object({l1BaseFee: z.string(), l1BlobBaseFee: z.string(), baseFeeScalar: z.string(), blobFeeScalar: z.string()}))), account: z.object({address: z.string(), accountType: z.enum(["smartAccount", "GENERIC", "EOA", "ERC7579"]).optional(), setupOps: z.array(z.object({to: z.string(), data: z.string()})).optional(), accountContext: z.record(z.string(), z.discriminatedUnion("accountType", [z.object({accountType: z.literal("EOA")}), z.object({accountType: z.literal("smartAccount"), isDeployed: z.boolean(), isERC7579: z.boolean(), erc7579AccountType: z.enum(["Safe", "Kernel", "Nexus"]).optional(), erc7579AccountVersion: z.string().optional()})])), requiredDelegations: z.record(z.string(), z.object({contract: z.string()})).optional()}), recipient: z.object({address: z.string().min(1), accountType: z.enum(["smartAccount", "GENERIC", "EOA", "ERC7579"]).optional(), setupOps: z.array(z.object({to: z.string(), data: z.string()})).optional(), accountContext: z.record(z.string(), z.discriminatedUnion("accountType", [z.object({accountType: z.literal("EOA")}), z.object({accountType: z.literal("smartAccount"), isDeployed: z.boolean(), isERC7579: z.boolean(), erc7579AccountType: z.enum(["Safe", "Kernel", "Nexus"]).optional(), erc7579AccountVersion: z.string().optional()})])), requiredDelegations: z.record(z.string(), z.object({contract: z.string()})).optional()}).optional(), fees: z.object({sponsorFee: z.object({relayer: z.number(), protocol: z.number()}).optional(), protocolFees: z.record(z.string(), z.string()).optional(), appFee: z.array(z.object({feeBps: z.number().int().gte(0).lte(10000), baseAmount: z.string(), amount: z.string(), chainId: z.number().int().gte(0), tokenAddress: z.string()})).optional()}).optional(), sponsorSettings: z.object({gasSponsored: z.boolean(), bridgeFeesSponsored: z.boolean(), swapFeesSponsored: z.boolean()}).optional(), executionTokensReceived: z.array(z.string()).optional(), preClaimExecutions: z.record(z.string(), z.array(z.object({to: z.string(), value: z.string(), data: z.string()}))).optional(), accounting: z.object({bridgeFill: z.object({tokensOut: z.array(z.object({address: z.string(), chainId: z.number(), amount: z.string()}))}).optional()}).optional()}), signedAuthorizations: z.array(z.object({chainId: z.number(), address: z.string(), nonce: z.number(), yParity: z.number(), r: z.string(), s: z.string()})).optional(), recipientSignedAuthorizations: z.array(z.object({chainId: z.number(), address: z.string(), nonce: z.number(), yParity: z.number(), r: z.string(), s: z.string()})).optional()}), intentCost: z.union([z.object({hasFulfilledAll: z.literal(true), tokensSpent: z.record(z.string(), z.record(z.string(), z.object({locked: z.string(), unlocked: z.string()}))), tokensReceived: z.array(z.object({tokenAddress: z.string().min(1), amountSpent: z.string(), destinationAmount: z.string(), fee: z.string(), feeBreakdown: z.object({gasFee: z.string(), bridgeFee: z.string(), protocolFee: z.string(), swapFee: z.string(), settlementFee: z.string(), appFee: z.string(), hyperCoreActivationFee: z.string()}), feesByToken: z.record(z.string(), z.object({amount: z.string(), breakdown: z.object({gasFee: z.string(), bridgeFee: z.string(), protocolFee: z.string(), swapFee: z.string(), settlementFee: z.string(), appFee: z.string(), hyperCoreActivationFee: z.string()})})), hasFulfilled: z.boolean()})), sponsorFee: z.object({relayer: z.number(), protocol: z.number()}), appFee: z.array(z.object({feeBps: z.number().int().gte(0).lte(10000), baseAmount: z.string(), amount: z.string(), chainId: z.number().int().gte(0), tokenAddress: z.string()})), gasCost: z.object({originChains: z.array(z.object({chainId: z.number(), gasUSD: z.number()})), destination: z.object({chainId: z.number(), gasUSD: z.number()}), totalUSD: z.number()}), feeBreakdownUSD: z.object({gasFeeUSD: z.number(), bridgeFeeUSD: z.number(), protocolFeeUSD: z.number(), swapFeeUSD: z.number(), settlementFeeUSD: z.number(), appFeeUSD: z.number(), totalFeeUSD: z.number()})}), z.object({hasFulfilledAll: z.literal(false), tokenShortfall: z.array(z.object({tokenAddress: z.string().min(1), destinationAmount: z.string(), amountSpent: z.string(), fee: z.string(), feesByToken: z.record(z.string(), z.object({amount: z.string(), breakdown: z.object({gasFee: z.string(), bridgeFee: z.string(), protocolFee: z.string(), swapFee: z.string(), settlementFee: z.string(), appFee: z.string(), hyperCoreActivationFee: z.string()})})), tokenSymbol: z.string(), decimals: z.number().gte(0)})), totalTokenShortfallInUSD: z.number().gte(0)})]), tokenRequirements: z.record(z.string(), z.record(z.string(), z.union([z.object({type: z.literal("approval"), amount: z.string(), spender: z.string()}), z.object({type: z.literal("wrap"), amount: z.string()})]))).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create Quote * * POST /intents/route */ export const createApiIntentsRoute = async (args: CreateApiIntentsRouteArgs, options: CreateApiIntentsRouteOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-api-version'] != null) headers.set("x-api-version", String(args['x-api-version'])) if (args['x-api-key'] != null) headers.set("x-api-key", String(args['x-api-key'])) const url = `${baseUrl.replace(/\/+$/, '')}/intents/route${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiIntentsRouteResponse, await res.json()) };