import {z} from 'zod' export type IdempotencyKey = string; export type QuoteId = string; export type CustomerId = string; export type AddressApi = {street: string, city: string, state: string, postal_code: string, country: string}; export type CreateTransferDestination = {type: 'bank', recipient_type?: ('individual' | 'business') | undefined, date_of_birth?: string | undefined, account_holder_name: string, account_number?: string | undefined, iban?: string | undefined, bank_name: string, bank_country: string, currency: string, account_type?: ('savings' | 'checking' | 'payment') | undefined, branch_name?: string | undefined, address?: AddressApi | undefined, swift_code?: string | undefined, bic_code?: string | undefined, ifsc_code?: string | undefined, aba_code?: string | undefined, sort_code?: string | undefined, branch_code?: string | undefined, bsb_code?: string | undefined, bank_code?: string | undefined, cnaps?: string | undefined, name_in_local_language?: string | undefined, national_identification_number?: string | undefined, logistics_tracking_details?: (Array<{tracking_number?: string | undefined, logistics_provider?: ({name?: string | undefined, code?: string | undefined}) | undefined}>) | undefined, documents?: (Array<{type: 'invoice' | 'contract' | 'other', base64_url: string}>) | undefined} | {type: 'crypto', currency: string, network: string, address: string}; export type Metadata = {[key: string]: string}; export type CreateTransferRequest = {quote_id: QuoteId, customer_id: CustomerId, destination: CreateTransferDestination, metadata?: Metadata | undefined, purpose_code?: ('PAYMENT_FOR_SERVICES' | 'PAYMENT_FOR_SOFTWARE' | 'PAYMENT_FOR_IMPORTED_GOODS' | 'TRAVEL_SERVICES' | 'VENDOR_CONTRACTOR_PAYOUTS' | 'TRANSFER_TO_OWN_ACCOUNT' | 'INVESTMENT_IN_SHARES' | 'PURCHASE_OF_PROPERTY' | 'REPAYMENT_OF_LOANS' | 'SALARY' | 'PAYMENT_OF_PROPERTY_RENTAL' | 'INFORMATION_SERVICE_CHARGES' | 'ADVERTISING_PR_EXPENSES' | 'ROYALTY_FEES' | 'BROKER_COMMITMENT_FEES' | 'ADVISOR_TECHNICAL_FEES' | 'REPRESENTATIVE_OFFICE_EXPENSES' | 'TAX_PAYMENT' | 'TRANSPORTATION_FEES_FOR_GOODS' | 'CONSTRUCTION_COSTS' | 'INSURANCE_PREMIUM' | 'GENERAL_GOODS_TRADES' | 'INSURANCE_CLAIMS_PAYMENT' | 'FAMILY_MAINTENANCE' | 'EDUCATION_EXPENSES' | 'MEDICAL_TREATMENT' | 'DONATIONS' | 'MUTUAL_FUND_INVESTMENT' | 'CURRENCY_EXCHANGE' | 'USER_WITHDRAWAL' | 'ADVANCE_PAYMENTS_FOR_GOODS' | 'VENDOR_CONTRACTOR_SOFTWARE_PAYOUTS' | 'MERCHANT_SETTLEMENT' | 'REPATRIATION_FUND_SETTLEMENT' | 'PERSONAL_REMITTANCE' | 'RETURN_OF_FUNDS') | undefined}; export type CreateApiApiV1TransferArgs = {'idempotency-key': IdempotencyKey, body: CreateTransferRequest}; export type CreateApiApiV1TransferOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const metadata = z.record(z.string(), z.string()); export const addressApiOutput = z.object({street: z.string(), city: z.string(), state: z.string(), postal_code: z.string(), country: z.string()}); export const transferResponse = z.object({id: z.string(), tenant_id: z.string(), customer_id: z.string(), quote_id: z.string(), type: z.enum(["offramp", "onramp"]), status: z.enum(["created", "unknown", "compliance_hold", "awaiting_funds_collection", "funds_collected", "in_progress", "payment_submitted", "payment_processed", "completed", "failed", "cancelled", "expired"]), created_at: z.string(), updated_at: z.string(), metadata: metadata.optional(), source_deposit_instructions: z.union([z.object({wallet_address: z.string(), currency: z.string(), network: z.string(), amount: z.string()}), z.object({bank_name: z.string().optional(), account_number: z.string().optional(), iban: z.string().optional(), bic: z.string().optional(), payment_rails: z.array(z.string()).optional(), bsb: z.string().optional(), account_name: z.string().optional(), reference: z.string().optional(), currency: z.string(), amount: z.string()})]).nullable().optional(), destination: z.union([z.object({amount: z.string(), currency: z.string(), network: z.string(), wallet_address: z.string()}), z.object({amount: z.string(), currency: z.string(), network: z.string(), account_holder_name: z.string().optional(), account_number: z.string().optional(), iban: z.string().optional(), bank_name: z.string().optional(), bank_country: z.string().min(2).max(2).optional(), account_type: z.enum(["savings", "checking", "payment"]).optional(), branch_name: z.string().optional(), address: addressApiOutput.optional(), swift_code: z.string().optional(), bic_code: z.string().optional(), ifsc_code: z.string().optional(), aba_code: z.string().optional(), sort_code: z.string().optional(), branch_code: z.string().optional(), bsb_code: z.string().optional(), bank_code: z.string().optional(), cnaps: z.string().optional(), name_in_local_language: z.string().optional(), national_identification_number: z.string().optional(), logistics_tracking_details: z.array(z.object({tracking_number: z.string().optional(), logistics_provider: z.object({name: z.string().optional(), code: z.string().optional()}).optional()})).optional(), documents: z.array(z.object({type: z.enum(["invoice", "contract", "other"]).optional()})).optional()})]).nullable().optional(), fees: z.object({fx_fee: z.object({amount: z.string(), currency: z.string()}).optional(), integrator_fee: z.object({amount: z.string(), currency: z.string()}).optional(), platform_fee: z.object({amount: z.string(), currency: z.string()}).optional(), payment_method_fee: z.object({amount: z.string(), currency: z.string()}).optional(), network_fee: z.object({amount: z.string(), currency: z.string()}).optional(), total_fee: z.object({amount: z.string(), currency: z.string()}).optional()}).nullable().optional(), exchange_rate: z.number().nullable().optional(), origin: z.enum(["api", "otc"])}); 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 an offramp payment for an existing customer * * POST /api/v1/transfer * * Also accepts auth: apiKeyAuth */ export const createApiApiV1Transfer = async (args: CreateApiApiV1TransferArgs, options?: CreateApiApiV1TransferOptions) => { const {baseUrl = "https://api.stables.money", 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 (args['idempotency-key'] != null) headers.set("idempotency-key", String(args['idempotency-key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/transfer${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(transferResponse, await res.json()) };