import {z} from 'zod' export type GetApiApiV1EventsFeedSinceArgs = {'X-Query-Validation'?: 'strict' | undefined, cursor?: string | undefined, limit?: number | undefined, trader?: string | undefined, condition_id?: string | undefined, min_grade?: ('S' | 'A' | 'B' | 'C' | 'D' | 'F') | undefined, min_size?: number | undefined, expand?: Array<'trade'> | undefined}; export type GetApiApiV1EventsFeedSinceOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const largeTrade = z.object({id: z.string(), traded_at: z.string(), size_usd: z.number(), side: z.enum(["BUY", "SELL"]), outcome: z.string().nullable(), token_id: z.string().nullable(), price: z.number(), review_score: z.number(), signal_score: z.number(), recorded_review_score: z.number().nullable(), recorded_signal_score: z.number().nullable(), suspicion_score: z.number().int().gte(0).lte(100).nullable(), suspicion_track: z.enum(["whale", "fresh_conviction", "sliced_position"]).nullable(), market_volume_share: z.number().gte(0).lte(1).optional(), trader: z.object({id: z.string(), address: z.string(), username: z.string().optional(), grade: z.string().optional(), grade_at_trade: z.enum(["S", "A", "B", "C", "D", "F"]).nullable(), grade_at_trade_status: z.enum(["graded", "ungraded", "unknown"])}), market: z.object({id: z.string(), condition_id: z.string(), title: z.string(), slug: z.string().optional(), category: z.string().optional()})}); export const eventReplaySource = z.object({kind: z.literal("local_durable_replay"), producer_family: z.literal("whale_trades"), owner: z.literal("whale_alerts"), provider_fetch_at_request_time: z.literal(false)}); export const eventReplayFreshness = z.object({status: z.literal("observed"), observed_at: z.string()}); export const eventReplayEvent = z.object({id: z.string(), type: z.literal("whale_trades_inserted"), cursor: z.string(), sequence: z.number().int().gte(1), published_at: z.string(), payload: z.object({count: z.number().int().gte(1), whale_alert_id: z.number().int().gte(1), condition_id: z.string(), trader_id: z.number().int(), platform: z.literal("polymarket")}).and(z.record(z.string(), z.unknown())), trade: largeTrade.nullable().optional(), source: eventReplaySource, freshness: eventReplayFreshness}); export const eventReplayMeta = z.object({request_id: z.string(), cached: z.boolean(), cache_age_s: z.number().int().optional(), cost: z.number().int(), replay: z.object({from_cursor: z.string(), to_cursor: z.string(), from_sequence: z.number().int().gte(0), to_sequence: z.number().int().gte(0), ordering: z.literal("commit_visibility_then_id_asc"), pending_beyond_horizon: z.boolean(), filters: z.object({trader: z.string().optional(), condition_id: z.string().optional(), min_grade: z.enum(["S", "A", "B", "C", "D", "F"]).optional(), min_size: z.number().optional()}).optional(), expand: z.array(z.literal("trade"))}), retention: z.object({status: z.literal("durable_database"), retained_events: z.number().int().gte(0), cursor_expired: z.literal(false)}), completeness: z.object({status: z.enum(["complete", "caught_up"]), reason: z.string()})}); export const getApiApiV1EventsFeedSinceResponse = z.object({object: z.literal("event_replay"), data: z.array(eventReplayEvent), has_more: z.boolean(), next_cursor: z.string(), meta: eventReplayMeta}); 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 }; /** * Replay public large-trade events * * GET /api/v1/events/feed/since * * Also accepts auth: oauth2 */ export const getApiApiV1EventsFeedSince = async (args: GetApiApiV1EventsFeedSinceArgs, options?: GetApiApiV1EventsFeedSinceOptions) => { const {baseUrl = "https://api.0xinsider.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['X-Query-Validation'] != null) headers.set("X-Query-Validation", String(args['X-Query-Validation'])) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.trader != null) query.append("trader", String(args.trader)) if (args.condition_id != null) query.append("condition_id", String(args.condition_id)) if (args.min_grade != null) query.append("min_grade", String(args.min_grade)) if (args.min_size != null) query.append("min_size", String(args.min_size)) for (const item of args.expand ?? []) query.append("expand", String(item)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/events/feed/since${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(getApiApiV1EventsFeedSinceResponse, await res.json()) };