import {z} from 'zod' 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 TradeType = 'EXACT_INPUT' | 'EXACT_OUTPUT'; export type SwapQuoteRequest = {source: CurrencyBase, destination: CurrencyBase, trade_type: TradeType, amount: string, sender?: (string | null) | undefined, recipient?: (string | null) | undefined, slippage_bps?: (number | null) | undefined}; export type CreateApiSwapQuoteArgs = {'X-API-KEY': string, body: SwapQuoteRequest}; export type CreateApiSwapQuoteOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const quoteResultType = z.enum(["OK", "NO_ROUTE", "HIGH_IMPACT"]); export const priceImpactWarning = z.object({impact: z.number(), threshold: z.number()}); export const quoteIssues = z.object({price_impact_warning: priceImpactWarning.nullable().optional()}); export const tradeType = z.enum(["EXACT_INPUT", "EXACT_OUTPUT"]); 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 swapQuote = z.object({quote_id: z.string(), expires_at: z.string(), stale: z.boolean(), trade_type: tradeType, slippage_bps: z.number().int().nullable().optional(), price_impact: z.number(), providers: z.array(z.string()).optional(), input: quoteInput, output: quoteOutput}); export const swapQuoteResponse = z.object({result_type: quoteResultType, issues: quoteIssues.nullable().optional(), quote: swapQuote.nullable().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 }; /** * Swap Quote * * POST /swap/quote */ export const createApiSwapQuote = async (args: CreateApiSwapQuoteArgs, options?: CreateApiSwapQuoteOptions) => { 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/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()) };