import {z} from 'zod' export type Metadata = {[key: string]: string}; export type TransferRequestV3 = {reference: string, originator: {amount?: number | undefined, currency: string, walletId: string}, beneficiary: {amount?: number | undefined, currency: string, walletId: string}, conversion?: ({type: 'QUOTE' | 'AUTO_CONVERSION', validityDuration?: ('PT20S' | 'PT60M') | undefined}) | undefined, metadata?: Metadata | undefined}; export type CreateApiPaymentV3TransfersArgs = {'Idempotency-Key': string, body: TransferRequestV3}; export type CreateApiPaymentV3TransfersOptions = {baseUrl?: string | undefined, Hawk?: string | undefined, fetch?: typeof fetch | undefined}; export const metadata = z.record(z.string(), z.string().max(100)); export const moneyFeeV2 = z.object({amount: z.number(), currency: z.string()}); export const transferIndividual = z.object({type: z.literal("INDIVIDUAL"), firstName: z.string().min(1), lastName: z.string().min(1)}); export const transferCompany = z.object({type: z.literal("COMPANY").optional(), legalName: z.string().min(1)}); export const transferResponseV3 = z.object({id: z.string(), reference: z.string(), type: z.literal("payment:transfer"), status: z.enum(["PROCESSING", "PENDING_QUOTE_ACCEPTANCE", "EXPIRED", "COMPLETED", "FAILED"]), metadata: metadata.optional(), fees: z.object({processingFee: moneyFeeV2.optional()}), originator: z.object({amount: z.number(), currency: z.string(), walletId: z.string(), entity: z.discriminatedUnion("type", [transferIndividual, transferCompany]).optional()}), beneficiary: z.object({amount: z.number().optional(), currency: z.string(), walletId: z.string(), entity: z.discriminatedUnion("type", [transferIndividual, transferCompany]).optional()}), conversion: z.object({type: z.enum(["QUOTE", "AUTO_CONVERSION"]).optional(), spread: z.object({percentage: z.number().optional(), amount: z.number().optional(), currency: z.string().optional()}).optional(), allInRate: z.number().optional(), baseRate: z.number().optional(), validityDuration: z.string().optional(), expiresAt: z.string().optional(), digest: z.string().optional()}).optional(), expiresAt: z.string().optional(), createdAt: z.string(), updatedAt: z.string(), trackingDetails: z.array(z.object({externalTransactionId: z.string().optional(), imad: z.string().max(22).optional(), omad: z.string().max(22).optional(), traceNumber: z.string().max(15).optional(), uetr: z.string().optional()})).optional(), method: z.literal("BOOK").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 internal transfer * * POST /payment/v3/transfers */ export const createApiPaymentV3Transfers = async (args: CreateApiPaymentV3TransfersArgs, options?: CreateApiPaymentV3TransfersOptions) => { const {baseUrl = "https://api.sandbox.bvnk.com", fetch: fetchFn = fetch, Hawk} = 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 (Hawk !== undefined) headers.set("Authorization", Hawk) const url = `${baseUrl.replace(/\/+$/, '')}/payment/v3/transfers${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(transferResponseV3, await res.json()) };