import {z} from 'zod' export type AccountKey = 'USDC' | 'EURC' | 'RD' | 'USDC_ARB' | 'FDIC_USD' | 'FDIC_EUR' | 'KYC_CARDS'; export type SwapCreateRequest = {sourceAccount: AccountKey, destinationAccount: AccountKey, amount?: (string | null) | undefined, amountTo?: (string | null) | undefined, publicKey: string}; export type CreateApiSwapsArgs = {'X-Hevn-Account'?: (string | null) | undefined, 'Idempotency-Key'?: (string | null) | undefined, body: SwapCreateRequest}; export type CreateApiSwapsOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const swapState = z.enum(["awaitingSignature", "submitted", "settled", "failed"]); export const accountKey = z.enum(["USDC", "EURC", "RD", "USDC_ARB", "FDIC_USD", "FDIC_EUR", "KYC_CARDS"]); export const swapQuoteView = z.object({fromAmount: z.string(), fromCurrency: z.string(), toAmount: z.string(), toCurrency: z.string(), rate: z.string(), feeAmount: z.string(), feeCurrency: z.string(), minimumToAmount: z.string().nullable().optional(), estimated: z.boolean().optional(), etaHours: z.number().int().nullable().optional(), expiresAt: z.string().nullable().optional()}); export const authorizationKind = z.enum(["debit", "intent", "client"]); export const approvalView = z.object({id: z.string(), payload: z.string(), expiresAt: z.string()}); export const debitView = z.object({address: z.string(), amount: z.string(), amountAtomic: z.string(), token: z.string(), chainId: z.number().int()}); export const intentView = z.object({digest: z.string(), settles: z.string()}); export const swapResponse = z.object({id: z.string(), status: swapState, idempotencyKey: z.string(), sourceAccount: accountKey, destinationAccount: accountKey, quote: swapQuoteView, authorization: authorizationKind, approval: approvalView, debit: debitView.nullable().optional(), intent: intentView.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 }; /** * Create a transfer between the client's own accounts * * POST /swaps */ export const createApiSwaps = async (args: CreateApiSwapsArgs, options: CreateApiSwapsOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Hevn-Account'] != null) headers.set("X-Hevn-Account", String(args['X-Hevn-Account'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/swaps${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(swapResponse, await res.json()) };