import {z} from 'zod' export type GetApiClearloopSettlementsSettlementIdArgs = {settlementId: string}; export type GetApiClearloopSettlementsSettlementIdOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const clearLoopSettlementExclusionDetails = z.object({exclusionReason: z.string(), exclusionSettlementId: z.string().optional()}); export const orderStatus = z.enum(["new", "waiting-funds", "reserving", "reserved", "queued", "validating-funds", "working", "waiting-approve", "co-sign-require", "approved", "processing", "executed", "canceled", "rejecting", "rejected", "declining", "declined", "suspending", "suspended", "blocked", "action-required", "accepting", "accepted", "require-initializer-approve", "waiting-counterparty-approve", "require-counterparty-approve", "ready-for-settlement", "settled", "part-signed-tx-added", "full-signed-tx-added", "rejected-part-signed-tx-added", "rejected-full-signed-tx-added", "accepted-part-signed-tx-added", "accepted-full-signed-tx-added", "awaiting-settlement", "master-password-required", "manual-resolving", "error", "pending-atomic-settlement-confirmation", "atomic-settlement-reservation-completed", "require-finalize", "waiting-accept-deposit", "waiting-reject-deposit"]); export const clearLoopSettlementStatus = z.enum(["new", "pending-exchange-confirmation", "in-progress", "post-pnl-fetch", "completed", "failed", "skipped", "cancelled", "partially-completed", "ignored", "pre-pnl-fetch", "trading-account-order-execution-completed", "on-chain-orders-in-progress", "pre-termination", "under-review", "pending-settlements-check", "excluded"]); export const clearLoopSettlementInstruction = z.object({balance: z.string().optional(), currency: z.string(), orderId: z.string().optional(), orderStatus: orderStatus.optional(), settlementAmount: z.string(), settlementAmountUSD: z.string().optional(), settlementInstructionId: z.string().optional(), status: clearLoopSettlementStatus.optional()}); export const clearLoopSettlementDetails = z.object({clientAccountId: z.string(), exchangeSettlementId: z.string(), exclusionDetails: clearLoopSettlementExclusionDetails.optional(), organizationId: z.string().optional(), pnlAttributionEndTimestamp: z.string().optional(), pnlAttributionStartTimestamp: z.string().optional(), portfolioId: z.string(), settlementInstructions: z.array(clearLoopSettlementInstruction), status: clearLoopSettlementStatus.optional()}); export const clearLoopSettlementSubStatus = z.enum(["started", "in-progress", "completed", "failed", "exchange-api-failure", "waiting-exchange-calculation", "insufficient-collateral", "negative-balances", "client-loss-greater-than-delegated", "pending-previous-settlement", "copper-order-flow-failed", "pending-order-processing", "pending-order-creation", "pending-delegations", "pending-exchange-notification", "paused", "waiting-funds", "settlement-not-complete-within-cycle-time", "manual-resolving", "partially-completed", "all-portfolios-excluded"]); export const clearLoopSettlementV2 = z.object({completedAt: z.string().optional(), createdAt: z.string().optional(), custodian: z.string().optional(), cycleEndTimestamp: z.string().optional(), cycleStartTimestamp: z.string(), deadline: z.string().optional(), exchange: z.string(), exchangeId: z.string(), failureReason: z.string().optional(), settlementDetails: z.array(clearLoopSettlementDetails).optional(), settlementId: z.string(), settlementStatus: clearLoopSettlementStatus, settlementSubStatus: clearLoopSettlementSubStatus, triggerOrigin: 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 }; /** * Get ClearLoop Settlement by ID * * GET /clearloop/settlements/{settlementId} */ export const getApiClearloopSettlementsSettlementId = async (args: GetApiClearloopSettlementsSettlementIdArgs, options?: GetApiClearloopSettlementsSettlementIdOptions) => { const {baseUrl = "https://api.copper.co/platform", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/clearloop/settlements/${encodeURIComponent(String(args.settlementId))}${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(clearLoopSettlementV2, await res.json()) };