import {z} from 'zod' export type OnrampSource = {amount?: number | undefined, currency: 'usd' | 'ngn' | 'mwk' | 'bwp' | 'xaf' | 'ghs' | 'kes' | 'rwf' | 'zar' | 'tzs' | 'ugx' | 'xof' | 'zmw' | 'brl' | 'mxn' | 'eur', transferType?: ('ach' | 'wire') | undefined, accountId?: string | undefined, userId: string}; export type OnrampDestination = {amount?: number | undefined, currency?: ('usdc' | 'usdt' | 'usdHifi') | undefined, chain?: ('POLYGON' | 'ETHEREUM' | 'SOLANA' | 'BASE') | undefined, userId?: string | undefined, externalWalletId?: string | undefined}; export type OnrampFee = {type: 'FIX' | 'PERCENT', value: number}; export type CreateOnramp = {requestId: string, purposeOfPayment?: ('gift' | 'bills' | 'groceries' | 'travel' | 'health' | 'entertainment' | 'housing' | 'school-fees' | 'other') | undefined, isInstant?: boolean | undefined, source: OnrampSource, destination: OnrampDestination, fee?: (OnrampFee | null) | undefined}; export type UsdOnrampSource = {amount?: number | undefined, currency: 'usd', transferType: 'ach' | 'wire', accountId?: string | undefined, userId: string}; export type CreateUsdOnramp = {requestId: string, source: UsdOnrampSource, destination: OnrampDestination, fee?: OnrampFee | undefined}; export type BrlOnrampSource = {amount?: number | undefined, currency: 'brl', userId: string}; export type CreateBrlOnramp = {requestId: string, purposeOfPayment?: ('gift' | 'bills' | 'groceries' | 'travel' | 'health' | 'entertainment' | 'housing' | 'school-fees' | 'other') | undefined, isInstant?: boolean | undefined, source: BrlOnrampSource, destination: OnrampDestination, fee?: (OnrampFee | null) | undefined}; export type MxnOnrampSource = {amount?: number | undefined, currency: 'mxn', userId: string}; export type CreateMxnOnramp = {requestId: string, purposeOfPayment?: ('gift' | 'bills' | 'groceries' | 'travel' | 'health' | 'entertainment' | 'housing' | 'school-fees' | 'other') | undefined, isInstant?: boolean | undefined, source: MxnOnrampSource, destination: OnrampDestination, fee?: (OnrampFee | null) | undefined}; export type AfricaOnrampSource = {amount?: number | undefined, currency: string, accountId: string, userId: string}; export type CreateAfricaOnramp = {requestId: string, purposeOfPayment: 'gift' | 'bills' | 'groceries' | 'travel' | 'health' | 'entertainment' | 'housing' | 'school-fees' | 'other', isInstant?: boolean | undefined, source: AfricaOnrampSource, destination: OnrampDestination, fee?: (OnrampFee | null) | undefined}; export type CreateApiV2OnrampsArgs = {body: CreateOnramp | CreateUsdOnramp | CreateBrlOnramp | CreateMxnOnramp | CreateAfricaOnramp}; export type CreateApiV2OnrampsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const onrampStatusEnum = z.enum(["NOT_INITIATED", "CREATED", "OPEN_QUOTE", "FIAT_INITIATED", "AWAITING_FUNDS", "FIAT_PENDING", "FIAT_PROCESSED", "CRYPTO_INITIATED", "CRYPTO_PENDING", "COMPLETED", "FIAT_FAILED", "FIAT_RETURNED", "CRYPTO_FAILED", "QUOTE_FAILED", "EXPIRED", "UNKNOWN"]); export const inboundObject = z.object({bankName: z.string().optional(), senderName: z.string().optional(), routingNumber: z.string().optional(), accountNumber: z.string().optional(), accountType: z.string().optional(), fedBatchId: z.string().optional(), imad: z.string().optional(), omad: z.string().optional(), traceNumber: z.string().optional(), bankAddress: z.string().optional(), description: z.string().optional(), paymentRail: z.enum(["ach", "wire", "rtp"]).optional()}); export const onrampDepositInfoObject = z.object({bankName: z.string().optional(), bankAddress: z.string().optional(), swiftCode: z.string().optional(), beneficiary: z.object({name: z.string().optional(), address: z.string().optional()}).optional(), ach: z.object({routingNumber: z.string().optional(), accountNumber: z.string().optional()}).optional(), wire: z.object({routingNumber: z.string().optional(), accountNumber: z.string().optional()}).optional(), rtp: z.object({routingNumber: z.string().optional(), accountNumber: z.string().optional()}).optional(), reference: z.string().optional(), depositBy: z.string().optional(), instruction: z.string().optional()}); export const onrampObject = z.object({transferType: z.string().optional(), transferDetails: z.object({id: z.string().optional(), requestId: z.string().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), status: onrampStatusEnum.optional(), failedReason: z.string().optional(), source: z.object({userId: z.string().optional(), currency: z.string().optional(), amount: z.number().optional(), accountId: z.string().optional(), user: z.object({email: z.string().optional(), lastName: z.string().optional(), firstName: z.string().optional(), businessName: z.string().optional()}).optional(), bankInfo: inboundObject.optional()}).optional(), destination: z.object({userId: z.string().optional(), currency: z.string().optional(), chain: z.string().optional(), walletAddress: z.string().optional(), externalWalletId: z.string().optional(), amount: z.number().optional(), user: z.object({email: z.string().optional(), lastName: z.string().optional(), firstName: z.string().optional(), businessName: z.string().optional()}).optional()}).optional(), receipt: z.object({transactionHash: z.string().optional()}).optional(), developerFee: z.object({}).optional(), quoteInformation: z.object({sendGross: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), sendNet: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), railFee: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), receiveGross: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), receiveNet: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), rate: z.string().optional(), expiresAt: z.string().optional()}).optional(), depositInfo: onrampDepositInfoObject.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 an onramp * * POST /v2/onramps */ export const createApiV2Onramps = async (args: CreateApiV2OnrampsArgs, options?: CreateApiV2OnrampsOptions) => { const {baseUrl = "https://production.hifibridge.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/onramps${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(onrampObject, await res.json()) };