@liberfi.io/react-predict 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1008 +0,0 @@
1
- import * as _tanstack_react_query from '@tanstack/react-query';
2
- import { UseQueryOptions } from '@tanstack/react-query';
3
-
4
- /**
5
- * Domain types for the prediction-server REST API.
6
- *
7
- * Mirrors: github.com/liberfi-io/prediction-server/internal/domain
8
- */
9
- /** Upstream data provider that produced a domain object. */
10
- type ProviderSource = "dflow" | "polymarket";
11
- /**
12
- * Provider-specific metadata attached to every domain aggregate.
13
- * Keys are namespaced field paths, e.g. "polymarket.conditionId" or "dflow.yesMint".
14
- * Values are raw JSON-decoded values.
15
- */
16
- type ProviderMeta = Record<string, unknown>;
17
- /** Provider-sourced label attached to an Event. */
18
- interface PredictTag {
19
- slug: string;
20
- label: string;
21
- source: ProviderSource;
22
- provider_meta?: ProviderMeta;
23
- }
24
- /** Lifecycle status of a prediction event (normalised across all providers). */
25
- type EventStatus = "pending" | "open" | "closed" | "voided";
26
- /** Settlement / resolution data source for an event. */
27
- interface SettlementSource {
28
- url: string;
29
- name?: string;
30
- }
31
- /** Root aggregate for a prediction event from the prediction-server API. */
32
- interface PredictEvent {
33
- /** Internal database surrogate key (absent when not yet persisted). */
34
- id?: number;
35
- /**
36
- * Canonical business key shared across all providers.
37
- * - DFlow: ticker (e.g. "KXBTCD-25FEB-T68000")
38
- * - Polymarket: slug (e.g. "will-trump-win-2024")
39
- */
40
- slug: string;
41
- title: string;
42
- subtitle?: string;
43
- description?: string;
44
- image_url?: string;
45
- status: EventStatus;
46
- /** ISO 8601 timestamp; absent if the provider does not supply it. */
47
- start_at?: string;
48
- end_at?: string;
49
- created_at?: string;
50
- updated_at?: string;
51
- /** Provider-sourced labels for display only. */
52
- tags?: PredictTag[];
53
- /** All values are USD amounts. */
54
- volume?: number;
55
- volume_24h?: number;
56
- liquidity?: number;
57
- open_interest?: number;
58
- settlement_sources?: SettlementSource[];
59
- /** Nested markets; omitted when the request used `with_markets=false`. */
60
- markets?: PredictMarket[];
61
- source: ProviderSource;
62
- provider_meta?: ProviderMeta;
63
- }
64
- /** Lifecycle status of a prediction market (normalised across all providers). */
65
- type MarketStatus = "pending" | "open" | "closed" | "voided";
66
- /** Final resolution of a closed market. Empty string means unresolved. */
67
- type MarketResult = "yes" | "no" | "voided" | "";
68
- /** One possible outcome in a binary (or multi-outcome) prediction market. */
69
- interface MarketOutcome {
70
- /** Display name, e.g. "Yes" or "No". */
71
- label: string;
72
- /** Current implied probability [0, 1]. */
73
- price?: number;
74
- best_bid?: number;
75
- best_ask?: number;
76
- }
77
- /** Tradeable prediction outcome within an Event. */
78
- interface PredictMarket {
79
- id?: number;
80
- event_id?: number;
81
- slug: string;
82
- event_slug: string;
83
- question: string;
84
- description?: string;
85
- image_url?: string;
86
- /** Resolution/settlement rules in order. */
87
- rules?: string[];
88
- status: MarketStatus;
89
- result?: MarketResult;
90
- start_at?: string;
91
- end_at?: string;
92
- expires_at?: string;
93
- closed_at?: string;
94
- created_at?: string;
95
- updated_at?: string;
96
- /** Always present; binary markets have exactly 2 outcomes (YES at [0], NO at [1]). */
97
- outcomes: MarketOutcome[];
98
- volume?: number;
99
- volume_24h?: number;
100
- liquidity?: number;
101
- open_interest?: number;
102
- source: ProviderSource;
103
- provider_meta?: ProviderMeta;
104
- }
105
- /** Generic paginated result set returned by the prediction-server list endpoints. */
106
- interface PredictPage<T> {
107
- items: T[];
108
- next_cursor?: string;
109
- has_more?: boolean;
110
- limit?: number;
111
- /** Not all backends support total count. */
112
- total?: number;
113
- }
114
- /** Valid sort fields accepted by `GET /api/v1/events`. */
115
- type EventSortField = "volume" | "volume_24h" | "liquidity" | "open_interest" | "end_at" | "start_at" | "created_at";
116
- /** Query parameters for `listEvents`. All fields are optional. */
117
- interface ListEventsParams {
118
- /** Page size. Server default: 20. */
119
- limit?: number;
120
- /** Opaque pagination cursor returned by the previous page's `next_cursor`. */
121
- cursor?: string;
122
- /** Filter by event lifecycle status. */
123
- status?: EventStatus;
124
- /** Filter by upstream provider. */
125
- source?: ProviderSource;
126
- /** Unified navigation tag slug (e.g. "politics", "sports"). */
127
- tag_slug?: string;
128
- /** Full-text search query. */
129
- search?: string;
130
- /** Field to sort by. */
131
- sort_by?: EventSortField;
132
- /** When `true`, sort ascending. Defaults to descending. */
133
- sort_asc?: boolean;
134
- /**
135
- * When `false`, markets are omitted from each event for lighter payloads.
136
- * Defaults to `true` on the server.
137
- */
138
- with_markets?: boolean;
139
- }
140
- /** Single price level in an order book. */
141
- interface OrderbookLevel {
142
- price: number;
143
- size: number;
144
- }
145
- /** Aggregated order book for a market. */
146
- interface Orderbook {
147
- market_id: string;
148
- /** Sorted by price descending. */
149
- bids: OrderbookLevel[];
150
- /** Sorted by price ascending. */
151
- asks: OrderbookLevel[];
152
- /** best_ask − best_bid; absent when either side is empty. */
153
- spread?: number;
154
- }
155
- /** On-chain trade type. */
156
- type TradeType = "TRADE" | "SPLIT" | "MERGE" | "REDEEM" | "REWARD" | "CONVERSION" | "MAKER_REBATE" | "REFERRAL_REWARD";
157
- /** Lightweight event summary embedded in a trade. */
158
- interface EventSummary {
159
- slug: string;
160
- title: string;
161
- image_url?: string;
162
- status: EventStatus;
163
- }
164
- /** Lightweight market summary embedded in a trade. */
165
- interface MarketSummary {
166
- slug: string;
167
- question: string;
168
- status: MarketStatus;
169
- }
170
- /** A single trade record. */
171
- interface PredictTrade {
172
- id: string;
173
- source: ProviderSource;
174
- side?: string;
175
- outcome?: string;
176
- outcome_index?: number;
177
- price?: number;
178
- size: number;
179
- usd_size?: number;
180
- /** Unix seconds. */
181
- timestamp: number;
182
- tx_hash?: string;
183
- wallet?: string;
184
- type: TradeType;
185
- event?: EventSummary;
186
- market?: MarketSummary;
187
- provider_meta?: ProviderMeta;
188
- }
189
- /** Query parameters for `GET /api/v1/markets/{slug}/trades`. */
190
- interface ListMarketTradesParams {
191
- source: ProviderSource;
192
- limit?: number;
193
- cursor?: string;
194
- /** Filter by side: `"BUY"` or `"SELL"`. */
195
- side?: string;
196
- }
197
- /** Query parameters for `GET /api/v1/trades` (by wallet). */
198
- interface ListTradesParams {
199
- /** Provider source. Omit to aggregate all providers. */
200
- source?: ProviderSource;
201
- wallet: string;
202
- limit?: number;
203
- cursor?: string;
204
- /** Comma-separated trade types. */
205
- type?: string;
206
- side?: string;
207
- }
208
- /** A single price-history data point. */
209
- interface PricePoint {
210
- /** Unix seconds. */
211
- t: number;
212
- /** Price [0, 1]. */
213
- p: number;
214
- }
215
- /** Response from `GET /api/v1/markets/{slug}/price-history`. */
216
- interface PriceHistoryResponse {
217
- points: PricePoint[];
218
- }
219
- /** Accepted values for the `range` query parameter. */
220
- type PriceHistoryRange = "1d" | "1w" | "1m" | "all";
221
- /** OHLCV candlestick data point. */
222
- interface Candlestick {
223
- timestamp: string;
224
- open: number;
225
- high: number;
226
- low: number;
227
- close: number;
228
- volume: number;
229
- }
230
- /** Query parameters for `GET /api/v1/markets/{slug}/candlesticks`. */
231
- interface ListCandlesticksParams {
232
- /** Candle interval (e.g. `"1m"`, `"5m"`, `"1h"`, `"1d"`). Default: `"1h"`. */
233
- interval?: string;
234
- /** Number of candles. Default: 100. */
235
- limit?: number;
236
- }
237
- /** Query parameters for `GET /api/v1/events/{slug}/similar`. */
238
- interface SimilarEventsParams {
239
- /** Number of results (default 5, max 20). */
240
- limit?: number;
241
- /** When true, only return events from the same provider. */
242
- same_source?: boolean;
243
- }
244
- /** A single user position in a prediction market. */
245
- interface PredictPosition {
246
- source: ProviderSource;
247
- side: string;
248
- size: number;
249
- avg_price?: number;
250
- current_price?: number;
251
- current_value?: number;
252
- initial_value?: number;
253
- pnl?: number;
254
- pnl_percent?: number;
255
- realized_pnl?: number;
256
- redeemable: boolean;
257
- event?: PredictEvent;
258
- market?: PredictMarket;
259
- provider_meta?: ProviderMeta;
260
- }
261
- /** Response from `GET /api/v1/positions`. */
262
- interface PositionsResponse {
263
- user: string;
264
- positions: PredictPosition[];
265
- }
266
- /** Response from `GET /api/v1/balance`. */
267
- interface BalanceResponse {
268
- user: string;
269
- source: ProviderSource;
270
- /** Token symbol (e.g. "USDC"). */
271
- token: string;
272
- /** Human-readable balance (e.g. "125.50"). */
273
- balance: string;
274
- /** Raw balance in smallest unit (e.g. "125500000"). */
275
- raw_balance: string;
276
- /** Token decimals (e.g. 6 for USDC). */
277
- decimals: number;
278
- }
279
- /** Lifecycle status of a user order. */
280
- type OrderStatus = "live" | "matched" | "cancelled" | "invalid" | "submitted" | "pending" | "open" | "pending_close" | "closed" | "failed" | "expired";
281
- /** Order direction. */
282
- type OrderSide = "BUY" | "SELL";
283
- /** A single user order record. */
284
- interface PredictOrder {
285
- id: string;
286
- source: ProviderSource;
287
- status: OrderStatus;
288
- market_id?: string;
289
- asset_id?: string;
290
- side?: OrderSide;
291
- outcome?: string;
292
- price?: string;
293
- original_size?: string;
294
- size_matched?: string;
295
- in_amount?: string;
296
- out_amount?: string;
297
- order_type?: string;
298
- /** Unix seconds. */
299
- created_at?: number;
300
- expires_at?: number;
301
- provider_meta?: ProviderMeta;
302
- }
303
- /** Query parameters for `GET /api/v1/orders`. */
304
- interface ListOrdersParams {
305
- /** Provider source. Omit to aggregate all providers. */
306
- source?: ProviderSource;
307
- wallet_address?: string;
308
- market_id?: string;
309
- asset_id?: string;
310
- next_cursor?: string;
311
- }
312
- /** Result of `DELETE /api/v1/orders/{id}`. */
313
- interface CancelOrderResult {
314
- cancelled: string[];
315
- not_cancelled: Record<string, string>;
316
- }
317
- /** Request body for `POST /api/v1/orders/dflow/quote`. */
318
- interface DFlowQuoteRequest {
319
- inputMint: string;
320
- outputMint: string;
321
- amount: string;
322
- userPublicKey: string;
323
- slippageBps?: number;
324
- }
325
- /** Raw upstream response from DFlow quote (transparent passthrough). */
326
- type DFlowQuoteResponse = Record<string, unknown>;
327
- /** Context stored alongside a DFlow order for later enrichment. */
328
- interface DFlowOrderContext {
329
- user_public_key: string;
330
- input_mint: string;
331
- output_mint: string;
332
- amount: string;
333
- price: string;
334
- side: string;
335
- outcome: string;
336
- market_slug: string;
337
- slippage_bps: number;
338
- }
339
- /** Request body for `POST /api/v1/orders/dflow/submit`. */
340
- interface DFlowSubmitRequest {
341
- signedTransaction: string;
342
- orderContext: DFlowOrderContext;
343
- }
344
- /** Response from `POST /api/v1/orders/dflow/submit`. */
345
- interface DFlowSubmitResponse {
346
- signature: string;
347
- status: OrderStatus;
348
- }
349
- /** Order type for Polymarket CLOB. */
350
- type PolymarketOrderType = "GTC" | "FOK" | "GTD" | "FAK";
351
- /** Input for creating a Polymarket limit order. */
352
- interface CreateOrderInput {
353
- /** Token ID (outcome asset ID) from market provider_meta. */
354
- tokenId: string;
355
- /** Price in range [0.01, 0.99]. */
356
- price: number;
357
- /** Order size in USDC. */
358
- size: number;
359
- side: OrderSide;
360
- orderType?: PolymarketOrderType;
361
- /** Minimum tick size for this market (from Polymarket gamma API). */
362
- tickSize: "0.1" | "0.01" | "0.001" | "0.0001";
363
- /** Whether this is a neg-risk market (uses different exchange contract). */
364
- negRisk?: boolean;
365
- /** Expiration timestamp (Unix seconds). Required for GTD orders. */
366
- expiration?: number;
367
- /**
368
- * The funder address that holds the USDC (proxy/Gnosis Safe wallet).
369
- * Defaults to the signer address when not provided.
370
- */
371
- funderAddress?: string;
372
- }
373
- /** WebSocket subscription channel. */
374
- type WsChannel = "orderbook" | "prices" | "trades";
375
- /** WebSocket connection lifecycle status. */
376
- type WsConnectionStatus = "connecting" | "connected" | "disconnected" | "reconnecting";
377
- /**
378
- * Full orderbook snapshot pushed via the `orderbook` channel.
379
- * Always a complete replacement — no delta merging required.
380
- */
381
- interface WsOrderbookEvent {
382
- market_slug: string;
383
- bids: OrderbookLevel[];
384
- asks: OrderbookLevel[];
385
- spread?: number;
386
- }
387
- /** Latest bid/ask prices pushed via the `prices` channel. */
388
- interface WsPriceEvent {
389
- market_slug: string;
390
- yes_bid?: number;
391
- yes_ask?: number;
392
- no_bid?: number;
393
- no_ask?: number;
394
- spread?: number;
395
- }
396
- /** Single trade execution pushed via the `trades` channel. */
397
- interface WsTradeEvent {
398
- market_slug: string;
399
- trade_id?: string;
400
- side: string;
401
- price: number;
402
- size: number;
403
- outcome?: string;
404
- }
405
- /** Union of all channel data payloads. */
406
- type WsChannelEvent = WsOrderbookEvent | WsPriceEvent | WsTradeEvent;
407
- /** Subscribe or unsubscribe message sent to the server. */
408
- interface WsSubscribeMessage {
409
- type: "subscribe" | "unsubscribe";
410
- channels: WsChannel[];
411
- market_slugs: string[];
412
- }
413
- /** Client ping (application-level keepalive). */
414
- interface WsPingMessage {
415
- type: "ping";
416
- }
417
- /** Union of all messages the client can send. */
418
- type WsClientMessage = WsSubscribeMessage | WsPingMessage;
419
- /** Pong response to a client ping. */
420
- interface WsPongMessage {
421
- type: "pong";
422
- }
423
- /** Subscription confirmation. */
424
- interface WsSubscribedMessage {
425
- type: "subscribed";
426
- channels: WsChannel[];
427
- market_slugs: string[];
428
- }
429
- /** Error codes the server may return. */
430
- type WsErrorCode = "invalid_message" | "market_not_found" | "provider_unavailable" | "provider_reconnecting";
431
- /** Error message from the server. */
432
- interface WsErrorMessage {
433
- type: "error";
434
- code: WsErrorCode;
435
- message: string;
436
- }
437
- /** Data message carrying a channel event payload. */
438
- interface WsDataMessage<T extends WsChannelEvent = WsChannelEvent> {
439
- channel: WsChannel;
440
- market_slug: string;
441
- data: T;
442
- ts: number;
443
- }
444
- /** Union of all messages the server can send. */
445
- type WsServerMessage = WsPongMessage | WsSubscribedMessage | WsErrorMessage | WsDataMessage;
446
-
447
- /**
448
- * HTTP client for the prediction-server REST API.
449
- *
450
- * Covers all prediction, market, order, position, and trading endpoints.
451
- *
452
- * @example
453
- * ```ts
454
- * const client = new PredictClient("https://api.example.com");
455
- * const page = await client.listEvents({ status: "open", limit: 20 });
456
- * const event = await client.getEvent("will-trump-win-2024");
457
- * const market = await client.getMarket("will-trump-win-2024-yes");
458
- * ```
459
- */
460
- declare class PredictClient {
461
- private readonly endpoint;
462
- constructor(endpoint: string);
463
- /**
464
- * List prediction events with optional filtering, sorting, and pagination.
465
- *
466
- * Maps to `GET /api/v1/events`.
467
- *
468
- * @param params - Optional query parameters (filter, sort, pagination).
469
- * @returns A paginated page of events.
470
- */
471
- listEvents(params?: ListEventsParams): Promise<PredictPage<PredictEvent>>;
472
- /**
473
- * Fetch a single prediction event by its slug.
474
- *
475
- * Maps to `GET /api/v1/events/:slug?source=...`.
476
- *
477
- * @param slug - Canonical event slug (e.g. "will-trump-win-2024" for Polymarket
478
- * or "KXBTCD-25FEB-T68000" for DFlow).
479
- * @param source - Upstream provider (`"dflow"` or `"polymarket"`).
480
- * @returns The matching event.
481
- * @throws When the server responds with 404 or any other non-2xx status.
482
- */
483
- getEvent(slug: string, source?: ProviderSource): Promise<PredictEvent>;
484
- /**
485
- * Fetch events similar to the given slug.
486
- *
487
- * Maps to `GET /api/v1/events/:slug/similar?source=...`.
488
- */
489
- getSimilarEvents(slug: string, source: ProviderSource, params?: SimilarEventsParams): Promise<PredictEvent[]>;
490
- /**
491
- * Fetch a single prediction market by its slug.
492
- *
493
- * Maps to `GET /api/v1/markets/:slug?source=...`.
494
- *
495
- * @param slug - Canonical market slug.
496
- * @param source - Upstream provider (`"dflow"` or `"polymarket"`).
497
- * @returns The matching market.
498
- * @throws When the server responds with 404 or any other non-2xx status.
499
- */
500
- getMarket(slug: string, source?: ProviderSource): Promise<PredictMarket>;
501
- /** Maps to `GET /api/v1/markets/:slug/orderbook?source=...`. */
502
- getOrderbook(slug: string, source: ProviderSource): Promise<Orderbook>;
503
- /** Maps to `GET /api/v1/markets/:slug/trades?source=...`. */
504
- listMarketTrades(slug: string, params: ListMarketTradesParams): Promise<PredictPage<PredictTrade>>;
505
- /** Maps to `GET /api/v1/markets/:slug/price-history?source=...&range=...`. */
506
- getPriceHistory(slug: string, source: ProviderSource, range?: PriceHistoryRange): Promise<PriceHistoryResponse>;
507
- /** Maps to `GET /api/v1/markets/:slug/candlesticks?interval=...&limit=...`. */
508
- listCandlesticks(slug: string, params?: ListCandlesticksParams): Promise<Candlestick[]>;
509
- /**
510
- * Maps to `GET /api/v1/positions?source=...&user=...`.
511
- *
512
- * @param user - Wallet address.
513
- * @param source - Provider source. Omit to aggregate all providers.
514
- */
515
- getPositions(user: string, source?: ProviderSource): Promise<PositionsResponse>;
516
- /**
517
- * Get the on-chain USDC balance for a wallet.
518
- *
519
- * Maps to `GET /api/v1/balance?source=...&user=...`.
520
- *
521
- * @param source - Provider source (`"dflow"` for Solana, `"polymarket"` for Polygon).
522
- * @param user - Wallet address.
523
- */
524
- getBalance(source: ProviderSource, user: string): Promise<BalanceResponse>;
525
- /** Maps to `GET /api/v1/orders?source=...&wallet_address=...`. */
526
- listOrders(params: ListOrdersParams): Promise<PredictPage<PredictOrder>>;
527
- /** Maps to `GET /api/v1/orders/:id?source=...`. */
528
- getOrder(id: string, source: ProviderSource): Promise<PredictOrder>;
529
- /** Maps to `DELETE /api/v1/orders/:id?source=...`. */
530
- cancelOrder(id: string, source: ProviderSource): Promise<CancelOrderResult>;
531
- /**
532
- * Create a Polymarket limit order via the prediction-server proxy.
533
- *
534
- * Maps to `POST /api/v1/orders/polymarket`.
535
- *
536
- * The caller must attach Polymarket CLOB authentication headers:
537
- * - `POLY_ADDRESS` — the EVM wallet address.
538
- * - `POLY_SIGNATURE` — L1 signature or L2 API key.
539
- * - `POLY_TIMESTAMP` — Unix milliseconds string.
540
- * - `POLY_NONCE` — credential nonce (use `"0"` for in-session derived creds).
541
- *
542
- * @param input - Order parameters.
543
- * @param headers - Polymarket CLOB auth headers (`POLY_*`).
544
- */
545
- createPolymarketOrder(input: CreateOrderInput, headers: Record<string, string>): Promise<PredictOrder>;
546
- /** Maps to `POST /api/v1/orders/dflow/quote`. */
547
- createDFlowQuote(body: DFlowQuoteRequest): Promise<DFlowQuoteResponse>;
548
- /** Maps to `POST /api/v1/orders/dflow/submit`. */
549
- submitDFlowTransaction(body: DFlowSubmitRequest): Promise<DFlowSubmitResponse>;
550
- /** Maps to `GET /api/v1/trades?source=...&wallet=...`. */
551
- listTrades(params: ListTradesParams): Promise<PredictPage<PredictTrade>>;
552
- }
553
- /**
554
- * Factory function for `PredictClient`.
555
- *
556
- * @param endpoint - Base URL of the prediction-server, without a trailing slash.
557
- */
558
- declare function createPredictClient(endpoint: string): PredictClient;
559
-
560
- /**
561
- * PredictWsClient — WebSocket client for prediction-server real-time data.
562
- *
563
- * Connects to `GET /api/v1/ws` (RFC 6455) and supports three channels:
564
- * `orderbook`, `prices`, and `trades`.
565
- *
566
- * Features:
567
- * - Auto-reconnect with exponential backoff
568
- * - Application-level ping/pong keepalive
569
- * - Subscription state tracking with automatic restore after reconnect
570
- * - Event-emitter pattern for typed message dispatch
571
- */
572
-
573
- /** Configuration for `PredictWsClient`. */
574
- interface PredictWsClientConfig {
575
- /** Full WebSocket URL, e.g. `"wss://api.example.com/api/v1/ws"`. */
576
- wsUrl: string;
577
- /** Connect immediately on construction. Default: `true`. */
578
- autoConnect?: boolean;
579
- /** Reconnect automatically on unexpected close. Default: `true`. */
580
- autoReconnect?: boolean;
581
- /** Base delay (ms) for exponential backoff. Default: `1000`. */
582
- reconnectIntervalBase?: number;
583
- /** Maximum reconnect delay (ms). Default: `30000`. */
584
- reconnectMaxInterval?: number;
585
- /** Interval (ms) between application-level pings. Default: `30000`. */
586
- pingInterval?: number;
587
- /**
588
- * How long (ms) to wait for a pong after sending a ping before
589
- * considering the connection dead. Default: `10000`.
590
- * Must be less than `pingInterval`.
591
- */
592
- pongTimeout?: number;
593
- }
594
- type EventCallback<T = unknown> = (data: T) => void;
595
- interface EventListeners {
596
- connect: EventCallback<void>[];
597
- disconnect: EventCallback<{
598
- code?: number;
599
- reason?: string;
600
- }>[];
601
- reconnecting: EventCallback<{
602
- attempt: number;
603
- delay: number;
604
- }>[];
605
- error: EventCallback<{
606
- code: WsErrorCode;
607
- message: string;
608
- }>[];
609
- status: EventCallback<WsConnectionStatus>[];
610
- subscribed: EventCallback<{
611
- channels: WsChannel[];
612
- market_slugs: string[];
613
- }>[];
614
- orderbook: EventCallback<WsDataMessage<WsOrderbookEvent>>[];
615
- prices: EventCallback<WsDataMessage<WsPriceEvent>>[];
616
- trades: EventCallback<WsDataMessage<WsTradeEvent>>[];
617
- }
618
- type WsEventType = keyof EventListeners;
619
- declare class PredictWsClient {
620
- private ws;
621
- private readonly wsUrl;
622
- private readonly autoReconnect;
623
- private readonly reconnectBase;
624
- private readonly reconnectMax;
625
- private readonly pingMs;
626
- private readonly pongTimeoutMs;
627
- private status;
628
- private reconnectAttempts;
629
- private reconnectTimer;
630
- private pingTimer;
631
- private pongTimer;
632
- private shouldReconnect;
633
- private listeners;
634
- private subs;
635
- constructor(config: PredictWsClientConfig);
636
- connect(): void;
637
- disconnect(): void;
638
- /** Disconnect and clear all subscription state and listeners. */
639
- destroy(): void;
640
- getStatus(): WsConnectionStatus;
641
- isConnected(): boolean;
642
- /**
643
- * Subscribe to one or more channels for the given market slugs.
644
- * The server acknowledges with a `subscribed` message.
645
- */
646
- subscribe(channels: WsChannel[], marketSlugs: string[]): void;
647
- /**
648
- * Unsubscribe from one or more channels for the given market slugs.
649
- */
650
- unsubscribe(channels: WsChannel[], marketSlugs: string[]): void;
651
- /**
652
- * Subscribe to price updates for the given slugs.
653
- * Returns an unsubscribe function.
654
- */
655
- subscribePrices(slugs: string[], onUpdate: (msg: WsDataMessage<WsPriceEvent>) => void): () => void;
656
- /**
657
- * Subscribe to orderbook snapshots for the given slugs.
658
- * Returns an unsubscribe function.
659
- */
660
- subscribeOrderbook(slugs: string[], onUpdate: (msg: WsDataMessage<WsOrderbookEvent>) => void): () => void;
661
- /**
662
- * Subscribe to trade events for the given slugs.
663
- * Returns an unsubscribe function.
664
- */
665
- subscribeTrades(slugs: string[], onUpdate: (msg: WsDataMessage<WsTradeEvent>) => void): () => void;
666
- /** Register a callback for connection status changes. Returns unsubscribe. */
667
- onStatusChange(cb: (status: WsConnectionStatus) => void): () => void;
668
- /** Register a callback for server-sent errors. Returns unsubscribe. */
669
- onError(cb: (err: {
670
- code: WsErrorCode;
671
- message: string;
672
- }) => void): () => void;
673
- on<T extends WsEventType>(event: T, callback: EventListeners[T][number]): () => void;
674
- off<T extends WsEventType>(event: T, callback: EventListeners[T][number]): void;
675
- private emit;
676
- private send;
677
- private setStatus;
678
- private handleMessage;
679
- private scheduleReconnect;
680
- private clearReconnectTimer;
681
- private restoreSubscriptions;
682
- private startPing;
683
- private stopPing;
684
- /**
685
- * Start a timer that fires if the server does not reply with pong
686
- * within `pongTimeoutMs`. On timeout the socket is closed so
687
- * the normal reconnect flow kicks in.
688
- */
689
- private armPongTimeout;
690
- private clearPongTimer;
691
- }
692
- /**
693
- * Factory function for `PredictWsClient`.
694
- *
695
- * @param config - WebSocket client configuration.
696
- */
697
- declare function createPredictWsClient(config: PredictWsClientConfig): PredictWsClient;
698
-
699
- /**
700
- * Server-safe pure functions for events query parameters.
701
- *
702
- * This module contains NO React imports and can be used in Server Components,
703
- * route handlers, or any non-browser context.
704
- */
705
-
706
- /** Default page size for list queries. */
707
- declare const DEFAULT_PAGE_SIZE = 48;
708
- /**
709
- * Selection emitted by a categories/tag selector widget.
710
- * Duplicated here to avoid pulling in UI component barrel into server-only bundles.
711
- */
712
- interface TagSlugSelection {
713
- categorySlug: string | null;
714
- tagSlug: string | null;
715
- }
716
- /**
717
- * Resolve a `TagSlugSelection` to a single `tag_slug` string for the API.
718
- */
719
- declare function resolveTagSlug(selection: TagSlugSelection | null | undefined): string | undefined;
720
- /**
721
- * Input accepted by {@link resolveEventsParams}. All fields optional;
722
- * defaults match the client-side `useInfiniteEvents` hook's initial state.
723
- */
724
- interface ResolveEventsParamsInput {
725
- tagSlugSelection?: TagSlugSelection | null;
726
- limit?: number;
727
- status?: EventStatus;
728
- sort_by?: EventSortField;
729
- sort_asc?: boolean;
730
- source?: ProviderSource;
731
- with_markets?: boolean;
732
- }
733
- /**
734
- * Build a clean `ListEventsParams` from loose user inputs.
735
- *
736
- * Server-side `prefetchInfiniteQuery` and client-side `useInfiniteEvents` must
737
- * both use this function to guarantee identical query keys.
738
- */
739
- declare function resolveEventsParams(input?: ResolveEventsParamsInput): ListEventsParams;
740
- /** Stable TanStack Query key for the events infinite query. */
741
- declare function infiniteEventsQueryKey(params: ListEventsParams): unknown[];
742
- /**
743
- * Fetch a single page of events. Can be used outside of React
744
- * (e.g. in Server Components, loaders, or tests).
745
- */
746
- declare function fetchEventsPage(client: PredictClient, params: ListEventsParams): Promise<PredictPage<PredictEvent>>;
747
- /** Stable TanStack Query key for a single event. */
748
- declare function eventQueryKey(slug: string, source?: ProviderSource): unknown[];
749
- /**
750
- * Fetch a single event. Can be used outside of React
751
- * (e.g. in Server Components, loaders, or tests).
752
- */
753
- declare function fetchEvent(client: PredictClient, slug: string, source?: ProviderSource): Promise<PredictEvent>;
754
-
755
- /** Stable TanStack Query key for a single market. */
756
- declare function marketQueryKey(slug: string, source?: ProviderSource): unknown[];
757
- /**
758
- * Fetch function usable outside React (e.g. in loaders or tests).
759
- */
760
- declare function fetchMarket(client: PredictClient, slug: string, source?: ProviderSource): Promise<PredictMarket>;
761
- interface UseMarketParams {
762
- /** Canonical market slug. */
763
- slug: string;
764
- /** Upstream provider. Required by prediction-server for single-market fetch. */
765
- source?: ProviderSource;
766
- }
767
- /**
768
- * React Query hook for `GET /api/v1/markets/:slug` via the prediction-server client.
769
- *
770
- * @example
771
- * ```tsx
772
- * const { data, isLoading } = useMarket({ slug: "KXBTCD-25FEB-T68000-yes", source: "dflow" });
773
- * ```
774
- */
775
- declare function useMarket(params: UseMarketParams, queryOptions?: Omit<UseQueryOptions<PredictMarket, Error, PredictMarket, unknown[]>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<PredictMarket, Error>;
776
-
777
- /**
778
- * Polymarket L2 HMAC-SHA256 signing utilities.
779
- *
780
- * Uses the Web Crypto API (available in all modern browsers and Node ≥18) to
781
- * avoid taking a dependency on Node.js `crypto` or any third-party library.
782
- *
783
- * References:
784
- * https://docs.polymarket.com/#authentication
785
- * https://github.com/Polymarket/clob-client/blob/main/src/headers/index.ts
786
- */
787
- /**
788
- * Compute an HMAC-SHA256 signature using the Web Crypto API.
789
- *
790
- * @param secretBase64 - The signing secret encoded as base64.
791
- * @param message - The plaintext message to sign.
792
- * @returns The signature as a base64 string.
793
- */
794
- declare function hmacSha256Base64(secretBase64: string, message: string): Promise<string>;
795
- /** HTTP method values accepted by Polymarket CLOB. */
796
- type HttpMethod = "GET" | "DELETE" | "POST" | "PUT";
797
- interface PolymarketL2HeadersInput {
798
- /** L2 API key (from credential exchange). */
799
- apiKey: string;
800
- /** L2 HMAC secret (base64-encoded). */
801
- secret: string;
802
- /** L2 passphrase. */
803
- passphrase: string;
804
- /** HTTP method of the request. */
805
- method: HttpMethod;
806
- /** Request path without host, e.g. "/order". */
807
- requestPath: string;
808
- /** Raw JSON request body string; empty string for GET/DELETE. */
809
- body?: string;
810
- }
811
- interface PolymarketL2Headers {
812
- POLY_ADDRESS: string;
813
- POLY_SIGNATURE: string;
814
- POLY_TIMESTAMP: string;
815
- POLY_API_KEY: string;
816
- POLY_PASSPHRASE: string;
817
- }
818
- /**
819
- * Build Polymarket L2 HMAC authentication headers for a CLOB API request.
820
- *
821
- * The signature is `HMAC-SHA256(secret, timestamp + method + requestPath + body)`.
822
- *
823
- * @param address - EVM wallet address (owner of the credentials).
824
- * @param input - Credential and request details.
825
- * @returns An object containing all required `POLY_*` headers.
826
- */
827
- declare function buildPolymarketL2Headers(address: string, input: PolymarketL2HeadersInput): Promise<PolymarketL2Headers>;
828
- /** EIP-712 domain used by Polymarket CLOB for L1 authentication. */
829
- declare const CLOB_AUTH_DOMAIN: {
830
- readonly name: "ClobAuthDomain";
831
- readonly version: "1";
832
- readonly chainId: 137;
833
- };
834
- /** EIP-712 types for the `ClobAuth` struct. */
835
- declare const CLOB_AUTH_TYPES: {
836
- readonly ClobAuth: readonly [{
837
- readonly name: "address";
838
- readonly type: "address";
839
- }, {
840
- readonly name: "timestamp";
841
- readonly type: "string";
842
- }, {
843
- readonly name: "nonce";
844
- readonly type: "uint256";
845
- }, {
846
- readonly name: "message";
847
- readonly type: "string";
848
- }];
849
- };
850
- interface BuildClobAuthMessageInput {
851
- /** EVM wallet address. */
852
- address: string;
853
- /** Unix seconds string. */
854
- timestamp: string;
855
- /** Credential nonce. Use `0` for a permanent / deterministic credential. */
856
- nonce: number;
857
- }
858
- /**
859
- * Build the EIP-712 typed data value for a `ClobAuth` message.
860
- * The resulting object is passed to `eth_signTypedData_v4`.
861
- */
862
- declare function buildClobAuthMessage(input: BuildClobAuthMessageInput): Record<string, unknown>;
863
- /**
864
- * Exchange an L1 EIP-712 signature for Polymarket L2 API credentials.
865
- *
866
- * Calls `GET https://clob.polymarket.com/auth/derive-api-key` directly from
867
- * the browser (the endpoint has `Access-Control-Allow-Origin: *`).
868
- *
869
- * @returns The raw API response `{ apiKey, secret, passphrase }`.
870
- */
871
- declare function derivePolymarketApiKey(address: string, signature: string, timestamp: string, nonce: number): Promise<{
872
- apiKey: string;
873
- secret: string;
874
- passphrase: string;
875
- }>;
876
-
877
- /**
878
- * Polymarket CTF Exchange order construction utilities.
879
- *
880
- * Implements EIP-712 signing for `Order` structs on the CTF Exchange and
881
- * Neg-Risk CTF Exchange contracts (Polygon mainnet).
882
- *
883
- * References:
884
- * https://github.com/Polymarket/clob-client/blob/main/src/order-builder/builder.ts
885
- * https://github.com/Polymarket/clob-client/blob/main/src/order-builder/helpers.ts
886
- * https://docs.polymarket.com/#create-order
887
- */
888
-
889
- /** Polymarket CTF Exchange contract (standard markets). */
890
- declare const CTF_EXCHANGE_ADDRESS: "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E";
891
- /** Polymarket Neg-Risk CTF Exchange contract (neg-risk markets). */
892
- declare const NEG_RISK_CTF_EXCHANGE_ADDRESS: "0xC5d563A36AE78145C45a50134d48A1215220f80a";
893
- /** USDC.e (Bridged USDC) on Polygon — the only collateral token on Polymarket. */
894
- declare const USDC_ADDRESS: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
895
- /** Chain ID for Polygon mainnet. */
896
- declare const POLYGON_CHAIN_ID = 137;
897
- /**
898
- * Build the EIP-712 domain for the CTF Exchange.
899
- *
900
- * @param negRisk - When `true`, use the Neg-Risk exchange address.
901
- */
902
- declare function buildCtfExchangeDomain(negRisk?: boolean): {
903
- name: string;
904
- version: string;
905
- chainId: number;
906
- verifyingContract: "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E" | "0xC5d563A36AE78145C45a50134d48A1215220f80a";
907
- };
908
- /** EIP-712 type definitions for the Polymarket `Order` struct. */
909
- declare const CTF_ORDER_TYPES: {
910
- readonly Order: readonly [{
911
- readonly name: "salt";
912
- readonly type: "uint256";
913
- }, {
914
- readonly name: "maker";
915
- readonly type: "address";
916
- }, {
917
- readonly name: "signer";
918
- readonly type: "address";
919
- }, {
920
- readonly name: "taker";
921
- readonly type: "address";
922
- }, {
923
- readonly name: "tokenId";
924
- readonly type: "uint256";
925
- }, {
926
- readonly name: "makerAmount";
927
- readonly type: "uint256";
928
- }, {
929
- readonly name: "takerAmount";
930
- readonly type: "uint256";
931
- }, {
932
- readonly name: "expiration";
933
- readonly type: "uint256";
934
- }, {
935
- readonly name: "nonce";
936
- readonly type: "uint256";
937
- }, {
938
- readonly name: "feeRateBps";
939
- readonly type: "uint256";
940
- }, {
941
- readonly name: "side";
942
- readonly type: "uint8";
943
- }, {
944
- readonly name: "signatureType";
945
- readonly type: "uint8";
946
- }];
947
- };
948
- /** Order type enum matching CTFExchange.sol. */
949
- declare const ORDER_TYPE: {
950
- readonly GTC: 0;
951
- readonly FOK: 1;
952
- readonly GTD: 2;
953
- readonly FAK: 3;
954
- };
955
- /** Side enum matching CTFExchange.sol (0 = BUY, 1 = SELL). */
956
- declare const SIDE: {
957
- readonly BUY: 0;
958
- readonly SELL: 1;
959
- };
960
- interface BuildOrderMessageInput extends CreateOrderInput {
961
- /** Signer / owner address. */
962
- signerAddress: string;
963
- /** Signature type (0 = EOA, 1 = Magic, 2 = Poly Proxy). */
964
- signatureType: 0 | 1 | 2;
965
- }
966
- interface OrderMessage {
967
- salt: string;
968
- maker: string;
969
- signer: string;
970
- taker: string;
971
- tokenId: string;
972
- makerAmount: string;
973
- takerAmount: string;
974
- expiration: string;
975
- nonce: string;
976
- feeRateBps: string;
977
- side: number;
978
- signatureType: number;
979
- }
980
- /**
981
- * Build the EIP-712 typed data value for a Polymarket limit order.
982
- *
983
- * All amounts are in micro-USDC (1 USDC = 1 000 000).
984
- *
985
- * For a BUY order:
986
- * - `makerAmount` = USDC spent (cost = size × price)
987
- * - `takerAmount` = shares received (= size)
988
- *
989
- * For a SELL order:
990
- * - `makerAmount` = shares sold (= size)
991
- * - `takerAmount` = USDC received (cost = size × price)
992
- */
993
- declare function buildOrderMessage(input: BuildOrderMessageInput): OrderMessage;
994
- interface SignedOrder extends OrderMessage {
995
- signature: string;
996
- orderType: string;
997
- }
998
- interface BuildSignedOrderInput extends BuildOrderMessageInput {
999
- /** Hex signature returned by `eth_signTypedData_v4`. */
1000
- signature: string;
1001
- }
1002
- /**
1003
- * Construct the final signed order payload to submit to the Polymarket CLOB
1004
- * (via prediction-server proxy `POST /api/v1/orders/polymarket`).
1005
- */
1006
- declare function buildSignedOrder(input: BuildSignedOrderInput): SignedOrder;
1007
-
1008
- export { type WsChannelEvent as $, type ProviderMeta as A, type BalanceResponse as B, type Candlestick as C, type DFlowQuoteRequest as D, type EventStatus as E, type PredictTag as F, type SettlementSource as G, type MarketResult as H, type MarketOutcome as I, type EventSortField as J, type OrderbookLevel as K, type ListEventsParams as L, type MarketStatus as M, type EventSummary as N, type Orderbook as O, PredictClient as P, type MarketSummary as Q, type PricePoint as R, type SimilarEventsParams as S, type TradeType as T, type PredictPosition as U, type OrderStatus as V, type WsConnectionStatus as W, type OrderSide as X, type DFlowOrderContext as Y, type PolymarketOrderType as Z, type WsChannel as _, PredictWsClient as a, type WsClientMessage as a0, type WsSubscribeMessage as a1, type WsPingMessage as a2, type WsServerMessage as a3, type WsPongMessage as a4, type WsSubscribedMessage as a5, type WsErrorCode as a6, type WsErrorMessage as a7, eventQueryKey as a8, fetchEvent as a9, ORDER_TYPE as aA, SIDE as aB, buildOrderMessage as aC, buildSignedOrder as aD, type BuildOrderMessageInput as aE, type OrderMessage as aF, type BuildSignedOrderInput as aG, type SignedOrder as aH, DEFAULT_PAGE_SIZE as aI, resolveTagSlug as aa, resolveEventsParams as ab, infiniteEventsQueryKey as ac, fetchEventsPage as ad, type ResolveEventsParamsInput as ae, type TagSlugSelection as af, marketQueryKey as ag, fetchMarket as ah, useMarket as ai, type UseMarketParams as aj, CLOB_AUTH_DOMAIN as ak, CLOB_AUTH_TYPES as al, buildClobAuthMessage as am, hmacSha256Base64 as an, buildPolymarketL2Headers as ao, derivePolymarketApiKey as ap, type HttpMethod as aq, type PolymarketL2HeadersInput as ar, type PolymarketL2Headers as as, type BuildClobAuthMessageInput as at, CTF_EXCHANGE_ADDRESS as au, NEG_RISK_CTF_EXCHANGE_ADDRESS as av, USDC_ADDRESS as aw, POLYGON_CHAIN_ID as ax, buildCtfExchangeDomain as ay, CTF_ORDER_TYPES as az, type PredictPage as b, type PredictEvent as c, type ProviderSource as d, type PredictMarket as e, type ListMarketTradesParams as f, type PredictTrade as g, type PriceHistoryRange as h, type PriceHistoryResponse as i, type ListCandlesticksParams as j, type PositionsResponse as k, type ListOrdersParams as l, type PredictOrder as m, type CancelOrderResult as n, type ListTradesParams as o, type DFlowQuoteResponse as p, type DFlowSubmitResponse as q, type DFlowSubmitRequest as r, type WsDataMessage as s, type WsPriceEvent as t, type WsOrderbookEvent as u, type WsTradeEvent as v, type CreateOrderInput as w, createPredictClient as x, createPredictWsClient as y, type PredictWsClientConfig as z };