import {z} from 'zod' export type FeesDeducted = {total: string, developer: string, oms: string, gas: string}; export type CashInSource = {asset: string, network?: string | undefined, email?: string | undefined, indicatedAmount?: string | undefined, amount?: string | undefined, amountGross?: string | undefined, amountNet?: string | undefined, feesDeducted?: FeesDeducted | undefined}; export type TypeId = string; export type CashInDestinationWallet = {id?: TypeId | undefined, externalAccount?: string | undefined, blockchainAddress?: string | undefined}; export type CashInDestination = {wallet?: CashInDestinationWallet | undefined, asset?: string | undefined, network?: string | undefined, amountGross?: string | undefined, amountNet?: string | undefined, feesDeducted?: FeesDeducted | undefined}; export type CashInfo = {locationId: string, locationReference: string}; export type CreateCashInRequest = {customerId: string, source: CashInSource, destination: CashInDestination, cash: CashInfo, sponsorGas?: boolean | undefined, metadata?: {[key: string]: string} | undefined}; export type CreateApiCashInsArgs = {'Idempotency-Key': string, body: CreateCashInRequest}; export type CreateApiCashInsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const typeId = z.string(); export const transferType = z.enum(["cryptoToCrypto", "fiatToCrypto", "cryptoToFiat"]); export const cashInStatus = z.enum(["pending", "processing", "completed", "failed", "expired"]); export const cashInSubStatus = z.enum(["order_reserved", "settled", "cash_deposit_expired", "cash_deposit_failed", "provider_order_failed", "provider_order_template_error"]); export const feesDeducted = z.object({total: z.string(), developer: z.string(), oms: z.string(), gas: z.string()}); export const cashInSource = z.object({asset: z.string(), network: z.string().optional(), email: z.string().optional(), indicatedAmount: z.string().optional(), amount: z.string().optional(), amountGross: z.string().optional(), amountNet: z.string().optional(), feesDeducted: feesDeducted.optional()}); export const cashInDestinationWallet = z.object({id: typeId.optional(), externalAccount: z.string().optional(), blockchainAddress: z.string().optional()}); export const cashInDestination = z.object({wallet: cashInDestinationWallet.optional(), asset: z.string().optional(), network: z.string().optional(), amountGross: z.string().optional(), amountNet: z.string().optional(), feesDeducted: feesDeducted.optional()}); export const cashInfo = z.object({locationId: z.string(), locationReference: z.string()}); export const cashInLocation = z.object({name: z.string().optional(), address: z.string().optional()}); export const cashInDepositInstructions = z.object({code: z.string(), expiresAt: z.string(), locationName: z.string().optional(), locationAddress: z.string().optional()}); export const rates = z.object({pair: z.string(), exchangeRate: z.string(), effectiveRate: z.string()}); export const omsFeeEntry = z.object({type: z.string(), rate: z.string().optional(), amount: z.string().optional()}); export const omsFeeSchedule = z.object({feeCurrency: z.string(), entries: z.array(omsFeeEntry)}); export const feeEntry = z.object({id: z.string().optional(), percentage: z.string().optional(), flatFee: z.string().optional(), amount: z.string().optional(), payoutAsset: z.enum(["usdc", "usdt"]).optional(), wallet: z.string().optional()}); export const cashIn = z.object({id: typeId, object: z.literal("cashIn").optional(), type: transferType, status: cashInStatus, subStatus: cashInSubStatus.optional(), customerId: typeId, fixedAmountSide: z.enum(["source", "destination"]).optional(), source: cashInSource, destination: cashInDestination, cash: cashInfo, location: cashInLocation, depositInstructions: cashInDepositInstructions.optional(), rates: rates.optional(), sponsorGasCost: z.string().optional(), omsFeeSchedule: omsFeeSchedule.optional(), transactionId: typeId.optional(), sponsorGas: z.boolean().optional(), metadata: z.record(z.string(), z.string()).optional(), developerFees: z.array(feeEntry).optional(), createdAt: z.string(), updatedAt: z.string(), completedAt: z.string().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 a cash-in deposit code * * POST /cash-ins */ export const createApiCashIns = async (args: CreateApiCashInsArgs, options?: CreateApiCashInsOptions) => { const {baseUrl = "https://sandbox-api.polygon.technology/v0.10", 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(/\/+$/, '')}/cash-ins${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(cashIn, await res.json()) };