import {z} from 'zod' export type CreateOfframpRequestRequest = {network: string, token: string, amount: number, email: string, customer: {country: 'US'}, successReturnUrl?: string | undefined, failReturnUrl?: string | undefined, settings?: ({payByMerchant?: true | undefined, feePayByMerchant?: true | undefined, releaseMethod?: ('automatic' | 'manual') | undefined}) | undefined, clientReferenceId?: (Array | boolean | number | Record | string | null) | undefined}; export type CreateApiV1OfframpArgs = {body: CreateOfframpRequestRequest}; export type CreateApiV1OfframpOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const createOfframpRequestResponse = z.object({id: z.string(), url: z.string(), network: z.enum(["ETHEREUM", "OPTIMISM", "BINANCE", "POLYGON", "ARBITRUM", "AVALANCHE", "SOLANA", "TRON", "BASE", "BITCOIN"]), token: z.string(), amount: z.number(), createdAt: z.number(), updatedAt: z.number().optional(), email: z.string(), payByMerchant: z.boolean(), feePayByMerchant: z.boolean(), clientReferenceId: z.string(), successReturnUrl: z.string().optional(), failReturnUrl: z.string().optional(), status: z.enum(["CREATED", "SUCCEEDED", "CANCELED", "EXPIRED", "PENDING_USER_ONBOARDING", "USER_ACCOUNT_ISSUE", "PENDING_USER_WITHDRAWAL", "REQUIRES_RELEASE", "PENDING_DEPOSIT_CRYPTO_USER", "PENDING_DEPOSIT_CRYPTO_MERCHANT", "IN_PROGRESS", "PENDING_MANUAL_INVESTIGATION", "REFUNDED", "REJECTED"]), livemode: z.boolean(), customerCountry: z.string(), customerRegion: z.string().optional(), releaseMethod: z.enum(["automatic", "manual"]), refundedAt: z.number().optional(), receiverBankAccountId: z.string().optional(), rejectionReason: z.union([z.enum(["UNDERAGE", "UNSUPPORTED_STATE", "USER_NAME_MISMATCH", "RISKY"]), z.enum(["UNSUPPORTED_STATE", "UNDERAGE", "GENERIC_REJECTION"])]).optional()}); export const createApiV1OfframpResponse = z.object({status: z.literal("SUCCEEDED"), data: createOfframpRequestResponse}); 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 offramp request * * POST /v1/offramp */ export const createApiV1Offramp = async (args: CreateApiV1OfframpArgs, options?: CreateApiV1OfframpOptions) => { const {baseUrl = "https://api.breeze.cash", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/offramp${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(createApiV1OfframpResponse, await res.json()) };