import {z} from 'zod' export type CreateApiV2TransactionsQuoteArgs = {body: {type: 'CRYPTO_WITHDRAWAL', beneficiary_id: string, amount: number, source: {crypto_wallet_id: string}}}; export type CreateApiV2TransactionsQuoteOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV2TransactionsQuoteResponse = z.object({data: z.object({quote_id: z.string().optional(), expire_at: z.string().optional(), amount: z.number().optional(), destination_details: z.object({address: z.string().optional(), currency: z.string().optional(), rail: z.string().optional()}).optional(), quote_estimation: z.object({developer_fee_fixed: z.number().optional(), developer_fee_percentage: z.number().optional(), network_fee: z.number().optional(), total_fee: z.number().optional(), receivable_amount: z.number().optional(), ata_fee_applied: z.boolean().optional()}).optional()}).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 Quote * * POST /v2/transactions/quote */ export const createApiV2TransactionsQuote = async (args: CreateApiV2TransactionsQuoteArgs, options?: CreateApiV2TransactionsQuoteOptions) => { const {baseUrl = "https://sandbox.api.fin.com", 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 (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/transactions/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(createApiV2TransactionsQuoteResponse, await res.json()) };