import {z} from 'zod' export type CreateApiV3OrdersArgs = {MID: string, body: {partnerId?: string | undefined, userId?: string | undefined, invoiceId?: string | undefined, customerMetaData?: Record | undefined, settlementAccountId?: string | undefined, purposeCode: string, sourceUrl?: string | undefined, successRedirectUrl?: string | undefined, failureRedirectUrl?: string | undefined, deviceDetails?: ({userAgent?: string | undefined, ipInfo?: ({ip?: string | undefined, countryCode3?: string | undefined}) | undefined}) | undefined, customization?: ({locale?: ('en' | 'id' | 'zh' | 'pt' | 'es' | 'vi' | 'tl' | 'bn') | undefined, paymentDescription?: string | undefined}) | undefined, headlessMode?: boolean | undefined, orderType: 'onramp' | 'offramp' | 'payin' | 'payout' | 'fiat_prefund' | 'crypto_prefund' | 'swap' | 'gaming', source: {currency: string, userId?: string | undefined, amount?: number | undefined, paymentCode?: string | undefined, paymentType?: ('bank_transfer' | 'card' | 'local_wallet') | undefined, additionalPaymentDetails?: Record | undefined, sendersWalletAddress?: string | undefined, walletAddress?: string | undefined}, destination: {currency: string, holdingCurrency?: string | undefined, userId?: string | undefined, amount?: number | undefined, paymentCode?: string | undefined, paymentType?: ('bank_transfer' | 'card' | 'local_wallet') | undefined, additionalPaymentDetails?: (Record | {walletOwner: 'exchange' | 'self', exchangeName?: string | undefined, userConfirmed?: boolean | undefined}) | undefined, walletAddress?: string | undefined, qrCode?: string | undefined}}}; export type CreateApiV3OrdersOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const createApiV3OrdersResponse = z.object({status: z.string().optional(), data: z.object({flow: z.string().optional(), orderId: z.string().optional(), amount: z.number().optional(), payUrl: z.string().optional(), paymentsData: z.object({accountDetails: z.object({iban: z.string().optional(), name: z.string().optional(), address: z.string().optional(), bic: z.string().optional(), reference: z.string().optional()}).optional(), type: z.string().optional()}).optional(), feeData: z.object({depositAmount: z.number().optional(), withdrawAmount: z.number().optional(), exchangeRate: z.number().optional(), totalFee: z.number().optional(), holdingRatesData: z.object({depositAmount: z.number().optional(), holdingAmount: z.number().optional(), exchangeRate: z.number().optional(), totalFee: z.number().optional()}).optional(), settlementRatesData: z.object({holdingAmount: z.number().optional(), withdrawAmount: z.number().optional(), exchangeRate: z.number().optional(), totalFee: z.number().optional()}).optional()}).optional(), quoteHistory: z.object({refreshCount: z.number().optional(), orderCreationQuote: z.object({isRefreshed: z.boolean().optional(), usedQuotes: z.object({sourceCurrency: z.string().optional(), sourceAmount: z.number().optional(), sourceAmountInUsd: z.number().optional(), sourceCurrencyType: z.string().optional(), destinationCurrency: z.string().optional(), destinationAmount: z.number().optional(), destinationAmountInUsd: z.number().optional(), destinationCurrencyType: z.string().optional(), conversionRate: z.number().optional(), minLimit: z.number().optional(), maxLimit: z.number().optional(), direction: z.string().optional(), processingFee: z.number().optional(), processingFeeRate: z.number().optional(), customerFee: z.number().optional(), customerFeeRate: z.number().optional(), rrFeeRate: z.number().optional(), discount: z.number().optional(), discountRate: z.number().optional(), additionalFee: z.number().optional(), fixedFee: z.object({totalFixedFees: z.number().optional(), totalFixedTfFees: z.number().optional(), totalFixedCxFees: z.number().optional(), fixedFeesCurrency: z.string().optional(), fixedFeeDetails: z.object({baseFeeFixedRate: z.number().optional(), tfFeeFixedRate: z.number().optional(), cxFeeFixedRate: z.number().optional(), currency: z.string().optional()}).optional()}).optional(), totalFee: z.number().optional(), feeMode: z.string().optional(), rateType: z.string().optional(), quoteId: z.string().optional()}).optional()}).optional()}).optional(), settlements: z.object({settlementAccountId: z.string().optional(), settlementType: z.string().optional()}).optional()}).optional(), traceId: z.string().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 Order * * POST /v3/orders */ export const createApiV3Orders = async (args: CreateApiV3OrdersArgs, options?: CreateApiV3OrdersOptions) => { const {baseUrl = "https://sandbox-api.transfi.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.MID != null) headers.set("MID", String(args.MID)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/orders${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(createApiV3OrdersResponse, await res.json()) };