import {z} from 'zod' export type IdempotencyKey = string; export type CountryCode = string; export type Metadata = {[key: string]: string}; export type CreateQuoteRequest = {source: {currency: string, network?: ('arbitrum' | 'avalanche' | 'base' | 'ethereum' | 'optimism' | 'polygon' | 'solana' | 'tron') | undefined, amount: string}, destination: {currency: string, country?: CountryCode | undefined, network?: string | undefined, address?: string | undefined}, metadata?: Metadata | undefined, preview?: boolean | undefined}; export type CreateApiApiV1QuotesArgs = {'idempotency-key': IdempotencyKey, body: CreateQuoteRequest}; export type CreateApiApiV1QuotesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const quoteId = z.string(); export const currencyAmountMajor = z.object({currency: z.string(), network: z.enum(["arbitrum", "avalanche", "base", "ethereum", "optimism", "polygon", "solana", "tron"]).optional(), amount: z.string()}); export const feeBreakdownApi = z.object({fx_fee: currencyAmountMajor, integrator_fee: currencyAmountMajor, platform_fee: currencyAmountMajor, payment_method_fee: currencyAmountMajor, network_fee: z.object({currency: z.string(), network: z.string().optional(), amount: z.string()}).optional(), total_fee: currencyAmountMajor}); export const metadata = z.record(z.string(), z.string()); export const quoteApi = z.object({quote_id: quoteId, source: z.object({currency: z.string(), network: z.string().optional(), amount: z.string()}), destination: z.object({currency: z.string(), network: z.string(), amount: z.string()}), fees: feeBreakdownApi, exchange_rate: z.number().gt(0), expires_at: z.string(), created_at: z.string(), status: z.enum(["active", "expired", "used", "cancelled", "preview"]), metadata: metadata.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 a new quote for a payment * * POST /api/v1/quotes * * Also accepts auth: apiKeyAuth */ export const createApiApiV1Quotes = async (args: CreateApiApiV1QuotesArgs, options?: CreateApiApiV1QuotesOptions) => { const {baseUrl = "https://api.stables.money", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['idempotency-key'] != null) headers.set("idempotency-key", String(args['idempotency-key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/quotes${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(quoteApi, await res.json()) };