import {z} from 'zod' export type EscrowVerb = 'authorize' | 'charge' | 'capture' | 'void' | 'refund'; export type EscrowActionRequest = {action: EscrowVerb, amount?: (string | null) | undefined, feeBps?: number | undefined}; export type CreateApiEscrowEscrowIdActionsArgs = {escrowId: string, 'X-Hevn-Account'?: (string | null) | undefined, 'Idempotency-Key'?: (string | null) | undefined, body: EscrowActionRequest}; export type CreateApiEscrowEscrowIdActionsOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const platformEscrowStatus = z.enum(["draft", "authorized", "charged", "partiallyCaptured", "captured", "voided", "reclaimed", "partiallyRefunded", "refunded"]); export const escrowAction = z.enum(["approve", "authorize", "charge", "capture", "reject", "void", "reclaim", "refund"]); export const escrowPartyView = z.object({clientId: z.string()}); export const escrowWindowsView = z.object({approveBy: z.string(), holdUntil: z.string(), refundableUntil: z.string()}); export const platformEscrowActionStatus = z.enum(["awaitingSignature", "signing", "submitted", "confirmed", "reverted", "failed", "superseded", "dropped"]); export const escrowApprovalView = z.object({id: z.string(), payload: z.string(), expiresAt: z.string()}); export const escrowActionView = z.object({action: escrowAction, idempotencyKey: z.string(), status: platformEscrowActionStatus, amount: z.string().nullable().optional(), feeBps: z.number().int().nullable().optional(), transactionHash: z.string().nullable().optional(), approval: escrowApprovalView.nullable().optional()}); export const escrowView = z.object({id: z.string(), status: platformEscrowStatus, availableActions: z.array(escrowAction), sender: escrowPartyView, receiver: escrowPartyView, onchainEscrowUrl: z.string(), description: z.string().nullable().optional(), completionConditions: z.string().nullable().optional(), token: z.string(), maxAmount: z.string(), authorizedAmount: z.string(), capturableAmount: z.string(), refundableAmount: z.string(), windows: escrowWindowsView, action: escrowActionView.nullable().optional(), consistent: z.boolean().nullable().optional(), createdAt: z.string(), updatedAt: z.string()}); export const escrowEventView = z.object({name: z.string(), transactionHash: z.string(), blockNumber: z.number().int(), amount: z.string().nullable().optional()}); export const escrowActionResultView = z.object({deal: escrowView, action: escrowActionView, events: z.array(escrowEventView).optional(), pollUrl: z.string().nullable().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 }; /** * Prepare an escrow action and return the payload to sign * * POST /escrow/{escrowId}/actions */ export const createApiEscrowEscrowIdActions = async (args: CreateApiEscrowEscrowIdActionsArgs, options: CreateApiEscrowEscrowIdActionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Hevn-Account'] != null) headers.set("X-Hevn-Account", String(args['X-Hevn-Account'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/escrow/${encodeURIComponent(String(args.escrowId))}/actions${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(escrowActionResultView, await res.json()) };