import {z} from 'zod' export type TradeType = 'EXACT_INPUT' | 'EXACT_OUTPUT'; export type ChainID = 1 | 10 | 56 | 137 | 4663 | 8453 | 42161 | 20000000000001 | 20000000000002 | 30000000000001 | 30000000000002; export type CurrencyBase = {address?: (string | null) | undefined, chain_id: ChainID}; export type SwapSource = {currency: CurrencyBase, sender_address?: (string | null) | undefined, slippage_bps?: (number | null) | undefined}; export type SwapDestination = {currency: CurrencyBase, recipient?: (string | null) | undefined}; export type MetadataItems = {name?: (string | null) | undefined, description?: (string | null) | undefined, image?: (string | null) | undefined, quantity?: (number | null) | undefined, unit_price?: (number | null) | undefined, currency?: (string | null) | undefined}; export type MetadataRefund = {name?: (string | null) | undefined, reason?: (string | null) | undefined, additional_info?: (string | null) | undefined, refund_amount?: (number | null) | undefined, currency?: (string | null) | undefined}; export type OrderMetadata = {items?: Array | undefined, refund?: (MetadataRefund | null) | undefined}; export type SwapExecuteRequest = {trade_type: TradeType, amount: string, source: SwapSource, destination: SwapDestination, metadata?: (OrderMetadata | null) | undefined, use_deposit_address?: boolean | undefined}; export type CreateApiSwapExecuteArgs = {'X-API-KEY': string, body: SwapExecuteRequest}; export type CreateApiSwapExecuteOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const orderStatus = z.enum(["PENDING", "EXPIRED", "FAILED", "AWAITING_PAYMENT", "OPTIMISTIC_CONFIRMED", "AWAITING_CONFIRMATION", "EXECUTING_ORDER", "COMPLETED", "REFUNDED", "PARTIAL_PAYMENT"]); export const paymentRail = z.enum(["CRYPTO", "FIAT"]); export const chainID = z.union([z.literal(1), z.literal(10), z.literal(56), z.literal(137), z.literal(4663), z.literal(8453), z.literal(42161), z.literal(20000000000001), z.literal(20000000000002), z.literal(30000000000001), z.literal(30000000000002)]); export const currency = z.object({id: z.string(), chain_id: chainID, address: z.string().nullable().optional(), symbol: z.string(), name: z.string().optional(), decimals: z.number().int(), image_uri: z.string().nullable().optional(), chain_image_uri: z.string().nullable().optional(), price_usd: z.number().nullable().optional()}); export const bigInt = z.string(); export const amount = z.object({ui: z.string(), raw: bigInt, value_usd: z.number().nullable().optional()}); export const quoteFees = z.object({total_fee: amount, protocol_fee: amount.nullable().optional(), custom_fee: amount.nullable().optional(), relayer_fee: amount.nullable().optional()}); export const quoteBreakdown = z.object({total: amount, base: amount, fees: quoteFees.nullable().optional(), gas: amount.nullable().optional()}); export const quoteInput = z.object({currency: currency, amount: amount, balance: amount.nullable().optional(), breakdown: quoteBreakdown.nullable().optional()}); export const quoteOutput = z.object({currency: currency, amount: amount, amount_out_minimum: amount.nullable().optional()}); export const paymentFundingTransaction = z.object({tx_hash: z.string(), amount: amount}); export const paymentFunding = z.object({required_amount: amount, received_amount: amount, remaining_amount: amount, transactions: z.array(paymentFundingTransaction)}); export const stepKind = z.enum(["deposit", "transaction", "stripe_onramp"]); export const currencyBase = z.object({address: z.string().nullable().optional(), chain_id: chainID}); export const depositStepData = z.object({deposit_address: z.string(), currency: currencyBase, amount: bigInt}); export const eVMPaymentData = z.object({from: z.string(), to: z.string(), data: z.string(), value: z.string(), chainId: chainID, maxFeePerGas: z.string().optional(), maxPriorityFeePerGas: z.string().optional()}); export const bitcoinPaymentData = z.object({transaction: z.string()}); export const solanaPaymentData = z.object({transaction: z.string()}); export const suiPaymentData = z.object({transaction: z.string()}); export const chainPaymentData = z.union([eVMPaymentData, bitcoinPaymentData, solanaPaymentData, suiPaymentData]); export const stripeOnrampCurrency = z.enum(["usd", "eur"]); export const stripeCryptoCurrency = z.enum(["usdc", "usdb", "usdsui", "usdt", "phantom_cash"]); export const stripeCryptoNetwork = z.enum(["arbitrum", "base", "bitcoin", "ethereum", "polygon", "solana", "sui", "tempo", "worldchain"]); export const stripeOnrampPaymentData = z.object({session_id: z.string().optional(), stripe_publishable_key: z.string(), status: z.string(), source_currency: stripeOnrampCurrency.nullable().optional(), destination_currency: stripeCryptoCurrency, destination_network: stripeCryptoNetwork, destination_amount: z.string(), wallet_address: z.string()}); export const paymentStep = z.object({id: z.string().optional(), purpose: z.string().optional(), status: z.string().optional(), expires_at: z.string().nullable().optional(), rail: paymentRail, kind: stepKind, action: z.string().optional(), description: z.string().optional(), data: z.union([depositStepData, chainPaymentData, stripeOnrampPaymentData]).optional()}); export const paymentRefund = z.object({address: z.string().nullable().optional(), tx_hash: z.string().nullable().optional(), reason: z.string().nullable().optional()}); export const paymentView = z.object({payment_rail: paymentRail, input: quoteInput, output: quoteOutput, funding: paymentFunding.nullable().optional(), recipient: z.string(), steps: z.array(paymentStep), expires_at: z.string(), estimated_duration_seconds: z.number().nullable().optional(), source_tx_hash: z.string().nullable().optional(), destination_tx_hash: z.string().nullable().optional(), fee_tx_hash: z.string().nullable().optional(), refund: paymentRefund.nullable().optional()}); export const swapExecuteResponse = z.object({order_id: z.string(), status: orderStatus, data: paymentView}); 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 }; /** * Execute Swap * * POST /swap/execute */ export const createApiSwapExecute = async (args: CreateApiSwapExecuteArgs, options?: CreateApiSwapExecuteOptions) => { const {baseUrl = "https://api.coinvoyage.io/v3", fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-API-KEY'] != null) headers.set("X-API-KEY", String(args['X-API-KEY'])) if (APIKeyHeader !== undefined) headers.set("X-API-KEY", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/swap/execute${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(swapExecuteResponse, await res.json()) };