import {z} from 'zod' export type OrderSide = 0 | 1; export type StopType = 0 | 1; export type GetApiV1OrderArgs = {order?: ('asc' | 'desc') | undefined, limit?: number | undefined, cursor?: string | undefined, subaccountId: string, clientOrderId?: string | undefined, productIds?: Array | undefined, createdAfter?: number | undefined, createdBefore?: number | undefined, side?: OrderSide | undefined, close?: boolean | undefined, stopTypes?: Array | undefined, isWorking?: true | undefined, isPending?: true | undefined, orderBy?: 'createdAt' | undefined}; export type GetApiV1OrderOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const groupContingencyType = z.union([z.literal(0), z.literal(1)]); export const orderSide = z.union([z.literal(0), z.literal(1)]); export const stopPriceType = z.union([z.literal(0), z.literal(1)]); export const stopType = z.union([z.literal(0), z.literal(1)]); export const orderDto = z.object({availableQuantity: z.string(), clientOrderId: z.string().optional(), close: z.boolean(), createdAt: z.number().int(), expiresAt: z.number().int(), filled: z.string(), groupContingencyType: groupContingencyType.optional(), groupId: z.string().optional(), id: z.string(), postOnly: z.boolean().optional(), price: z.string(), productId: z.string(), quantity: z.string(), reduceOnly: z.boolean(), rejectedReason: z.enum(["AccountSuspended", "CausesImmediateLiquidation", "DuplicateSameSideOco", "ExchangeSuspended", "ImmediateMatchPostOnly", "InstrumentOpenValueCapExceeded", "InsufficientBalance", "Liquidation", "MarketOrderReachedMaxSlippage", "OcoFilled", "OrderIncreasesPosition", "RiskLimitExceeded", "SignerRevoked", "TriggerCanceled", "QuantityAboveMaximum", "UnfilledFillOrKill", "UnfilledImmediateOrCancel", "UnfilledMarketOrder", "MakerCanceledByTaker", "CloseOrder"]).optional(), sender: z.string(), side: orderSide, status: z.enum(["NEW", "PENDING", "FILLED_PARTIAL", "FILLED", "REJECTED", "CANCELED", "EXPIRED"]), stopPrice: z.string(), stopPriceType: stopPriceType.optional(), stopType: stopType.optional(), subaccountId: z.string(), timeInForce: z.enum(["GTD", "IOC", "FOK"]).optional(), triggered: z.enum(["NOT_TRIGGERED", "TRIGGERED", "STOP_ORDER_TRIGGERED", "OCO_ORDER_TRIGGERED", "OTO_ORDER_TRIGGERED"]), type: z.enum(["MARKET", "LIMIT"]), updatedAt: z.number().int()}); export const pageOfOrderDtos = z.object({data: z.array(orderDto), hasNext: z.boolean(), nextCursor: 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 }; /** * Returns a filtered array of orders by the subaccount * * GET /v1/order */ export const getApiV1Order = async (args: GetApiV1OrderArgs, options?: GetApiV1OrderOptions) => { const {baseUrl = "https://api.ethereal.trade", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.order != null) query.append("order", String(args.order)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.subaccountId != null) query.append("subaccountId", String(args.subaccountId)) if (args.clientOrderId != null) query.append("clientOrderId", String(args.clientOrderId)) for (const item of args.productIds ?? []) query.append("productIds", String(item)) if (args.createdAfter != null) query.append("createdAfter", String(args.createdAfter)) if (args.createdBefore != null) query.append("createdBefore", String(args.createdBefore)) if (args.side != null) query.append("side", String(args.side)) if (args.close != null) query.append("close", String(args.close)) for (const item of args.stopTypes ?? []) query.append("stopTypes", String(item)) if (args.isWorking != null) query.append("isWorking", String(args.isWorking)) if (args.isPending != null) query.append("isPending", String(args.isPending)) if (args.orderBy != null) query.append("orderBy", String(args.orderBy)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/order${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(pageOfOrderDtos, await res.json()) };