import {z} from 'zod' export type StringNoEdgeSpaces = string; export type CountryCodeForRequest = string; export type SubdivisionCodeForRequest = string; export type CreateTransactionRequirement = {name: 'authorize:3ds', returnUrl: string} | {name: 'authorize:apple-pay' | 'authorize:google-pay', provider: 'checkout', deviceData: string, tokenizedPayment: {[key: string]: unknown}} | {name: 'authorize:paypal' | 'authorize:venmo', provider: 'braintree', deviceData: string, tokenizedPayment?: ({details?: {[key: string]: unknown} | undefined, nonce?: string | undefined}) | undefined}; export type Metadata = {[key: string]: unknown}; export type CreateApiCoreTransactionsArgs = {'X-On-Behalf-Of'?: string | undefined, 'X-Uphold-User-Ip'?: (string | string) | undefined, 'X-Uphold-User-Agent'?: StringNoEdgeSpaces | undefined, 'X-Uphold-User-Origin'?: StringNoEdgeSpaces | undefined, 'X-Uphold-User-Country'?: CountryCodeForRequest | undefined, 'X-Uphold-User-Subdivision'?: SubdivisionCodeForRequest | undefined, 'X-Uphold-User-City'?: StringNoEdgeSpaces | undefined, body: {quoteId: string, params?: ({requirements?: Array | undefined, returnUrl?: string | undefined}) | undefined, metadata?: Metadata | undefined}}; export type CreateApiCoreTransactionsOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const transactionNodeExternalAccountBank = z.object({type: z.literal("external-account"), id: z.string(), ownerId: z.string(), via: z.literal("bank"), network: z.string()}); export const transactionNodeExternalAccountCard = z.object({type: z.literal("external-account"), id: z.string(), ownerId: z.string(), via: z.literal("card"), network: z.string(), confirmationUrl: z.string().optional()}); export const transactionNodeExternalAccountApm = z.object({type: z.literal("external-account"), id: z.string(), ownerId: z.string(), via: z.literal("apm"), confirmationUrl: z.string().optional()}); export const stringNoEdgeSpaces = z.string(); export const transactionNodeCryptoAddressExecution = z.discriminatedUnion("mode", [z.object({mode: z.literal("onchain"), transactionHash: stringNoEdgeSpaces.optional()}), z.object({mode: z.literal("offchain"), accountId: z.string().optional(), accountOwnerId: z.string().optional()}), z.object({mode: z.literal("simulated"), transactionHash: stringNoEdgeSpaces.optional()})]); export const transactionNodeExternalAccountCrypto = z.object({type: z.literal("external-account"), id: z.string(), ownerId: z.string(), via: z.literal("crypto"), network: z.string(), execution: transactionNodeCryptoAddressExecution.optional()}); export const transactionOriginNode = z.discriminatedUnion("type", [z.object({type: z.literal("account"), id: z.string(), ownerId: z.string()}), transactionNodeExternalAccountBank, transactionNodeExternalAccountCard, transactionNodeExternalAccountApm, transactionNodeExternalAccountCrypto, z.object({type: z.literal("apm"), method: z.enum(["apple-pay", "google-pay", "paypal", "venmo"]), confirmationUrl: z.string().optional()}), z.object({type: z.literal("bank-address"), network: z.string()}), z.object({type: z.literal("crypto-address"), network: stringNoEdgeSpaces, address: stringNoEdgeSpaces.optional(), reference: z.string().optional(), execution: transactionNodeCryptoAddressExecution.optional()})]); export const transactionOriginEndpoint = z.object({asset: z.string(), amount: z.string(), rate: z.string(), node: transactionOriginNode}); export const transactionDestinationNode = z.discriminatedUnion("type", [z.object({type: z.literal("account"), id: z.string(), ownerId: z.string()}), transactionNodeExternalAccountBank, transactionNodeExternalAccountCard, transactionNodeExternalAccountApm, transactionNodeExternalAccountCrypto, z.object({type: z.literal("apm"), method: z.enum(["apple-pay", "google-pay", "paypal", "venmo"]), confirmationUrl: z.string().optional()}), z.object({type: z.literal("bank-address"), network: z.string()}), z.object({type: z.literal("crypto-address"), network: stringNoEdgeSpaces, address: stringNoEdgeSpaces.optional(), reference: z.string().optional(), execution: transactionNodeCryptoAddressExecution.optional()})]); export const transactionDestinationEndpoint = z.object({asset: z.string(), amount: z.string(), rate: z.string(), node: transactionDestinationNode}); export const transactionDenomination = z.object({asset: z.string(), amount: z.string(), rate: z.string(), target: z.enum(["origin", "destination"])}); export const transactionFees = z.array(z.object({type: z.enum(["deposit", "exchange", "network", "withdrawal"]), code: z.string(), asset: z.string(), amount: z.string(), percentage: z.string().optional(), beneficiary: z.enum(["uphold", "partner"]).optional()})); export const transactionStatusReason = z.enum(["apm-account-holder-data-mismatch", "apm-authorization-failed", "apm-missing-account-holder-data", "apm-payment-method-declined", "bank-account-holder-name-mismatch", "beneficiary-country-restricted", "card-declined", "card-declined-by-bank", "card-expired", "card-permanently-declined-by-bank", "card-unauthorized", "card-unsupported", "card-withdrawals-unsupported", "insufficient-funds", "pending-requests-for-information", "provider-maximum-limit-exceeded", "screening-verification-failed", "travel-rule-verification-failed", "unspecified-error", "velocity"]); export const transaction = z.object({id: z.string(), origin: transactionOriginEndpoint, destination: transactionDestinationEndpoint, denomination: transactionDenomination.optional(), fees: transactionFees, status: z.enum(["processing", "on-hold", "completed", "failed"]), statusDetails: z.object({reason: transactionStatusReason.optional()}).optional(), quotedAt: z.string(), createdAt: z.string(), updatedAt: z.string(), completedAt: z.string().optional()}); export const createApiCoreTransactionsResponse = z.object({transaction: transaction, errors: z.object({metadata: z.object({code: z.string(), message: z.string(), details: z.record(z.string(), z.unknown()).optional()}).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 transaction * * POST /core/transactions */ export const createApiCoreTransactions = async (args: CreateApiCoreTransactionsArgs, options?: CreateApiCoreTransactionsOptions) => { const {baseUrl = "https://api.enterprise.sandbox.uphold.com", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-On-Behalf-Of'] != null) headers.set("X-On-Behalf-Of", String(args['X-On-Behalf-Of'])) if (args['X-Uphold-User-Ip'] != null) headers.set("X-Uphold-User-Ip", String(args['X-Uphold-User-Ip'])) if (args['X-Uphold-User-Agent'] != null) headers.set("X-Uphold-User-Agent", String(args['X-Uphold-User-Agent'])) if (args['X-Uphold-User-Origin'] != null) headers.set("X-Uphold-User-Origin", String(args['X-Uphold-User-Origin'])) if (args['X-Uphold-User-Country'] != null) headers.set("X-Uphold-User-Country", String(args['X-Uphold-User-Country'])) if (args['X-Uphold-User-Subdivision'] != null) headers.set("X-Uphold-User-Subdivision", String(args['X-Uphold-User-Subdivision'])) if (args['X-Uphold-User-City'] != null) headers.set("X-Uphold-User-City", String(args['X-Uphold-User-City'])) if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/core/transactions${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(createApiCoreTransactionsResponse, await res.json()) };