import {z} from 'zod' export type ClearLoopSettlementStatus = '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 type GetApiClearloopSettlementsArgs = {portfolioId?: string | undefined, clientAccountId?: string | undefined, exchangeSettlementId?: string | undefined, createdAfter?: string | undefined, createdBefore?: string | undefined, cycleStartTimestamp?: string | undefined, cycles?: string | undefined, clearLoopSettlementStatuses?: Array | undefined, clearLoopSettlementStatusesNotIn?: Array | undefined, limit?: string | undefined, sortDirection?: string | undefined, offset?: string | undefined}; export type GetApiClearloopSettlementsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const clearLoopPagination = z.object({limit: z.string().optional(), page: z.string().optional(), pages: z.string().optional(), totalItems: z.string().optional()}); 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 clearLoopSettlementsResponseV2 = z.object({pagination: clearLoopPagination.optional(), settlements: z.array(clearLoopSettlementV2)}); 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 Settlements * * GET /clearloop/settlements */ export const getApiClearloopSettlements = async (args: GetApiClearloopSettlementsArgs, options?: GetApiClearloopSettlementsOptions) => { const {baseUrl = "https://api.copper.co/platform", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.portfolioId != null) query.append("portfolioId", String(args.portfolioId)) if (args.clientAccountId != null) query.append("clientAccountId", String(args.clientAccountId)) if (args.exchangeSettlementId != null) query.append("exchangeSettlementId", String(args.exchangeSettlementId)) if (args.createdAfter != null) query.append("createdAfter", String(args.createdAfter)) if (args.createdBefore != null) query.append("createdBefore", String(args.createdBefore)) if (args.cycleStartTimestamp != null) query.append("cycleStartTimestamp", String(args.cycleStartTimestamp)) if (args.cycles != null) query.append("cycles", String(args.cycles)) for (const item of args.clearLoopSettlementStatuses ?? []) query.append("clearLoopSettlementStatuses", String(item)) for (const item of args.clearLoopSettlementStatusesNotIn ?? []) query.append("clearLoopSettlementStatusesNotIn", String(item)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.sortDirection != null) query.append("sortDirection", String(args.sortDirection)) if (args.offset != null) query.append("offset", String(args.offset)) const url = `${baseUrl.replace(/\/+$/, '')}/clearloop/settlements${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(clearLoopSettlementsResponseV2, await res.json()) };