import {z} from 'zod' export type WidgetAmountCurrency = 'local' | 'crypto'; export type OffRampPaymentChannel = 'bank' | 'airtime' | 'mobile_money' | 'paybill'; export type OffRampNetwork = 'AVALANCHE' | 'POLYGON' | 'CELO' | 'ETHEREUM'; export type OffRampAsset = 'USDC' | 'USDT' | 'CUSD' | 'CKES' | 'CGHS'; export type GetApiApiOfframpBestOfferArgs = {amount: number, currency: WidgetAmountCurrency, countryIsoCode: string, paymentChannel: OffRampPaymentChannel, network: OffRampNetwork, asset: OffRampAsset}; export type GetApiApiOfframpBestOfferOptions = {baseUrl?: string | undefined, ClientIdHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const offRampPaymentChannel = z.enum(["bank", "airtime", "mobile_money", "paybill"]); export const requiredFieldType = z.enum(["number", "string", "date", "boolean", "email", "enum"]); export const offrampBestOfferResponse = z.object({quoteId: z.string().optional(), offer: z.object({paymentChannel: offRampPaymentChannel.optional(), countryIsoCode: z.string().optional(), currencyIsoCode: z.string().optional(), exchangeRate: z.number().optional(), cryptoExchangeRate: z.number().optional(), requiredFields: z.record(z.string(), z.object({type: requiredFieldType.optional(), label: z.string().optional(), required: z.boolean().optional(), options: z.array(z.object({value: z.string().optional(), label: z.string().optional()})).optional()})).optional()}).optional(), cashout: z.object({localCurrencyAmount: z.number().optional(), usdAmount: z.number().optional(), feeAmountUsd: z.number().optional(), feeAmountUsdFonbnk: z.number().optional(), feeAmountUsdPartner: z.number().optional(), feeAmountLocalCurrency: z.number().optional(), feeAmountLocalCurrencyFonbnk: z.number().optional(), feeAmountLocalCurrencyPartner: z.number().optional(), cryptoAmount: z.number().optional(), feeAmountCrypto: z.number().optional(), feeAmountCryptoFonbnk: z.number().optional(), feeAmountCryptoPartner: z.number().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 }; /** * Get best offer * * GET /api/offramp/best-offer * * Also accepts auth: TimestampHeader, SignatureHeader */ export const getApiApiOfframpBestOffer = async (args: GetApiApiOfframpBestOfferArgs, options?: GetApiApiOfframpBestOfferOptions) => { const {baseUrl = "https://sandbox-api.fonbnk.com", fetch: fetchFn = fetch, ClientIdHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.amount != null) query.append("amount", String(args.amount)) if (args.currency != null) query.append("currency", String(args.currency)) if (args.countryIsoCode != null) query.append("countryIsoCode", String(args.countryIsoCode)) if (args.paymentChannel != null) query.append("paymentChannel", String(args.paymentChannel)) if (args.network != null) query.append("network", String(args.network)) if (args.asset != null) query.append("asset", String(args.asset)) if (ClientIdHeader !== undefined) headers.set("x-client-id", ClientIdHeader) const url = `${baseUrl.replace(/\/+$/, '')}/api/offramp/best-offer${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(offrampBestOfferResponse, await res.json()) };