@agg-build/sdk 4.17.4 → 4.18.0

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.
@@ -0,0 +1,4320 @@
1
+ type CandleInterval = "1m" | "5m" | "1h" | "1d";
2
+ /** Universal OHLCV candle. Chart-library-agnostic. */
3
+ interface Candle {
4
+ /** Interval-aligned open time in seconds. */
5
+ openTime: number;
6
+ o: number;
7
+ h: number;
8
+ l: number;
9
+ c: number;
10
+ /** Accumulated trade volume. 0 if no trades in interval. */
11
+ v: number;
12
+ tradeCount: number;
13
+ isFinal: boolean;
14
+ }
15
+ /**
16
+ * Accumulates OHLCV candles from orderbook delta midpoints and trades.
17
+ * All 4 intervals computed simultaneously. onChange batched via rAF (~16ms).
18
+ */
19
+ declare class CandleBuilder {
20
+ private forming;
21
+ private closedMap;
22
+ private listeners;
23
+ private _midpoint;
24
+ private dirty;
25
+ private scheduled;
26
+ constructor();
27
+ /** Feed a midpoint (from orderbook delta). Updates O/H/L/C for all intervals. */
28
+ addMidpoint(midpoint: number, timestampSecs: number): void;
29
+ /** Feed a trade. Updates volume + refines H/L/C from trade price. */
30
+ addTrade(price: number, size: number, timestampSecs: number): void;
31
+ /** Current forming candle for an interval. */
32
+ getForming(interval: CandleInterval): Candle | null;
33
+ /** Closed candles for an interval (ring buffer, max 500, newest last). */
34
+ getClosed(interval: CandleInterval): Candle[];
35
+ /** Apply a bounded Worker view without recomputing candles from presentation samples. */
36
+ replaceTail(tail: Record<CandleInterval, {
37
+ forming: Candle | null;
38
+ closed: Candle[];
39
+ }>): void;
40
+ /** Current midpoint (latest value fed). */
41
+ get midpoint(): number | null;
42
+ /**
43
+ * Subscribe to state changes. Returns unsubscribe function.
44
+ * BATCHED: callbacks fire at most once per rAF frame (~16ms).
45
+ * In non-browser environments, falls back to 16ms setTimeout.
46
+ */
47
+ onChange(listener: () => void): () => void;
48
+ /** Clear all state (on reconnect). */
49
+ reset(): void;
50
+ /** Clear all state AND unsubscribe all listeners. Called on store eviction. */
51
+ dispose(): void;
52
+ private updateCandle;
53
+ private markDirty;
54
+ }
55
+
56
+ /**
57
+ * WebSocket protocol types for the Agg platform.
58
+ * All callback timestamps are in **seconds** (converted from server ms at SDK dispatch).
59
+ * These are plain TS interfaces — no Zod dependency for partner-side usage.
60
+ */
61
+ /** Aggregated level wire format: [price, totalSize, {venue: sizeAtPrice}] */
62
+ type WsAttributedLevel = [number, number, Record<string, number>];
63
+ /** Per-venue level wire format: [price, size] */
64
+ type WsVenueLevel = [number, number];
65
+ interface WsVenueInfo {
66
+ bestBid: number | null;
67
+ bestAsk: number | null;
68
+ }
69
+ interface WsVenueBook {
70
+ bids: WsVenueLevel[];
71
+ asks: WsVenueLevel[];
72
+ }
73
+ interface WsOrderbookSnapshot {
74
+ type: "orderbook_snapshot";
75
+ outcomeId: string;
76
+ channel?: "orderbook" | "trades";
77
+ seq: number;
78
+ checksum: number;
79
+ bids: WsAttributedLevel[];
80
+ asks: WsAttributedLevel[];
81
+ venueOrderbooks: Record<string, WsVenueBook>;
82
+ venues: Record<string, WsVenueInfo>;
83
+ midpoint: number | null;
84
+ spread: number | null;
85
+ /** @unit seconds (converted from server ms) */
86
+ timestamp: number;
87
+ /**
88
+ * Sticky tick of this outcome's book, inferred at runtime by the engine.
89
+ * `null` until inferred. Optional — older snapshot producers (REST fallback)
90
+ * may omit this field entirely.
91
+ */
92
+ tick?: number | null;
93
+ /** Provenance of the published `midpoint`. See {@link MarkSource}. */
94
+ markSource?: MarkSource$1;
95
+ }
96
+ /**
97
+ * Provenance tag for a published midpoint. Mirrors the Rust engine
98
+ * `MarkSource::as_str()` output.
99
+ */
100
+ type WsMarkSource = "local" | "local_merged" | "local_one_sided" | "sibling" | "local_boundary" | "none";
101
+ type MarkSource$1 = WsMarkSource;
102
+ interface WsOrderbookDelta {
103
+ type: "orderbook_delta";
104
+ outcomeId: string;
105
+ channel?: "orderbook" | "trades";
106
+ seq: number;
107
+ checksum: number;
108
+ bidChanges: WsAttributedLevel[];
109
+ askChanges: WsAttributedLevel[];
110
+ venueDeltaBooks: Record<string, {
111
+ bidChanges: WsVenueLevel[];
112
+ askChanges: WsVenueLevel[];
113
+ }>;
114
+ venues: Record<string, WsVenueInfo>;
115
+ midpoint: number | null;
116
+ spread: number | null;
117
+ /** @unit seconds (converted from server ms) */
118
+ timestamp: number;
119
+ }
120
+ interface WsTrade {
121
+ type: "trade";
122
+ outcomeId: string;
123
+ channel?: "orderbook" | "trades";
124
+ venue: string;
125
+ side: "buy" | "sell";
126
+ price: number;
127
+ size: number;
128
+ /** @unit seconds (converted from server ms) */
129
+ timestamp: number;
130
+ }
131
+ type WsCandleInterval = "1m" | "5m" | "1h" | "1d";
132
+ interface WsSubscribed {
133
+ type: "subscribed";
134
+ /** Confirmed ids. For `orderbook`/`trades` these are venueMarketOutcomeIds.
135
+ * For `arb` this historically mirrors the marketIds — prefer `marketIds`. */
136
+ outcomeIds: string[];
137
+ /** Confirmed marketIds — only set on `arb` confirmations, whose
138
+ * subscriptions are keyed by marketIds, not outcomeIds. */
139
+ marketIds?: string[];
140
+ channel: "orderbook" | "trades" | "arb" | "arb-feed";
141
+ }
142
+ interface WsUnsubscribed {
143
+ type: "unsubscribed";
144
+ /** See {@link WsSubscribed.outcomeIds}. */
145
+ outcomeIds: string[];
146
+ /** Confirmed marketIds — only set on `arb` confirmations. */
147
+ marketIds?: string[];
148
+ channel: "orderbook" | "trades" | "arb" | "arb-feed";
149
+ }
150
+ interface WsConnected {
151
+ type: "connected";
152
+ appId: string;
153
+ userId?: string;
154
+ }
155
+ interface WsAuthenticated {
156
+ type: "authenticated";
157
+ userId: string;
158
+ }
159
+ interface WsHeartbeat {
160
+ type: "heartbeat";
161
+ /** @unit seconds (converted from server ms) */
162
+ ts: number;
163
+ }
164
+ interface WsResolvedOutcome {
165
+ label: string;
166
+ winner?: boolean;
167
+ externalIdentifier?: string;
168
+ }
169
+ interface WsMarketResolved {
170
+ type: "market_resolved";
171
+ outcomeId: string;
172
+ status: "resolved" | "closed";
173
+ /** Winning outcome label, or null if unknown. */
174
+ result: string | null;
175
+ /** Per-outcome resolution data. */
176
+ outcomes: WsResolvedOutcome[];
177
+ /** @unit seconds (converted from server ms) */
178
+ timestamp: number;
179
+ }
180
+ interface WsError {
181
+ type: "error";
182
+ message: string;
183
+ }
184
+ interface WsOrderSubmitted {
185
+ type: "order_submitted";
186
+ venue: string;
187
+ orderId: string;
188
+ side: string;
189
+ price: number;
190
+ size: number;
191
+ outcomeId?: string;
192
+ /** @unit seconds (converted from server ms) */
193
+ timestamp: number;
194
+ }
195
+ interface WsBalanceUpdate {
196
+ type: "balance_update";
197
+ venue: string;
198
+ tradingBalanceCents: number;
199
+ walletBalanceCents?: number;
200
+ /** @unit seconds (converted from server ms) */
201
+ timestamp: number;
202
+ }
203
+ type WsOrderEventType = "cancelled" | "created" | "signed" | "pending_bridge" | "bridge_complete" | "submitting" | "submitted" | "expired" | "dag_started" | "dag_completed" | "dag_failed" | "dag_cancelled" | "step_started" | "step_completed" | "step_waiting" | "step_failed" | "step_retrying" | "filled" | "partial_fill" | "failed" | "bridge_ws_subscribed" | "bridge_ws_subscribe_failed" | "bridge_polling_fallback";
204
+ interface WsOrderEvent {
205
+ type: "order_event";
206
+ event: WsOrderEventType;
207
+ userId: string;
208
+ orderId: string;
209
+ /** Partner trade id from `placeOrder()`, when the order carried one. */
210
+ externalId?: string;
211
+ venue: string;
212
+ dagRunId?: string;
213
+ stepId?: string;
214
+ stepType?: string;
215
+ /** 1-based step index. Pair with `totalSteps` to render "Step 3 of 7". */
216
+ sequence?: number;
217
+ totalSteps?: number;
218
+ templateName?: string;
219
+ /** Maps sequence → stepType for all steps — sent on dag_started so labels are available upfront. */
220
+ stepTypes?: Record<number, string>;
221
+ filledAmountRaw?: string;
222
+ remainingAmountRaw?: string;
223
+ /**
224
+ * Quote-time and actual shares + payout. All 6-decimal atomic units
225
+ * (so 1.234567 shares = "1234567", "$50 to win" = "50000000"). Set
226
+ * on `filled` / `partial_fill` so the UI can render "Quoted X / Got Y"
227
+ * without re-deriving from cost ÷ price (which loses precision on
228
+ * fractional fills and divides by zero before `executionPrice` exists).
229
+ */
230
+ quotedSharesRaw?: string;
231
+ actualSharesRaw?: string;
232
+ quotedToWinRaw?: string;
233
+ actualToWinRaw?: string;
234
+ /** Quote-time price (decimal string, e.g. "0.5"). Pair with `executionPriceRaw`
235
+ * to render the slippage diff inline. */
236
+ quotedPriceRaw?: string;
237
+ /** Actual avg fill price (decimal string). */
238
+ executionPriceRaw?: string;
239
+ /**
240
+ * Set on `partial_fill` events only. One of `"venue_capacity"`,
241
+ * `"price_slipped"`, `"user_cancelled"`, `"timeout"`, `"bridge_short"`,
242
+ * or a venue-specific tag.
243
+ */
244
+ partialFillReason?: string;
245
+ errorReason?: string;
246
+ attempt?: number;
247
+ correlationId?: string;
248
+ /** @unit milliseconds (raw from server — NOT converted like other WS types) */
249
+ timestamp: number;
250
+ }
251
+ interface WsRedeemEvent {
252
+ type: "redeem_event";
253
+ redeemId: string;
254
+ venueMarketOutcomeId: string;
255
+ status: "submitted" | "confirmed" | "failed";
256
+ callsId: string | null;
257
+ pendingUserOpId: string | null;
258
+ txHash: string | null;
259
+ errorMessage: string | null;
260
+ /** @unit seconds (converted from server ms) */
261
+ timestamp: number;
262
+ }
263
+ /** Top-level withdrawal lifecycle states surfaced to partner clients. */
264
+ type WsWithdrawalLifecycleStatus = "pending" | "bridging" | "transferring" | "completed" | "partial" | "failed";
265
+ type WsWithdrawalLegStatus = "planned" | "submitted" | "confirmed" | "failed";
266
+ interface WsWithdrawalLifecycleLeg {
267
+ sourceChainId: number;
268
+ destChainId: number;
269
+ type: "transfer" | "bridge";
270
+ status: WsWithdrawalLegStatus;
271
+ amountRaw: string;
272
+ txHash: string | null;
273
+ bridgeOperationId: string | null;
274
+ /** Human-readable failure reason when `status === "failed"`. Null/absent when succeeded or in-flight. */
275
+ errorMessage?: string | null;
276
+ }
277
+ /**
278
+ * Per-withdrawal lifecycle event. Wire shape is intentionally additive:
279
+ * consumers should pass through unknown enum values rather than failing.
280
+ */
281
+ interface WsWithdrawalLifecycleEvent {
282
+ type: "withdrawal_lifecycle";
283
+ withdrawalId: string;
284
+ userId: string;
285
+ status: WsWithdrawalLifecycleStatus;
286
+ /** Requested withdrawal amount in destination-token native decimals. */
287
+ requestedAmountRaw?: string;
288
+ /** Terminal settled amount in destination-token native decimals. */
289
+ completedAmountRaw?: string | null;
290
+ /** Realized platform fee in destination-token native decimals. Only present on terminal events. */
291
+ feeRaw?: string | null;
292
+ /** True when `status` is terminal (`completed` / `partial` / `failed`). */
293
+ terminal: boolean;
294
+ /** Optional leg delta — present when this event was triggered by a leg flip. */
295
+ leg?: WsWithdrawalLifecycleLeg;
296
+ /** All legs at the moment of emission (snapshot). */
297
+ legs?: WsWithdrawalLifecycleLeg[];
298
+ /** Failure reason for terminal `failed` / `partial`. */
299
+ errorMessage?: string;
300
+ correlationId?: string;
301
+ /** @unit milliseconds (raw from server — NOT converted like other WS types) */
302
+ timestamp: number;
303
+ }
304
+ interface WsArbMarketUpdate {
305
+ type: "arb_market_update";
306
+ marketId: string;
307
+ /** Producer assertion that globally inactive venues were excluded. */
308
+ activeVenuesOnly: true;
309
+ venueEventId: string | null;
310
+ arbReturn: number;
311
+ ts: number;
312
+ liquidityUsd?: number;
313
+ liquidityTier?: "deep" | "shallow";
314
+ }
315
+ interface WsArbFeedEntry {
316
+ marketId: string;
317
+ venueEventId: string | null;
318
+ arbReturn: number;
319
+ ts: number;
320
+ liquidityUsd?: number;
321
+ liquidityTier?: "deep" | "shallow";
322
+ }
323
+ interface WsArbFeedBatch {
324
+ type: "arb_feed_batch";
325
+ feed: "arb";
326
+ /** Producer assertion that globally inactive venues were excluded. */
327
+ activeVenuesOnly: true;
328
+ entries: WsArbFeedEntry[];
329
+ flushTs: number;
330
+ chunk: number;
331
+ chunkCount: number;
332
+ }
333
+ type WsServerMessage = WsOrderbookSnapshot | WsOrderbookDelta | WsTrade | WsSubscribed | WsUnsubscribed | WsConnected | WsAuthenticated | WsHeartbeat | WsMarketResolved | WsError | WsOrderSubmitted | WsBalanceUpdate | WsOrderEvent | WsRedeemEvent | WsWithdrawalLifecycleEvent | WsArbMarketUpdate | WsArbFeedBatch;
334
+ type WsClientMessage = {
335
+ action: "subscribe";
336
+ channel: "orderbook" | "trades";
337
+ outcomeIds: string[];
338
+ } | {
339
+ action: "unsubscribe";
340
+ channel: "orderbook" | "trades";
341
+ outcomeIds: string[];
342
+ } | {
343
+ action: "resnapshot";
344
+ channel: "orderbook";
345
+ outcomeIds: string[];
346
+ } | {
347
+ action: "subscribe";
348
+ channel: "arb";
349
+ marketIds: string[];
350
+ } | {
351
+ action: "unsubscribe";
352
+ channel: "arb";
353
+ marketIds: string[];
354
+ } | {
355
+ action: "subscribe";
356
+ channel: "arb-feed";
357
+ } | {
358
+ action: "unsubscribe";
359
+ channel: "arb-feed";
360
+ } | {
361
+ action: "authenticate";
362
+ token: string;
363
+ };
364
+ type DiagnosticEvent = {
365
+ type: "seq_gap";
366
+ marketId: string;
367
+ outcomeId: string;
368
+ expected: number;
369
+ received: number;
370
+ } | {
371
+ type: "checksum_mismatch";
372
+ marketId: string;
373
+ outcomeId: string;
374
+ expected: number;
375
+ computed: number;
376
+ } | {
377
+ type: "reconnect";
378
+ attempt: number;
379
+ delayMs: number;
380
+ } | {
381
+ type: "stale_connection";
382
+ lastMessageAge: number;
383
+ };
384
+ type DiagnosticCallback = (event: DiagnosticEvent) => void;
385
+
386
+ /**
387
+ * Immutable orderbook utility functions for the SDK.
388
+ * Applies WS deltas to local book state, computes checksums for integrity verification.
389
+ * Every function returns a **new object** — never mutates inputs.
390
+ */
391
+
392
+ interface OrderbookLevel {
393
+ price: number;
394
+ size: number;
395
+ venues: Record<string, number>;
396
+ }
397
+ interface VenueOrderbookLevel {
398
+ price: number;
399
+ size: number;
400
+ }
401
+ interface OrderbookState {
402
+ marketId: string;
403
+ /** The outcome whose price the midpoint represents (e.g. the "Yes" outcome in binary markets). */
404
+ outcomeId?: string | null;
405
+ bids: OrderbookLevel[];
406
+ asks: OrderbookLevel[];
407
+ venueOrderbooks: Record<string, {
408
+ bids: VenueOrderbookLevel[];
409
+ asks: VenueOrderbookLevel[];
410
+ }>;
411
+ venues: Record<string, WsVenueInfo>;
412
+ midpoint: number | null;
413
+ spread: number | null;
414
+ seq: number;
415
+ checksum: number;
416
+ /** @unit seconds */
417
+ timestamp: number;
418
+ }
419
+ /**
420
+ * Compute the XOR-based checksum of an orderbook.
421
+ * Matches the Rust engine's checksum: XOR of crc32("B{price}:{size}") for each
422
+ * bid and crc32("A{price}:{size}") for each ask, independently hashed then XOR'd.
423
+ */
424
+ declare function computeChecksum(book: {
425
+ bids: OrderbookLevel[];
426
+ asks: OrderbookLevel[];
427
+ }): number;
428
+ /**
429
+ * Convert a WS snapshot message into local OrderbookState.
430
+ * Timestamp is expected to already be in seconds (converted by AggWebSocket).
431
+ */
432
+ declare function snapshotToOrderbook(snapshot: WsOrderbookSnapshot): OrderbookState;
433
+ /**
434
+ * Apply a WS delta to an existing OrderbookState, returning a new state.
435
+ * Bids sorted descending, asks ascending (maintained invariant).
436
+ */
437
+ declare function applyOrderbookDelta(state: OrderbookState, delta: WsOrderbookDelta): OrderbookState;
438
+
439
+ /** Use these constants instead of hardcoding "kalshi" or "polymarket". */
440
+ declare enum Venue {
441
+ kalshi = "kalshi",
442
+ polymarket = "polymarket",
443
+ limitless = "limitless",
444
+ opinion = "opinion",
445
+ predict = "predict",
446
+ pred = "pred",
447
+ tiprun = "tiprun",
448
+ probable = "probable",
449
+ myriad = "myriad",
450
+ hyperliquid = "hyperliquid",
451
+ novig = "novig",
452
+ prophetx = "prophetx",
453
+ betdex = "betdex"
454
+ }
455
+ /** Single source of truth for venue identifiers. */
456
+ declare const VENUES: readonly [Venue.kalshi, Venue.polymarket, Venue.limitless, Venue.opinion, Venue.predict, Venue.pred, Venue.tiprun, Venue.probable, Venue.myriad, Venue.hyperliquid, Venue.novig, Venue.prophetx, Venue.betdex];
457
+ /** Canonical destination chain for venues with on-chain funding or settlement. */
458
+ declare const VENUE_CHAIN_IDS: Partial<Record<Venue, number>>;
459
+ /**
460
+ * Venues that participate in new discovery, market-data, and execution flows.
461
+ *
462
+ * Keep retired venues in {@link Venue} and {@link VENUES}: historical orders,
463
+ * positions, settlement, and redemption still rely on those identifiers.
464
+ * Re-activating a venue is therefore an intentional code change here rather
465
+ * than a runtime configuration toggle.
466
+ */
467
+ declare const ACTIVE_VENUES: readonly [Venue.kalshi, Venue.polymarket, Venue.limitless, Venue.opinion, Venue.predict, Venue.pred, Venue.tiprun, Venue.probable, Venue.myriad, Venue.hyperliquid, Venue.novig, Venue.prophetx, Venue.betdex];
468
+ /**
469
+ * Venues excluded from new user-facing activity. BETDEX is active at the
470
+ * compile-time boundary now that discovery and execution are implemented;
471
+ * partner rollout remains controlled by app policy and runtime flags.
472
+ */
473
+ declare const INACTIVE_VENUES: readonly [];
474
+ /** Whether a venue may participate in new user-facing activity. */
475
+ declare function isVenueActive(venue: string): boolean;
476
+ /** Whether a venue is intentionally retained only for wind-down/history flows. */
477
+ declare function isVenueInactive(venue: string): boolean;
478
+ /**
479
+ * Data-plane visibility (listings/search/orderbook DISPLAY). Distinct from
480
+ * {@link isVenueActive} (execution/routing) — this predicate never affects
481
+ * whether a venue can trade. `dataVisibleOverride` un-hides specific venues
482
+ * for DATA surfaces only; callers pass an env-derived list.
483
+ */
484
+ declare function isVenueDataVisible(venue: string, dataVisibleOverride?: readonly Venue[]): boolean;
485
+ /**
486
+ * Merge app-specific disabled venues with the compile-time retired set, then
487
+ * remove any venue explicitly opted into data visibility via
488
+ * `dataVisibleVenues` (see {@link isVenueDataVisible}). Results use the
489
+ * canonical {@link VENUES} order and ignore unknown values.
490
+ */
491
+ declare function getEffectiveDisabledVenues(disabledVenues?: readonly (Venue | string)[], dataVisibleVenues?: readonly Venue[]): Venue[];
492
+
493
+ declare enum AccountType {
494
+ oauth = "oauth",
495
+ siwe = "siwe",
496
+ siws = "siws",
497
+ email = "email"
498
+ }
499
+ declare enum AccountProvider {
500
+ wallet = "wallet",
501
+ solana_wallet = "solana_wallet",
502
+ google = "google",
503
+ twitter = "twitter",
504
+ apple = "apple",
505
+ email = "email"
506
+ }
507
+
508
+ declare enum Chain {
509
+ evm = "evm",
510
+ svm = "svm"
511
+ }
512
+
513
+ declare enum MatchStatus {
514
+ pending = "pending",
515
+ unmatched = "unmatched",
516
+ review = "review",
517
+ matched = "matched",
518
+ verified = "verified",
519
+ rejected = "rejected"
520
+ }
521
+ declare enum MatchType {
522
+ manual = "manual",
523
+ llm = "llm"
524
+ }
525
+ /** Match statuses considered "confirmed" for user-facing data (orderbooks, listings, aggregation). */
526
+ declare const CONFIRMED_MATCH_STATUSES: MatchStatus[];
527
+ declare enum MarketStatus {
528
+ open = "open",
529
+ closed = "closed",
530
+ resolved = "resolved",
531
+ unopened = "unopened",
532
+ paused = "paused"
533
+ }
534
+
535
+ declare enum OrderStatus {
536
+ pending = "pending",
537
+ signing = "signing",
538
+ pending_bridge = "pending_bridge",
539
+ submitting = "submitting",
540
+ submitted = "submitted",
541
+ open = "open",
542
+ partially_filled_open = "partially_filled_open",
543
+ cancel_pending = "cancel_pending",
544
+ filled = "filled",
545
+ partial_fill = "partial_fill",
546
+ failed = "failed",
547
+ expired = "expired",
548
+ cancelled = "cancelled"
549
+ }
550
+ declare enum TradeSide$1 {
551
+ Buy = "buy",
552
+ Sell = "sell"
553
+ }
554
+ declare enum OrderType {
555
+ Market = "market",
556
+ Limit = "limit"
557
+ }
558
+ declare enum TimeInForce {
559
+ GTC = "GTC",
560
+ GTD = "GTD",
561
+ FOK = "FOK",
562
+ FAK = "FAK",
563
+ IOC = "IOC",
564
+ ALO = "ALO"
565
+ }
566
+
567
+ /**
568
+ * Standalone type definitions — no Zod dependency.
569
+ * These mirror the types in types/index.ts but are defined as plain interfaces.
570
+ * Used by the types-only barrel to avoid leaking Zod into SDK/hooks declarations.
571
+ */
572
+
573
+ type HelloResponse = {
574
+ message: string;
575
+ };
576
+ type App = {
577
+ id: string;
578
+ name: string;
579
+ allowedOrigins: string[];
580
+ active: boolean;
581
+ blockedCountries: string[];
582
+ blockedRegions: string[];
583
+ orderFee: string;
584
+ signupBonus: string;
585
+ createdAt: string;
586
+ updatedAt: string;
587
+ };
588
+ type CreateApp = {
589
+ name: string;
590
+ allowedOrigins: string[];
591
+ blockedCountries: string[];
592
+ blockedRegions: string[];
593
+ };
594
+ type NonceResponse = {
595
+ nonce: string;
596
+ };
597
+ type AuthUser = {
598
+ id: string;
599
+ };
600
+ type UserProfile = {
601
+ id: string;
602
+ username: string | null;
603
+ avatarUrl: string | null;
604
+ externalId: string | null;
605
+ isLocationBlocked: boolean;
606
+ accounts: {
607
+ type: AccountType;
608
+ provider: AccountProvider;
609
+ providerAccountId: string;
610
+ }[];
611
+ wallets: {
612
+ chain: Chain;
613
+ address: string;
614
+ }[];
615
+ venueAccounts: {
616
+ status: string;
617
+ id: string;
618
+ venue: Venue;
619
+ kycStatus: string;
620
+ }[] | null;
621
+ };
622
+ type Account = {
623
+ type: AccountType;
624
+ provider: AccountProvider;
625
+ providerAccountId: string;
626
+ };
627
+ type ServerWallet = {
628
+ chain: Chain;
629
+ address: string;
630
+ };
631
+ type UpdateUserBody = {
632
+ username?: string | undefined;
633
+ confirmAvatar?: true | undefined;
634
+ removeAvatar?: true | undefined;
635
+ };
636
+ type VerifyBody = {
637
+ message: string;
638
+ signature: string;
639
+ };
640
+ type VerifyResponse = {
641
+ accessToken: string;
642
+ user: {
643
+ id: string;
644
+ };
645
+ refreshToken?: string | undefined;
646
+ };
647
+ type AuthTokenResponse = {
648
+ accessToken: string;
649
+ user: {
650
+ id: string;
651
+ };
652
+ refreshToken?: string | undefined;
653
+ };
654
+ type AuthCodeResponse = {
655
+ code: string;
656
+ };
657
+ type ProphetxExecutionMode = "clearinghouse" | "direct";
658
+ type UpsertVenueKey = {
659
+ venue: Venue.prophetx;
660
+ credentials: {
661
+ accessKey: string;
662
+ secretKey: string;
663
+ };
664
+ } | {
665
+ venue: Venue.kalshi;
666
+ credentials: {
667
+ keyId: string;
668
+ privateKey: string;
669
+ };
670
+ } | {
671
+ venue: Venue.polymarket;
672
+ credentials: {
673
+ apiKey: string;
674
+ secret: string;
675
+ passphrase: string;
676
+ };
677
+ };
678
+ type VenueKeySummary = {
679
+ updatedAt: string;
680
+ venue: Venue;
681
+ };
682
+ type VenueKeyStatus = {
683
+ hasAccountHistory?: boolean;
684
+ venue: Venue;
685
+ connected: boolean;
686
+ validatedAt: string | null;
687
+ kycStatus: string;
688
+ };
689
+ type TradeSplit = {
690
+ venue: Venue;
691
+ venueMarketOutcomeId: string;
692
+ side: TradeSide$1;
693
+ price: number;
694
+ size: number;
695
+ signedOrder?: any;
696
+ negRisk?: boolean | undefined;
697
+ outcomeExternalIdentifier?: string | undefined;
698
+ };
699
+ type ComputeSplitsSelection = {
700
+ venue: Venue;
701
+ venueMarketOutcomeId: string;
702
+ };
703
+ type SetupVenueKeyStep = {
704
+ type: "setup_venue_key";
705
+ venue: Venue;
706
+ stepPayload: {
707
+ instructions: string;
708
+ setupUrl?: string | undefined;
709
+ };
710
+ };
711
+ type DepositStep = {
712
+ type: "deposit";
713
+ venue: Venue;
714
+ currency: string;
715
+ stepPayload?: {
716
+ instructions: string;
717
+ setupUrl?: string | undefined;
718
+ depositUrl?: string | undefined;
719
+ } | undefined;
720
+ requiredAmountCents?: number | undefined;
721
+ requiredAmountUsd?: string | undefined;
722
+ transactionData?: {
723
+ value: string;
724
+ chainId: number;
725
+ to: string;
726
+ data: string;
727
+ } | undefined;
728
+ };
729
+ type SetupDepositAddressStep = {
730
+ type: "setup_deposit_address";
731
+ venue: Venue.polymarket;
732
+ stepPayload: {
733
+ setupUrl: string;
734
+ instructions: string;
735
+ };
736
+ };
737
+ type ValidateBalanceOnClientStep = {
738
+ type: "validate_balance_on_client";
739
+ venue: Venue.polymarket;
740
+ stepPayload: {
741
+ requiredAmountUsd: string;
742
+ instructions?: string | undefined;
743
+ currency?: string | undefined;
744
+ };
745
+ };
746
+ type TradeStep = {
747
+ type: "setup_venue_key";
748
+ venue: Venue;
749
+ stepPayload: {
750
+ instructions: string;
751
+ setupUrl?: string | undefined;
752
+ };
753
+ } | {
754
+ type: "deposit";
755
+ venue: Venue;
756
+ currency: string;
757
+ stepPayload?: {
758
+ instructions: string;
759
+ setupUrl?: string | undefined;
760
+ depositUrl?: string | undefined;
761
+ } | undefined;
762
+ requiredAmountCents?: number | undefined;
763
+ requiredAmountUsd?: string | undefined;
764
+ transactionData?: {
765
+ value: string;
766
+ chainId: number;
767
+ to: string;
768
+ data: string;
769
+ } | undefined;
770
+ } | {
771
+ type: "setup_deposit_address";
772
+ venue: Venue.polymarket;
773
+ stepPayload: {
774
+ setupUrl: string;
775
+ instructions: string;
776
+ };
777
+ } | {
778
+ type: "validate_balance_on_client";
779
+ venue: Venue.polymarket;
780
+ stepPayload: {
781
+ requiredAmountUsd: string;
782
+ instructions?: string | undefined;
783
+ currency?: string | undefined;
784
+ };
785
+ };
786
+ type ValidateTradeRequest = {
787
+ splits: {
788
+ venue: Venue;
789
+ venueMarketOutcomeId: string;
790
+ side: TradeSide$1;
791
+ price: number;
792
+ size: number;
793
+ signedOrder?: any;
794
+ negRisk?: boolean | undefined;
795
+ outcomeExternalIdentifier?: string | undefined;
796
+ }[];
797
+ };
798
+ type ValidateTradeResponse = {
799
+ steps: ({
800
+ type: "setup_venue_key";
801
+ venue: Venue;
802
+ stepPayload: {
803
+ instructions: string;
804
+ setupUrl?: string | undefined;
805
+ };
806
+ } | {
807
+ type: "deposit";
808
+ venue: Venue;
809
+ currency: string;
810
+ stepPayload?: {
811
+ instructions: string;
812
+ setupUrl?: string | undefined;
813
+ depositUrl?: string | undefined;
814
+ } | undefined;
815
+ requiredAmountCents?: number | undefined;
816
+ requiredAmountUsd?: string | undefined;
817
+ transactionData?: {
818
+ value: string;
819
+ chainId: number;
820
+ to: string;
821
+ data: string;
822
+ } | undefined;
823
+ } | {
824
+ type: "setup_deposit_address";
825
+ venue: Venue.polymarket;
826
+ stepPayload: {
827
+ setupUrl: string;
828
+ instructions: string;
829
+ };
830
+ } | {
831
+ type: "validate_balance_on_client";
832
+ venue: Venue.polymarket;
833
+ stepPayload: {
834
+ requiredAmountUsd: string;
835
+ instructions?: string | undefined;
836
+ currency?: string | undefined;
837
+ };
838
+ })[];
839
+ canExecute: boolean;
840
+ };
841
+ type ExecuteTradeRequest = {
842
+ splits: {
843
+ venue: Venue;
844
+ venueMarketOutcomeId: string;
845
+ side: TradeSide$1;
846
+ price: number;
847
+ size: number;
848
+ signedOrder?: any;
849
+ negRisk?: boolean | undefined;
850
+ outcomeExternalIdentifier?: string | undefined;
851
+ }[];
852
+ };
853
+ type ExecuteTradeResponse = {
854
+ orders: {
855
+ venue: Venue;
856
+ orders: {
857
+ orderId: string;
858
+ }[];
859
+ }[];
860
+ errors?: {
861
+ message: string;
862
+ venue: Venue;
863
+ }[] | undefined;
864
+ };
865
+ type GetBalanceQuery = {
866
+ venue: Venue;
867
+ };
868
+ type GetBalanceResponse = {
869
+ venue: Venue;
870
+ currency: string;
871
+ balances: {
872
+ tradingBalanceCents?: number | undefined;
873
+ walletBalanceCents?: number | undefined;
874
+ };
875
+ };
876
+ type WalletChainBalance = {
877
+ chainId: number;
878
+ tokenAddress: string;
879
+ balanceRaw: string;
880
+ heldRaw?: string | undefined;
881
+ availableRaw?: string | undefined;
882
+ decimals: number;
883
+ lastSyncedAt: string;
884
+ tokenSymbol?: string | undefined;
885
+ };
886
+ type WalletTokenBalance = {
887
+ tokenSymbol: string;
888
+ totalRaw: string;
889
+ availableRaw?: string | undefined;
890
+ reservedRaw?: string | undefined;
891
+ decimals: number;
892
+ chains: {
893
+ chainId: number;
894
+ tokenAddress: string;
895
+ tokenSymbol?: string | undefined;
896
+ balanceRaw: string;
897
+ heldRaw?: string | undefined;
898
+ availableRaw?: string | undefined;
899
+ decimals: number;
900
+ lastSyncedAt: string;
901
+ }[];
902
+ };
903
+ type PriceSource = "orderbook" | "cached" | "entry" | "settled";
904
+ /**
905
+ * Health of the orderbook a position was marked against — passthrough of
906
+ * the engine's `BookQuality` verdict. `priceSource` says where a mark came
907
+ * from; this says whether that source was trustworthy. Anything other than
908
+ * `healthy` is a low-confidence mark.
909
+ *
910
+ * Read `priceSource` first — this only qualifies book-derived marks. A
911
+ * `settled` position is exact (1/0) and consults no book, so it reports
912
+ * `empty`; that is not a confidence signal.
913
+ */
914
+ type BookQuality = "healthy" | "wide_spread" | "bid_only" | "ask_only" | "endpoint_stub" | "crossed" | "empty";
915
+ type VenuePositionBalance = {
916
+ venue: Venue;
917
+ balance: number;
918
+ costBasis: number;
919
+ unrealizedPnl: number;
920
+ realizedPnl: number;
921
+ priceSource: PriceSource;
922
+ bookQuality: BookQuality;
923
+ };
924
+ type UnifiedBalanceResponse = {
925
+ cash: {
926
+ tokenSymbol: string;
927
+ totalRaw: string;
928
+ availableRaw?: string | undefined;
929
+ reservedRaw?: string | undefined;
930
+ decimals: number;
931
+ chains: {
932
+ chainId: number;
933
+ tokenAddress: string;
934
+ tokenSymbol?: string | undefined;
935
+ balanceRaw: string;
936
+ heldRaw?: string | undefined;
937
+ availableRaw?: string | undefined;
938
+ decimals: number;
939
+ lastSyncedAt: string;
940
+ /** Chain wallet address; native venue collateral uses account IDs instead. */
941
+ address?: string | undefined;
942
+ custodyKind?: "EOA" | "DEPOSIT_WALLET" | "POLYMARKET_LEGACY" | "VENUE_ACCOUNT" | undefined;
943
+ /** Native cash is venue-scoped, not fungible EOA inventory. */
944
+ venue?: Venue | undefined;
945
+ venueAccountId?: string | undefined;
946
+ externalAccountId?: string | undefined;
947
+ isFresh?: boolean | undefined;
948
+ /**
949
+ * A `proxy` balance is spendable on Polymarket only, yet is still part
950
+ * of the parent token's `totalRaw`/`availableRaw`; subtract these rows
951
+ * for fungible-only spending power.
952
+ */
953
+ legacyKind?: "safe" | "proxy" | undefined;
954
+ }[];
955
+ }[];
956
+ positions: {
957
+ venue: Venue;
958
+ balance: number;
959
+ costBasis: number;
960
+ unrealizedPnl: number;
961
+ realizedPnl: number;
962
+ }[];
963
+ venueCash?: {
964
+ transferable?: boolean;
965
+ executionBackend?: ProphetxExecutionMode;
966
+ venue: Venue;
967
+ balanceCents: number;
968
+ accountModel?: "platform-hosted";
969
+ asset?: "USDC";
970
+ decimals?: 6;
971
+ balanceRaw?: string;
972
+ availableRaw?: string;
973
+ unmatchedExposureRaw?: string;
974
+ portfolioValueCents?: number | undefined;
975
+ updatedAt: string;
976
+ }[];
977
+ /**
978
+ * Paper-account summary. Present only when the request resolved to paper
979
+ * mode; absent in a live response. Mirrors `UnifiedBalanceResponseSchemaTB`
980
+ * in `typebox/schemas/trading.ts` — keep the two in sync. All dollars.
981
+ */
982
+ paper?: {
983
+ startingBalance: number;
984
+ cashBalance: number;
985
+ positionsValue: number;
986
+ /** Banked P&L from closed trades — account-level, not summable from positions. */
987
+ realizedPnl: number;
988
+ unrealizedPnl: number;
989
+ /** realized + unrealized. */
990
+ earnings: number;
991
+ };
992
+ };
993
+ type UserHolding = {
994
+ venue: Venue;
995
+ side: "long" | "short";
996
+ size: number;
997
+ marketId: string;
998
+ outcomeId: string;
999
+ outcomeLabel?: string | undefined;
1000
+ conditionId?: string | undefined;
1001
+ avgPrice?: number | undefined;
1002
+ pnl?: number | undefined;
1003
+ };
1004
+ type GetHoldingsResponse = {
1005
+ data: {
1006
+ venue: Venue;
1007
+ side: "long" | "short";
1008
+ size: number;
1009
+ marketId: string;
1010
+ outcomeId: string;
1011
+ outcomeLabel?: string | undefined;
1012
+ conditionId?: string | undefined;
1013
+ avgPrice?: number | undefined;
1014
+ pnl?: number | undefined;
1015
+ }[];
1016
+ nextCursor: string | null;
1017
+ hasMore: boolean;
1018
+ };
1019
+ type GetHoldingsQuery = {
1020
+ venue: Venue;
1021
+ venueMarketId?: string | undefined;
1022
+ venueEventId?: string | undefined;
1023
+ cursor?: string | undefined;
1024
+ };
1025
+ type GetOrdersQuery = {
1026
+ status?: OrderStatus | undefined;
1027
+ orderType?: "market" | "limit" | undefined;
1028
+ orderId?: string | undefined;
1029
+ /** Filter to all legs of one quote (multi-venue split routes). */
1030
+ quoteId?: string | undefined;
1031
+ /** Filter to the order(s) carrying this partner trade id. */
1032
+ externalId?: string | undefined;
1033
+ /** Filter to orders on any of these venue markets. */
1034
+ venueMarketIds?: string[] | undefined;
1035
+ cursor?: string | undefined;
1036
+ limit?: number | undefined;
1037
+ };
1038
+ type GetPositionsQuery = {
1039
+ cursor?: string | undefined;
1040
+ limit?: number | undefined;
1041
+ status?: "active" | "closed" | undefined;
1042
+ };
1043
+ type OrderListItem = {
1044
+ status: string;
1045
+ id: string;
1046
+ /**
1047
+ * Parent quote — lets the frontend correlate legs of a multi-venue
1048
+ * split route without a second request. Nullable for sell-side /
1049
+ * standalone orders without a Quote row.
1050
+ */
1051
+ quoteId: string | null;
1052
+ /** Partner-supplied trade id from POST /execution/orders. */
1053
+ externalId: string | null;
1054
+ /** Partner-supplied order id from POST /execution/limit-orders. */
1055
+ clientOrderId: string | null;
1056
+ createdAt: Date;
1057
+ updatedAt: Date;
1058
+ venue: Venue;
1059
+ side: string;
1060
+ amountRaw: string;
1061
+ orderType?: "market" | "limit" | undefined;
1062
+ limitPriceRaw: string | null;
1063
+ limitSizeRaw?: string | null | undefined;
1064
+ timeInForce: TimeInForce | null;
1065
+ postOnly?: boolean | undefined;
1066
+ expiresAt: Date | string | null;
1067
+ reservedCostRaw?: string | null | undefined;
1068
+ filledSizeRaw?: string | null | undefined;
1069
+ filledCostRaw?: string | null | undefined;
1070
+ remainingSizeRaw?: string | null | undefined;
1071
+ averageFillPriceRaw?: string | null | undefined;
1072
+ venueOrderId?: string | null | undefined;
1073
+ cancelRequestedAt?: Date | string | null | undefined;
1074
+ cancelledAt?: Date | string | null | undefined;
1075
+ slippageBps: number | null;
1076
+ quotedPriceRaw: string | null;
1077
+ quotedCostRaw: string | null;
1078
+ /**
1079
+ * Quote-time shares + payout, 6-decimal atomic. Lets the UI render
1080
+ * "Quoted X shares / $Y to win" without re-deriving from cost ÷
1081
+ * price (precision drift on fractional fills; divide-by-zero before
1082
+ * `executionPrice` exists).
1083
+ */
1084
+ quotedSharesRaw: string | null;
1085
+ quotedToWinRaw: string | null;
1086
+ filledAmountRaw: string | null;
1087
+ executionPrice: string | null;
1088
+ /**
1089
+ * Actual shares + payout, populated by the venue's finalize handler.
1090
+ * Pair with the quoted-side fields above to render the diff inline.
1091
+ */
1092
+ actualSharesRaw: string | null;
1093
+ actualToWinRaw: string | null;
1094
+ /**
1095
+ * Set only on `partial_fill`. One of `"venue_capacity"`,
1096
+ * `"price_slipped"`, `"user_cancelled"`, `"timeout"`, `"bridge_short"`,
1097
+ * or a venue-specific tag.
1098
+ */
1099
+ partialFillReason: string | null;
1100
+ /**
1101
+ * Fee breakdown. Optional so paper-trading orders, which have no venue
1102
+ * fees, no bridges and no app-fee charge, stay valid without fabricating
1103
+ * a zeroed breakdown that would read as "this trade was free".
1104
+ *
1105
+ * `quoted` is what the route promised at accept time; `actual` is money
1106
+ * that moved. `actual.appFee` and `actual.bridge` are TRADE-level and
1107
+ * shared by every order under one `actual.dagRunId` — group by it before
1108
+ * summing. `quoted.venueFeeRaw` and `actual.venueFeeRaw` are per-leg.
1109
+ */
1110
+ fees?: {
1111
+ /**
1112
+ * How the venue charges: `"fill"`, `"fill_in_game_only"`,
1113
+ * `"winnings"`, `"exit"`, or null when the schedule cannot be
1114
+ * expressed as a rate. Decides what the venue-fee figures mean.
1115
+ */
1116
+ venueFeeBasis: string | null;
1117
+ quoted: {
1118
+ /** 6-dec USD atoms. Null when the router emitted no fee for this leg. */
1119
+ venueFeeRaw: string | null;
1120
+ /** Worst-case partner fee if the route fills 100%. */
1121
+ appFeeRaw: string | null;
1122
+ appFeeBips: number | null;
1123
+ };
1124
+ actual: {
1125
+ /** Null until the order reaches a DAG run. */
1126
+ dagRunId: string | null;
1127
+ /** Venue-reported fee, 6-dec USD atoms. Null = unknown, never free. */
1128
+ venueFeeRaw: string | null;
1129
+ appFee: {
1130
+ bips: number;
1131
+ /** floor(filled × bips / 10_000). */
1132
+ dueRaw: string;
1133
+ /** Below `dueRaw` on `under_collected`, "0" on skips. */
1134
+ collectedRaw: string;
1135
+ status: string;
1136
+ } | null;
1137
+ bridge: {
1138
+ relayFeeUsd: string | null;
1139
+ originGasCostUsd: string | null;
1140
+ operationCount: number;
1141
+ pricedOperationCount: number;
1142
+ } | null;
1143
+ };
1144
+ } | undefined;
1145
+ txHash: string | null;
1146
+ errorMessage: string | null;
1147
+ dagRunId: string | null;
1148
+ venueMarket: {
1149
+ id: string;
1150
+ venueEventId?: string | undefined;
1151
+ question: string;
1152
+ image: string | null;
1153
+ } | null;
1154
+ venueMarketOutcome: {
1155
+ label: string;
1156
+ title: string | null;
1157
+ } | null;
1158
+ };
1159
+ type PositionGroup = {
1160
+ venueMarket: {
1161
+ venueEventId: string;
1162
+ question: string;
1163
+ image: string | null;
1164
+ status: MarketStatus;
1165
+ venueMarketOutcomes: {
1166
+ unrealizedPnl: number;
1167
+ label: string;
1168
+ title: string | null;
1169
+ winner: boolean | null;
1170
+ venueBreakdown: {
1171
+ executionBackend?: ProphetxExecutionMode;
1172
+ venue: Venue;
1173
+ size: number;
1174
+ venueMarketId: string;
1175
+ venueMarketOutcomeId: string;
1176
+ custodyKind?: "EOA" | "DEPOSIT_WALLET" | "VENUE_OMNIBUS" | "VENUE_ACCOUNT";
1177
+ venueAccountId?: string;
1178
+ externalAccountId?: string;
1179
+ }[];
1180
+ totalSize: number;
1181
+ /** Weighted over legs with a known entry price — see `costBasisUnknown`. */
1182
+ avgEntryPrice: number;
1183
+ /**
1184
+ * At least one leg was imported from an externally-acquired self-custody
1185
+ * balance with no acquisition price we could reconcile. `totalValue`
1186
+ * covers every leg; `avgEntryPrice` and `unrealizedPnl` cover only the
1187
+ * legs with a known entry, and are 0 when none of them do.
1188
+ */
1189
+ costBasisUnknown?: boolean;
1190
+ currentPrice: number;
1191
+ totalValue: number;
1192
+ unrealizedPnlPercent: number;
1193
+ priceSource: PriceSource;
1194
+ bookQuality: BookQuality;
1195
+ }[];
1196
+ };
1197
+ targetMarketId: string;
1198
+ eventId?: string | undefined;
1199
+ redeemStatus: "eligible" | "pending" | "redeemed" | "ineligible";
1200
+ status: "active" | "closed";
1201
+ resolutionDate: string | null;
1202
+ };
1203
+ type VenueMarket = {
1204
+ id: string;
1205
+ venue: Venue;
1206
+ question: string;
1207
+ venueMarketOutcomes: {
1208
+ id: string;
1209
+ /** REMOVED — no longer returned; use GET /midpoints for live prices. */
1210
+ price?: number | undefined;
1211
+ venueMarketId: string;
1212
+ label: string;
1213
+ title?: string | null | undefined;
1214
+ externalIdentifier?: string | null | undefined;
1215
+ winner?: boolean | null | undefined;
1216
+ /** Per-share USDC payout of this outcome in [0, 1] once settled; source of truth over `winner` when set. */
1217
+ payoutPerShare?: number | null | undefined;
1218
+ /** Counterpart outcomes on matched sibling markets — only populated
1219
+ * on the parent (queried) market's outcomes. Each entry is a
1220
+ * `{ venueMarketId, venueMarketOutcomeId }` ref into the same
1221
+ * response's `matchedVenueMarkets[].venueMarketOutcomes[]`. */
1222
+ matchedVenueMarketOutcomes?: {
1223
+ venueMarketId: string;
1224
+ venueMarketOutcomeId: string;
1225
+ }[];
1226
+ }[];
1227
+ externalIdentifier: string;
1228
+ status?: MarketStatus | undefined;
1229
+ createdAt?: string | null | undefined;
1230
+ negRisk?: boolean | undefined;
1231
+ marketId?: string | null | undefined;
1232
+ conditionId?: string | null | undefined;
1233
+ venueEventId?: string | null | undefined;
1234
+ image?: string | null | undefined;
1235
+ description?: string | null | undefined;
1236
+ rulesPrimary?: string | null | undefined;
1237
+ rulesSecondary?: string | null | undefined;
1238
+ volume?: number | null | undefined;
1239
+ startDate?: string | null | undefined;
1240
+ endDate?: string | null | undefined;
1241
+ creationDate?: string | null | undefined;
1242
+ resolutionDate?: string | null | undefined;
1243
+ /** Sports market classification for type-aware sorting (moneyline, spread, total, etc.). */
1244
+ sportsMarketType?: string | null | undefined;
1245
+ /** Sort rank within a sports section (0=moneyline, 1=spread, 2=total, 3+=other). */
1246
+ sectionRank?: number | null | undefined;
1247
+ /** Period identifier for sports markets (e.g., "1H", "2H", "Q1", etc.). */
1248
+ period?: string | null | undefined;
1249
+ /** Normalized subject category for prop-tab grouping (e.g., game_lines, exact_score, etc.). */
1250
+ marketCategory?: string | null | undefined;
1251
+ /** Section/tab grouping key for sports markets (e.g. "player_props", "totals"). */
1252
+ marketGroup?: string | null | undefined;
1253
+ /** Fine-grained sub-classification within a marketGroup (e.g. "moneyline", "rushing_yards"). */
1254
+ marketSubtype?: string | null | undefined;
1255
+ /** Line value for spread/total markets (e.g., 2.5 for totals, 3 for spreads). */
1256
+ lineValue?: number | null | undefined;
1257
+ /** Per-market minimum order size in shares/contracts, where AGG ingests one:
1258
+ * Polymarket (the market's own floor) and PRED (0.001); null elsewhere.
1259
+ * POST /execution/limit-orders validates `sizeRaw` against it on Polymarket.
1260
+ * `null` means no value was ingested — NOT that the market is unconstrained;
1261
+ * other venues enforce floors this field does not carry. */
1262
+ minOrderSize?: number | null | undefined;
1263
+ /** Price increment from venue metadata — a seed, not a guarantee. Prefer the
1264
+ * runtime-inferred `tick` from the orderbook endpoints when aligning a limit
1265
+ * price: the live grid can be finer than this. */
1266
+ tickSize?: number | null | undefined;
1267
+ matchedVenueMarkets?: {
1268
+ id: string;
1269
+ venue: Venue;
1270
+ question: string;
1271
+ externalIdentifier: string;
1272
+ status?: MarketStatus | undefined;
1273
+ conditionId?: string | null | undefined;
1274
+ description?: string | null | undefined;
1275
+ rulesPrimary?: string | null | undefined;
1276
+ rulesSecondary?: string | null | undefined;
1277
+ venueMarketOutcomes?: {
1278
+ id: string;
1279
+ /** REMOVED — no longer returned; use GET /midpoints for live prices. */
1280
+ price?: number | undefined;
1281
+ venueMarketId: string;
1282
+ label: string;
1283
+ winner?: boolean | null | undefined;
1284
+ /** Per-share USDC payout of this outcome in [0, 1] once settled; source of truth over `winner` when set. */
1285
+ payoutPerShare?: number | null | undefined;
1286
+ }[] | undefined;
1287
+ volume?: number | null | undefined;
1288
+ venueEvent?: {
1289
+ id: string;
1290
+ externalIdentifier: string;
1291
+ slug?: string | null | undefined;
1292
+ series?: {
1293
+ id: string;
1294
+ venue: string;
1295
+ externalIdentifier: string;
1296
+ name?: string | null | undefined;
1297
+ } | null | undefined;
1298
+ } | null | undefined;
1299
+ }[] | undefined;
1300
+ };
1301
+ type VenueEvent = {
1302
+ id: string;
1303
+ venue: Venue;
1304
+ image: string | null;
1305
+ title: string;
1306
+ externalIdentifier: string;
1307
+ categories: {
1308
+ id: string;
1309
+ category: {
1310
+ id: string;
1311
+ name: string;
1312
+ displayName: string | null;
1313
+ parentId: string | null;
1314
+ eventCount: number;
1315
+ volume24hr: number;
1316
+ volume: number;
1317
+ };
1318
+ }[];
1319
+ status?: MarketStatus | undefined;
1320
+ updatedAt?: string | null | undefined;
1321
+ description?: string | null | undefined;
1322
+ volume?: number | null | undefined;
1323
+ startDate?: string | null | undefined;
1324
+ endDate?: string | null | undefined;
1325
+ creationDate?: string | null | undefined;
1326
+ /**
1327
+ * Scheduled kickoff/start of the underlying game (sports events only).
1328
+ * Distinct from `endDate` (market close/expiration), which can sit well
1329
+ * after the game. The FE prefers this over `endDate` for the game-date
1330
+ * title suffix. Null for non-sports events.
1331
+ */
1332
+ gameStartTime?: string | null | undefined;
1333
+ slug?: string | null | undefined;
1334
+ subtitle?: string | null | undefined;
1335
+ venues?: Venue[];
1336
+ venueCount?: number | undefined;
1337
+ groupMarketCount?: number | undefined;
1338
+ /**
1339
+ * Same-venue companion grouping: the id of this event's group base. NULL means
1340
+ * the event IS the base, or is standalone. A venue splits one game into several
1341
+ * events (`… - More Markets`, `… : Spread`), and same-venue events never share
1342
+ * a matched cluster — so on a companion, `matchedVenueEvents[]` lists the other
1343
+ * venues' EQUIVALENT companions, not the game's cluster. Use this id (or the
1344
+ * shared `aggKey`) to reach the base.
1345
+ */
1346
+ groupParentId?: string | null | undefined;
1347
+ marketCount?: number | undefined;
1348
+ /**
1349
+ * ISO-8601 duration denormalized from Series.recurrence. `null` means
1350
+ * the event has no recurring schedule (one-off). Use this value with
1351
+ * the `?recurrence=` filter on /venue-events using public recurrence
1352
+ * enum values.
1353
+ */
1354
+ recurrence?: string | null | undefined;
1355
+ /** Deterministic game-level canonical key for cross-venue sports detail loading. */
1356
+ aggKey?: string | null | undefined;
1357
+ /** Type-aware structure classification used to sort markets under this event. */
1358
+ structureType?: "candidate" | "sport" | "axis" | "dates" | null | undefined;
1359
+ /** Canonical sport slug for sports events (e.g. "basketball", "soccer"); null for non-sports. */
1360
+ sport?: string | null | undefined;
1361
+ /** Structured per-venue settlement key-differences for this event's cluster. */
1362
+ settlementDiff?: SettlementDiff | null | undefined;
1363
+ };
1364
+ type Orderbook = {
1365
+ bids: {
1366
+ price: number;
1367
+ size: number;
1368
+ }[];
1369
+ asks: {
1370
+ price: number;
1371
+ size: number;
1372
+ }[];
1373
+ negRisk?: boolean | undefined;
1374
+ };
1375
+ type AttributedOrderbookLevel = {
1376
+ price: number;
1377
+ size: number;
1378
+ venues: Record<string, number>;
1379
+ };
1380
+ type AttributedOrderbook = {
1381
+ bids: {
1382
+ price: number;
1383
+ size: number;
1384
+ venues: Record<string, number>;
1385
+ }[];
1386
+ asks: {
1387
+ price: number;
1388
+ size: number;
1389
+ venues: Record<string, number>;
1390
+ }[];
1391
+ };
1392
+ type PricePoint = {
1393
+ price: number;
1394
+ timestamp: number;
1395
+ open?: number | undefined;
1396
+ high?: number | undefined;
1397
+ low?: number | undefined;
1398
+ close?: number | undefined;
1399
+ };
1400
+ type MarketPriceHistory = {
1401
+ venue: Venue;
1402
+ marketId: string;
1403
+ marketTicker: string;
1404
+ points: {
1405
+ price: number;
1406
+ timestamp: number;
1407
+ open?: number | undefined;
1408
+ high?: number | undefined;
1409
+ low?: number | undefined;
1410
+ close?: number | undefined;
1411
+ }[];
1412
+ };
1413
+ type PricesHistoryResponse = {
1414
+ data: {
1415
+ venue: Venue;
1416
+ marketId: string;
1417
+ marketTicker: string;
1418
+ points: {
1419
+ price: number;
1420
+ timestamp: number;
1421
+ open?: number | undefined;
1422
+ high?: number | undefined;
1423
+ low?: number | undefined;
1424
+ close?: number | undefined;
1425
+ }[];
1426
+ }[];
1427
+ };
1428
+ type OrderbookHistoryPoint = {
1429
+ volume: number | null;
1430
+ timestamp: number;
1431
+ midpoint: number;
1432
+ bestBid: number | null;
1433
+ bestAsk: number | null;
1434
+ spread: number | null;
1435
+ open?: number | undefined;
1436
+ high?: number | undefined;
1437
+ low?: number | undefined;
1438
+ close?: number | undefined;
1439
+ };
1440
+ type OrderbookHistoryResponse = {
1441
+ venueMarketOutcomeId: string;
1442
+ points: {
1443
+ volume: number | null;
1444
+ timestamp: number;
1445
+ midpoint: number;
1446
+ bestBid: number | null;
1447
+ bestAsk: number | null;
1448
+ spread: number | null;
1449
+ open?: number | undefined;
1450
+ high?: number | undefined;
1451
+ low?: number | undefined;
1452
+ close?: number | undefined;
1453
+ }[];
1454
+ };
1455
+ /** Reference to a counterpart outcome on a matched sibling market.
1456
+ * Resolves into the same response's `matchedVenueMarkets[].venueMarketOutcomes[]`
1457
+ * by id. Sourced from `MatchedVenueMarketOutcome` so the alignment is
1458
+ * robust to inversely-framed binary markets and multi-outcome markets. */
1459
+ type MatchedVenueMarketOutcomeRef = {
1460
+ venueMarketId: string;
1461
+ venueMarketOutcomeId: string;
1462
+ };
1463
+ type VenueMarketOutcome = {
1464
+ id: string;
1465
+ /**
1466
+ * REMOVED — /venue-events and /venue-markets no longer return outcome
1467
+ * prices. Fetch live prices from GET /midpoints (or the live-price hooks),
1468
+ * keyed by this outcome's `id`.
1469
+ */
1470
+ price?: number | undefined;
1471
+ venueMarketId: string;
1472
+ label: string;
1473
+ title?: string | null | undefined;
1474
+ externalIdentifier?: string | null | undefined;
1475
+ winner?: boolean | null | undefined;
1476
+ /** Per-share USDC payout of this outcome in [0, 1] once settled; source of truth over `winner` when set. */
1477
+ payoutPerShare?: number | null | undefined;
1478
+ /** Counterpart outcomes on matched sibling markets — only populated on
1479
+ * the parent (queried) market's outcomes. */
1480
+ matchedVenueMarketOutcomes?: MatchedVenueMarketOutcomeRef[];
1481
+ };
1482
+ type VenueEventWithMarkets = VenueEvent & {
1483
+ venueMarkets: VenueMarket[];
1484
+ };
1485
+ type VenueMarketListItem = Omit<VenueMarket, "matchedVenueMarkets">;
1486
+ type VenueEventListItem = VenueEvent & {
1487
+ venueMarkets: VenueMarketListItem[];
1488
+ marketCount: number;
1489
+ };
1490
+ /** Per-outcome midpoint inside a matched-sibling entry. Aligned via MVMO
1491
+ * so the `venueMarketOutcomeId` resolves the same outcome the parent's
1492
+ * `matchedVenueMarketOutcomes` ref points to. */
1493
+ type MatchedMidpointOutcome = {
1494
+ venueMarketOutcomeId: string;
1495
+ midpoint: number | null;
1496
+ bestBid?: number | null;
1497
+ bestAsk?: number | null;
1498
+ };
1499
+ type MatchedMidpoint = {
1500
+ venueMarketId: string;
1501
+ venue: string;
1502
+ /** Sibling's market-level midpoint. Kept for backwards compat — the
1503
+ * authoritative cross-venue alignment lives in `outcomes`. */
1504
+ midpoint: number | null;
1505
+ /** Per-outcome midpoints keyed by sibling outcome id. Optional during
1506
+ * rollout — older engine builds may omit it. */
1507
+ outcomes?: MatchedMidpointOutcome[];
1508
+ };
1509
+ type OutcomeMidpoint = {
1510
+ venueMarketOutcomeId: string;
1511
+ label: string;
1512
+ midpoint: number | null;
1513
+ bestBid?: number | null;
1514
+ bestAsk?: number | null;
1515
+ };
1516
+ type MidpointItem = {
1517
+ venueMarketId: string;
1518
+ venue: string;
1519
+ midpoint: number | null;
1520
+ spread: number | null;
1521
+ timestamp: number | null;
1522
+ outcomes: OutcomeMidpoint[];
1523
+ matched: MatchedMidpoint[];
1524
+ arbReturn?: number | null | undefined;
1525
+ };
1526
+ type ComputeSplitsRequest = {
1527
+ side: TradeSide$1;
1528
+ selections: {
1529
+ venue: Venue;
1530
+ venueMarketOutcomeId: string;
1531
+ }[];
1532
+ maxDollarAmount: number;
1533
+ };
1534
+ type ComputeSplitsResponse = {
1535
+ splits: {
1536
+ venue: Venue;
1537
+ venueMarketOutcomeId: string;
1538
+ side: TradeSide$1;
1539
+ price: number;
1540
+ size: number;
1541
+ signedOrder?: any;
1542
+ negRisk?: boolean | undefined;
1543
+ outcomeExternalIdentifier?: string | undefined;
1544
+ }[];
1545
+ totalSize: number;
1546
+ totalCost: number;
1547
+ };
1548
+ type Category = {
1549
+ id: string;
1550
+ name: string;
1551
+ displayName: string | null;
1552
+ parentId: string | null;
1553
+ eventCount: number;
1554
+ volume24hr: number;
1555
+ volume: number;
1556
+ };
1557
+ type SettlementSource = {
1558
+ name: string;
1559
+ url?: string | null | undefined;
1560
+ };
1561
+ type SettlementDifference = {
1562
+ type: string;
1563
+ title: string;
1564
+ perVenue: Record<string, string>;
1565
+ summary?: string | undefined;
1566
+ };
1567
+ type SettlementDiff = {
1568
+ sharedSummary: string;
1569
+ differences: SettlementDifference[];
1570
+ };
1571
+ type ExecuteManagedRequest = {
1572
+ quoteId: string;
1573
+ };
1574
+ type ValidateManagedRequest = {
1575
+ venueMarketOutcomeIds: string[];
1576
+ side: "buy" | "sell";
1577
+ amount: number;
1578
+ };
1579
+ type WithdrawTokenSymbol$1 = "USDC" | "USDC.e" | "USDT";
1580
+ type WithdrawalSourceTokenSymbol$1 = WithdrawTokenSymbol$1 | "pUSD" | "USD1";
1581
+ type WithdrawManagedRequest = {
1582
+ /** Positive integer string in the token's native decimals (e.g. "100000" = 0.1 USDC). */
1583
+ amountRaw: string;
1584
+ tokenSymbol: WithdrawTokenSymbol$1;
1585
+ /** EVM 0x-prefixed 20-byte recipient address. */
1586
+ destinationAddress: string;
1587
+ /** EVM chain ID where the recipient should receive funds. Required since v2026.04. */
1588
+ destinationChainId: number;
1589
+ };
1590
+ type WithdrawalSourceStatus$1 = "pending" | "submitted" | "confirmed" | "failed";
1591
+ type WithdrawalSourceItem = {
1592
+ sourceId: string;
1593
+ chainId: number;
1594
+ tokenSymbol: WithdrawalSourceTokenSymbol$1;
1595
+ /** On-chain token address on `chainId`. */
1596
+ tokenAddress: string;
1597
+ /**
1598
+ * On-chain decimals for `(chainId, tokenAddress)`. Critical for clients
1599
+ * because `amountRaw` is in source-native decimals (BNB USDC is 18-dec,
1600
+ * EVM USDC is 6-dec).
1601
+ */
1602
+ decimals: number;
1603
+ amountRaw: string;
1604
+ custodyKind?: "DEPOSIT_WALLET" | "VENUE_ACCOUNT";
1605
+ venue?: string;
1606
+ sourceVenueAccountId?: string;
1607
+ sourceExternalAccountId?: string;
1608
+ status: WithdrawalSourceStatus$1;
1609
+ txHash: string | null;
1610
+ bridgeOperationId: string | null;
1611
+ };
1612
+ /** @deprecated Use `WithdrawalSourceItem` from the lifecycle response. */
1613
+ type WithdrawalSource = {
1614
+ amountRaw: string;
1615
+ chainId: number;
1616
+ txHash?: string | undefined;
1617
+ bridgeOperationId?: string | undefined;
1618
+ };
1619
+ type SyncBalancesResponse = {
1620
+ synced: true;
1621
+ };
1622
+
1623
+ /** App-level paper/live mode. An app is one or the other, never both. */
1624
+ type AppTradingMode = "live" | "paper";
1625
+ interface AppClientConfigResponse {
1626
+ prophetxExecutionMode?: "clearinghouse" | "direct";
1627
+ disabledVenues: Venue[];
1628
+ disabledCategoryPresets: string[];
1629
+ earlyAccessEnabled: boolean;
1630
+ authOptions: AppClientAuthOption[];
1631
+ /**
1632
+ * Server-owned execution mode. Prefer this over any locally-configured
1633
+ * `trading.executionMode` — the API enforces it regardless of what the
1634
+ * client sends, and end users cannot change it.
1635
+ */
1636
+ tradingMode: AppTradingMode;
1637
+ /**
1638
+ * One-time simulated balance granted on first paper use, in dollars.
1639
+ * Interpolate this into paper copy rather than hardcoding a figure.
1640
+ */
1641
+ paperStartingBalance: number;
1642
+ }
1643
+ interface VenueGeoPolicyEntry {
1644
+ venue: Venue;
1645
+ /** ISO 3166-1 alpha-2, upper-case. Empty means no country restriction. */
1646
+ blockedCountries: string[];
1647
+ /**
1648
+ * ISO 3166-1 alpha-2, upper-case. When present, this venue is ALLOWLIST
1649
+ * mode: ONLY these countries are permitted (`blockedCountries` is always
1650
+ * `[]` alongside this and must be ignored). Absent/undefined ⇒ ordinary
1651
+ * denylist mode, use `blockedCountries` as before. Only Novig uses this
1652
+ * today — a client that reads only `blockedCountries` sees an allowlisted
1653
+ * venue as unrestricted, which is exactly the misread this field closes.
1654
+ */
1655
+ allowedCountries?: string[];
1656
+ }
1657
+ interface VenueGeoPolicyResponse {
1658
+ venues: VenueGeoPolicyEntry[];
1659
+ }
1660
+ interface RpcTokenResponse {
1661
+ token: string;
1662
+ expiresAt: number;
1663
+ }
1664
+ type AggAuthProviderType = "siwe" | "siws" | "google" | "twitter" | "apple" | "email";
1665
+ interface AppClientAuthOption {
1666
+ provider: AggAuthProviderType;
1667
+ type: "oauth" | "email" | "wallet";
1668
+ enabled: boolean;
1669
+ callbackUrl?: string;
1670
+ statement?: string;
1671
+ }
1672
+ type AggAuthDeliveryMode = "body" | "cookie-refresh";
1673
+ interface AggClientAuthOptions {
1674
+ getEarlyAccessCode?: () => string | null;
1675
+ }
1676
+ type AggAuthStartBody = {
1677
+ provider: Exclude<AggAuthProviderType, "email">;
1678
+ redirectUrl?: string;
1679
+ /** Cloudflare Turnstile token — required when a prior authStart returned `challenge_required`. */
1680
+ turnstileToken?: string;
1681
+ earlyAccessCode?: string;
1682
+ } | {
1683
+ provider: "email";
1684
+ email: string;
1685
+ redirectUrl?: string;
1686
+ /** Cloudflare Turnstile token — required when a prior authStart returned `challenge_required`. */
1687
+ turnstileToken?: string;
1688
+ earlyAccessCode?: string;
1689
+ };
1690
+ /** SIWE / SIWS sign-in. `kind` is optional so callers that predate the discriminator still compile. */
1691
+ interface AggAuthWalletVerifyBody {
1692
+ kind?: "wallet";
1693
+ message: string;
1694
+ signature: string;
1695
+ earlyAccessCode?: string;
1696
+ }
1697
+ /** Privy sign-in. Requires the app's wallet provider to be Privy; the token must come from that Privy app. */
1698
+ interface AggAuthPrivyVerifyBody {
1699
+ kind: "privy";
1700
+ privyToken: string;
1701
+ earlyAccessCode?: string;
1702
+ }
1703
+ /** Body for `POST /auth/verify` — mirrors the API's union on `kind`. */
1704
+ type AggAuthVerifyBody = AggAuthWalletVerifyBody | AggAuthPrivyVerifyBody;
1705
+ type AggAuthStartResult = {
1706
+ type: "nonce";
1707
+ nonce: string;
1708
+ statement?: string;
1709
+ } | {
1710
+ type: "redirect";
1711
+ url: string;
1712
+ } | {
1713
+ type: "magic_link";
1714
+ success: true;
1715
+ } | {
1716
+ type: "challenge_required";
1717
+ siteKey: string;
1718
+ };
1719
+ /**
1720
+ * Body for `POST /users/me/link-account/start` — authenticated account linking.
1721
+ *
1722
+ * `redirectUrl` is required for OAuth/email providers: the callback / magic-link
1723
+ * verify hands the partner a `link_confirm_token` by redirecting to `redirectUrl`,
1724
+ * and the partner app completes the flow by calling `/confirm` from that page.
1725
+ *
1726
+ * Wallet providers (`siwe`/`siws`) instead return a `wallet_challenge` with a
1727
+ * `message` the user signs VERBATIM; the signature is then confirmed with
1728
+ * `{ kind: "wallet_signature", message, signature }`.
1729
+ */
1730
+ type AggLinkAccountBody = {
1731
+ provider: "google" | "twitter" | "apple";
1732
+ redirectUrl: string;
1733
+ } | {
1734
+ provider: "email";
1735
+ email: string;
1736
+ redirectUrl: string;
1737
+ } | {
1738
+ provider: "siwe" | "siws";
1739
+ address: string;
1740
+ };
1741
+ type AggLinkAccountResult = {
1742
+ type: "redirect";
1743
+ url: string;
1744
+ } | {
1745
+ type: "magic_link";
1746
+ success: true;
1747
+ } | {
1748
+ type: "wallet_challenge";
1749
+ message: string;
1750
+ };
1751
+ /**
1752
+ * Wallet branch of `POST /users/me/link-account/confirm`. Requires `kind` so it
1753
+ * can never be confused with the `token` branch. `message` MUST be the exact
1754
+ * `message` returned by `/start`'s `wallet_challenge` — the server compares it
1755
+ * byte-for-byte, so do not reconstruct or edit it client-side.
1756
+ */
1757
+ type AggLinkAccountWalletConfirmBody = {
1758
+ kind: "wallet_signature";
1759
+ message: string;
1760
+ signature: string;
1761
+ };
1762
+ /**
1763
+ * Success result of /users/me/link-account/confirm.
1764
+ * - `linked` — new Account row written.
1765
+ * - `already_linked_same` — identity was already attached to the caller's Principal
1766
+ * (idempotent; safe to retry).
1767
+ *
1768
+ * Collisions with a different Principal surface as HTTP 409 and are thrown by the
1769
+ * SDK's request layer — catch them at the call site, don't expect them here.
1770
+ */
1771
+ type AggLinkAccountConfirmResult = {
1772
+ status: "linked" | "already_linked_same";
1773
+ provider: string;
1774
+ };
1775
+ type AggSessionUser = AuthUser | UserProfile;
1776
+ interface AggClientSessionInput {
1777
+ accessToken: string;
1778
+ refreshToken?: string;
1779
+ user?: AggSessionUser;
1780
+ }
1781
+ /** Non-sensitive auth snapshot persisted to localStorage for UI bootstrapping.
1782
+ * Tokens are NEVER included — they exist only in process memory. */
1783
+ interface PersistedAuthSnapshot {
1784
+ user: {
1785
+ id: string;
1786
+ username: string | null;
1787
+ avatarUrl: string | null;
1788
+ walletAddress?: string | null;
1789
+ } | null;
1790
+ authHint: {
1791
+ wasAuthenticated: boolean;
1792
+ };
1793
+ }
1794
+ /** Auth lifecycle status for UI state machines. */
1795
+ type AuthStatus = "unknown" | "authenticated" | "unauthenticated";
1796
+ type SignatureRequestType = "eip712" | "personal_sign"
1797
+ /** EVM transaction — bridge legs and approvals. secp256k1. */
1798
+ | "transaction"
1799
+ /** Solana transaction — bridge legs on SVM. ed25519, NOT secp256k1. */
1800
+ | "solana_transaction" | "hl_l1_action"
1801
+ /**
1802
+ * EIP-7702 authorization over `{ contractAddress, chainId, nonce }`.
1803
+ *
1804
+ * A signature over a RAW digest — `keccak(0x05 ‖ rlp([chainId, delegate,
1805
+ * nonce]))` — not EIP-191 and not EIP-712. Many wallets do not expose this,
1806
+ * and that is expected: reject it and the server falls back to asking the
1807
+ * user to broadcast a plain approve instead.
1808
+ */
1809
+ | "eip7702_authorization"
1810
+ /**
1811
+ * A Gnosis Safe transaction relayed through Polymarket — a legacy Polymarket
1812
+ * wallet funding a fill. The payload is the SafeTx as EIP-712 typed data,
1813
+ * but the wallet must `personal_sign` the RAW 32 bytes of
1814
+ * `hashTypedData(payload)` (`signMessage({ message: { raw: hash } })`):
1815
+ * Polymarket's relayer only accepts that shape. `payload.safeTxHash` carries
1816
+ * the digest for convenience; the server recomputes it from the typed data.
1817
+ */
1818
+ | "safe_tx";
1819
+ /** One payload the client must sign before a fill can proceed. */
1820
+ interface SignatureRequest {
1821
+ /** Echo this back with the signature. */
1822
+ stepId: string;
1823
+ /** Payload shape. Discriminates how to sign — not which venue. */
1824
+ type: SignatureRequestType;
1825
+ venue: string;
1826
+ /** The address that must produce this signature. Sign with this key, not another. */
1827
+ signerAddress: string;
1828
+ /** Absent for non-EVM payloads (e.g. Hyperliquid L1 actions). */
1829
+ chainId?: number;
1830
+ /** Sign verbatim. */
1831
+ payload: unknown;
1832
+ expiresAt: string;
1833
+ /** Why this signature is being asked for, when the server knows (e.g. `"fee"`, `"funding_and_fee"`). Display only. */
1834
+ purpose?: string;
1835
+ }
1836
+ /**
1837
+ * Supplied by the partner. Receives a payload, returns a signature. The SDK
1838
+ * never sees the key.
1839
+ *
1840
+ * Return a 0x-prefixed hex string for anything the wallet SIGNS:
1841
+ *
1842
+ * - `eip712` — `signTypedData` over `payload`.
1843
+ * - `personal_sign` — `personal_sign` over `payload`.
1844
+ * - `safe_tx` — `personal_sign` over the RAW 32 bytes of
1845
+ * `hashTypedData(payload)` (viem: `signMessage({ message: { raw: hash } })`,
1846
+ * MetaMask: `personal_sign` with the hex hash). The wallet shows a hash, not
1847
+ * a structured prompt — that is what Polymarket's own relayer requires.
1848
+ * - `hl_l1_action` — Hyperliquid L1 action, EIP-712 in phantom-agent form.
1849
+ * - `eip7702_authorization` — an EIP-7702 authorization over
1850
+ * `{ contractAddress, chainId, nonce }`. This is a signature over a RAW
1851
+ * digest, not EIP-191 and not EIP-712, and many wallets do not expose it.
1852
+ * **Throwing here does not help**: there is no reject verb, so a thrown
1853
+ * signer is indistinguishable from a slow user — the request simply expires
1854
+ * and the fill dies. If your wallet cannot produce this signature, declare
1855
+ * `approveMode: "user_broadcast"` on the fill instead and the approve is
1856
+ * requested as a `transaction` the user sends themselves. Handling this
1857
+ * request is what makes funding gasless.
1858
+ *
1859
+ * Return `{ txHash }` for anything the wallet BROADCASTS:
1860
+ *
1861
+ * - `transaction` — send it, then return the hash **immediately, without
1862
+ * awaiting the receipt**. The server watches for the mined receipt itself
1863
+ * and will not resume until it matches the request byte-for-byte.
1864
+ */
1865
+ type SignerFn = (req: SignatureRequest) => Promise<string | {
1866
+ txHash: string;
1867
+ }>;
1868
+ /**
1869
+ * How long `fillSelfCustody` will keep waiting before giving up.
1870
+ *
1871
+ * Covers a first-time user: sign the wallet-setup batch, wait for it on-chain,
1872
+ * then sign the order. Generous because the wait is a relayer transaction
1873
+ * confirming, not a human deciding.
1874
+ */
1875
+ declare const SELF_CUSTODY_FILL_TIMEOUT_MS: number;
1876
+ /** Gap between re-reads while an on-chain step is in flight. */
1877
+ declare const SELF_CUSTODY_POLL_INTERVAL_MS = 2000;
1878
+ /**
1879
+ * States a run never leaves. Everything else means "still working".
1880
+ *
1881
+ * Typed against `ExecutionOverallState` so a typo'd or renamed literal (e.g.
1882
+ * `cancelled` drifting to `canceled`) is a compile error instead of a state
1883
+ * that silently stops being treated as terminal. Mirrors
1884
+ * `ExecutionOverallStateTB` in the contract; keep the two in step.
1885
+ */
1886
+ declare const TERMINAL_EXECUTION_STATES: ReadonlySet<ExecutionOverallState>;
1887
+ type SportsGameStatus = "scheduled" | "live" | "paused" | "finished" | "cancelled" | "postponed" | "unknown";
1888
+ interface SportsLiveParticipant {
1889
+ position: "first" | "second";
1890
+ name: string;
1891
+ shortName: string | null;
1892
+ imageUrl: string | null;
1893
+ score: string | null;
1894
+ }
1895
+ interface SportsLiveState {
1896
+ eventId: string;
1897
+ sport: string;
1898
+ status: SportsGameStatus;
1899
+ participants: [SportsLiveParticipant, SportsLiveParticipant];
1900
+ period: string | null;
1901
+ clock: string | null;
1902
+ updatedAt: string | null;
1903
+ }
1904
+ interface SportsLiveResponse {
1905
+ data: SportsLiveState[];
1906
+ missingEventIds: string[];
1907
+ }
1908
+ interface AggClientOptions {
1909
+ /** Browser adapters can inject a Worker transport; other runtimes keep the native client. */
1910
+ webSocketFactory?: (options: AggWebSocketOptions) => AggWebSocket;
1911
+ baseUrl: string;
1912
+ /** Public App ID — sent as x-app-id header. For client-side partner usage. */
1913
+ appId?: string;
1914
+ /** Secret admin key — sent as x-admin-key header. Server-side only. */
1915
+ adminKey?: string;
1916
+ /**
1917
+ * Partner API key for server-side use. Sent as `x-app-api-key`. NEVER embed
1918
+ * in browser bundles, source maps, or logs. Keys start with `agg_<appId>_`.
1919
+ */
1920
+ apiKey?: string;
1921
+ /** WebSocket URL for real-time feeds. Must be set explicitly to use createWebSocket(). */
1922
+ wsUrl?: string;
1923
+ /** Opt in after immutable history publication/CDN rollout. Defaults false. */
1924
+ preferImmutableHistory?: boolean;
1925
+ /**
1926
+ * @deprecated Kalshi live discovery and trading are retired. This ignored
1927
+ * compatibility option remains to avoid breaking existing SDK consumers.
1928
+ */
1929
+ kalshiDemo?: boolean;
1930
+ /** Optional auth request hooks used to enrich auth payloads. */
1931
+ auth?: AggClientAuthOptions;
1932
+ /** Move refresh delivery to an HttpOnly cookie on auth endpoints. Defaults to "body". */
1933
+ authDelivery?: AggAuthDeliveryMode;
1934
+ /** Persist a non-sensitive auth hint to localStorage for UI bootstrapping.
1935
+ * Tokens are NEVER persisted — they exist only in process memory.
1936
+ * When authDelivery is "body", refresh tokens are lost on page reload.
1937
+ * When authDelivery is "cookie-refresh", refresh tokens survive via HttpOnly cookies
1938
+ * and the SDK attempts a silent refresh on cold start. Defaults to true. */
1939
+ persistSession?: boolean;
1940
+ /**
1941
+ * Supplies signatures for self-custodial fills. Required whenever
1942
+ * `fillSelfCustody()` is called with `signingAddress` — the SDK never
1943
+ * holds a key itself, so without this option a fill that needs a
1944
+ * client-side signature cannot proceed. The signature requests never
1945
+ * come back on `POST /execution/fill` itself: `fillSelfCustody()` polls
1946
+ * `GET /execution/status` for them (`pendingSignatures`), signs each one
1947
+ * with this function, and posts the result to
1948
+ * `POST /execution/fill/:quoteId/signatures`.
1949
+ */
1950
+ signer?: SignerFn;
1951
+ }
1952
+ interface SiweMessageParams {
1953
+ domain: string;
1954
+ address: string;
1955
+ uri: string;
1956
+ nonce: string;
1957
+ chainId?: number;
1958
+ statement?: string;
1959
+ issuedAt?: string;
1960
+ }
1961
+ interface SiwsMessageParams {
1962
+ domain: string;
1963
+ /** Base58-encoded Solana public key. */
1964
+ address: string;
1965
+ uri: string;
1966
+ nonce: string;
1967
+ /** Solana chain ID: "mainnet", "devnet", "testnet", or "localnet". Defaults to "mainnet". */
1968
+ chainId?: string;
1969
+ statement?: string;
1970
+ issuedAt?: string;
1971
+ }
1972
+ /** OHLCV bar point for chart rendering. */
1973
+ interface ChartCandle {
1974
+ /** Venue average; distinct from OHLC close. */
1975
+ mean?: number;
1976
+ /** Open time in Unix milliseconds. */
1977
+ t: number;
1978
+ /** Open price (0-1). */
1979
+ o: number;
1980
+ /** High price (0-1). */
1981
+ h: number;
1982
+ /** Low price (0-1). */
1983
+ l: number;
1984
+ /** Close price (0-1). */
1985
+ c: number;
1986
+ /** Volume (null if unavailable). */
1987
+ v: number | null;
1988
+ }
1989
+ /** @deprecated Historical chart bars are canonical per outcome. Use ChartBarsResponse instead. */
1990
+ interface ChartVenueCandles {
1991
+ venue: string;
1992
+ candles: ChartCandle[];
1993
+ }
1994
+ type ChartResolution = "1m" | "5m" | "1h" | "1d";
1995
+ /**
1996
+ * Freshness signal embedded in every chart response. Compare
1997
+ * `staleSeconds` against the resolution to decide whether to show a
1998
+ * "delayed" badge on the chart.
1999
+ */
2000
+ interface ChartBarsMeta {
2001
+ state?: "ready" | "warming" | "unsupported" | "failed" | "empty";
2002
+ complete?: boolean;
2003
+ retryAfterMs?: number;
2004
+ /** Agg fetch/publication time. Does not measure upstream delivery latency. */
2005
+ fetchedAtMs?: number;
2006
+ /** Server-side wall clock when the response was assembled, in milliseconds. */
2007
+ serverTime: number;
2008
+ /** `open_time` of the most-recent bar in `data`, in milliseconds. Null if `data` is empty. */
2009
+ lastBarOpenTime: number | null;
2010
+ /** `serverTime - lastBarOpenTime` in seconds. Null if `data` is empty. */
2011
+ staleSeconds: number | null;
2012
+ }
2013
+ /** Response from GET /charts/bars. */
2014
+ interface ChartBarsResponse {
2015
+ /** VenueMarketOutcome.id requested by the caller. */
2016
+ venueMarketOutcomeId: string;
2017
+ /** Venue of the canonical historical series. */
2018
+ venue: string;
2019
+ /** Resolution returned by the backend. */
2020
+ resolution: ChartResolution;
2021
+ /** Bars sorted in ascending open time. */
2022
+ data: ChartCandle[];
2023
+ /** Freshness signal — see {@link ChartBarsMeta}. */
2024
+ meta: ChartBarsMeta;
2025
+ }
2026
+ interface ChartHistoryManifest {
2027
+ version: 1;
2028
+ revision: string | null;
2029
+ venueMarketOutcomeId: string;
2030
+ venue: string;
2031
+ resolution: ChartResolution;
2032
+ semantics: "venue-ohlcv-v1" | "polymarket-price-samples-v1" | "kalshi-ohlcv-quote-fallback-v2";
2033
+ from: number;
2034
+ to: number;
2035
+ finalizedThrough: number;
2036
+ chunks: Array<{
2037
+ key: string;
2038
+ url: string;
2039
+ sha256: string;
2040
+ from: number;
2041
+ to: number;
2042
+ points: number;
2043
+ }>;
2044
+ meta: ChartBarsMeta;
2045
+ }
2046
+ /** Matched market reference returned by batch/aggregate endpoints. */
2047
+ interface VenueMarketRef {
2048
+ venue: string;
2049
+ venueMarketId: string;
2050
+ }
2051
+ type OrderbookBatchItemStatus = "ok" | "market_not_found" | "market_resolved" | "market_closed" | "market_paused" | "market_unopened" | "book_not_loaded";
2052
+ type OrderbookBatchItemErrorCode = "market_not_found" | "market_resolved" | "market_closed" | "market_paused" | "market_unopened" | "book_not_loaded";
2053
+ interface OrderbookBatchItemError {
2054
+ code: OrderbookBatchItemErrorCode;
2055
+ message: string;
2056
+ retryable: boolean;
2057
+ }
2058
+ interface OrderbooksOnlyError {
2059
+ code: "use_orderbooks_endpoint";
2060
+ message: string;
2061
+ retryable: boolean;
2062
+ }
2063
+ interface OrderbookServiceUnavailableError {
2064
+ code: "orderbook_service_unavailable";
2065
+ message: string;
2066
+ retryable: boolean;
2067
+ }
2068
+ interface RequestedOrderbookMarket {
2069
+ venueMarketId: string;
2070
+ venue: string;
2071
+ marketStatus: "open" | "closed" | "resolved" | "unopened" | "paused";
2072
+ tickSize: number | null;
2073
+ endDate: string | null;
2074
+ resolutionDate: string | null;
2075
+ }
2076
+ interface MatchedOrderbookMarket extends VenueMarketRef {
2077
+ marketStatus: "open" | "closed" | "resolved" | "unopened" | "paused";
2078
+ tickSize: number | null;
2079
+ hasOrderbook: boolean;
2080
+ /**
2081
+ * Hyperliquid HIP-4 deployer namespace this member belongs to (e.g. "ap").
2082
+ * `null` for every other venue and for Hyperliquid members without one.
2083
+ * Names which deployer this cluster member is — distinct from whether its
2084
+ * book was published (see `hasOrderbook`).
2085
+ */
2086
+ deployerVenue?: string | null;
2087
+ }
2088
+ /**
2089
+ * Provenance of a published `midpoint`. Mirrors the engine's `MarkSource`.
2090
+ *
2091
+ * - `local` — true two-sided midpoint from the venue's own book
2092
+ * - `local_merged` — midpoint from the cross-venue merged book
2093
+ * - `local_one_sided` — only one side present; mark is the live side, NOT a midpoint
2094
+ * - `sibling` — derived from the complementary outcome (e.g. NO from YES)
2095
+ * - `local_boundary` — clamped to the [tick, 1-tick] boundary
2096
+ * - `none` — no mark available
2097
+ */
2098
+ type MarkSource = "local" | "local_merged" | "local_one_sided" | "sibling" | "local_boundary" | "none";
2099
+ declare const RECURRENCE_CADENCES: readonly ["PT5M", "PT10M", "PT15M", "PT30M", "PT1H", "PT4H", "P1D", "P1W", "P1M", "P1Y"];
2100
+ type RecurrenceCadence = (typeof RECURRENCE_CADENCES)[number];
2101
+ type RecurrenceFilter = RecurrenceCadence | "null";
2102
+ type RecurringCryptoDuration = "PT5M" | "PT15M" | "PT30M" | "PT1H" | "PT4H" | "P1D";
2103
+ type RecurringCryptoDurationInput = RecurringCryptoDuration | "5m" | "15m" | "30m" | "1h" | "4h" | "1d";
2104
+ type RecurringCryptoSourceConfidence = "verified" | "inferred" | "missing";
2105
+ interface ListRecurringCryptoMarketsOptions {
2106
+ assets?: string[];
2107
+ durations?: RecurringCryptoDurationInput[];
2108
+ interval?: RecurringCryptoDurationInput;
2109
+ window?: "current";
2110
+ venues?: Venue[];
2111
+ status?: MarketStatus[];
2112
+ windowStartFrom?: string;
2113
+ windowStartTo?: string;
2114
+ cursor?: string;
2115
+ limit?: number;
2116
+ includeOrderbookPrices?: boolean;
2117
+ includeReferencePrices?: boolean;
2118
+ includeDirectVenueMarkets?: boolean;
2119
+ includeOrderbookDepth?: boolean;
2120
+ orderbookDepth?: number;
2121
+ orderbookDepthAmountUsd?: number;
2122
+ }
2123
+ interface RecurringCryptoOrderbookDepthLevel {
2124
+ price: number;
2125
+ size: number;
2126
+ notionalUsd: number;
2127
+ cumulativeSize: number;
2128
+ cumulativeNotionalUsd: number;
2129
+ fillSize: number | null;
2130
+ fillNotionalUsd: number | null;
2131
+ }
2132
+ interface RecurringCryptoOrderbookDepthSide {
2133
+ levels: RecurringCryptoOrderbookDepthLevel[];
2134
+ totalSize: number;
2135
+ totalNotionalUsd: number;
2136
+ requestedNotionalUsd: number | null;
2137
+ filledSize: number | null;
2138
+ filledNotionalUsd: number | null;
2139
+ unfilledNotionalUsd: number | null;
2140
+ avgPrice: number | null;
2141
+ worstPrice: number | null;
2142
+ fillsComplete: boolean | null;
2143
+ }
2144
+ interface RecurringCryptoOutcomeOrderbookDepth {
2145
+ currency: "USD";
2146
+ amountUsd: number | null;
2147
+ buy: RecurringCryptoOrderbookDepthSide;
2148
+ sell: RecurringCryptoOrderbookDepthSide;
2149
+ }
2150
+ interface RecurringCryptoOutcome {
2151
+ /**
2152
+ * Canonical Agg outcome id. Null for direct live venue rows because those
2153
+ * rows are discovery data and cannot be passed to smart order routing.
2154
+ */
2155
+ venueMarketOutcomeId: string | null;
2156
+ /** Venue-native outcome id or synthetic external id for direct live rows. */
2157
+ externalOutcomeId: string | null;
2158
+ /** False for this endpoint; live crypto markets are not smart-route inputs. */
2159
+ routeable: boolean;
2160
+ /** False for this endpoint; split-order routing is not supported here. */
2161
+ splitOrdersAllowed: boolean;
2162
+ label: string;
2163
+ title: string | null;
2164
+ midpoint: number | null;
2165
+ bestBid: number | null;
2166
+ bestAsk: number | null;
2167
+ markSource: MarkSource | string | null;
2168
+ lastKnownPrice: number | null;
2169
+ orderbookDepth: RecurringCryptoOutcomeOrderbookDepth | null;
2170
+ }
2171
+ interface RecurringCryptoMarketMetrics {
2172
+ volume: number | null;
2173
+ volume24h: number | null;
2174
+ openInterest: number | null;
2175
+ liquidity: number | null;
2176
+ spread: number | null;
2177
+ }
2178
+ interface RecurringCryptoResolution {
2179
+ sourceName: string | null;
2180
+ sourceUrl: string | null;
2181
+ sourceDomain: string | null;
2182
+ rawCriteria: unknown;
2183
+ confidence: RecurringCryptoSourceConfidence;
2184
+ }
2185
+ interface RecurringCryptoReferencePrice {
2186
+ asset: string;
2187
+ quoteAsset: "USD";
2188
+ raw: string | null;
2189
+ decimals: number | null;
2190
+ normalized: number | null;
2191
+ timestamp: string | null;
2192
+ provider: string | null;
2193
+ providerMarketId: string | null;
2194
+ confidence: RecurringCryptoSourceConfidence;
2195
+ fetchedAt?: string | null;
2196
+ ageMs?: number | null;
2197
+ refreshing?: boolean;
2198
+ stale?: boolean;
2199
+ }
2200
+ type CryptoReferencePriceTarget = {
2201
+ type: "venueMarket";
2202
+ venueMarketId: string;
2203
+ } | {
2204
+ type: "venueEvent";
2205
+ venueEventId: string;
2206
+ } | {
2207
+ type: "externalVenueMarket";
2208
+ venue: Venue;
2209
+ externalMarketId: string;
2210
+ } | {
2211
+ type: "market";
2212
+ venue: Venue;
2213
+ venueEventId?: string;
2214
+ venueMarketId: string;
2215
+ externalEventId?: string | null;
2216
+ externalMarketId?: string;
2217
+ asset: string;
2218
+ quoteAsset?: "USD";
2219
+ resolution: RecurringCryptoResolution;
2220
+ };
2221
+ interface CryptoReferencePriceExternalMarketInput {
2222
+ venue: Venue;
2223
+ externalMarketId: string;
2224
+ }
2225
+ interface CryptoReferencePriceMarketInput extends RecurringCryptoVenueMarket {
2226
+ asset: string;
2227
+ quoteAsset?: "USD";
2228
+ }
2229
+ interface GetCryptoReferencePricesOptions {
2230
+ targets?: CryptoReferencePriceTarget[];
2231
+ venueMarketIds?: string[];
2232
+ venueEventIds?: string[];
2233
+ externalMarkets?: CryptoReferencePriceExternalMarketInput[];
2234
+ markets?: CryptoReferencePriceMarketInput[];
2235
+ windowMarkets?: RecurringCryptoWindowMarket[];
2236
+ signal?: AbortSignal;
2237
+ }
2238
+ interface CryptoReferencePriceError {
2239
+ code: "not_found" | "not_recurring_crypto" | "reference_feed_missing" | "price_unavailable" | "stale_price";
2240
+ message: string;
2241
+ }
2242
+ interface CryptoReferencePriceSource {
2243
+ provider: string | null;
2244
+ providerMarketId: string | null;
2245
+ confidence: RecurringCryptoSourceConfidence;
2246
+ }
2247
+ interface CryptoReferencePriceResult {
2248
+ target: CryptoReferencePriceTarget;
2249
+ venue: Venue | null;
2250
+ venueEventId: string | null;
2251
+ venueMarketId: string | null;
2252
+ externalEventId: string | null;
2253
+ externalMarketId: string | null;
2254
+ asset: string | null;
2255
+ quoteAsset: "USD" | null;
2256
+ raw: string | null;
2257
+ decimals: number | null;
2258
+ normalized: number | null;
2259
+ providerTimestamp: string | null;
2260
+ fetchedAt: string | null;
2261
+ ageMs: number | null;
2262
+ refreshing: boolean;
2263
+ stale: boolean;
2264
+ source: CryptoReferencePriceSource;
2265
+ error: CryptoReferencePriceError | null;
2266
+ }
2267
+ interface CryptoReferencePricesResponse {
2268
+ data: CryptoReferencePriceResult[];
2269
+ softRefreshMs: number;
2270
+ hardMaxAgeMs: number;
2271
+ }
2272
+ type RecurringCryptoComparisonPriceSource = "referencePrice" | "midpoint" | "lastKnownPrice";
2273
+ interface RecurringCryptoComparisonPoint {
2274
+ venue: Venue;
2275
+ venueMarketId: string;
2276
+ value: number;
2277
+ label: string | null;
2278
+ source: RecurringCryptoComparisonPriceSource;
2279
+ provider: string | null;
2280
+ providerMarketId: string | null;
2281
+ timestamp: string | null;
2282
+ confidence: RecurringCryptoSourceConfidence | null;
2283
+ }
2284
+ interface RecurringCryptoPriceComparison {
2285
+ count: number;
2286
+ min: RecurringCryptoComparisonPoint | null;
2287
+ max: RecurringCryptoComparisonPoint | null;
2288
+ spread: number | null;
2289
+ spreadBps: number | null;
2290
+ byVenue: RecurringCryptoComparisonPoint[];
2291
+ }
2292
+ interface RecurringCryptoWindowComparisons {
2293
+ referencePrice: RecurringCryptoPriceComparison;
2294
+ outcomePrices: {
2295
+ up: RecurringCryptoPriceComparison;
2296
+ down: RecurringCryptoPriceComparison;
2297
+ };
2298
+ }
2299
+ interface RecurringCryptoVenueMarket {
2300
+ venue: Venue;
2301
+ venueEventId: string;
2302
+ venueMarketId: string;
2303
+ externalEventId: string | null;
2304
+ externalMarketId: string;
2305
+ question: string;
2306
+ status: MarketStatus;
2307
+ priceSource: "snag" | "direct";
2308
+ /** False for this endpoint; live crypto markets are not smart-route inputs. */
2309
+ routeable: boolean;
2310
+ /** False for this endpoint; split-order routing is not supported here. */
2311
+ splitOrdersAllowed: boolean;
2312
+ outcomes: RecurringCryptoOutcome[];
2313
+ metrics: RecurringCryptoMarketMetrics;
2314
+ resolution: RecurringCryptoResolution;
2315
+ referencePrice: RecurringCryptoReferencePrice;
2316
+ }
2317
+ interface RecurringCryptoWindowMarket {
2318
+ id: string;
2319
+ asset: string;
2320
+ quoteAsset: "USD";
2321
+ duration: RecurringCryptoDuration;
2322
+ windowStart: string;
2323
+ windowEnd: string;
2324
+ status: MarketStatus;
2325
+ markets: RecurringCryptoVenueMarket[];
2326
+ comparisons: RecurringCryptoWindowComparisons;
2327
+ }
2328
+ interface RecurringCryptoMarketsResponse {
2329
+ data: RecurringCryptoWindowMarket[];
2330
+ nextCursor: string | null;
2331
+ hasMore: boolean;
2332
+ }
2333
+ /** Per-venue orderbook entry with native tick spacing. */
2334
+ interface VenueOrderbookEntry {
2335
+ venueMarketId: string;
2336
+ tickSize: number | null;
2337
+ orderbook: Orderbook;
2338
+ /**
2339
+ * Sticky tick of this venue's book inferred at runtime by the engine. May
2340
+ * differ from the seed `tickSize` when the live grid is finer than the DB
2341
+ * metadata. Optional — only populated when the engine has emitted runtime
2342
+ * metadata for this entry.
2343
+ */
2344
+ tick?: number | null;
2345
+ /** Provenance of this venue book's published midpoint. See {@link MarkSource}. */
2346
+ markSource?: MarkSource;
2347
+ /**
2348
+ * Hyperliquid HIP-4 deployer namespace whose book this entry publishes
2349
+ * (e.g. "ap"). `null` for every other venue. When a cluster has more than
2350
+ * one Hyperliquid deployer member, only one member's book is published per
2351
+ * request — this names which one, so a caller never pairs this entry's depth
2352
+ * with a different member's `venueMarketId`.
2353
+ */
2354
+ deployerVenue?: string | null;
2355
+ }
2356
+ /** Response from GET /orderbooks (batch). */
2357
+ interface BatchOrderbooksResponse {
2358
+ data: Array<{
2359
+ venueMarketId: string;
2360
+ status: OrderbookBatchItemStatus;
2361
+ error: OrderbookBatchItemError | null;
2362
+ requestedMarket: RequestedOrderbookMarket | null;
2363
+ venueOrderbooks: Record<string, VenueOrderbookEntry>;
2364
+ matchedMarkets: MatchedOrderbookMarket[];
2365
+ }>;
2366
+ meta: {
2367
+ requestedCount: number;
2368
+ okCount: number;
2369
+ errorCount: number;
2370
+ };
2371
+ }
2372
+ /** A single market midpoint row returned by GET /midpoints. */
2373
+ interface MidpointRow {
2374
+ venueMarketId: string;
2375
+ venue: string;
2376
+ midpoint: number | null;
2377
+ spread: number | null;
2378
+ timestamp: number | null;
2379
+ arbReturn?: number | null;
2380
+ /** Provenance of `midpoint`. */
2381
+ markSource?: MarkSource;
2382
+ /**
2383
+ * When `markSource === "sibling"`, the matched venueMarketId whose book
2384
+ * supplied the headline mark. Allows the FE to label "sourced from venue X"
2385
+ * without re-running the matching logic.
2386
+ */
2387
+ siblingVenueMarketId?: string;
2388
+ /** Top-of-book buy-side price. Only present when `bestPrice=true`. */
2389
+ bestBid?: number | null;
2390
+ /** Top-of-book sell-side price. Only present when `bestPrice=true`. */
2391
+ bestAsk?: number | null;
2392
+ }
2393
+ /** Per-outcome midpoint from a live orderbook. */
2394
+ interface OutcomeMidpointRow {
2395
+ venueMarketOutcomeId: string;
2396
+ label: string;
2397
+ midpoint: number | null;
2398
+ /** Provenance of `midpoint`. */
2399
+ markSource?: MarkSource;
2400
+ /** Top-of-book buy-side price. Only present when `bestPrice=true`. */
2401
+ bestBid?: number | null;
2402
+ /** Top-of-book sell-side price. Only present when `bestPrice=true`. */
2403
+ bestAsk?: number | null;
2404
+ }
2405
+ /** Response from GET /midpoints (batch). */
2406
+ interface BatchMidpointsResponse {
2407
+ data: Array<MidpointRow & {
2408
+ outcomes: OutcomeMidpointRow[];
2409
+ matched: MidpointRow[];
2410
+ /**
2411
+ * Live, quality-gated cross-venue arbitrage return for this market's
2412
+ * cluster as a decimal fraction (`0.0085` = 0.85%), computed fresh by
2413
+ * the engine on this request. Prefer it over the `arbReturn` embedded
2414
+ * in venue-event listings, which a background sync can leave stale.
2415
+ * Only present when the request set `bestPrice=true`.
2416
+ */
2417
+ arbReturn?: number | null;
2418
+ /**
2419
+ * DB status of the requested market. Present whenever the id resolves
2420
+ * to a known market. Resolved markets never serve a price (see `error`).
2421
+ */
2422
+ marketStatus?: MarketStatus;
2423
+ /**
2424
+ * Structured refusal, mirroring GET /orderbooks per-item errors:
2425
+ * `market_resolved` for settled markets (prices are nulled instead of
2426
+ * serving a stale mark), `market_not_found` for unknown ids.
2427
+ */
2428
+ error?: {
2429
+ code: "market_resolved" | "market_not_found";
2430
+ message: string;
2431
+ retryable: boolean;
2432
+ };
2433
+ }>;
2434
+ }
2435
+ /** Response from GET /orderbook/outcome/:id (single outcome). */
2436
+ interface OutcomeOrderbookResponse {
2437
+ /** CRC of returned depth-limited levels; full engine checksum remains unchanged. */
2438
+ snapshotChecksum?: number;
2439
+ venueMarketOutcomeId: string;
2440
+ venueMarketId: string;
2441
+ venue: string;
2442
+ orderbook: {
2443
+ bids: Array<{
2444
+ price: number;
2445
+ size: number;
2446
+ }>;
2447
+ asks: Array<{
2448
+ price: number;
2449
+ size: number;
2450
+ }>;
2451
+ };
2452
+ midpoint: number | null;
2453
+ spread: number | null;
2454
+ seq: number;
2455
+ checksum: number;
2456
+ timestamp: number;
2457
+ /** Sticky tick of this outcome's book, inferred at runtime. `null` until inferred. */
2458
+ tick: number | null;
2459
+ /** Provenance of `midpoint`. See {@link MarkSource}. */
2460
+ markSource: MarkSource;
2461
+ }
2462
+ /** Standard paginated list response from the API. */
2463
+ interface PaginatedResponse<T> {
2464
+ data: T[];
2465
+ nextCursor: string | null;
2466
+ hasMore: boolean;
2467
+ }
2468
+ interface OrderListQuery {
2469
+ userId?: string;
2470
+ status?: string;
2471
+ limit?: number;
2472
+ offset?: number;
2473
+ }
2474
+ interface TradeExecutorOrder {
2475
+ id: string;
2476
+ userId: string;
2477
+ venue: string;
2478
+ status: string;
2479
+ marketId: string;
2480
+ tokenId: string;
2481
+ side: string;
2482
+ amountRaw: string;
2483
+ quoteId: string | null;
2484
+ externalId: string | null;
2485
+ clientOrderId: string | null;
2486
+ dagRunId: string | null;
2487
+ filledAmountRaw: string | null;
2488
+ executionPrice: string | null;
2489
+ txHash: string | null;
2490
+ errorMessage: string | null;
2491
+ createdAt: string;
2492
+ updatedAt: string;
2493
+ }
2494
+ interface TradeExecutorOrderListResponse {
2495
+ orders: TradeExecutorOrder[];
2496
+ total: number;
2497
+ }
2498
+ /** A single level in the aggregated orderbook with per-venue attribution. */
2499
+ interface AggregatedOrderbookLevel {
2500
+ price: number;
2501
+ size: number;
2502
+ venues: Record<string, number>;
2503
+ }
2504
+ /** A simple orderbook level without venue attribution. */
2505
+ interface SimpleOrderbookLevel {
2506
+ price: number;
2507
+ size: number;
2508
+ }
2509
+ /** Per-venue best-bid/ask info. */
2510
+ interface VenuePriceInfo {
2511
+ bestBid: number | null;
2512
+ bestAsk: number | null;
2513
+ }
2514
+ /** Response from GET /orderbook/:venueMarketId — canonical aggregated orderbook. */
2515
+ interface AggregatedOrderbookResponse {
2516
+ venueMarketId: string;
2517
+ orderbook: {
2518
+ bids: AggregatedOrderbookLevel[];
2519
+ asks: AggregatedOrderbookLevel[];
2520
+ };
2521
+ venueOrderbooks: Record<string, {
2522
+ bids: SimpleOrderbookLevel[];
2523
+ asks: SimpleOrderbookLevel[];
2524
+ }>;
2525
+ venues: Record<string, VenuePriceInfo>;
2526
+ midpoint: number | null;
2527
+ spread: number | null;
2528
+ timestamp: number;
2529
+ /** Sequence number (present in live responses). */
2530
+ seq?: number;
2531
+ /** CRC32 checksum (present in live responses). */
2532
+ checksum?: number | null;
2533
+ /** Markets matched across venues for this canonical market. */
2534
+ matchedMarkets?: Array<{
2535
+ venue: string;
2536
+ venueMarketId: string;
2537
+ }>;
2538
+ }
2539
+ interface ExecuteManagedParams {
2540
+ quoteId: string;
2541
+ /** Trading mode. Defaults to live. */
2542
+ mode?: ExecutionMode;
2543
+ /**
2544
+ * Optional intent fallback. When the supplied `quoteId` has expired in the
2545
+ * cache (e.g. user clicked Buy after a tab was inactive), the server
2546
+ * resolves the latest quote for this intent and refreshes/executes against
2547
+ * that instead of returning 400 `quote_not_found`. Same intent = same buttons
2548
+ * the user pressed in the UI; a different `maxSpend`, mode, or venue scope is
2549
+ * a different intent and won't match.
2550
+ */
2551
+ fallbackToLatest?: {
2552
+ outcomeId: string;
2553
+ side: "buy" | "sell";
2554
+ maxSpend?: number;
2555
+ sellShares?: number;
2556
+ allowedVenues?: Venue[];
2557
+ };
2558
+ /**
2559
+ * Self-custody: the wallet that will sign this fill. Must be a wallet
2560
+ * already linked to this account. Omit for managed custody (the default).
2561
+ */
2562
+ signingAddress?: string;
2563
+ /**
2564
+ * Self-custody only: which approve shape a cross-chain fill uses when the
2565
+ * bridge needs an ERC20 approve. Omit (the default) for "sponsored" — the
2566
+ * approve costs the wallet no gas, but the wallet must sign a one-time
2567
+ * EIP-7702 authorization over a RAW DIGEST, which many wallets cannot
2568
+ * produce. Send "user_broadcast" when yours cannot: the user sends the
2569
+ * approve from their own wallet and pays its gas. Only your client can know
2570
+ * which applies — it is a property of the wallet software, not of the
2571
+ * address or the chain.
2572
+ *
2573
+ * Worth surfacing in your UI: "user_broadcast" never establishes the
2574
+ * delegation, so an approve is needed on EVERY bridge. "sponsored" costs one
2575
+ * signature once per chain.
2576
+ *
2577
+ * Neither mode makes bridging free — the approve is only one of the costs.
2578
+ * Relay's fee comes out of the amount delivered on every bridge, and one-time
2579
+ * costs apply per route. Quote with `deepEstimate` and read
2580
+ * `feeBreakdown.bridgeFees` and `feeBreakdown.setupCosts` rather than
2581
+ * inferring cost from the approve mode.
2582
+ */
2583
+ approveMode?: "sponsored" | "user_broadcast";
2584
+ }
2585
+ interface ExecuteManagedResponse {
2586
+ alreadyAccepted?: boolean;
2587
+ quoteId: string;
2588
+ orderIds: string[];
2589
+ status: "pending";
2590
+ redeemId?: string;
2591
+ message?: string;
2592
+ /**
2593
+ * What this fill is waiting to be signed, if anything. On the immediate
2594
+ * `POST /execution/fill` response this is always absent or empty — even
2595
+ * for a self-custody fill, the DAG parks asynchronously, after this
2596
+ * response has already been sent. Real entries only ever come back from
2597
+ * polling `GET /execution/status` or from the next
2598
+ * `POST /execution/fill/:quoteId/signatures` response (this same shape,
2599
+ * reused). Drive the whole round trip through `fillSelfCustody()` rather
2600
+ * than reading this field on the fill response by hand.
2601
+ */
2602
+ pendingSignatures?: SignatureRequest[];
2603
+ }
2604
+ type LimitOrderTimeInForce = "GTC" | "GTD" | "FOK" | "FAK" | "IOC" | "ALO";
2605
+ type CancelOrderSignature = {
2606
+ signature: string;
2607
+ timestamp: number;
2608
+ } | {
2609
+ venue: "hyperliquid";
2610
+ action: {
2611
+ type: "cancel";
2612
+ cancels: Array<{
2613
+ a: number;
2614
+ o: number;
2615
+ }>;
2616
+ };
2617
+ nonce: number;
2618
+ signature: {
2619
+ r: string;
2620
+ s: string;
2621
+ v: 27 | 28;
2622
+ };
2623
+ };
2624
+ interface PlaceLimitOrderParams {
2625
+ /** BETDEX uses hosted cash: GTC/IOC only, no signer, post-only or expiry.
2626
+ * Native odds are rounded conservatively and stake is rounded down. GTC
2627
+ * unmatched liquidity is cancelled at the in-play transition. SELL closes
2628
+ * the same For outcome and requires collateral as well as owned inventory.
2629
+ */
2630
+ venue: Venue;
2631
+ venueMarketOutcomeId: string;
2632
+ side: "buy" | "sell";
2633
+ limitPriceRaw: string;
2634
+ sizeRaw: string;
2635
+ timeInForce: LimitOrderTimeInForce;
2636
+ postOnly?: boolean;
2637
+ expiresAt?: string;
2638
+ clientOrderId?: string;
2639
+ /** Linked account EOA. Polymarket supports GTC/GTD buys; Hyperliquid supports GTC/ALO buys and sells. Agent keys stay on the client. Omit for managed custody. */
2640
+ signingAddress?: string;
2641
+ /** Same bridge approval mode as market fills; defaults to sponsored. */
2642
+ approveMode?: ExecuteManagedParams["approveMode"];
2643
+ /** Self-custody buys only: other wallets linked to this account whose balances may bridge in to fund the order. Requires signingAddress. */
2644
+ fundingAddresses?: string[];
2645
+ }
2646
+ interface PlaceLimitOrderResponse {
2647
+ orderId: string;
2648
+ /** Poll getExecutionStatus and answer submitFillSignatures using this ID. */
2649
+ quoteId?: string;
2650
+ status: "pending" | "submitting" | "submitted" | "cancel_pending" | "partial_fill" | "open" | "partially_filled_open" | "filled" | "cancelled" | "expired" | "failed";
2651
+ venue: Venue;
2652
+ venueOrderId?: string | null;
2653
+ reservedCostRaw?: string | null;
2654
+ limitPriceRaw: string;
2655
+ limitSizeRaw: string;
2656
+ filledSizeRaw: string;
2657
+ remainingSizeRaw: string;
2658
+ }
2659
+ interface PlaceOrderParams {
2660
+ venue: Venue;
2661
+ venueMarketOutcomeId: string;
2662
+ side: "buy" | "sell";
2663
+ /** Buy only. Maximum all-in USD spend, inclusive of app fee. */
2664
+ maxSpend?: number;
2665
+ /** Sell only. Number of contracts to sell. */
2666
+ sellShares?: number;
2667
+ /**
2668
+ * Your trade id. Required, unique within your app — two different users of
2669
+ * the same app cannot share one. A repeat returns 409 instead of trading twice.
2670
+ */
2671
+ externalId: string;
2672
+ /** Slippage cap in bps. Defaults to 500 (5%). Set explicitly on sells. */
2673
+ slipCapBps?: number;
2674
+ /** Restrict funding to these chain IDs. Omit to allow every funded chain. */
2675
+ allowedSourceChainIds?: number[];
2676
+ /** USD budgets capped by refreshed wallet balances; omitted chains cannot fund. */
2677
+ chainBalances?: Record<string, number>;
2678
+ /** Referral: EVM address that receives the referral fee. Needs an app API key. */
2679
+ referrer?: string;
2680
+ /** Referral fee in bips of routed notional (1..10000). Snag-free. */
2681
+ referrerFeeBips?: number;
2682
+ /** Who funds the referral: "user" (default) reserves it from maxSpend; "app" pays from `referralPayerAddress` after the fill. */
2683
+ referralPayer?: "user" | "app";
2684
+ /** Required with `referralPayer: "app"`: the wallet that signs the parked payout transaction. */
2685
+ referralPayerAddress?: string;
2686
+ /**
2687
+ * Skip the smart-route solver and send one order straight to `venue` (predict,
2688
+ * hyperliquid, novig and prophetx only; others return 400). Requires a `read_write` `x-app-api-key`. No
2689
+ * bridging: funds must already sit on the venue's own chain, and `allowedSourceChainIds` /
2690
+ * `chainBalances` are ignored alongside it. You own price and minimum
2691
+ * checks — an order the venue refuses fails after acceptance and uses up its `externalId`.
2692
+ */
2693
+ skipQuote?: boolean;
2694
+ /**
2695
+ * With `skipQuote`, skip the balance check and fund hold on a buy: nothing checks the
2696
+ * balance and an underfunded order fails at the venue. Sells still check the position.
2697
+ */
2698
+ skipBalance?: boolean;
2699
+ /**
2700
+ * With `skipQuote`, the price to trade at (e.g. `0.52`). Optional: if omitted, the best
2701
+ * available price at submission is used (best ask to buy, bid to sell). Ignored on
2702
+ * prophetx, which prices the order itself within `slipCapBps`.
2703
+ */
2704
+ price?: number;
2705
+ }
2706
+ interface PlaceOrderResponse {
2707
+ orderId: string;
2708
+ externalId: string;
2709
+ venue: Venue;
2710
+ status: "pending";
2711
+ quoteId: string;
2712
+ /** `null` if the order row doesn't carry a quoted price. Not zero. */
2713
+ quotedPriceRaw: string | null;
2714
+ /** `null` under the same conditions as `quotedPriceRaw`. Not zero. */
2715
+ quotedCostRaw: string | null;
2716
+ /** `null` under the same conditions as `quotedPriceRaw`. Not zero. */
2717
+ quotedSharesRaw: string | null;
2718
+ }
2719
+ interface ValidateManagedParams {
2720
+ venueMarketOutcomeIds: string[];
2721
+ side: "buy" | "sell";
2722
+ amount: number;
2723
+ }
2724
+ interface ValidateManagedResponse {
2725
+ canExecute: boolean;
2726
+ availableBalanceRaw: string;
2727
+ requiredBalanceRaw: string;
2728
+ bridgeSourceChainId?: number;
2729
+ bridgeAmountRaw?: string;
2730
+ }
2731
+ type BalanceRefillPolicyStatus = "enabled" | "paused";
2732
+ type BalanceRefillAttemptStatus = "reserved" | "executing" | "completed" | "failed";
2733
+ interface BalanceRefillAttempt {
2734
+ id: string;
2735
+ policyId: string;
2736
+ status: BalanceRefillAttemptStatus;
2737
+ /** Target-chain balance when the threshold was crossed, in 6-decimal USD units. */
2738
+ triggerBalanceRaw: string;
2739
+ /** Minimum amount the refill must deliver, in 6-decimal USD units. */
2740
+ requestedDeliveryRaw: string;
2741
+ /** Reserved source amount, in 6-decimal USD units. */
2742
+ sourceAmountRaw: string;
2743
+ completedAmountRaw: string | null;
2744
+ sourceChainId: number;
2745
+ targetChainId: number;
2746
+ feeRaw: string | null;
2747
+ errorMessage: string | null;
2748
+ startedAt: string | null;
2749
+ completedAt: string | null;
2750
+ createdAt: string;
2751
+ }
2752
+ interface BalanceRefillPolicy {
2753
+ id: string;
2754
+ targetChainId: number;
2755
+ targetTokenAddress: string;
2756
+ targetTokenSymbol: "USDC";
2757
+ /** Balance floor, in 6-decimal USD units. */
2758
+ minimumRaw: string;
2759
+ /** Minimum delivered amount per refill, in 6-decimal USD units. */
2760
+ refillAmountRaw: string;
2761
+ dailyCapRaw: string;
2762
+ maxFeeRaw: string;
2763
+ status: BalanceRefillPolicyStatus;
2764
+ cooldownSeconds: number;
2765
+ lastObservedRaw: string | null;
2766
+ lastEvaluatedAt: string | null;
2767
+ nextEligibleAt: string | null;
2768
+ consentedAt: string;
2769
+ createdAt: string;
2770
+ updatedAt: string;
2771
+ latestAttempt: BalanceRefillAttempt | null;
2772
+ }
2773
+ interface CreateBalanceRefillPolicyParams {
2774
+ targetChainId: number;
2775
+ targetTokenSymbol?: "USDC";
2776
+ minimumRaw: string;
2777
+ refillAmountRaw: string;
2778
+ /** Optional daily refill limit. Defaults to $1,002 in 6-decimal USD units. */
2779
+ dailyCapRaw?: string;
2780
+ /** Optional per-refill fee limit. Defaults to $2 in 6-decimal USD units. */
2781
+ maxFeeRaw?: string;
2782
+ }
2783
+ interface UpdateBalanceRefillPolicyParams {
2784
+ minimumRaw?: string;
2785
+ refillAmountRaw?: string;
2786
+ dailyCapRaw?: string;
2787
+ maxFeeRaw?: string;
2788
+ status?: BalanceRefillPolicyStatus;
2789
+ }
2790
+ type WithdrawTokenSymbol = "USDC" | "USDC.e" | "USDT";
2791
+ type WithdrawalSourceTokenSymbol = WithdrawTokenSymbol | "pUSD" | "USD1";
2792
+ interface WithdrawManagedParams {
2793
+ /** Positive integer string in the token's native decimals (e.g. "100000" = 0.1 USDC). */
2794
+ amountRaw: string;
2795
+ tokenSymbol: WithdrawTokenSymbol;
2796
+ /** Recipient address. EVM destinations use 0x-prefixed 20-byte hex; Solana uses base58. */
2797
+ destinationAddress: string;
2798
+ /** Chain ID where the recipient should receive funds. Required as of v2026.04. */
2799
+ destinationChainId: number;
2800
+ /**
2801
+ * When `true`, the server caps the withdrawal to the maximum deliverable amount
2802
+ * instead of rejecting an over-balance request. Use only when the user explicitly
2803
+ * clicked Max — manual over-typed amounts must still surface the unviable state.
2804
+ */
2805
+ max?: boolean;
2806
+ }
2807
+ type WithdrawalLifecycleStatus = "pending" | "bridging" | "transferring" | "completed" | "partial" | "failed";
2808
+ type WithdrawalSourceStatus = "pending" | "submitted" | "confirmed" | "failed";
2809
+ type WithdrawalLegType = "transfer" | "bridge";
2810
+ type WithdrawalLegStatus = "planned" | "submitted" | "confirmed" | "failed";
2811
+ interface WithdrawalLeg {
2812
+ type: WithdrawalLegType;
2813
+ status: WithdrawalLegStatus;
2814
+ sourceChainId: number;
2815
+ destChainId: number;
2816
+ amountRaw: string;
2817
+ txHash: string | null;
2818
+ bridgeOperationId: string | null;
2819
+ /** Human-readable failure reason when `status === "failed"`. Null when succeeded or in-flight. */
2820
+ errorMessage?: string | null;
2821
+ }
2822
+ interface WithdrawManagedSourceItem {
2823
+ sourceId: string;
2824
+ chainId: number;
2825
+ tokenSymbol: WithdrawalSourceTokenSymbol;
2826
+ /** On-chain token address on `chainId`. */
2827
+ tokenAddress: string;
2828
+ /**
2829
+ * On-chain decimals for `(chainId, tokenAddress)`. Required to interpret
2830
+ * `amountRaw`: BNB USDC is 18-dec, EVM USDC is 6-dec.
2831
+ */
2832
+ decimals: number;
2833
+ amountRaw: string;
2834
+ /** Smart-wallet or native-account custody; absent for ordinary EOA sources. */
2835
+ custodyKind?: "DEPOSIT_WALLET" | "VENUE_ACCOUNT";
2836
+ /** Venue that owns the source (for example, `pred` or `tiprun`). */
2837
+ venue?: string;
2838
+ sourceVenueAccountId?: string;
2839
+ /** Lossless native account ID, not an EVM address. */
2840
+ sourceExternalAccountId?: string;
2841
+ status: WithdrawalSourceStatus;
2842
+ txHash: string | null;
2843
+ bridgeOperationId: string | null;
2844
+ }
2845
+ /**
2846
+ * `pricingStatus === "quoted"` means the response includes a fresh preflight
2847
+ * quote; other states may carry null `expected.*` fields. Do NOT treat null
2848
+ * fields as missing.
2849
+ */
2850
+ interface WithdrawalExpected {
2851
+ outputRaw: string | null;
2852
+ feeRaw: string | null;
2853
+ etaSeconds: number | null;
2854
+ }
2855
+ /** Body for POST /execution/withdraw/preview — identical to a withdraw request. */
2856
+ type WithdrawPreviewParams = WithdrawManagedParams;
2857
+ interface WithdrawalQuoteParams {
2858
+ tokenSymbol: WithdrawTokenSymbol;
2859
+ destinationChainId: number;
2860
+ }
2861
+ interface WithdrawalQuoteResponse {
2862
+ tokenSymbol: WithdrawTokenSymbol;
2863
+ destinationChainId: number;
2864
+ maxDeliverableRaw: string;
2865
+ rawBalanceRaw: string;
2866
+ decimals: number;
2867
+ }
2868
+ /** Response from POST /execution/withdraw/preview. All amounts are raw strings in destination-token native decimals. */
2869
+ interface WithdrawPreviewResponse {
2870
+ receiveAmountRaw: string | null;
2871
+ feeRaw: string | null;
2872
+ relayFeeRaw: string | null;
2873
+ networkFeeRaw: string | null;
2874
+ pricingStatus: "quoted" | "unviable";
2875
+ quoteExpiresAt: string | null;
2876
+ unviableReason: string | null;
2877
+ maxDeliverableRaw: string | null;
2878
+ }
2879
+ interface WithdrawManagedResponse {
2880
+ withdrawalId: string;
2881
+ status: WithdrawalLifecycleStatus;
2882
+ requested: {
2883
+ tokenSymbol: WithdrawTokenSymbol;
2884
+ amountRaw: string;
2885
+ };
2886
+ /**
2887
+ * Terminal settled amount in destination-token native decimals.
2888
+ * Null until at least one source confirms.
2889
+ */
2890
+ completedAmountRaw: string | null;
2891
+ destination: {
2892
+ chainId: number;
2893
+ address: string;
2894
+ tokenSymbol: WithdrawTokenSymbol;
2895
+ };
2896
+ legs: WithdrawalLeg[];
2897
+ expected: WithdrawalExpected;
2898
+ pricingStatus: "unquoted" | "quoting" | "quoted" | "unviable";
2899
+ /**
2900
+ * Persisted terminal-state error reason. Always `null` until the
2901
+ * withdrawal reaches `failed` / `partial`. The submit response always
2902
+ * returns `null`; populated values arrive via the GET status endpoint or
2903
+ * via a terminal `withdrawal_lifecycle` WS event.
2904
+ */
2905
+ errorMessage: string | null;
2906
+ sources: WithdrawManagedSourceItem[];
2907
+ }
2908
+ interface DepositAddressesToken {
2909
+ symbol: string;
2910
+ address: string;
2911
+ decimals: number;
2912
+ }
2913
+ interface DepositAddressesSupportedChain {
2914
+ chainId: number;
2915
+ name: string;
2916
+ tokens: DepositAddressesToken[];
2917
+ }
2918
+ interface DepositAddressesReadyResponse {
2919
+ ready: true;
2920
+ evmAddress: string;
2921
+ svmAddress: string;
2922
+ supportedChains: DepositAddressesSupportedChain[];
2923
+ }
2924
+ interface DepositAddressesPendingResponse {
2925
+ ready: false;
2926
+ }
2927
+ type DepositAddressesResponse = DepositAddressesReadyResponse | DepositAddressesPendingResponse;
2928
+ interface GetPositionsParams {
2929
+ cursor?: string;
2930
+ limit?: number;
2931
+ status?: "active" | "closed";
2932
+ mode?: ExecutionMode;
2933
+ }
2934
+ interface GetOrdersParams {
2935
+ status?: string;
2936
+ cursor?: string;
2937
+ limit?: number;
2938
+ }
2939
+ interface OrderbookQuoteParams {
2940
+ marketId: string;
2941
+ side: "buy" | "sell";
2942
+ size: number;
2943
+ }
2944
+ interface OrderbookQuoteFill {
2945
+ venue: string;
2946
+ size: number;
2947
+ avgPrice: number;
2948
+ cost: number;
2949
+ }
2950
+ interface OrderbookQuoteResponse {
2951
+ marketId: string;
2952
+ side: "buy" | "sell";
2953
+ requestedSize: number;
2954
+ filledSize: number;
2955
+ avgPrice: number | null;
2956
+ totalCost: number;
2957
+ slippage: number | null;
2958
+ fills: OrderbookQuoteFill[];
2959
+ }
2960
+ type ExecutionOrdersQuery = GetOrdersQuery & {
2961
+ mode?: ExecutionMode;
2962
+ };
2963
+ type ExecutionOrderItem = OrderListItem;
2964
+ type ExecutionStatusQuery = {
2965
+ quoteId: string;
2966
+ mode?: ExecutionMode;
2967
+ };
2968
+ type ExecutionOverallState = "created" | "routing" | "quoting" | "placing" | "confirming" | "filled" | "partially_filled" | "failed" | "cancelled" | "expired";
2969
+ interface ExecutionDagProgress {
2970
+ dagRunId: string;
2971
+ totalSteps: number;
2972
+ currentSequence: number;
2973
+ currentStepType: string | null;
2974
+ completedSequences: number[];
2975
+ stepTypes: Record<number, string>;
2976
+ status: "running" | "completed" | "failed";
2977
+ errorReason: string | null;
2978
+ }
2979
+ type ExecutionDisplayStepKind = "submit" | "setup" | "bridge" | "fill" | "internal";
2980
+ type ExecutionDisplayGroupStatus = "pending" | "in_progress" | "completed" | "failed" | "skipped";
2981
+ interface ExecutionStatusStep {
2982
+ sequence: number;
2983
+ stepType: string;
2984
+ status: "pending" | "in_progress" | "completed" | "failed" | "skipped";
2985
+ attempt: number;
2986
+ startedAt: string | null;
2987
+ completedAt: string | null;
2988
+ errorReason: string | null;
2989
+ /** Venue legs this step funds or executes; join to `orders[].orderId`. */
2990
+ orderIds: string[];
2991
+ /** Display class. `internal` steps are not meant to be rendered. */
2992
+ kind: ExecutionDisplayStepKind;
2993
+ /** Steps sharing a groupId render as ONE row. */
2994
+ groupId: string;
2995
+ /** Rolled-up status for the group; identical on every member. */
2996
+ groupStatus: ExecutionDisplayGroupStatus;
2997
+ /** Row copy, phrased for the current `groupStatus`. */
2998
+ label: string;
2999
+ /** Set on `kind: "bridge"` only. */
3000
+ bridge?: {
3001
+ amount: string;
3002
+ tokenSymbol: string;
3003
+ fromChain: string;
3004
+ toChain: string;
3005
+ };
3006
+ }
3007
+ interface ExecutionStatusOrder {
3008
+ orderId: string;
3009
+ venue: string;
3010
+ status: string;
3011
+ event: "filled" | "partial_fill" | "failed" | null;
3012
+ filledAmountRaw?: string;
3013
+ remainingAmountRaw?: string;
3014
+ quotedSharesRaw?: string;
3015
+ actualSharesRaw?: string;
3016
+ quotedToWinRaw?: string;
3017
+ actualToWinRaw?: string;
3018
+ quotedPriceRaw?: string;
3019
+ executionPriceRaw?: string;
3020
+ partialFillReason?: string;
3021
+ errorReason?: string;
3022
+ venueOrderId?: string;
3023
+ txHash?: string;
3024
+ updatedAt: string;
3025
+ }
3026
+ interface ExecutionStatusResponse {
3027
+ executionId: string | null;
3028
+ quoteId: string;
3029
+ orderIds: string[];
3030
+ overallState: ExecutionOverallState;
3031
+ terminal: boolean;
3032
+ errorReason: string | null;
3033
+ pollAfterMs: number | null;
3034
+ dagProgress: ExecutionDagProgress | null;
3035
+ steps: ExecutionStatusStep[];
3036
+ orders: ExecutionStatusOrder[];
3037
+ /**
3038
+ * What this run is waiting to be signed, mirroring the fill response's
3039
+ * field of the same name. This is the polling route `fillSelfCustody` reads
3040
+ * while an on-chain step is in flight — a caller polling this route for
3041
+ * progress learns about newly-parked steps here too, not just from the
3042
+ * signatures endpoint.
3043
+ */
3044
+ pendingSignatures?: SignatureRequest[];
3045
+ }
3046
+ type ExecutionPositionsQuery = GetPositionsQuery & {
3047
+ mode?: ExecutionMode;
3048
+ };
3049
+ type ExecutionPositionGroup = PositionGroup;
3050
+ /** Whose cash to return: the managed server wallet (default) or the account's linked wallets. */
3051
+ type BalanceCustody = "managed" | "self";
3052
+ type ManagedBalancesParams = {
3053
+ mode?: ExecutionMode;
3054
+ custody?: BalanceCustody;
3055
+ };
3056
+ interface PaperTradingAppOptions {
3057
+ /** App ID for the paper account namespace. Defaults to AggClient appId. */
3058
+ appId?: string;
3059
+ }
3060
+ interface PaperTradingListParams {
3061
+ limit?: number;
3062
+ cursor?: string;
3063
+ }
3064
+ interface PaperTradingAccountListParams extends PaperTradingListParams {
3065
+ externalId?: string;
3066
+ }
3067
+ interface CreatePaperTradingAccountParams {
3068
+ name?: string;
3069
+ externalId?: string;
3070
+ initialBalanceRaw?: string;
3071
+ initialBalance?: number;
3072
+ }
3073
+ interface SetPaperTradingBalanceParams {
3074
+ balanceRaw?: string;
3075
+ balance?: number;
3076
+ reason?: string;
3077
+ }
3078
+ interface ResetPaperTradingAccountParams {
3079
+ balanceRaw?: string;
3080
+ balance?: number;
3081
+ reason?: string;
3082
+ }
3083
+ interface PlacePaperTradingOrderParams {
3084
+ venueMarketOutcomeId: string;
3085
+ side: "buy" | "sell";
3086
+ spendRaw?: string;
3087
+ spend?: number;
3088
+ shares?: number;
3089
+ slippageBps?: number;
3090
+ clientOrderId?: string;
3091
+ }
3092
+ type PaperTradingMarkSource = "orderbook_midpoint" | "orderbook_best_bid" | "catalog_price";
3093
+ type PaperTradingLiquidityStatus = "full" | "partial" | "none";
3094
+ interface PaperTradingAccount {
3095
+ id: string;
3096
+ appId: string;
3097
+ name: string | null;
3098
+ externalId: string | null;
3099
+ currency: string;
3100
+ startingBalanceRaw: string;
3101
+ startingBalance: number;
3102
+ cashBalanceRaw: string;
3103
+ cashBalance: number;
3104
+ realizedPnlRaw: string;
3105
+ realizedPnl: number;
3106
+ kycStatus: "verified";
3107
+ kycVerified: true;
3108
+ status: "active" | "archived";
3109
+ createdAt: string;
3110
+ updatedAt: string;
3111
+ }
3112
+ interface PaperTradingPosition {
3113
+ id: string;
3114
+ accountId: string;
3115
+ venue: string;
3116
+ venueMarketId: string;
3117
+ venueMarketOutcomeId: string;
3118
+ marketQuestion: string;
3119
+ outcomeLabel: string;
3120
+ size: number;
3121
+ avgEntryPrice: number;
3122
+ markPrice: number;
3123
+ markSource: PaperTradingMarkSource;
3124
+ markTimestamp: number | null;
3125
+ bestBidPrice: number | null;
3126
+ bestAskPrice: number | null;
3127
+ midpoint: number | null;
3128
+ spread: number | null;
3129
+ marketValueRaw: string;
3130
+ marketValue: number;
3131
+ unrealizedPnlRaw: string;
3132
+ unrealizedPnl: number;
3133
+ liquidationPrice: number | null;
3134
+ liquidationValueRaw: string;
3135
+ liquidationValue: number;
3136
+ liquidationPnlRaw: string;
3137
+ liquidationPnl: number;
3138
+ liquidityShares: number;
3139
+ liquidityStatus: PaperTradingLiquidityStatus;
3140
+ realizedPnlRaw: string;
3141
+ realizedPnl: number;
3142
+ createdAt: string;
3143
+ updatedAt: string;
3144
+ }
3145
+ interface PaperTradingOrder {
3146
+ id: string;
3147
+ accountId: string;
3148
+ venue: string;
3149
+ venueMarketId: string;
3150
+ venueMarketOutcomeId: string;
3151
+ marketQuestion: string;
3152
+ outcomeLabel: string;
3153
+ side: "buy" | "sell";
3154
+ status: "filled" | "rejected";
3155
+ clientOrderId: string | null;
3156
+ requestedSpendRaw: string | null;
3157
+ requestedSpend: number | null;
3158
+ requestedShares: number | null;
3159
+ filledShares: number;
3160
+ avgPrice: number | null;
3161
+ slippageBps: number | null;
3162
+ notionalRaw: string;
3163
+ notional: number;
3164
+ cashDeltaRaw: string;
3165
+ cashDelta: number;
3166
+ realizedPnlRaw: string;
3167
+ realizedPnl: number;
3168
+ rejectionReason: string | null;
3169
+ createdAt: string;
3170
+ }
3171
+ interface PaperTradingBalanceAdjustment {
3172
+ id: string;
3173
+ accountId: string;
3174
+ type: "set_balance" | "reset";
3175
+ amountRaw: string;
3176
+ amount: number;
3177
+ previousCashBalanceRaw: string;
3178
+ previousCashBalance: number;
3179
+ newCashBalanceRaw: string;
3180
+ newCashBalance: number;
3181
+ reason: string | null;
3182
+ createdAt: string;
3183
+ }
3184
+ interface PaperTradingPortfolio {
3185
+ account: PaperTradingAccount;
3186
+ cashBalanceRaw: string;
3187
+ cashBalance: number;
3188
+ marketValueRaw: string;
3189
+ marketValue: number;
3190
+ equityRaw: string;
3191
+ equity: number;
3192
+ realizedPnlRaw: string;
3193
+ realizedPnl: number;
3194
+ unrealizedPnlRaw: string;
3195
+ unrealizedPnl: number;
3196
+ liquidationValueRaw: string;
3197
+ liquidationValue: number;
3198
+ liquidationEquityRaw: string;
3199
+ liquidationEquity: number;
3200
+ liquidationPnlRaw: string;
3201
+ liquidationPnl: number;
3202
+ positions: PaperTradingPosition[];
3203
+ }
3204
+ interface PaperTradingAccountsPage {
3205
+ data: PaperTradingAccount[];
3206
+ nextCursor: string | null;
3207
+ hasMore: boolean;
3208
+ }
3209
+ interface PaperTradingPositionsPage {
3210
+ data: PaperTradingPosition[];
3211
+ nextCursor: string | null;
3212
+ hasMore: boolean;
3213
+ }
3214
+ interface PaperTradingOrdersPage {
3215
+ data: PaperTradingOrder[];
3216
+ nextCursor: string | null;
3217
+ hasMore: boolean;
3218
+ }
3219
+ interface PaperTradingBalanceResponse {
3220
+ account: PaperTradingAccount;
3221
+ adjustment: PaperTradingBalanceAdjustment;
3222
+ }
3223
+ type UserActivityType = "trade" | "withdrawal" | "bridge" | "deposit" | "user_op" | "redeem";
3224
+ interface UserActivityBase {
3225
+ id: string;
3226
+ createdAt: string;
3227
+ updatedAt: string;
3228
+ status: string;
3229
+ }
3230
+ interface UserActivityVenueMarket {
3231
+ id: string;
3232
+ venueEventId: string;
3233
+ question: string | null;
3234
+ image: string | null;
3235
+ }
3236
+ interface UserActivityVenueMarketOutcome {
3237
+ id: string;
3238
+ label: string;
3239
+ title: string | null;
3240
+ price: number;
3241
+ }
3242
+ interface UserActivityTrade extends UserActivityBase {
3243
+ type: "trade";
3244
+ venue: string;
3245
+ side: string;
3246
+ amountRaw: string;
3247
+ filledAmountRaw: string | null;
3248
+ executionPrice: string | null;
3249
+ venueMarket: UserActivityVenueMarket | null;
3250
+ venueMarketOutcome: UserActivityVenueMarketOutcome | null;
3251
+ txHash: string | null;
3252
+ errorMessage: string | null;
3253
+ /** @deprecated Use venueMarket.question. */
3254
+ marketQuestion?: string | null;
3255
+ /** @deprecated Use venueMarketOutcome.label/title. */
3256
+ outcomeLabel?: string | null;
3257
+ }
3258
+ interface UserActivityWithdrawal extends UserActivityBase {
3259
+ type: "withdrawal";
3260
+ tokenSymbol: string;
3261
+ amountRaw: string;
3262
+ destinationAddress: string;
3263
+ destinationChainId: string;
3264
+ completedAmountRaw: string | null;
3265
+ chainId?: string | null;
3266
+ txHash?: string | null;
3267
+ errorMessage: string | null;
3268
+ }
3269
+ interface UserActivityBridge extends UserActivityBase {
3270
+ type: "bridge";
3271
+ tokenSymbol: string;
3272
+ amountRaw: string;
3273
+ sourceChainId: string;
3274
+ destChainId: string;
3275
+ sourceTxHash: string | null;
3276
+ destTxHash: string | null;
3277
+ }
3278
+ interface UserActivityDeposit extends UserActivityBase {
3279
+ type: "deposit";
3280
+ tokenSymbol: string;
3281
+ amountRaw: string;
3282
+ chainId: string;
3283
+ fromAddress: string;
3284
+ txHash: string;
3285
+ source: "connected_wallet" | "external_wallet";
3286
+ }
3287
+ interface UserActivityUserOp extends UserActivityBase {
3288
+ type: "user_op";
3289
+ callsId: string;
3290
+ chainId: string;
3291
+ walletAddress: string;
3292
+ txHash: string | null;
3293
+ confirmedAt: string | null;
3294
+ }
3295
+ interface UserActivityRedeemLeg {
3296
+ id: string;
3297
+ venueMarketOutcomeId: string;
3298
+ venue: string;
3299
+ status: string;
3300
+ chainId: string;
3301
+ payoutTokenSymbol: string;
3302
+ payoutAmountRaw: string | null;
3303
+ txHash: string | null;
3304
+ errorMessage: string | null;
3305
+ venueMarket: UserActivityVenueMarket | null;
3306
+ venueMarketOutcome: Omit<UserActivityVenueMarketOutcome, "price"> | null;
3307
+ }
3308
+ interface UserActivityRedeem extends UserActivityBase {
3309
+ type: "redeem";
3310
+ totalPayoutRaw: string | null;
3311
+ legs: UserActivityRedeemLeg[];
3312
+ }
3313
+ type UserActivityItem = UserActivityTrade | UserActivityWithdrawal | UserActivityBridge | UserActivityDeposit | UserActivityUserOp | UserActivityRedeem;
3314
+ interface UserActivityQuery {
3315
+ type?: UserActivityType;
3316
+ cursor?: string;
3317
+ limit?: number;
3318
+ }
3319
+ interface RampQuoteRequest {
3320
+ sourceAmount: string;
3321
+ sourceCurrencyCode: string;
3322
+ destinationCurrencyCode: string;
3323
+ paymentMethodType?: string;
3324
+ }
3325
+ interface RampQuote {
3326
+ serviceProvider: string;
3327
+ transactionType: string;
3328
+ sourceAmount: number;
3329
+ sourceCurrencyCode: string;
3330
+ destinationAmount: number;
3331
+ destinationCurrencyCode: string;
3332
+ exchangeRate: number;
3333
+ totalFee: number;
3334
+ networkFee: number;
3335
+ transactionFee: number;
3336
+ partnerFee: number;
3337
+ fiatAmountWithoutFees: number;
3338
+ paymentMethodType: string;
3339
+ countryCode: string;
3340
+ rampScore: number;
3341
+ lowKyc: boolean;
3342
+ }
3343
+ interface RampSessionRequest {
3344
+ sourceAmount: string;
3345
+ sourceCurrencyCode: string;
3346
+ destinationCurrencyCode: string;
3347
+ serviceProvider: string;
3348
+ walletAddress: string;
3349
+ redirectUrl?: string;
3350
+ }
3351
+ interface RampWidgetSession {
3352
+ id: string;
3353
+ token: string;
3354
+ widgetUrl: string;
3355
+ serviceProviderWidgetUrl: string;
3356
+ }
3357
+ type SmartRouteStatus = "ok" | "infeasible" | "checker_rejected" | "solver_error" | "invalid_input" | "no_orderbooks" | "min_order_size_violated" | "insufficient_input_amount" | "engine_unavailable" | "insufficient_position" | "insufficient_depth" | "no_bids_above_min_price" | "insufficient_balance";
3358
+ /** A single fill at a price level within a venue. */
3359
+ interface SmartRouteFill {
3360
+ price: number;
3361
+ size: number;
3362
+ fill: number;
3363
+ }
3364
+ /** Per-venue routing result with fills and chain info. */
3365
+ interface SmartRouteVenueFill {
3366
+ /** CH executable price and normalized input, in micro-USDC. */
3367
+ limitPriceMicroUsdc?: string;
3368
+ inAmount?: string;
3369
+ outAmount?: string;
3370
+ venue: string;
3371
+ venueMarketId: string;
3372
+ venueMarketOutcomeId: string;
3373
+ chain: string;
3374
+ avgPrice: number;
3375
+ yesPrice: number;
3376
+ noPrice: number;
3377
+ fills: SmartRouteFill[];
3378
+ executionBackend?: "clearinghouse" | "direct";
3379
+ venueAccountId?: string;
3380
+ venueQty: number;
3381
+ /**
3382
+ * Builder fee for this fill in USD — the slice paid to a builder code
3383
+ * rather than to the venue. Excluded from `venueFee`. Optional so an
3384
+ * older engine build that does not emit it still validates.
3385
+ */
3386
+ builderFee?: number;
3387
+ /**
3388
+ * What the venue takes from this leg's payout if the outcome wins (USD):
3389
+ * Hyperliquid HIP-4's close fee on the $1 settlement, 0 elsewhere. Not a
3390
+ * cost at fill; already netted out of `estimatedPayout`.
3391
+ */
3392
+ settlementFee?: number;
3393
+ /** Inclusive fee/reserve funding budget. For fee display, use the route's
3394
+ * feeBreakdown.venueFees and executionReserve instead. */
3395
+ venueFee?: number;
3396
+ }
3397
+ interface SmartRouteAllocation {
3398
+ sourceChainId: string;
3399
+ venue: string;
3400
+ amount: number;
3401
+ sourceTokenAddress?: string;
3402
+ custodyKind?: "EOA" | "DEPOSIT_WALLET" | "POLYMARKET_LEGACY" | "VENUE_ACCOUNT";
3403
+ custodyAddress?: string;
3404
+ /** Native venue cash identifies an account, not an EVM custody address. */
3405
+ sourceVenueAccountId?: string;
3406
+ /** Lossless decimal native account ID; never convert this to a JS number. */
3407
+ sourceExternalAccountId?: string;
3408
+ /** On-chain funding wallet, when present; absent for native venue cash. */
3409
+ sourceAddress?: string;
3410
+ exactToken?: boolean;
3411
+ }
3412
+ interface SmartRouteBridgeStep {
3413
+ sourceChainId: string;
3414
+ destChainId: string;
3415
+ /** Source-side amount sent into the bridge, in USD: the allocations this lane funds plus `cost`. */
3416
+ amount: number;
3417
+ /**
3418
+ * Delivery margin, in USD, sent on top of the allocations so the destination
3419
+ * still receives them in full after the bridge takes its fee. A planning
3420
+ * reserve, not the expected fee: excluded from `feeBreakdown.bridgeFees` and
3421
+ * `totalCost`, and whatever the bridge does not charge arrives at the
3422
+ * destination as the user's balance. Read `feeBreakdown.bridgeFees` for the
3423
+ * expected bridge fee.
3424
+ */
3425
+ cost: number;
3426
+ sourceTokenAddress?: string;
3427
+ destTokenAddress?: string;
3428
+ }
3429
+ interface VenueSoloQuote {
3430
+ quoteFailure?: {
3431
+ venue: string;
3432
+ code: string;
3433
+ retryAt?: string;
3434
+ };
3435
+ /**
3436
+ * Minted by the API per successful + executable solo; send this to
3437
+ * /execution/fill to execute single-venue. `null` when the solo is not
3438
+ * executable (status !== "ok", filledQty === 0, or venue not in
3439
+ * SUPPORTED_FILL_VENUES). FE filters on truthiness.
3440
+ */
3441
+ quoteId: string | null;
3442
+ /** Why this venue cannot execute when quoteId is null (or execution is geo-gated). */
3443
+ unavailableReason?: string;
3444
+ venue: string;
3445
+ /**
3446
+ * The outcome this solo is bound to. `venue` alone is NOT unique — one venue
3447
+ * can list the same matched outcome more than once (e.g. two Hyperliquid
3448
+ * deployers listing the same game), producing two solo cards with the same
3449
+ * `venue`. Key on this alongside `venue` when identifying a card.
3450
+ */
3451
+ venueMarketOutcomeId?: string;
3452
+ avgPrice: number | null;
3453
+ filledQty: number;
3454
+ rawExecCost: number;
3455
+ estimatedPayout: number;
3456
+ estimatedProfit: number;
3457
+ returnPct: number;
3458
+ /**
3459
+ * `feeBreakdown.totalCost` plus this solo's own user-paid app fee and
3460
+ * referral — same composition as the primary route's `totalCostIncFees`.
3461
+ * `estimatedProfit`/`returnPct` stay router values, unaffected. Absent
3462
+ * when the router sent no `feeBreakdown` for this solo.
3463
+ */
3464
+ totalCostIncFees?: number;
3465
+ status: string;
3466
+ /** Per-price-level fills, identical shape to primary fills. Empty for non-ok statuses. */
3467
+ fills: SmartRouteVenueFill[];
3468
+ allocations?: SmartRouteAllocation[];
3469
+ bridgeSteps?: SmartRouteBridgeStep[];
3470
+ /**
3471
+ * One-time setup costs for this solo's chosen venue + market. Populated
3472
+ * only when the originating quote opted in via `deepEstimate=true`; absent
3473
+ * on cheap quotes and on non-executable / failed solos. Same shape as the
3474
+ * multi-route `feeBreakdown.setupCosts`. The solo's `estimatedProfit` and
3475
+ * `returnPct` are recomputed against `cost basis + setupCostsTotal` so
3476
+ * per-venue comparisons are setup-inclusive.
3477
+ */
3478
+ setupCosts?: SmartRouteSetupCostLine[];
3479
+ /** Sum of this solo's `setupCosts` entries where `alreadyPaid=false`. */
3480
+ setupCostsTotal?: number;
3481
+ /**
3482
+ * Cost breakdown for executing THIS venue alone. Present when
3483
+ * `status === "ok"`; absent otherwise.
3484
+ *
3485
+ * Read this — not the top-level `feeBreakdown` — when rendering fees for a
3486
+ * single venue. A solo's bridge lanes and venue fee are its own, so a venue
3487
+ * needing no bridge reports `bridgeFees: 0` here even when the multi-route
3488
+ * plan bridged.
3489
+ */
3490
+ feeBreakdown?: SmartRouteFeeBreakdown;
3491
+ }
3492
+ /** @deprecated Smart-route side overrides are kept only for source compatibility. */
3493
+ type SmartRouteSide = "yes" | "no";
3494
+ /** Trade direction for order routing. "buy" (default) reads asks, "sell" reads bids. */
3495
+ type TradeSide = "buy" | "sell";
3496
+ /** Trading mode for normal execution endpoints. Defaults to live. */
3497
+ type ExecutionMode = "live" | "paper";
3498
+ /** Request params for GET /orderbook/:venueMarketOutcomeId/route. */
3499
+ interface SmartRouteParams {
3500
+ venueMarketOutcomeId?: string;
3501
+ /** @deprecated Use venueMarketOutcomeId. */
3502
+ venueMarketId?: string;
3503
+ /** @deprecated Use venueMarketOutcomeId. */
3504
+ outcomeId?: string;
3505
+ /** @deprecated Side is ignored for routing and echoed back only for legacy consumers. */
3506
+ side?: SmartRouteSide;
3507
+ /** Trade direction: "buy" (default) or "sell". */
3508
+ tradeSide?: TradeSide;
3509
+ /** Trading mode. Defaults to live. */
3510
+ mode?: ExecutionMode;
3511
+ maxSpend?: number;
3512
+ /** Sell only: target number of contracts to sell. Required for sell unless maxSpend is given. */
3513
+ sellShares?: number;
3514
+ chainBalances?: Record<string, number>;
3515
+ slipCapBps?: number;
3516
+ compareVenues?: boolean;
3517
+ /** Restrict this quote to one or more executable venues. */
3518
+ allowedVenues?: Venue[];
3519
+ /**
3520
+ * Opt in to the deep cost-estimate surface. When `true`, the response
3521
+ * `feeBreakdown` includes `setupCosts` (one-time chain approvals + Kalshi
3522
+ * SPL token-account rents) with per-item `alreadyPaid` flags from the
3523
+ * user's prior trade history. Buy-only; ignored for sells.
3524
+ *
3525
+ * Deep quotes also pre-deduct the unpaid setup total from `maxSpend`
3526
+ * before routing, so `totalCostIncFees` (and the recomputed
3527
+ * `estimatedProfit` / `returnPct`) stay within the partner's stated
3528
+ * budget.
3529
+ */
3530
+ deepEstimate?: boolean;
3531
+ /** Referral: EVM address that receives the referral fee. Needs an app API key. */
3532
+ referrer?: string;
3533
+ /** Referral fee in bips of routed notional (1..10000). Snag-free. */
3534
+ referrerFeeBips?: number;
3535
+ /** Who funds the referral: "user" (default) reserves it from maxSpend; "app" pays from `referralPayerAddress` after the fill. */
3536
+ referralPayer?: "user" | "app";
3537
+ /** Required with `referralPayer: "app"`: the wallet that signs the parked payout transaction. */
3538
+ referralPayerAddress?: string;
3539
+ }
3540
+ /** One-time setup line item — populated only on deep-estimate quotes. */
3541
+ interface SmartRouteSetupCostLine {
3542
+ /** "chainApproval" = ERC-20 + venue-contract approvals on the venue's
3543
+ * chain (Polymarket / Polygon, Limitless / Base, predict.fun / BNB).
3544
+ * "venueMarketAta" = Kalshi-on-Solana per-market token-account rent.
3545
+ * "hyperliquidActivation" = Hyperliquid's one-time 1 USDC fee to activate
3546
+ * the user's address on its first deposit; `alreadyPaid` once the address
3547
+ * exists on Hyperliquid. Deducted from the bridged amount, not a step. */
3548
+ kind: "chainApproval" | "venueMarketAta" | "hyperliquidActivation";
3549
+ venue: string;
3550
+ /** Set when `kind === "chainApproval"`. */
3551
+ chainId?: number;
3552
+ /** Set when `kind === "venueMarketAta"`. */
3553
+ venueMarketId?: string;
3554
+ /** Per-item cost in USD. Sourced from documented chain-paymaster floors
3555
+ * (Polygon/Base/Arbitrum ≈ $0.05, BNB $0.20, Solana ATA ≈ $0.30). */
3556
+ costUsd: number;
3557
+ /** True if the user has already paid this on a prior fill — render as a
3558
+ * strike-through "first-time fee" chip rather than charging again. */
3559
+ alreadyPaid: boolean;
3560
+ }
3561
+ /** Cost breakdown for a route quote. */
3562
+ interface SmartRouteFeeBreakdown {
3563
+ rawExecCost: number;
3564
+ venueFees: number;
3565
+ /**
3566
+ * Builder fee in USD — the slice paid to a builder code rather than to the
3567
+ * venue. Partners with their own builder code see their own rate here;
3568
+ * everyone else sees the platform default. Excluded from `venueFees`,
3569
+ * included in `totalCost`.
3570
+ */
3571
+ builderFee?: number;
3572
+ /** Additional CH funding reserve for slippage or possible venue charges.
3573
+ * Excluded from venueFees and totalCost; included in funding allocations.
3574
+ * Only the unused portion is released after execution. */
3575
+ executionReserve?: number;
3576
+ bridgeFees: number;
3577
+ executionGas: number;
3578
+ totalCost: number;
3579
+ /** Populated only when the request specified `deepEstimate=true`. */
3580
+ setupCosts?: SmartRouteSetupCostLine[];
3581
+ /** Sum of `setupCosts` entries where `alreadyPaid === false`. */
3582
+ setupCostsTotal?: number;
3583
+ /**
3584
+ * Partner-level execution fee in USD. The worst-case fee the user will
3585
+ * pay against the routed buy notional at quote time. Buy-side only —
3586
+ * sell quotes don't carry this field.
3587
+ *
3588
+ * Actual collection happens after the trade fills, against realized
3589
+ * notional (which may be less on partial fills). Partner UIs should
3590
+ * render this as "you'll pay up to $X in app fees".
3591
+ *
3592
+ * Both `appFee` and `appFeeBips` are present iff `appFee > 0`.
3593
+ */
3594
+ appFee?: number;
3595
+ /** Partner's configured bips for this market — the rate that produced `appFee`. */
3596
+ appFeeBips?: number;
3597
+ /** Category key the bips resolved against (e.g. "sports", or "all" for the fallback). */
3598
+ appFeeCategory?: string;
3599
+ /** The `executionGas` line when it is actually collected with the app fee. Present iff > 0; already inside `totalCost`. */
3600
+ gasReimbursement?: number;
3601
+ /** Referral fee the USER pays, in USD. Present iff > 0 and `referralPayer` is "user"; already inside `totalCostIncFees`. An app-paid referral never appears here. */
3602
+ referralFee?: number;
3603
+ }
3604
+ /** Response from GET /orderbook/:venueMarketOutcomeId/route. */
3605
+ interface SmartRouteSettlementLeg {
3606
+ action: "redeem";
3607
+ venue: string;
3608
+ venueMarketId: string;
3609
+ venueMarketOutcomeId: string;
3610
+ positionId: string;
3611
+ size: string;
3612
+ redeemPath: "evm" | "svm";
3613
+ }
3614
+ interface SmartRouteSettlementPlan {
3615
+ redeemId: string;
3616
+ status: "redeem_only" | "partial_redeem";
3617
+ message: string;
3618
+ totalRedeemableShares: number;
3619
+ totalRedeemShares: number;
3620
+ totalSellShares: number;
3621
+ redeemLegs: SmartRouteSettlementLeg[];
3622
+ }
3623
+ /** Slippage metrics for the route. Mirrors `SmartRouteResponseTB.slippage`. */
3624
+ interface SmartRouteSlippage {
3625
+ /** Volume-weighted average price. */
3626
+ vwap: number;
3627
+ /** Reference midpoint used by the optimizer. */
3628
+ refMidpoint: number;
3629
+ /** Route slippage = max(0, VWAP - refMidpoint). */
3630
+ slippage: number;
3631
+ /** Slippage in basis points relative to ref midpoint. */
3632
+ slippageBps: number;
3633
+ }
3634
+ interface SmartRouteResponse {
3635
+ quoteRefreshNotBefore?: string;
3636
+ quoteFailure?: {
3637
+ venue: string;
3638
+ code: string;
3639
+ retryAt?: string;
3640
+ };
3641
+ quoteId: string;
3642
+ venueMarketOutcomeId: string;
3643
+ venueMarketId: string;
3644
+ estimatedCostRaw: string;
3645
+ expiresAt: string;
3646
+ /**
3647
+ * Timestamp at which the quote begins to drift — frontends should refetch
3648
+ * a fresh `getSmartRoute` at this point even though the cached quoteId
3649
+ * remains executable until `expiresAt`. Always earlier than `expiresAt`.
3650
+ */
3651
+ refreshAt: string;
3652
+ status: SmartRouteStatus;
3653
+ fills: SmartRouteVenueFill[];
3654
+ totalFilled: number;
3655
+ rawExecCost: number;
3656
+ solveTimeMs: number;
3657
+ verifyTimeMs: number;
3658
+ matchedMarkets: Array<{
3659
+ venue: string;
3660
+ venueMarketId: string;
3661
+ }>;
3662
+ error?: string;
3663
+ message?: string;
3664
+ settlementPlan?: SmartRouteSettlementPlan;
3665
+ warnings?: Array<{
3666
+ venue: string;
3667
+ venueMarketOutcomeId: string;
3668
+ reason: string;
3669
+ }>;
3670
+ venueSoloQuotes?: VenueSoloQuote[];
3671
+ allocations?: SmartRouteAllocation[];
3672
+ bridgeSteps?: SmartRouteBridgeStep[];
3673
+ /**
3674
+ * Route slippage metrics. Present on the wire (`SmartRouteResponseTB`) but
3675
+ * missing from this mirror until now — `@agg-build/hooks` already reads
3676
+ * `slippage.slippageBps` to flag thin liquidity.
3677
+ */
3678
+ slippage?: SmartRouteSlippage;
3679
+ /** Estimated payout if the outcome wins (= totalFilled shares × $1, less
3680
+ * settlement fees — see `fills[].settlementFee`). */
3681
+ estimatedPayout?: number;
3682
+ /** Total cost including all fees (rawExecCost + venueFees + bridgeFees +
3683
+ * executionGas). For deep-estimate quotes, `setupCostsTotal` is folded
3684
+ * into this number and `estimatedProfit` / `returnPct` are recomputed
3685
+ * against it. */
3686
+ totalCostIncFees?: number;
3687
+ /** Estimated profit if the outcome wins (= estimatedPayout − totalCostIncFees). */
3688
+ estimatedProfit?: number;
3689
+ /** Return on investment percentage (= estimatedProfit / totalCostIncFees × 100). */
3690
+ returnPct?: number;
3691
+ /** Per-route fee breakdown. Always present when the engine produced a
3692
+ * feasible plan; omitted on solo / failed quotes. The `setupCosts` and
3693
+ * `setupCostsTotal` fields are populated only when the request set
3694
+ * `deepEstimate=true`. */
3695
+ feeBreakdown?: SmartRouteFeeBreakdown;
3696
+ /**
3697
+ * Quote-time snapshot of the partner fee configuration that produced
3698
+ * `feeBreakdown.appFee`, frozen so config drift between quote and execute
3699
+ * cannot change what the user is charged.
3700
+ *
3701
+ * This is NOT the display number — that is `feeBreakdown.appFee`, in USD.
3702
+ * This is the audit record: `quotedAppFeeRaw` is the worst-case charge in
3703
+ * 6-decimal USD atoms, and is what a partner reconciles against their
3704
+ * `AppFeeCharge` rows. `null` when the app has no fee configured.
3705
+ */
3706
+ appFee?: {
3707
+ bips: number;
3708
+ categoryKey: string;
3709
+ quotedAppFeeRaw: string;
3710
+ } | null;
3711
+ /** Referral snapshot; null/absent when no referrer was accepted. */
3712
+ referral?: {
3713
+ referrer: string;
3714
+ feeBips: number;
3715
+ payer: "user" | "app";
3716
+ payerAddress?: string;
3717
+ quotedFeeUsd: number;
3718
+ } | null;
3719
+ /** Populated only when status === "insufficient_position". */
3720
+ positionAvailability?: {
3721
+ totalSellableShares: number;
3722
+ venueMarketOutcomes: Array<{
3723
+ id: string;
3724
+ venue: string;
3725
+ venueMarketId: string;
3726
+ availableShares: number;
3727
+ }>;
3728
+ };
3729
+ /** @deprecated Echoed only when the deprecated request-side override is provided. */
3730
+ side?: SmartRouteSide;
3731
+ }
3732
+ interface CancelManagedExecutionResponse {
3733
+ quoteId: string | null;
3734
+ orderIds: string[];
3735
+ status: "cancelled" | "cancel_pending";
3736
+ }
3737
+ type PositionRedeemStatus = "eligible" | "pending" | "redeemed" | "ineligible";
3738
+ type RedeemLegStatus = "submitted" | "confirmed" | "ineligible" | "rejected";
3739
+ interface RedeemLegResult {
3740
+ venueMarketOutcomeId: string;
3741
+ status: RedeemLegStatus;
3742
+ callsId: string | null;
3743
+ pendingUserOpId: string | null;
3744
+ txHash: string | null;
3745
+ reason: string | null;
3746
+ }
3747
+ interface RedeemRequest {
3748
+ venueMarketOutcomeIds: string[];
3749
+ /**
3750
+ * Trading mode. Defaults to live, matching the other execution methods.
3751
+ * Honoured on a live app; ignored on a paper app, which has no real-money
3752
+ * path and always settles on paper.
3753
+ */
3754
+ mode?: ExecutionMode;
3755
+ }
3756
+ interface RedeemResponse {
3757
+ redeemId: string;
3758
+ results: RedeemLegResult[];
3759
+ }
3760
+ type SearchType = "events" | "markets";
3761
+ interface SearchParams {
3762
+ mode?: "instant" | "full";
3763
+ q: string;
3764
+ type: SearchType;
3765
+ categoryIds?: string[];
3766
+ /**
3767
+ * Filter results by status (e.g. `["open"]` for tradeable-only). Without
3768
+ * it the server returns all statuses; recurring series ("BTC Up or Down -
3769
+ * 5 Min") can then fill a page with resolved history, which a UI that
3770
+ * hides non-open rows renders as an empty result.
3771
+ */
3772
+ status?: MarketStatus[];
3773
+ limit?: number;
3774
+ cursor?: string;
3775
+ /**
3776
+ * Opt in to the server-side reranker for higher-quality top results.
3777
+ *
3778
+ * Send `deep: true` for the final search-results page (submit / Enter) and
3779
+ * leave it off for debounced typeahead. Adds ~100–150 ms on a cold rerank
3780
+ * cache and ~3 ms on a warm one — typeahead can't afford the cold cost,
3781
+ * and the result orderings differ enough that the server gives the two
3782
+ * modes separate cache slots.
3783
+ *
3784
+ * Defaults to `false`.
3785
+ */
3786
+ deep?: boolean;
3787
+ }
3788
+ type SearchResponse<T> = {
3789
+ meta?: {
3790
+ complete?: boolean;
3791
+ degradedSignals?: string[];
3792
+ };
3793
+ type: SearchType;
3794
+ data: T[];
3795
+ nextCursor: string | null;
3796
+ hasMore: boolean;
3797
+ };
3798
+ interface NewsFeedPageOptions {
3799
+ cursor?: string;
3800
+ since?: string;
3801
+ before?: string;
3802
+ limit?: number;
3803
+ }
3804
+ interface NewsFeedMarketNewsParams {
3805
+ venueMarketIds?: string[];
3806
+ venueEventIds?: string[];
3807
+ customQuery?: string;
3808
+ tbs?: string;
3809
+ limit?: number;
3810
+ }
3811
+ interface NewsFeedArticleWithSummary {
3812
+ title: string;
3813
+ url: string;
3814
+ snippet: string;
3815
+ source: string;
3816
+ imageUrl: string | null;
3817
+ publishedAt: string | null;
3818
+ summary: string;
3819
+ relevanceScore: number;
3820
+ }
3821
+ interface NewsFeedMarketNewsResult {
3822
+ venueMarketId: string;
3823
+ venueEventId: string;
3824
+ question: string;
3825
+ eventTitle: string;
3826
+ category: string;
3827
+ searchQuery: string;
3828
+ timeRange: string;
3829
+ timeRangeLabel: string;
3830
+ articles: NewsFeedArticleWithSummary[];
3831
+ }
3832
+ interface NewsFeedMarketNewsResponse {
3833
+ results: NewsFeedMarketNewsResult[];
3834
+ }
3835
+ interface NewsFeedLinkedMarket {
3836
+ venueMarketId: string;
3837
+ question: string;
3838
+ venue: string;
3839
+ yesPrice: number;
3840
+ eventTitle: string;
3841
+ eventId: string;
3842
+ summary: string;
3843
+ relevanceScore: number;
3844
+ }
3845
+ interface NewsFeedArticleFeedItem {
3846
+ article: {
3847
+ id: string;
3848
+ title: string;
3849
+ url: string;
3850
+ snippet: string;
3851
+ source: string;
3852
+ imageUrl: string | null;
3853
+ publishedAt: string | null;
3854
+ };
3855
+ markets: NewsFeedLinkedMarket[];
3856
+ category: string;
3857
+ id: string;
3858
+ seq: number;
3859
+ timestamp: string;
3860
+ }
3861
+ interface NewsFeedMarketFeedArticle {
3862
+ title: string;
3863
+ url: string;
3864
+ source: string;
3865
+ imageUrl: string | null;
3866
+ publishedAt: string | null;
3867
+ summary: string;
3868
+ relevanceScore: number;
3869
+ seq: number;
3870
+ addedAt: string;
3871
+ }
3872
+ interface NewsFeedMarketFeedItem {
3873
+ venueMarketId: string;
3874
+ question: string;
3875
+ venue: string;
3876
+ yesPrice: number;
3877
+ eventTitle: string;
3878
+ eventId: string;
3879
+ category: string;
3880
+ articleCount: number;
3881
+ articles: NewsFeedMarketFeedArticle[];
3882
+ }
3883
+ interface NewsFeedArticleFeedResponse {
3884
+ data: NewsFeedArticleFeedItem[];
3885
+ nextCursor: string | null;
3886
+ hasMore: boolean;
3887
+ }
3888
+ interface NewsFeedMarketFeedResponse {
3889
+ data: NewsFeedMarketFeedItem[];
3890
+ nextCursor: string | null;
3891
+ hasMore: boolean;
3892
+ }
3893
+ interface NewsFeedListResponse {
3894
+ feeds: Array<{
3895
+ id: string;
3896
+ name: string;
3897
+ itemCount: number;
3898
+ }>;
3899
+ }
3900
+ interface NewsFeedStatusResponse {
3901
+ articles: {
3902
+ total: number;
3903
+ today: number;
3904
+ };
3905
+ feedItems: {
3906
+ total: number;
3907
+ today: number;
3908
+ };
3909
+ perCategory: Array<{
3910
+ category: string;
3911
+ todayCount: number;
3912
+ dailyLimit: number;
3913
+ }>;
3914
+ config: {
3915
+ cronEnabled: boolean;
3916
+ itemsPerDay: number;
3917
+ batchSize: number;
3918
+ categories: string[];
3919
+ };
3920
+ }
3921
+ type CorrelatedMarketSide = "yes" | "no";
3922
+ type CorrelatedMarketSignalDirection = "more_likely" | "less_likely";
3923
+ interface CorrelatedMarketSignal {
3924
+ id: string;
3925
+ text: string;
3926
+ side: CorrelatedMarketSide;
3927
+ direction: CorrelatedMarketSignalDirection;
3928
+ domain: string;
3929
+ }
3930
+ interface CorrelatedMarketSignalBatch {
3931
+ id: string;
3932
+ venueMarketId: string;
3933
+ sourceModel: string;
3934
+ promptVersion: number;
3935
+ createdAt: string;
3936
+ signals: CorrelatedMarketSignal[];
3937
+ }
3938
+ interface CorrelatedMarketsStatus {
3939
+ markets: {
3940
+ total: number;
3941
+ processed: number;
3942
+ coverage: number;
3943
+ };
3944
+ signals: {
3945
+ total: number;
3946
+ withEmbeddings: number;
3947
+ missingEmbeddings: number;
3948
+ };
3949
+ eventTitleEmbeddings: {
3950
+ total: number;
3951
+ events: number;
3952
+ coverage: number;
3953
+ };
3954
+ config: {
3955
+ batchSize: number;
3956
+ jobsEnabled: boolean;
3957
+ backfillInterval: string;
3958
+ reembedInterval: string;
3959
+ eventEmbeddingInterval: string;
3960
+ };
3961
+ }
3962
+ interface CorrelatedMarketQueryResult {
3963
+ venueMarketId: string;
3964
+ marketQuestion: string;
3965
+ marketStatus: MarketStatus;
3966
+ marketStartDate: string;
3967
+ marketEndDate: string | null;
3968
+ eventTitle: string;
3969
+ eventStatus: MarketStatus;
3970
+ eventStartDate: string;
3971
+ eventEndDate: string | null;
3972
+ score: number;
3973
+ matchedSignal: CorrelatedMarketSignal;
3974
+ matchSource: "signal" | "title_fallback";
3975
+ venue: string;
3976
+ }
3977
+ interface CorrelatedMarketCascadeItem {
3978
+ venueEventId: string;
3979
+ eventTitle: string;
3980
+ eventStatus: MarketStatus;
3981
+ eventStartDate: string;
3982
+ eventEndDate: string | null;
3983
+ score: number;
3984
+ action: string;
3985
+ reason: string;
3986
+ reasonDomain: string;
3987
+ }
3988
+ interface CorrelatedMarketCascadeResponse {
3989
+ data: CorrelatedMarketCascadeItem[];
3990
+ nextCursor: string | null;
3991
+ hasMore: boolean;
3992
+ }
3993
+ interface ResolveCorrelatedMarketsParams {
3994
+ venue?: string;
3995
+ externalId?: string;
3996
+ slug?: string;
3997
+ conditionId?: string;
3998
+ q?: string;
3999
+ side?: CorrelatedMarketSide;
4000
+ mode?: "expand" | "hedge";
4001
+ limit?: number;
4002
+ cursor?: string;
4003
+ includeResolved?: boolean;
4004
+ }
4005
+ type ResolveCorrelatedMarketsResponse = ({
4006
+ market: {
4007
+ id: string;
4008
+ question: string;
4009
+ };
4010
+ } & CorrelatedMarketCascadeResponse) | {
4011
+ market: {
4012
+ id: string;
4013
+ question: string;
4014
+ };
4015
+ status: "processing";
4016
+ message: string;
4017
+ };
4018
+ interface ResolvedCorrelatedMarketsResponse extends CorrelatedMarketCascadeResponse {
4019
+ market: {
4020
+ id: string;
4021
+ question: string;
4022
+ };
4023
+ }
4024
+ /** Display-first event navigation payload; market pages remain cursor paginated. */
4025
+ interface EventBootstrapResponse {
4026
+ detailsDeferred: true;
4027
+ event: VenueEvent;
4028
+ markets: PaginatedResponse<VenueMarket>;
4029
+ selectedOutcomeIds: string[];
4030
+ references: {
4031
+ historyManifestPath: "/charts/history/manifest";
4032
+ liveChannel: "orderbook";
4033
+ };
4034
+ freshness: {
4035
+ assembledAt: number;
4036
+ marketStatus: "open" | null;
4037
+ };
4038
+ }
4039
+
4040
+ type MarketSubscription = {
4041
+ id: string;
4042
+ channel: "orderbook" | "trades" | "arb" | "arb-feed";
4043
+ };
4044
+ type CandleTail = Record<CandleInterval, {
4045
+ forming: Candle | null;
4046
+ closed: Candle[];
4047
+ }>;
4048
+ interface MarketView {
4049
+ revision: number;
4050
+ integrity: "ok" | "resyncing";
4051
+ outcomeId: string;
4052
+ book: OrderbookState | null;
4053
+ snapshot: boolean;
4054
+ candles: CandleTail;
4055
+ trades: WsTrade[];
4056
+ receivedAtMs: number;
4057
+ }
4058
+ interface MarketViewBatch {
4059
+ generation: number;
4060
+ views: MarketView[];
4061
+ publishedAtMs: number;
4062
+ }
4063
+ type EngineEvent = {
4064
+ name: keyof AggWebSocketCallbacks;
4065
+ args: unknown[];
4066
+ revision: number;
4067
+ };
4068
+ interface HistoryRangeRequest {
4069
+ key: string;
4070
+ generation: number;
4071
+ url: string;
4072
+ headers?: Record<string, string>;
4073
+ }
4074
+ /** Framework-independent processing. The native worker and replay tests run this exact engine. */
4075
+ declare class MarketDataEngine {
4076
+ private socket;
4077
+ private generation;
4078
+ private receivedAtMs;
4079
+ private revision;
4080
+ private deliveredClosed;
4081
+ private subscriptions;
4082
+ private builders;
4083
+ private dirty;
4084
+ private observer?;
4085
+ private timer?;
4086
+ private inFlight;
4087
+ private deliveryToken;
4088
+ private cancelDelivery?;
4089
+ private disposed;
4090
+ private history;
4091
+ private measurements;
4092
+ start(options: Omit<AggWebSocketOptions, "callbacks">, event: (event: EngineEvent) => void): void;
4093
+ observeViews(observer: (batch: MarketViewBatch) => Promise<void> | void): void;
4094
+ setSubscriptions(subscriptions: MarketSubscription[], generation: number): void;
4095
+ authenticate(token: string): void;
4096
+ resnapshot(ids: string[]): void;
4097
+ connect(): void;
4098
+ disconnect(): void;
4099
+ resume(): void;
4100
+ getMeasurements(): {
4101
+ activeSubscriptions: number;
4102
+ activeOutcomes: number;
4103
+ cachedBooks: number;
4104
+ builders: number;
4105
+ historyTasks: number;
4106
+ pendingOutcomes: number;
4107
+ inFlightDeliveries: number;
4108
+ retainedCandleOutcomes: number;
4109
+ socket: AggWebSocketDiagnostics | null;
4110
+ received: number;
4111
+ published: number;
4112
+ coalesced: number;
4113
+ maxPendingOutcomes: number;
4114
+ maxInFlight: number;
4115
+ };
4116
+ decodeHistory(payload: string): ChartBarsResponse;
4117
+ /** Fetch/decode on the processing side; newer range generations abort obsolete fetches. */
4118
+ loadHistoryRange(request: HistoryRangeRequest): Promise<ChartBarsResponse | null>;
4119
+ loadImmutableRange(key: string, generation: number, manifest: ChartHistoryManifest): Promise<ChartCandle[]>;
4120
+ cancelHistoryRange(key: string, generation?: number): void;
4121
+ dispose(): void;
4122
+ private builder;
4123
+ private mark;
4124
+ private schedule;
4125
+ private publish;
4126
+ }
4127
+
4128
+ interface AggWebSocketCallbacks {
4129
+ /** Local receipt clock, distinct from venue/source timestamps. */
4130
+ onFrameReceived?: (receivedAtMs: number) => void;
4131
+ /** Pre-accumulated live views from the optional processing engine. */
4132
+ onMarketView?: (view: MarketView) => void;
4133
+ /** Invoked with the venueMarketOutcomeId the snapshot belongs to. */
4134
+ onSnapshot?: (outcomeId: string, book: OrderbookState) => void;
4135
+ /** Invoked with the venueMarketOutcomeId the delta belongs to. */
4136
+ onDelta?: (outcomeId: string, book: OrderbookState) => void;
4137
+ onTrade?: (trade: WsTrade) => void;
4138
+ /** Every validated update, before optional view batching. Timestamps are seconds. */
4139
+ onBookTick?: (outcomeId: string, tick: {
4140
+ midpoint: number | null;
4141
+ timestamp: number;
4142
+ source: "snapshot" | "delta";
4143
+ }) => void;
4144
+ onHeartbeat?: (hb: WsHeartbeat) => void;
4145
+ onSubscribed?: (msg: WsSubscribed) => void;
4146
+ onUnsubscribed?: (msg: WsUnsubscribed) => void;
4147
+ onConnected?: (msg: WsConnected) => void;
4148
+ onAuthenticated?: (msg: WsAuthenticated) => void;
4149
+ onMarketResolved?: (msg: WsMarketResolved) => void;
4150
+ onError?: (msg: WsError) => void;
4151
+ onOrderSubmitted?: (msg: WsOrderSubmitted) => void;
4152
+ onBalanceUpdate?: (msg: WsBalanceUpdate) => void;
4153
+ onOrderEvent?: (msg: WsOrderEvent) => void;
4154
+ onRedeemEvent?: (msg: WsRedeemEvent) => void;
4155
+ onWithdrawalLifecycle?: (msg: WsWithdrawalLifecycleEvent) => void;
4156
+ onArbMarket?: (msg: WsArbMarketUpdate) => void;
4157
+ onArbFeed?: (batch: WsArbFeedBatch) => void;
4158
+ onDiagnostics?: DiagnosticCallback;
4159
+ onConnectionStateChange?: (connected: boolean) => void;
4160
+ }
4161
+ interface AggWebSocketDiagnostics {
4162
+ connected: boolean;
4163
+ transport: "direct" | "worker" | "disposed";
4164
+ orderbookOutcomeIds: string[];
4165
+ tradeOutcomeIds: string[];
4166
+ arbMarketIds: string[];
4167
+ arbFeedSubscribers: number;
4168
+ cachedBooks: number;
4169
+ cachedArb: number;
4170
+ resyncingBooks: number;
4171
+ pendingResnapshots: number;
4172
+ pendingHistoryRequests: number;
4173
+ workerAttached?: boolean;
4174
+ bridgeListeners?: number;
4175
+ host?: Record<string, unknown>;
4176
+ }
4177
+ interface AggWebSocketOptions {
4178
+ /** Full WebSocket URL including query params (appId). Token should NOT be in the URL. */
4179
+ url: string;
4180
+ callbacks?: AggWebSocketCallbacks;
4181
+ /** JWT to send via the authenticate message after connecting (avoids token in URL/logs). */
4182
+ initialToken?: string;
4183
+ /** Enable websocket debug logs. Default: false. */
4184
+ enableLogs?: boolean;
4185
+ /** Engine-only: read immutable books through getBook at presentation cadence. */
4186
+ deferBookViews?: boolean;
4187
+ }
4188
+ /**
4189
+ * Agg WebSocket client. Single WS connection with refcounted market subscriptions.
4190
+ */
4191
+ declare class AggWebSocket {
4192
+ private ws;
4193
+ private readonly url;
4194
+ private callbacks;
4195
+ private readonly subs;
4196
+ private readonly pendingSubs;
4197
+ private readonly pendingTradeSubs;
4198
+ private readonly pendingResnapshots;
4199
+ private readonly pendingFlushSubs;
4200
+ private readonly pendingFlushUnsubs;
4201
+ private readonly pendingFlushTradeSubs;
4202
+ private readonly pendingFlushTradeUnsubs;
4203
+ private readonly pendingFlushArbSubs;
4204
+ private readonly pendingFlushArbUnsubs;
4205
+ private flushScheduled;
4206
+ private readonly arbSubs;
4207
+ private readonly arbFeedCbs;
4208
+ /** Latest arb market update per marketId (last-value-wins, loss-tolerant). */
4209
+ private readonly latestArb;
4210
+ private readonly books;
4211
+ private readonly deferBookViews;
4212
+ /** Markets currently resyncing (awaiting snapshot after seq gap / checksum mismatch). */
4213
+ private readonly resyncing;
4214
+ private connecting;
4215
+ private _connected;
4216
+ private reconnectAttempts;
4217
+ private reconnectTimer;
4218
+ private staleTimer;
4219
+ private lastMessageTime;
4220
+ private destroyed;
4221
+ private historyControllers;
4222
+ private hostDiagnostics?;
4223
+ private initialToken?;
4224
+ private readonly enableLogs;
4225
+ constructor(options: AggWebSocketOptions);
4226
+ get connected(): boolean;
4227
+ /** Decode dynamic authenticated REST bytes in the same processing environment as live data. */
4228
+ decodeHistory(payload: string): Promise<ChartBarsResponse>;
4229
+ /** Immutable history decoder. Browser adapters execute this inside their Worker. */
4230
+ loadHistory(manifest: ChartHistoryManifest, options?: {
4231
+ signal?: AbortSignal;
4232
+ }): Promise<ChartCandle[]>;
4233
+ /** Optional framework-independent host diagnostics, cleared on disposal. */
4234
+ setHostDiagnostics(provider?: () => Record<string, unknown>): void;
4235
+ /** On-demand ownership diagnostics; contains no credentials or user/account data. */
4236
+ getDiagnostics(): AggWebSocketDiagnostics;
4237
+ /** Get the current orderbook state for an outcome (or null if no snapshot received yet). */
4238
+ getBook(outcomeId: string): OrderbookState | null;
4239
+ /** Whether an outcome is currently resyncing (waiting for fresh snapshot). */
4240
+ isResyncing(outcomeId: string): boolean;
4241
+ /** Get the latest arb update for a market (or null if none received yet). */
4242
+ getArb(marketId: string): WsArbMarketUpdate | null;
4243
+ /**
4244
+ * Subscribe to per-market arb updates for a given marketId.
4245
+ * Ref-counted: multiple callers for the same marketId share one server subscription.
4246
+ * Returns an unsubscribe function.
4247
+ */
4248
+ subscribeArb(marketId: string, cb: (m: WsArbMarketUpdate) => void): () => void;
4249
+ /**
4250
+ * Subscribe to the global arb-feed batches.
4251
+ * Only one server subscription is maintained regardless of how many callers.
4252
+ * Returns an unsubscribe function.
4253
+ */
4254
+ subscribeArbFeed(cb: (b: WsArbFeedBatch) => void): () => void;
4255
+ /**
4256
+ * Subscribe to a feed by outcome ID.
4257
+ * @param outcomeId The venueMarketOutcomeId to subscribe to.
4258
+ * @param channel "orderbook" (default) or "trades".
4259
+ * Returns an unsubscribe function (ref-counted).
4260
+ */
4261
+ subscribe(outcomeId: string, channel?: "orderbook" | "trades"): () => void;
4262
+ /**
4263
+ * Subscribe to an outcome's trade feed.
4264
+ * @deprecated Use `subscribe(outcomeId, "trades")` instead.
4265
+ * Returns an unsubscribe function.
4266
+ */
4267
+ subscribeTrades(outcomeId: string): () => void;
4268
+ private _subscribeTrades;
4269
+ /** Send a JWT to authenticate (or re-authenticate) the connection. */
4270
+ authenticate(token: string): void;
4271
+ /** Request a fresh snapshot for one or more subscribed outcomes. */
4272
+ resnapshot(outcomeIdOrIds: string | string[]): void;
4273
+ /** Connect (idempotent). Called automatically on first subscribe. */
4274
+ connect(): void;
4275
+ /** Disconnect and clean up. Reusable — call connect() to reconnect. */
4276
+ disconnect(): void;
4277
+ /** Permanently destroy. Cannot reconnect after this. */
4278
+ destroy(): void;
4279
+ /** Update callbacks (e.g., after React re-render). */
4280
+ setCallbacks(callbacks: AggWebSocketCallbacks): void;
4281
+ private ensureConnected;
4282
+ private doConnect;
4283
+ private scheduleReconnect;
4284
+ private cancelReconnect;
4285
+ private resetStaleTimer;
4286
+ private cancelStaleTimer;
4287
+ private handleMessage;
4288
+ /**
4289
+ * Server confirmed the connection — gateway has validated our appId and is
4290
+ * ready to accept subscriptions. Now flush all pending subs.
4291
+ */
4292
+ private handleConnected;
4293
+ private handleSnapshot;
4294
+ private handleDelta;
4295
+ private handleTrade;
4296
+ private handleHeartbeat;
4297
+ private handleMarketResolved;
4298
+ private handleOrderSubmitted;
4299
+ private handleBalanceUpdate;
4300
+ private handleRedeemEvent;
4301
+ private requestResnapshot;
4302
+ /**
4303
+ * Schedule a microtask that flushes queued subscribe/unsubscribe frames.
4304
+ * Coalesces multiple same-tick sub/unsub calls into at most one frame per
4305
+ * channel+action pair.
4306
+ */
4307
+ private scheduleFlush;
4308
+ private flushPending;
4309
+ private sendSubscribe;
4310
+ private send;
4311
+ private activeOrderbookMarkets;
4312
+ private activeTradeMarkets;
4313
+ private activeArbMarkets;
4314
+ private emitDiagnostic;
4315
+ private summarizeTopLevels;
4316
+ private debugOrderbook;
4317
+ private isOrderbookDebugEnabled;
4318
+ }
4319
+
4320
+ export { type SetPaperTradingBalanceParams as $, AggWebSocket as A, type ExecutionStatusQuery as B, type ChartBarsResponse as C, type ExecutionStatusResponse as D, type ExecutionOrdersQuery as E, type UserActivityQuery as F, type UserActivityItem as G, type ExecutionPositionsQuery as H, type ExecutionPositionGroup as I, type ManagedBalancesParams as J, type UnifiedBalanceResponse as K, type UpsertVenueKey as L, MarketDataEngine as M, type VenueKeySummary as N, type OrderbookState as O, type PaginatedResponse as P, type VenueKeyStatus as Q, type CreatePaperTradingAccountParams as R, type SiweMessageParams as S, type TradeSplit as T, type UserProfile as U, Venue as V, type WsArbMarketUpdate as W, type PaperTradingAppOptions as X, type PaperTradingAccount as Y, type PaperTradingAccountListParams as Z, type PaperTradingAccountsPage as _, type AggWebSocketOptions as a, type SyncBalancesResponse as a$, type PaperTradingBalanceResponse as a0, type ResetPaperTradingAccountParams as a1, type PlacePaperTradingOrderParams as a2, type PaperTradingOrder as a3, type PaperTradingListParams as a4, type PaperTradingPositionsPage as a5, type PaperTradingOrdersPage as a6, type PaperTradingPortfolio as a7, type CancelOrderSignature as a8, type CancelManagedExecutionResponse as a9, type CorrelatedMarketCascadeResponse as aA, type ResolveCorrelatedMarketsParams as aB, type ResolveCorrelatedMarketsResponse as aC, type ChartResolution as aD, type BatchOrderbooksResponse as aE, type BatchMidpointsResponse as aF, type OutcomeOrderbookResponse as aG, type SmartRouteParams as aH, type SmartRouteResponse as aI, type ExecuteManagedParams as aJ, type ExecuteManagedResponse as aK, type PlaceLimitOrderParams as aL, type PlaceLimitOrderResponse as aM, type PlaceOrderParams as aN, type PlaceOrderResponse as aO, type RedeemRequest as aP, type RedeemResponse as aQ, type BalanceRefillPolicy as aR, type CreateBalanceRefillPolicyParams as aS, type UpdateBalanceRefillPolicyParams as aT, type BalanceRefillAttempt as aU, type WithdrawManagedParams as aV, type WithdrawManagedResponse as aW, type WithdrawPreviewParams as aX, type WithdrawPreviewResponse as aY, type WithdrawalQuoteParams as aZ, type WithdrawalQuoteResponse as a_, MatchStatus as aa, MarketStatus as ab, type RecurrenceFilter as ac, type VenueEvent as ad, type EventBootstrapResponse as ae, type SportsLiveResponse as af, type ListRecurringCryptoMarketsOptions as ag, type RecurringCryptoMarketsResponse as ah, type GetCryptoReferencePricesOptions as ai, type CryptoReferencePricesResponse as aj, type Category as ak, type AppClientConfigResponse as al, type VenueGeoPolicyResponse as am, type RpcTokenResponse as an, type NewsFeedListResponse as ao, type NewsFeedPageOptions as ap, type NewsFeedArticleFeedResponse as aq, type NewsFeedMarketFeedResponse as ar, type NewsFeedStatusResponse as as, type NewsFeedMarketNewsParams as at, type NewsFeedMarketNewsResponse as au, type SearchParams as av, type SearchResponse as aw, type CorrelatedMarketsStatus as ax, type CorrelatedMarketSignalBatch as ay, type CorrelatedMarketQueryResult as az, type ChartHistoryManifest as b, type ExecutionDisplayGroupStatus as b$, type DepositAddressesResponse as b0, type GetPositionsParams as b1, type PositionGroup as b2, type RampQuoteRequest as b3, type RampQuote as b4, type RampSessionRequest as b5, type RampWidgetSession as b6, type Candle as b7, ACTIVE_VENUES as b8, type Account as b9, type ChartBarsMeta as bA, type ChartVenueCandles as bB, type ComputeSplitsRequest as bC, type ComputeSplitsResponse as bD, type ComputeSplitsSelection as bE, type CorrelatedMarketCascadeItem as bF, type CorrelatedMarketSide as bG, type CorrelatedMarketSignal as bH, type CorrelatedMarketSignalDirection as bI, type CreateApp as bJ, type CryptoReferencePriceError as bK, type CryptoReferencePriceExternalMarketInput as bL, type CryptoReferencePriceMarketInput as bM, type CryptoReferencePriceResult as bN, type CryptoReferencePriceSource as bO, type CryptoReferencePriceTarget as bP, type DepositAddressesPendingResponse as bQ, type DepositAddressesReadyResponse as bR, type DepositAddressesSupportedChain as bS, type DepositAddressesToken as bT, type DepositStep as bU, type DiagnosticCallback as bV, type DiagnosticEvent as bW, type ExecuteManagedRequest as bX, type ExecuteTradeRequest as bY, type ExecuteTradeResponse as bZ, type ExecutionDagProgress as b_, AccountProvider as ba, AccountType as bb, type AggAuthDeliveryMode as bc, type AggAuthPrivyVerifyBody as bd, type AggAuthProviderType as be, type AggAuthWalletVerifyBody as bf, type AggClientAuthOptions as bg, type AggSessionUser as bh, type AggregatedOrderbookLevel as bi, type AggregatedOrderbookResponse as bj, type App as bk, type AppTradingMode as bl, type AttributedOrderbook as bm, type AttributedOrderbookLevel as bn, type AuthCodeResponse as bo, type AuthTokenResponse as bp, type AuthUser as bq, type BalanceCustody as br, type BalanceRefillAttemptStatus as bs, type BalanceRefillPolicyStatus as bt, type BookQuality as bu, CONFIRMED_MATCH_STATUSES as bv, CandleBuilder as bw, type CandleInterval as bx, type CandleTail as by, Chain as bz, type ChartCandle as c, type RecurringCryptoComparisonPriceSource as c$, type ExecutionDisplayStepKind as c0, type ExecutionMode as c1, type ExecutionOverallState as c2, type ExecutionStatusOrder as c3, type ExecutionStatusStep as c4, type GetBalanceQuery as c5, type GetBalanceResponse as c6, type GetHoldingsQuery as c7, type GetHoldingsResponse as c8, type GetOrdersParams as c9, OrderType as cA, type OrderbookBatchItemError as cB, type OrderbookBatchItemErrorCode as cC, type OrderbookBatchItemStatus as cD, type OrderbookHistoryPoint as cE, type OrderbookHistoryResponse as cF, type OrderbookLevel as cG, type OrderbookQuoteFill as cH, type OrderbookQuoteParams as cI, type OrderbookQuoteResponse as cJ, type OrderbookServiceUnavailableError as cK, type OrderbooksOnlyError as cL, type OutcomeMidpoint as cM, type OutcomeMidpointRow as cN, type PaperTradingBalanceAdjustment as cO, type PaperTradingLiquidityStatus as cP, type PaperTradingMarkSource as cQ, type PaperTradingPosition as cR, type PersistedAuthSnapshot as cS, type PositionRedeemStatus as cT, type PricePoint as cU, type PriceSource as cV, type PricesHistoryResponse as cW, type ProphetxExecutionMode as cX, RECURRENCE_CADENCES as cY, type RecurrenceCadence as cZ, type RecurringCryptoComparisonPoint as c_, type GetOrdersQuery as ca, type GetPositionsQuery as cb, type HelloResponse as cc, type HistoryRangeRequest as cd, INACTIVE_VENUES as ce, type LimitOrderTimeInForce as cf, type MarkSource as cg, type MarketPriceHistory as ch, type MarketView as ci, type MarketViewBatch as cj, MatchType as ck, type MatchedMidpoint as cl, type MatchedMidpointOutcome as cm, type MatchedOrderbookMarket as cn, type MatchedVenueMarketOutcomeRef as co, type MidpointItem as cp, type MidpointRow as cq, type NewsFeedArticleFeedItem as cr, type NewsFeedArticleWithSummary as cs, type NewsFeedLinkedMarket as ct, type NewsFeedMarketFeedArticle as cu, type NewsFeedMarketFeedItem as cv, type NewsFeedMarketNewsResult as cw, type NonceResponse as cx, type OrderListItem as cy, OrderStatus as cz, type AggWebSocketDiagnostics as d, type ValidateTradeResponse as d$, type RecurringCryptoDuration as d0, type RecurringCryptoDurationInput as d1, type RecurringCryptoMarketMetrics as d2, type RecurringCryptoOrderbookDepthLevel as d3, type RecurringCryptoOrderbookDepthSide as d4, type RecurringCryptoOutcome as d5, type RecurringCryptoOutcomeOrderbookDepth as d6, type RecurringCryptoPriceComparison as d7, type RecurringCryptoReferencePrice as d8, type RecurringCryptoResolution as d9, type SmartRouteSettlementPlan as dA, type SmartRouteSetupCostLine as dB, type SmartRouteSide as dC, type SmartRouteStatus as dD, type SmartRouteVenueFill as dE, type SportsGameStatus as dF, type SportsLiveParticipant as dG, type SportsLiveState as dH, TERMINAL_EXECUTION_STATES as dI, TimeInForce as dJ, type TradeExecutorOrder as dK, type TradeStep as dL, type UserActivityBridge as dM, type UserActivityDeposit as dN, type UserActivityRedeem as dO, type UserActivityRedeemLeg as dP, type UserActivityTrade as dQ, type UserActivityType as dR, type UserActivityUserOp as dS, type UserActivityWithdrawal as dT, VENUES as dU, VENUE_CHAIN_IDS as dV, type ValidateBalanceOnClientStep as dW, type ValidateManagedParams as dX, type ValidateManagedRequest as dY, type ValidateManagedResponse as dZ, type ValidateTradeRequest as d_, type RecurringCryptoSourceConfidence as da, type RecurringCryptoVenueMarket as db, type RecurringCryptoWindowComparisons as dc, type RecurringCryptoWindowMarket as dd, type RedeemLegResult as de, type RedeemLegStatus as df, type RequestedOrderbookMarket as dg, type ResolvedCorrelatedMarketsResponse as dh, SELF_CUSTODY_FILL_TIMEOUT_MS as di, SELF_CUSTODY_POLL_INTERVAL_MS as dj, type ServerWallet as dk, type SettlementDiff as dl, type SettlementDifference as dm, type SettlementSource as dn, type SetupDepositAddressStep as dp, type SetupVenueKeyStep as dq, type SignatureRequest as dr, type SignatureRequestType as ds, type SignerFn as dt, type SimpleOrderbookLevel as du, type SmartRouteAllocation as dv, type SmartRouteBridgeStep as dw, type SmartRouteFeeBreakdown as dx, type SmartRouteFill as dy, type SmartRouteSettlementLeg as dz, type WsArbFeedBatch as e, type VenueEventListItem as e0, type VenueEventWithMarkets as e1, type VenueGeoPolicyEntry as e2, type VenueMarketListItem as e3, type VenueMarketRef as e4, type VenueOrderbookEntry as e5, type VenueOrderbookLevel as e6, type VenuePositionBalance as e7, type VenuePriceInfo as e8, type VenueSoloQuote as e9, type WsMarketResolved as eA, type WsOrderEvent as eB, type WsOrderEventType as eC, type WsOrderSubmitted as eD, type WsOrderbookDelta as eE, type WsOrderbookSnapshot as eF, type WsRedeemEvent as eG, type WsServerMessage as eH, type WsSubscribed as eI, type WsTrade as eJ, type WsUnsubscribed as eK, type WsVenueBook as eL, type WsVenueInfo as eM, type WsVenueLevel as eN, type WsWithdrawalLegStatus as eO, type WsWithdrawalLifecycleEvent as eP, type WsWithdrawalLifecycleLeg as eQ, type WsWithdrawalLifecycleStatus as eR, applyOrderbookDelta as eS, computeChecksum as eT, getEffectiveDisabledVenues as eU, isVenueActive as eV, isVenueDataVisible as eW, isVenueInactive as eX, snapshotToOrderbook as eY, type VerifyBody as ea, type VerifyResponse as eb, type WalletChainBalance as ec, type WalletTokenBalance as ed, type WithdrawManagedRequest as ee, type WithdrawManagedSourceItem as ef, type WithdrawTokenSymbol as eg, type WithdrawalExpected as eh, type WithdrawalLeg as ei, type WithdrawalLegStatus as ej, type WithdrawalLegType as ek, type WithdrawalLifecycleStatus as el, type WithdrawalSource as em, type WithdrawalSourceItem as en, type WithdrawalSourceStatus as eo, type WithdrawalSourceTokenSymbol as ep, type WsArbFeedEntry as eq, type WsAttributedLevel as er, type WsAuthenticated as es, type WsBalanceUpdate as et, type WsCandleInterval as eu, type WsClientMessage as ev, type WsConnected as ew, type WsError as ex, type WsHeartbeat as ey, type WsMarkSource as ez, type AggWebSocketCallbacks as f, type VenueMarket as g, type VenueMarketOutcome as h, type Orderbook as i, TradeSide$1 as j, type AggClientOptions as k, type AggClientSessionInput as l, type AuthStatus as m, type SiwsMessageParams as n, type AggAuthVerifyBody as o, type AggAuthStartBody as p, type AggAuthStartResult as q, type AggLinkAccountBody as r, type AggLinkAccountResult as s, type AggLinkAccountWalletConfirmBody as t, type AggLinkAccountConfirmResult as u, type UpdateUserBody as v, type UserHolding as w, type OrderListQuery as x, type TradeExecutorOrderListResponse as y, type ExecutionOrderItem as z };