import {z} from 'zod' export type GetApiV1OrderbookSymbolBboArgs = {symbol: string}; export type GetApiV1OrderbookSymbolBboOptions = {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 getBBOResponse = z.object({symbol: z.string().optional(), bestBid: bookEntry.optional(), bestOffer: bookEntry.optional(), spread: z.string().optional(), midPrice: z.string().optional(), state: instrumentState.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 best bid/offer * * GET /v1/orderbook/{symbol}/bbo */ export const getApiV1OrderbookSymbolBbo = async (args: GetApiV1OrderbookSymbolBboArgs, options?: GetApiV1OrderbookSymbolBboOptions) => { 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 (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))}/bbo${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(getBBOResponse, await res.json()) };