import {z} from 'zod' export type BeneficiaryRequestAddress = {addressLine1: string, addressLine2?: string | undefined, region?: string | undefined, city: string, country: string, postCode?: string | undefined}; export type IndividualRequest = {type: 'INDIVIDUAL', firstName: string, lastName: string, dateOfBirth?: string | undefined, address: BeneficiaryRequestAddress, relationshipType: 'SELF_OWNED' | 'THIRD_PARTY'}; export type CompanyRequest = {type: 'COMPANY', legalName: string, address: BeneficiaryRequestAddress, relationshipType: 'SELF_OWNED' | 'THIRD_PARTY'}; export type BankV2 = {identificationCode?: string | undefined, nid?: string | undefined, address?: ({addressLine1?: string | undefined, addressLine2?: string | undefined, region?: string | undefined, city?: string | undefined, country: string, postCode?: string | undefined}) | undefined}; export type BankAccountV2 = {accountNumber: string, accountType?: ('CHEQUE' | 'CHECKING' | 'SAVINGS' | 'TRANSMISSION') | undefined, bank: BankV2, intermediaryBanks?: Array | undefined}; export type BeneficiaryRequest = {remittanceInformation: string, entity: IndividualRequest | CompanyRequest, bankAccount: BankAccountV2}; export type Metadata = {[key: string]: string}; export type RequestDetails = {originator: {ipAddress?: string | undefined}}; export type PayoutRequest = {walletId: string, amount: number, currency: 'USD' | 'EUR' | 'GBP', reference?: string | undefined, method?: ('ACH' | 'ACH_SAME_DAY' | 'SEPA_CT' | 'SEPA_INST' | 'FEDWIRE' | 'FASTER_PAYMENT' | 'BOOK' | 'SWIFT' | 'RTP' | 'FEDNOW') | undefined, beneficiary: BeneficiaryRequest, fees?: ({customerFee?: ({amount?: number | undefined, currency?: ('USD' | 'EUR' | 'GBP') | undefined}) | undefined}) | undefined, metadata?: Metadata | undefined, requestDetails?: RequestDetails | undefined}; export type CreateApiPaymentV2PayoutsArgs = {'Idempotency-Key': string, 'X-Verification-Id'?: string | undefined, body: PayoutRequest}; export type CreateApiPaymentV2PayoutsOptions = {baseUrl?: string | undefined, Hawk?: string | undefined, fetch?: typeof fetch | undefined}; export const moneyFeeV2 = z.object({amount: z.number(), currency: z.string()}); export const feesResponse = z.object({customerFee: moneyFeeV2.optional(), processingFee: moneyFeeV2}); export const beneficiaryAddress = z.object({addressLine1: z.string().max(35).optional(), addressLine2: z.string().max(35).optional(), region: z.string().optional(), city: z.string().optional(), country: z.string(), postCode: z.string().optional()}); export const individual = z.object({type: z.literal("INDIVIDUAL"), firstName: z.string().min(1), lastName: z.string().min(1), dateOfBirth: z.string().optional(), address: beneficiaryAddress.optional(), relationshipType: z.enum(["SELF_OWNED", "THIRD_PARTY"])}); export const company = z.object({type: z.literal("COMPANY"), legalName: z.string().min(1), address: beneficiaryAddress.optional(), relationshipType: z.enum(["SELF_OWNED", "THIRD_PARTY"])}); export const bankV2 = z.object({identificationCode: z.string().optional(), nid: z.string().optional(), address: z.object({addressLine1: z.string().max(35).optional(), addressLine2: z.string().max(35).optional(), region: z.string().optional(), city: z.string().optional(), country: z.string(), postCode: z.string().optional()}).optional()}); export const bankAccountV2 = z.object({accountNumber: z.string().min(1), accountType: z.enum(["CHEQUE", "CHECKING", "SAVINGS", "TRANSMISSION"]).optional(), bank: bankV2, intermediaryBanks: z.array(bankV2).optional()}); export const beneficiaryResponse = z.object({remittanceInformation: z.string(), amount: z.number(), currency: z.string(), entity: z.discriminatedUnion("type", [individual, company]), bankAccount: bankAccountV2.optional()}); export const metadata = z.record(z.string(), z.string().max(100)); export const payoutResponse = z.object({id: z.string(), method: z.enum(["SEPA_CT", "SEPA_INST", "FASTER_PAYMENT", "BACS", "TARGET2", "TIPS", "SWIFT", "ACH", "ACH_SAME_DAY", "FEDWIRE", "FEDNOW", "RTP", "BOOK", "UNKNOWN", "BANK_TRANSFER", "WIRE", "SEPA"]), reference: z.string().optional(), status: z.enum(["PENDING", "PROCESSING", "PENDING_APPROVAL", "ON_HOLD", "COMPLETED", "EXPIRED", "CANCELLED", "FAILED", "RETURNED"]), fees: feesResponse, originator: z.object({amount: z.number(), currency: z.string(), walletId: z.string(), customerId: z.string().optional(), entity: z.discriminatedUnion("type", [individual, company])}), beneficiary: beneficiaryResponse, metadata: metadata, createdAt: z.string(), updatedAt: z.string(), type: z.literal("payment:payout:fiat"), direction: z.literal("OUT"), 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()}); 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 }; /** * Initiate payout * * POST /payment/v2/payouts */ export const createApiPaymentV2Payouts = async (args: CreateApiPaymentV2PayoutsArgs, options?: CreateApiPaymentV2PayoutsOptions) => { 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 (args['X-Verification-Id'] != null) headers.set("X-Verification-Id", String(args['X-Verification-Id'])) if (Hawk !== undefined) headers.set("Authorization", Hawk) const url = `${baseUrl.replace(/\/+$/, '')}/payment/v2/payouts${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(payoutResponse, await res.json()) };