import {z} from 'zod' export type GetApiV1OrderbookSymbolArgs = {symbol: string, depth?: number | undefined}; export type GetApiV1OrderbookSymbolOptions = {baseUrl?: string | undefined, XPMAccessKey?: string | undefined, XPMTimestamp?: string | undefined, XPMSignature?: string | undefined, fetch?: typeof fetch | undefined}; export const bookEntry = z.object({px: z.string().optional(), qty: z.string().optional()}); export const instrumentState = z.enum(["INSTRUMENT_STATE_CLOSED", "INSTRUMENT_STATE_OPEN", "INSTRUMENT_STATE_PREOPEN", "INSTRUMENT_STATE_SUSPENDED", "INSTRUMENT_STATE_EXPIRED", "INSTRUMENT_STATE_TERMINATED", "INSTRUMENT_STATE_HALTED", "INSTRUMENT_STATE_MATCH_AND_CLOSE_AUCTION", "INSTRUMENT_STATE_PENDING"]); export const instrumentStats = z.object({openPx: z.string().optional(), closePx: z.string().optional(), lowPx: z.string().optional(), highPx: z.string().optional(), lastTradePx: z.string().optional(), lastTradeQty: z.string().optional(), indicativeOpenPx: z.string().optional(), settlementPx: z.string().optional(), settlementSetTime: z.string().optional(), settlementPreliminary: z.boolean().optional(), settlementPriceCalculationMethod: z.string().optional(), settlementPriceCalculationText: z.string().optional(), sharesTraded: z.string().optional(), notionalTraded: z.string().optional(), openInterest: z.string().optional()}); export const getOrderBookResponse = z.object({symbol: z.string().optional(), bids: z.array(bookEntry).optional(), offers: z.array(bookEntry).optional(), state: instrumentState.optional(), stats: instrumentStats.optional(), transactTime: 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 order book * * GET /v1/orderbook/{symbol} */ export const getApiV1OrderbookSymbol = async (args: GetApiV1OrderbookSymbolArgs, options?: GetApiV1OrderbookSymbolOptions) => { const {baseUrl = "https://api.polymarket.us", fetch: fetchFn = fetch, XPMAccessKey, XPMTimestamp, XPMSignature} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.depth != null) query.append("depth", String(args.depth)) if (XPMAccessKey !== undefined) headers.set("X-PM-Access-Key", XPMAccessKey) if (XPMTimestamp !== undefined) headers.set("X-PM-Timestamp", XPMTimestamp) if (XPMSignature !== undefined) headers.set("X-PM-Signature", XPMSignature) const url = `${baseUrl.replace(/\/+$/, '')}/v1/orderbook/${encodeURIComponent(String(args.symbol))}${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(getOrderBookResponse, await res.json()) };