import {z} from 'zod' 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 PaymentRail = 'CRYPTO' | 'FIAT'; export type ChainID = 1 | 10 | 56 | 137 | 8453 | 42161 | 20000000000001 | 30000000000001 | 30000000000002; export type CurrencyBase = {address?: (string | null) | undefined, chain_id: ChainID}; export type SwapMode = 'ExactIn' | 'ExactOut'; export type CryptoSwapInput = {slippage_bps?: (number | null) | undefined, source_currency: CurrencyBase, sender_address?: (string | null) | undefined}; export type SwapIntent = {payment_rail?: PaymentRail | undefined, destination_currency: CurrencyBase, amount: string, swap_mode: SwapMode, receiving_address?: (string | null) | undefined, crypto?: (CryptoSwapInput | null) | undefined, source_currency?: (CurrencyBase | null) | undefined, sender_address?: (string | null) | undefined}; export type SwapQuoteRequest = {metadata?: (OrderMetadata | null) | undefined, intent: SwapIntent}; export type CreateApiSwapQuoteArgs = {'X-API-KEY': string, body: SwapQuoteRequest}; export type CreateApiSwapQuoteOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const chainID = z.union([z.literal(1), z.literal(10), z.literal(56), z.literal(137), z.literal(8453), z.literal(42161), z.literal(20000000000001), z.literal(30000000000001), z.literal(30000000000002)]); export const bigInt = z.string(); export const currencyAmount = z.object({ui_amount: z.number(), ui_amount_display: z.string(), raw_amount: bigInt, value_usd: z.number()}); export const feeBreakdown = z.object({total_fee: currencyAmount, protocol_fee: currencyAmount.nullable().optional(), custom_fee: currencyAmount.nullable().optional(), relayer_fee: currencyAmount.nullable().optional()}); export const quoteWithBalance = z.object({id: z.string(), address: z.string().nullable().optional(), chain_id: chainID, decimals: z.number().int(), name: z.string(), ticker: z.string(), image_uri: z.string().nullable().optional(), price_usd: z.number().nullable().optional(), currency_amount: currencyAmount, amount_out_minimum: currencyAmount.nullable().optional(), total: currencyAmount, base: currencyAmount, fees: feeBreakdown.nullable().optional(), gas: currencyAmount.nullable().optional(), balance: currencyAmount.nullable().optional()}); export const currencyWithAmount = z.object({id: z.string(), address: z.string().nullable().optional(), chain_id: chainID, decimals: z.number().int(), name: z.string(), ticker: z.string(), image_uri: z.string().nullable().optional(), price_usd: z.number().nullable().optional(), currency_amount: currencyAmount, amount_out_minimum: currencyAmount.nullable().optional()}); export const swapMode = z.enum(["ExactIn", "ExactOut"]); export const swapQuoteResponse = z.object({input: quoteWithBalance, output: currencyWithAmount, swap_mode: swapMode, providers: z.array(z.string()).optional(), slippage_bps: z.number().int().nullable().optional(), price_impact: z.number()}); 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 }; /** * Get Swap Quote * * POST /swap/quote */ export const createApiSwapQuote = async (args: CreateApiSwapQuoteArgs, options?: CreateApiSwapQuoteOptions) => { const {baseUrl = "https://api.coinvoyage.io/v2", 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/quote${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(swapQuoteResponse, await res.json()) };