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