import {z} from 'zod' export type SwapRequest = {request_id: string, source_currency: 'USDC' | 'USDT' | 'USD', target_currency: 'USDC' | 'USDT' | 'USD', amount: string, min_output_amount?: string | undefined}; export type CreateApiSwapArgs = {'X-API-Key-ID': string, 'X-API-Timestamp': string, 'X-API-Nonce': string, Digest: string, Authorization: string, body: SwapRequest}; export type CreateApiSwapOptions = {baseUrl?: string | undefined, Ed25519?: string | undefined, fetch?: typeof fetch | undefined}; export const swapResponse = z.object({request_id: z.string(), output_amount: z.string(), price: z.string(), fx_fee: z.string(), fx_fee_currency: z.enum(["USDC", "USDT", "USD"]), is_duplicate: z.boolean()}); export const swapEnvelope = z.object({code: z.literal(0), message: z.string(), data: swapResponse}); export const errorEnvelope = z.object({code: z.number().int().gte(1), message: z.string(), data: z.object({}).nullable()}); export const createApiSwapResponse = z.union([swapEnvelope, errorEnvelope]); 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 funds * * POST /swap */ export const createApiSwap = async (args: CreateApiSwapArgs, options?: CreateApiSwapOptions) => { const {baseUrl = "https://openapi.infini.money/v2/funds", fetch: fetchFn = fetch, Ed25519} = 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-ID'] != null) headers.set("X-API-Key-ID", String(args['X-API-Key-ID'])) if (args['X-API-Timestamp'] != null) headers.set("X-API-Timestamp", String(args['X-API-Timestamp'])) if (args['X-API-Nonce'] != null) headers.set("X-API-Nonce", String(args['X-API-Nonce'])) if (args.Digest != null) headers.set("Digest", String(args.Digest)) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (Ed25519 !== undefined) headers.set("Authorization", Ed25519) const url = `${baseUrl.replace(/\/+$/, '')}/swap${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(createApiSwapResponse, await res.json()) };