import {z} from 'zod' export type GetApiV1OrderIdArgs = {id: string}; export type GetApiV1OrderIdOptions = {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 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 an order by their id * * GET /v1/order/{id} */ export const getApiV1OrderId = async (args: GetApiV1OrderIdArgs, options?: GetApiV1OrderIdOptions) => { const {baseUrl = "https://api.ethereal.trade", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/order/${encodeURIComponent(String(args.id))}${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(orderDto, await res.json()) };