@agg-build/sdk 1.0.1 → 1.2.11

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.mts CHANGED
@@ -389,12 +389,14 @@ type WalletTokenBalance = {
389
389
  lastSyncedAt: string;
390
390
  }[];
391
391
  };
392
+ type PriceSource = "orderbook" | "cached" | "entry" | "settled";
392
393
  type VenuePositionBalance = {
393
394
  venue: Venue;
394
395
  balance: number;
395
396
  costBasis: number;
396
397
  unrealizedPnl: number;
397
398
  realizedPnl: number;
399
+ priceSource: PriceSource;
398
400
  };
399
401
  type UnifiedBalanceResponse = {
400
402
  cash: {
@@ -452,6 +454,8 @@ type GetHoldingsQuery = {
452
454
  type GetOrdersQuery = {
453
455
  status?: OrderStatus | undefined;
454
456
  orderId?: string | undefined;
457
+ /** Filter to all legs of one quote (multi-venue split routes). */
458
+ quoteId?: string | undefined;
455
459
  cursor?: string | undefined;
456
460
  limit?: number | undefined;
457
461
  };
@@ -463,6 +467,12 @@ type GetPositionsQuery = {
463
467
  type OrderListItem = {
464
468
  status: string;
465
469
  id: string;
470
+ /**
471
+ * Parent quote — lets the frontend correlate legs of a multi-venue
472
+ * split route without a second request. Nullable for sell-side /
473
+ * standalone orders without a Quote row.
474
+ */
475
+ quoteId: string | null;
466
476
  createdAt: Date;
467
477
  updatedAt: Date;
468
478
  venue: Venue;
@@ -471,8 +481,28 @@ type OrderListItem = {
471
481
  slippageBps: number | null;
472
482
  quotedPriceRaw: string | null;
473
483
  quotedCostRaw: string | null;
484
+ /**
485
+ * Quote-time shares + payout, 6-decimal atomic. Lets the UI render
486
+ * "Quoted X shares / $Y to win" without re-deriving from cost ÷
487
+ * price (precision drift on fractional fills; divide-by-zero before
488
+ * `executionPrice` exists).
489
+ */
490
+ quotedSharesRaw: string | null;
491
+ quotedToWinRaw: string | null;
474
492
  filledAmountRaw: string | null;
475
493
  executionPrice: string | null;
494
+ /**
495
+ * Actual shares + payout, populated by the venue's finalize handler.
496
+ * Pair with the quoted-side fields above to render the diff inline.
497
+ */
498
+ actualSharesRaw: string | null;
499
+ actualToWinRaw: string | null;
500
+ /**
501
+ * Set only on `partial_fill`. One of `"venue_capacity"`,
502
+ * `"price_slipped"`, `"user_cancelled"`, `"timeout"`, `"bridge_short"`,
503
+ * or a venue-specific tag.
504
+ */
505
+ partialFillReason: string | null;
476
506
  txHash: string | null;
477
507
  errorMessage: string | null;
478
508
  dagRunId: string | null;
@@ -502,13 +532,14 @@ type PositionGroup = {
502
532
  venue: Venue;
503
533
  size: number;
504
534
  venueMarketId: string;
505
- venueMarketOutcomeId?: string | null;
535
+ venueMarketOutcomeId: string;
506
536
  }[];
507
537
  totalSize: number;
508
538
  avgEntryPrice: number;
509
539
  currentPrice: number;
510
540
  totalValue: number;
511
541
  unrealizedPnlPercent: number;
542
+ priceSource: PriceSource;
512
543
  }[];
513
544
  };
514
545
  targetMarketId: string;
@@ -529,6 +560,14 @@ type VenueMarket = {
529
560
  title?: string | null | undefined;
530
561
  externalIdentifier?: string | null | undefined;
531
562
  winner?: boolean | null | undefined;
563
+ /** Counterpart outcomes on matched sibling markets — only populated
564
+ * on the parent (queried) market's outcomes. Each entry is a
565
+ * `{ venueMarketId, venueMarketOutcomeId }` ref into the same
566
+ * response's `matchedVenueMarkets[].venueMarketOutcomes[]`. */
567
+ matchedVenueMarketOutcomes?: {
568
+ venueMarketId: string;
569
+ venueMarketOutcomeId: string;
570
+ }[];
532
571
  }[];
533
572
  externalIdentifier: string;
534
573
  status?: MarketStatus | undefined;
@@ -601,6 +640,13 @@ type VenueEvent = {
601
640
  venues?: Venue[];
602
641
  venueCount?: number | undefined;
603
642
  marketCount?: number | undefined;
643
+ /**
644
+ * ISO-8601 duration denormalized from Series.recurrence. `null` means
645
+ * the event has no recurring schedule (one-off). Use this value with
646
+ * the `?recurrence=` filter on /venue-events; discover all available
647
+ * values via GET /recurrences.
648
+ */
649
+ recurrence?: string | null | undefined;
604
650
  };
605
651
  type Orderbook = {
606
652
  bids: {
@@ -693,6 +739,14 @@ type OrderbookHistoryResponse = {
693
739
  close?: number | undefined;
694
740
  }[];
695
741
  };
742
+ /** Reference to a counterpart outcome on a matched sibling market.
743
+ * Resolves into the same response's `matchedVenueMarkets[].venueMarketOutcomes[]`
744
+ * by id. Sourced from `MatchedVenueMarketOutcome` so the alignment is
745
+ * robust to inversely-framed binary markets and multi-outcome markets. */
746
+ type MatchedVenueMarketOutcomeRef = {
747
+ venueMarketId: string;
748
+ venueMarketOutcomeId: string;
749
+ };
696
750
  type VenueMarketOutcome = {
697
751
  id: string;
698
752
  price: number;
@@ -701,6 +755,9 @@ type VenueMarketOutcome = {
701
755
  title?: string | null | undefined;
702
756
  externalIdentifier?: string | null | undefined;
703
757
  winner?: boolean | null | undefined;
758
+ /** Counterpart outcomes on matched sibling markets — only populated on
759
+ * the parent (queried) market's outcomes. */
760
+ matchedVenueMarketOutcomes?: MatchedVenueMarketOutcomeRef[];
704
761
  };
705
762
  type VenueEventWithMarkets = VenueEvent & {
706
763
  venueMarkets: VenueMarket[];
@@ -710,15 +767,31 @@ type VenueEventListItem = VenueEvent & {
710
767
  venueMarkets: VenueMarketListItem[];
711
768
  marketCount: number;
712
769
  };
770
+ /** Per-outcome midpoint inside a matched-sibling entry. Aligned via MVMO
771
+ * so the `venueMarketOutcomeId` resolves the same outcome the parent's
772
+ * `matchedVenueMarketOutcomes` ref points to. */
773
+ type MatchedMidpointOutcome = {
774
+ venueMarketOutcomeId: string;
775
+ midpoint: number | null;
776
+ bestBid?: number | null;
777
+ bestAsk?: number | null;
778
+ };
713
779
  type MatchedMidpoint = {
714
780
  venueMarketId: string;
715
781
  venue: string;
782
+ /** Sibling's market-level midpoint. Kept for backwards compat — the
783
+ * authoritative cross-venue alignment lives in `outcomes`. */
716
784
  midpoint: number | null;
785
+ /** Per-outcome midpoints keyed by sibling outcome id. Optional during
786
+ * rollout — older engine builds may omit it. */
787
+ outcomes?: MatchedMidpointOutcome[];
717
788
  };
718
789
  type OutcomeMidpoint = {
719
790
  venueMarketOutcomeId: string;
720
791
  label: string;
721
792
  midpoint: number | null;
793
+ bestBid?: number | null;
794
+ bestAsk?: number | null;
722
795
  };
723
796
  type MidpointItem = {
724
797
  venueMarketId: string;
@@ -961,6 +1034,35 @@ declare function formatMarketQuestion(venue: Venue, market: {
961
1034
  title?: string | null;
962
1035
  }>;
963
1036
  }): string;
1037
+ /**
1038
+ * Resolve the display title for a VenueMarketOutcome.
1039
+ *
1040
+ * Returns `null` when every outcome on the market shares the same `title`
1041
+ * (Kalshi binary markets often store the same human-readable phrase on
1042
+ * both Yes/No outcomes — repeating it on each option is redundant). The
1043
+ * frontend should fall back to `label` in that case.
1044
+ *
1045
+ * Otherwise returns the outcome's stored `title` verbatim (or `null` when
1046
+ * unset). The DB `label` is always returned untouched by this helper.
1047
+ *
1048
+ * Polymarket player-prop fallback: when a binary Yes/No outcome has no
1049
+ * stored title (Gamma sends `outcomes=["Yes","No"]` for these markets,
1050
+ * e.g. *"Mikal Bridges: Rebounds O/U 2.5"*), derive `Over`/`Under` from
1051
+ * the question's `O/U <n>` token so the FE has something meaningful to
1052
+ * show. Sports-totals (`["Over","Under"]`) and spread markets
1053
+ * (`["<TeamA>","<TeamB>"]`) already get titles from upstream and are
1054
+ * unaffected.
1055
+ */
1056
+ declare function formatOutcomeTitle(_venue: Venue, outcome: {
1057
+ label: string;
1058
+ title?: string | null;
1059
+ }, market: {
1060
+ question?: string | null;
1061
+ venueMarketOutcomes?: Array<{
1062
+ label: string;
1063
+ title?: string | null;
1064
+ }>;
1065
+ }): string | null;
964
1066
 
965
1067
  declare function getWalletAddressFromUserProfile(user: UserProfile | undefined): string | undefined;
966
1068
 
@@ -1049,6 +1151,31 @@ declare const normalizeVenueMarketCluster: <TMarket extends VenueMarketClusterNo
1049
1151
 
1050
1152
  declare const sortVenues: <T extends string>(venues: readonly T[]) => T[];
1051
1153
 
1154
+ /**
1155
+ * Build an external URL to a venue's event/market page.
1156
+ *
1157
+ * Single source of truth — used by API services (market-intel digests,
1158
+ * gap-alerts) AND by the admin Matched Events page to deep-link rows out
1159
+ * to the venue's UI.
1160
+ *
1161
+ * Returns `null` when there isn't enough data to construct a working URL.
1162
+ * Callers should hide the link button rather than render a broken href.
1163
+ *
1164
+ * Per-venue URL conventions are kept here so any future change (e.g.
1165
+ * Kalshi moves to a new path, Polymarket rebrands) is a one-file edit.
1166
+ */
1167
+ interface BuildVenueUrlOpts {
1168
+ /** VenueEvent.slug — preferred input for venues that use slug-style URLs. */
1169
+ eventSlug?: string | null;
1170
+ /** VenueEvent.externalIdentifier — used by Kalshi (with series) and as a fallback. */
1171
+ eventExternalId?: string | null;
1172
+ /** VenueEvent.series.externalIdentifier — required for Kalshi's canonical URL. */
1173
+ seriesExternalId?: string | null;
1174
+ /** VenueMarket.conditionId — used as a fallback for Polymarket when slug is missing. */
1175
+ conditionId?: string | null;
1176
+ }
1177
+ declare function buildVenueUrl(venue: string, opts: BuildVenueUrlOpts): string | null;
1178
+
1052
1179
  /**
1053
1180
  * WebSocket protocol types for the Agg platform.
1054
1181
  * All callback timestamps are in **seconds** (converted from server ms at SDK dispatch).
@@ -1206,6 +1333,28 @@ interface WsOrderEvent {
1206
1333
  stepTypes?: Record<number, string>;
1207
1334
  filledAmountRaw?: string;
1208
1335
  remainingAmountRaw?: string;
1336
+ /**
1337
+ * Quote-time and actual shares + payout. All 6-decimal atomic units
1338
+ * (so 1.234567 shares = "1234567", "$50 to win" = "50000000"). Set
1339
+ * on `filled` / `partial_fill` so the UI can render "Quoted X / Got Y"
1340
+ * without re-deriving from cost ÷ price (which loses precision on
1341
+ * fractional fills and divides by zero before `executionPrice` exists).
1342
+ */
1343
+ quotedSharesRaw?: string;
1344
+ actualSharesRaw?: string;
1345
+ quotedToWinRaw?: string;
1346
+ actualToWinRaw?: string;
1347
+ /** Quote-time price (decimal string, e.g. "0.5"). Pair with `executionPriceRaw`
1348
+ * to render the slippage diff inline. */
1349
+ quotedPriceRaw?: string;
1350
+ /** Actual avg fill price (decimal string). */
1351
+ executionPriceRaw?: string;
1352
+ /**
1353
+ * Set on `partial_fill` events only. One of `"venue_capacity"`,
1354
+ * `"price_slipped"`, `"user_cancelled"`, `"timeout"`, `"bridge_short"`,
1355
+ * or a venue-specific tag.
1356
+ */
1357
+ partialFillReason?: string;
1209
1358
  errorReason?: string;
1210
1359
  attempt?: number;
1211
1360
  correlationId?: string;
@@ -1235,6 +1384,8 @@ interface WsWithdrawalLifecycleLeg {
1235
1384
  amountRaw: string;
1236
1385
  txHash: string | null;
1237
1386
  bridgeOperationId: string | null;
1387
+ /** Human-readable failure reason when `status === "failed"`. Null/absent when succeeded or in-flight. */
1388
+ errorMessage?: string | null;
1238
1389
  }
1239
1390
  /**
1240
1391
  * Per-withdrawal lifecycle event. Wire shape is intentionally additive:
@@ -1245,6 +1396,10 @@ interface WsWithdrawalLifecycleEvent {
1245
1396
  withdrawalId: string;
1246
1397
  userId: string;
1247
1398
  status: WsWithdrawalLifecycleStatus;
1399
+ /** Requested withdrawal amount in destination-token native decimals. */
1400
+ requestedAmountRaw?: string;
1401
+ /** Terminal settled amount in destination-token native decimals. */
1402
+ completedAmountRaw?: string | null;
1248
1403
  /** True when `status` is terminal (`completed` / `partial` / `failed`). */
1249
1404
  terminal: boolean;
1250
1405
  /** Optional leg delta — present when this event was triggered by a leg flip. */
@@ -1491,8 +1646,16 @@ interface AppClientConfigResponse {
1491
1646
  disabledVenues: Venue[];
1492
1647
  disabledCategoryPresets: string[];
1493
1648
  earlyAccessEnabled: boolean;
1649
+ authOptions: AppClientAuthOption[];
1494
1650
  }
1495
1651
  type AggAuthProviderType = "siwe" | "siws" | "google" | "twitter" | "apple" | "email";
1652
+ interface AppClientAuthOption {
1653
+ provider: AggAuthProviderType;
1654
+ type: "oauth" | "email" | "wallet";
1655
+ enabled: boolean;
1656
+ callbackUrl?: string;
1657
+ statement?: string;
1658
+ }
1496
1659
  type AggAuthDeliveryMode = "body" | "cookie-refresh";
1497
1660
  interface AggClientAuthOptions {
1498
1661
  getEarlyAccessCode?: () => string | null;
@@ -1519,6 +1682,7 @@ interface AggAuthVerifyBody {
1519
1682
  type AggAuthStartResult = {
1520
1683
  type: "nonce";
1521
1684
  nonce: string;
1685
+ statement?: string;
1522
1686
  } | {
1523
1687
  type: "redirect";
1524
1688
  url: string;
@@ -1916,6 +2080,20 @@ interface QuoteManagedResponse {
1916
2080
  }
1917
2081
  interface ExecuteManagedParams {
1918
2082
  quoteId: string;
2083
+ /**
2084
+ * Optional intent fallback. When the supplied `quoteId` has expired in the
2085
+ * cache (e.g. user clicked Buy after a tab was inactive), the server
2086
+ * resolves the latest live quote for this intent and refreshes/executes
2087
+ * against that instead of returning 400 `quote_not_found`. Same intent =
2088
+ * same buttons the user pressed in the UI; a different `maxSpend` is a
2089
+ * different intent and won't match.
2090
+ */
2091
+ fallbackToLatest?: {
2092
+ outcomeId: string;
2093
+ side: "buy" | "sell";
2094
+ maxSpend?: number;
2095
+ sellShares?: number;
2096
+ };
1919
2097
  }
1920
2098
  interface ExecuteManagedResponse {
1921
2099
  quoteId: string;
@@ -1956,6 +2134,8 @@ interface WithdrawalLeg {
1956
2134
  amountRaw: string;
1957
2135
  txHash: string | null;
1958
2136
  bridgeOperationId: string | null;
2137
+ /** Human-readable failure reason when `status === "failed"`. Null when succeeded or in-flight. */
2138
+ errorMessage?: string | null;
1959
2139
  }
1960
2140
  interface WithdrawManagedSourceItem {
1961
2141
  sourceId: string;
@@ -1989,6 +2169,11 @@ interface WithdrawManagedResponse {
1989
2169
  tokenSymbol: WithdrawTokenSymbol;
1990
2170
  amountRaw: string;
1991
2171
  };
2172
+ /**
2173
+ * Terminal settled amount in destination-token native decimals.
2174
+ * Null until at least one source confirms.
2175
+ */
2176
+ completedAmountRaw: string | null;
1992
2177
  destination: {
1993
2178
  chainId: number;
1994
2179
  address: string;
@@ -2211,6 +2396,17 @@ interface VenueSoloQuote {
2211
2396
  status: string;
2212
2397
  /** Per-price-level fills, identical shape to primary fills. Empty for non-ok statuses. */
2213
2398
  fills: SmartRouteVenueFill[];
2399
+ /**
2400
+ * One-time setup costs for this solo's chosen venue + market. Populated
2401
+ * only when the originating quote opted in via `deepEstimate=true`; absent
2402
+ * on cheap quotes and on non-executable / failed solos. Same shape as the
2403
+ * multi-route `feeBreakdown.setupCosts`. The solo's `estimatedProfit` and
2404
+ * `returnPct` are recomputed against `cost basis + setupCostsTotal` so
2405
+ * per-venue comparisons are setup-inclusive.
2406
+ */
2407
+ setupCosts?: SmartRouteSetupCostLine[];
2408
+ /** Sum of this solo's `setupCosts` entries where `alreadyPaid=false`. */
2409
+ setupCostsTotal?: number;
2214
2410
  }
2215
2411
  /** @deprecated Smart-route side overrides are kept only for source compatibility. */
2216
2412
  type SmartRouteSide = "yes" | "no";
@@ -2233,6 +2429,71 @@ interface SmartRouteParams {
2233
2429
  chainBalances?: Record<string, number>;
2234
2430
  slipCapBps?: number;
2235
2431
  compareVenues?: boolean;
2432
+ /**
2433
+ * Opt in to the deep cost-estimate surface. When `true`, the response
2434
+ * `feeBreakdown` includes `setupCosts` (one-time chain approvals + Kalshi
2435
+ * SPL token-account rents) with per-item `alreadyPaid` flags from the
2436
+ * user's prior trade history. Buy-only; ignored for sells.
2437
+ *
2438
+ * Deep quotes also pre-deduct the unpaid setup total from `maxSpend`
2439
+ * before routing, so `totalCostIncFees` (and the recomputed
2440
+ * `estimatedProfit` / `returnPct`) stay within the partner's stated
2441
+ * budget.
2442
+ */
2443
+ deepEstimate?: boolean;
2444
+ }
2445
+ /** One-time setup line item — populated only on deep-estimate quotes. */
2446
+ interface SmartRouteSetupCostLine {
2447
+ /** "chainApproval" = ERC-20 + venue-contract approvals on the venue's
2448
+ * chain (Polymarket / Polygon, Limitless / Base, predict.fun / BNB).
2449
+ * "venueMarketAta" = Kalshi-on-Solana per-market token-account rent. */
2450
+ kind: "chainApproval" | "venueMarketAta";
2451
+ venue: string;
2452
+ /** Set when `kind === "chainApproval"`. */
2453
+ chainId?: number;
2454
+ /** Set when `kind === "venueMarketAta"`. */
2455
+ venueMarketId?: string;
2456
+ /** Per-item cost in USD. Sourced from documented chain-paymaster floors
2457
+ * (Polygon/Base/Arbitrum ≈ $0.05, BNB $0.20, Solana ATA ≈ $0.30). */
2458
+ costUsd: number;
2459
+ /** True if the user has already paid this on a prior fill — render as a
2460
+ * strike-through "first-time fee" chip rather than charging again. */
2461
+ alreadyPaid: boolean;
2462
+ }
2463
+ interface SmartRouteFeeBreakdown {
2464
+ rawExecCost: number;
2465
+ venueFees: number;
2466
+ bridgeFees: number;
2467
+ executionGas: number;
2468
+ totalCost: number;
2469
+ }
2470
+ /** Cost breakdown for a route quote. */
2471
+ interface SmartRouteFeeBreakdown {
2472
+ rawExecCost: number;
2473
+ venueFees: number;
2474
+ bridgeFees: number;
2475
+ executionGas: number;
2476
+ totalCost: number;
2477
+ /** Populated only when the request specified `deepEstimate=true`. */
2478
+ setupCosts?: SmartRouteSetupCostLine[];
2479
+ /** Sum of `setupCosts` entries where `alreadyPaid === false`. */
2480
+ setupCostsTotal?: number;
2481
+ /**
2482
+ * Partner-level execution fee in USD. The worst-case fee the user will
2483
+ * pay against the routed buy notional at quote time. Buy-side only —
2484
+ * sell quotes don't carry this field.
2485
+ *
2486
+ * Actual collection happens after the trade fills, against realized
2487
+ * notional (which may be less on partial fills). Partner UIs should
2488
+ * render this as "you'll pay up to $X in app fees".
2489
+ *
2490
+ * Both `appFee` and `appFeeBips` are present iff `appFee > 0`.
2491
+ */
2492
+ appFee?: number;
2493
+ /** Partner's configured bips for this market — the rate that produced `appFee`. */
2494
+ appFeeBips?: number;
2495
+ /** Category key the bips resolved against (e.g. "sports", or "all" for the fallback). */
2496
+ appFeeCategory?: string;
2236
2497
  }
2237
2498
  /** Response from GET /orderbook/:venueMarketOutcomeId/route. */
2238
2499
  interface SmartRouteResponse {
@@ -2241,6 +2502,12 @@ interface SmartRouteResponse {
2241
2502
  venueMarketId: string;
2242
2503
  estimatedCostRaw: string;
2243
2504
  expiresAt: string;
2505
+ /**
2506
+ * Timestamp at which the quote begins to drift — frontends should refetch
2507
+ * a fresh `getSmartRoute` at this point even though the cached quoteId
2508
+ * remains executable until `expiresAt`. Always earlier than `expiresAt`.
2509
+ */
2510
+ refreshAt: string;
2244
2511
  status: SmartRouteStatus;
2245
2512
  fills: SmartRouteVenueFill[];
2246
2513
  totalFilled: number;
@@ -2261,12 +2528,20 @@ interface SmartRouteResponse {
2261
2528
  venueSoloQuotes?: VenueSoloQuote[];
2262
2529
  /** Estimated payout if the outcome wins (= totalFilled shares × $1). */
2263
2530
  estimatedPayout?: number;
2264
- /** Total cost including all fees (rawExecCost + venueFees + bridgeFees + executionGas). */
2531
+ /** Total cost including all fees (rawExecCost + venueFees + bridgeFees +
2532
+ * executionGas). For deep-estimate quotes, `setupCostsTotal` is folded
2533
+ * into this number and `estimatedProfit` / `returnPct` are recomputed
2534
+ * against it. */
2265
2535
  totalCostIncFees?: number;
2266
2536
  /** Estimated profit if the outcome wins (= estimatedPayout − totalCostIncFees). */
2267
2537
  estimatedProfit?: number;
2268
2538
  /** Return on investment percentage (= estimatedProfit / totalCostIncFees × 100). */
2269
2539
  returnPct?: number;
2540
+ /** Per-route fee breakdown. Always present when the engine produced a
2541
+ * feasible plan; omitted on solo / failed quotes. The `setupCosts` and
2542
+ * `setupCostsTotal` fields are populated only when the request set
2543
+ * `deepEstimate=true`. */
2544
+ feeBreakdown?: SmartRouteFeeBreakdown;
2270
2545
  /** Populated only when status === "insufficient_position". */
2271
2546
  positionAvailability?: {
2272
2547
  totalSellableShares: number;
@@ -2309,6 +2584,18 @@ interface SearchParams {
2309
2584
  categoryIds?: string[];
2310
2585
  limit?: number;
2311
2586
  cursor?: string;
2587
+ /**
2588
+ * Opt in to the server-side reranker for higher-quality top results.
2589
+ *
2590
+ * Send `deep: true` for the final search-results page (submit / Enter) and
2591
+ * leave it off for debounced typeahead. Adds ~100–150 ms on a cold rerank
2592
+ * cache and ~3 ms on a warm one — typeahead can't afford the cold cost,
2593
+ * and the result orderings differ enough that the server gives the two
2594
+ * modes separate cache slots.
2595
+ *
2596
+ * Defaults to `false`.
2597
+ */
2598
+ deep?: boolean;
2312
2599
  }
2313
2600
  type SearchResponse<T> = {
2314
2601
  type: SearchType;
@@ -2316,6 +2603,99 @@ type SearchResponse<T> = {
2316
2603
  nextCursor: string | null;
2317
2604
  hasMore: boolean;
2318
2605
  };
2606
+ type CorrelatedMarketSide = "yes" | "no";
2607
+ type CorrelatedMarketSignalDirection = "more_likely" | "less_likely";
2608
+ interface CorrelatedMarketSignal {
2609
+ id: string;
2610
+ text: string;
2611
+ side: CorrelatedMarketSide;
2612
+ direction: CorrelatedMarketSignalDirection;
2613
+ domain: string;
2614
+ }
2615
+ interface CorrelatedMarketSignalBatch {
2616
+ id: string;
2617
+ venueMarketId: string;
2618
+ sourceModel: string;
2619
+ promptVersion: number;
2620
+ createdAt: string;
2621
+ signals: CorrelatedMarketSignal[];
2622
+ }
2623
+ interface CorrelatedMarketsStatus {
2624
+ markets: {
2625
+ total: number;
2626
+ processed: number;
2627
+ coverage: number;
2628
+ };
2629
+ signals: {
2630
+ total: number;
2631
+ withEmbeddings: number;
2632
+ missingEmbeddings: number;
2633
+ };
2634
+ eventTitleEmbeddings: {
2635
+ total: number;
2636
+ events: number;
2637
+ coverage: number;
2638
+ };
2639
+ config: {
2640
+ batchSize: number;
2641
+ jobsEnabled: boolean;
2642
+ backfillInterval: string;
2643
+ reembedInterval: string;
2644
+ eventEmbeddingInterval: string;
2645
+ };
2646
+ }
2647
+ interface CorrelatedMarketQueryResult {
2648
+ venueMarketId: string;
2649
+ marketQuestion: string;
2650
+ eventTitle: string;
2651
+ score: number;
2652
+ matchedSignal: CorrelatedMarketSignal;
2653
+ venue: string;
2654
+ }
2655
+ interface CorrelatedMarketCascadeItem {
2656
+ venueEventId: string;
2657
+ eventTitle: string;
2658
+ score: number;
2659
+ action: string;
2660
+ reason: string;
2661
+ reasonDomain: string;
2662
+ }
2663
+ interface CorrelatedMarketCascadeResponse {
2664
+ data: CorrelatedMarketCascadeItem[];
2665
+ nextCursor: string | null;
2666
+ hasMore: boolean;
2667
+ }
2668
+ interface ResolveCorrelatedMarketsParams {
2669
+ venue?: string;
2670
+ externalId?: string;
2671
+ slug?: string;
2672
+ conditionId?: string;
2673
+ q?: string;
2674
+ side?: CorrelatedMarketSide;
2675
+ mode?: "expand" | "hedge";
2676
+ limit?: number;
2677
+ cursor?: string;
2678
+ includeResolved?: boolean;
2679
+ }
2680
+ type ResolveCorrelatedMarketsResponse = ({
2681
+ market: {
2682
+ id: string;
2683
+ question: string;
2684
+ };
2685
+ } & CorrelatedMarketCascadeResponse) | {
2686
+ market: {
2687
+ id: string;
2688
+ question: string;
2689
+ };
2690
+ status: "processing";
2691
+ message: string;
2692
+ };
2693
+ interface ResolvedCorrelatedMarketsResponse extends CorrelatedMarketCascadeResponse {
2694
+ market: {
2695
+ id: string;
2696
+ question: string;
2697
+ };
2698
+ }
2319
2699
 
2320
2700
  type AuthStateListener = (authenticated: boolean) => void;
2321
2701
  type UserAuthResult = {
@@ -2453,7 +2833,13 @@ declare class AggClient {
2453
2833
  }): Promise<PaginatedResponse<UserHolding>>;
2454
2834
  /** List trade-executor orders for the authenticated user. */
2455
2835
  getOrders(params?: OrderListQuery): Promise<TradeExecutorOrderListResponse>;
2456
- /** List execution orders for the authenticated user (cursor pagination). */
2836
+ /**
2837
+ * List execution orders for the authenticated user (cursor pagination).
2838
+ *
2839
+ * Pass `quoteId` to fetch every leg of a multi-venue split route in
2840
+ * one call — `useQuoteSummary(quoteId)` reduces the list into a
2841
+ * rollup (total cost, share-weighted avg price, to-win).
2842
+ */
2457
2843
  getExecutionOrders(params?: ExecutionOrdersQuery): Promise<PaginatedResponse<ExecutionOrderItem>>;
2458
2844
  /** Unified user activity feed (trades, deposits, withdrawals, bridges, wallet ops). */
2459
2845
  getUserActivity(params?: UserActivityQuery): Promise<PaginatedResponse<UserActivityItem>>;
@@ -2505,8 +2891,49 @@ declare class AggClient {
2505
2891
  }): Promise<PaginatedResponse<Category>>;
2506
2892
  /** Get per-app UI config (disabled venues + category presets). Requires appId. */
2507
2893
  getAppConfig(init?: RequestInit): Promise<AppClientConfigResponse>;
2508
- /** Search events or markets by query string. Supports cursor-based pagination. */
2894
+ /**
2895
+ * Search events or markets by query string. Supports cursor-based pagination.
2896
+ *
2897
+ * Pass `deep: true` on submit (Enter / Search button) to opt in to the
2898
+ * server-side reranker. Leave it off for debounced typeahead — the wire
2899
+ * format intentionally omits the param so the server hits the cheaper
2900
+ * (and longer-TTL) light cache slot.
2901
+ */
2509
2902
  search<T = VenueEvent>(params: SearchParams): Promise<SearchResponse<T>>;
2903
+ /** Get Correlated Markets processing and embedding coverage. */
2904
+ getCorrelatedMarketsStatus(options?: {
2905
+ signal?: AbortSignal;
2906
+ }): Promise<CorrelatedMarketsStatus>;
2907
+ /** Get the generated correlated market signals for a market. */
2908
+ getMarketCorrelatedSignals(venueMarketId: string, options?: {
2909
+ signal?: AbortSignal;
2910
+ includeResolved?: boolean;
2911
+ }): Promise<CorrelatedMarketSignalBatch>;
2912
+ /** Search markets by Correlated Markets signal similarity. */
2913
+ queryCorrelatedMarkets(params: {
2914
+ text: string;
2915
+ limit?: number;
2916
+ includeResolved?: boolean;
2917
+ }, options?: {
2918
+ signal?: AbortSignal;
2919
+ }): Promise<{
2920
+ results: CorrelatedMarketQueryResult[];
2921
+ }>;
2922
+ /** Get expansion and hedge candidates for an already-processed market. */
2923
+ getCorrelatedMarketCascade(params: {
2924
+ venueMarketId: string;
2925
+ side?: "yes" | "no";
2926
+ mode?: "expand" | "hedge";
2927
+ limit?: number;
2928
+ cursor?: string;
2929
+ includeResolved?: boolean;
2930
+ }, options?: {
2931
+ signal?: AbortSignal;
2932
+ }): Promise<CorrelatedMarketCascadeResponse>;
2933
+ /** Resolve a market by ID, venue identifier, slug, conditionId, or text, then return candidates. */
2934
+ resolveCorrelatedMarkets(params: ResolveCorrelatedMarketsParams, options?: {
2935
+ signal?: AbortSignal;
2936
+ }): Promise<ResolveCorrelatedMarketsResponse>;
2510
2937
  /** Get the canonical TradingView-style bar series for a single venue market outcome. */
2511
2938
  getChartBars(params: {
2512
2939
  venueMarketOutcomeId: string;
@@ -2527,11 +2954,13 @@ declare class AggClient {
2527
2954
  /** Get live midpoints for the explicit venueMarketIds requested. */
2528
2955
  getMidpoints(params: {
2529
2956
  venueMarketIds: string[];
2957
+ bestPrice?: boolean;
2530
2958
  }, options?: {
2531
2959
  signal?: AbortSignal;
2532
2960
  }): Promise<BatchMidpointsResponse>;
2533
2961
  getMidpoints(venueMarketIds: string[], options?: {
2534
2962
  signal?: AbortSignal;
2963
+ bestPrice?: boolean;
2535
2964
  }): Promise<BatchMidpointsResponse>;
2536
2965
  /** Get a single outcome-level orderbook from the engine. */
2537
2966
  getOutcomeOrderbook(outcomeId: string, options?: {
@@ -2665,4 +3094,4 @@ declare function aggregateMidpoint(midpoints: (number | null | undefined)[]): nu
2665
3094
 
2666
3095
  declare function createAggClient(options: AggClientOptions): AggClient;
2667
3096
 
2668
- export { type Account, AccountProvider, AccountType, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BatchMidpointsResponse, type BatchOrderbooksResponse, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, type Candle, CandleBuilder, type CandleInterval, type Category, Chain, type ChartBarsResponse, type ChartCandle, type ChartResolution, type ChartVenueCandles, type ComputeSplitsRequest, type ComputeSplitsResponse, type ComputeSplitsSelection, type CreateApp, 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 ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionPositionGroup, type ExecutionPositionsQuery, type GetBalanceQuery, type GetBalanceResponse, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, ImageSize, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedOrderbookMarket, type MatchingReport, type MidpointItem, type MidpointRow, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, 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 PersistedAuthSnapshot, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PricesHistoryResponse, type QuoteManagedParams, type QuoteManagedRequest, type QuoteManagedResponse, type QuoteManagedSplit, type QuoteManagedStep, type QuoteSplit, type QuoteStep, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SimpleOrderbookLevel, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SyncBalancesResponse, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, 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 WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, 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, aggregateMidpoint, applyOrderbookDelta, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, getWalletAddressFromUserProfile, hasShape, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };
3097
+ export { type Account, AccountProvider, AccountType, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BatchMidpointsResponse, type BatchOrderbooksResponse, type BuildVenueUrlOpts, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, 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 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 ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionPositionGroup, type ExecutionPositionsQuery, type GetBalanceQuery, type GetBalanceResponse, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, ImageSize, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedMidpointOutcome, type MatchedOrderbookMarket, type MatchedVenueMarketOutcomeRef, type MatchingReport, type MidpointItem, type MidpointRow, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, 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 PersistedAuthSnapshot, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PriceSource, type PricesHistoryResponse, type QuoteManagedParams, type QuoteManagedRequest, type QuoteManagedResponse, type QuoteManagedSplit, type QuoteManagedStep, type QuoteSplit, type QuoteStep, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type ResolveCorrelatedMarketsParams, type ResolveCorrelatedMarketsResponse, type ResolvedCorrelatedMarketsResponse, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SimpleOrderbookLevel, type SmartRouteFeeBreakdown, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSetupCostLine, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SyncBalancesResponse, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, 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 WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, 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, aggregateMidpoint, applyOrderbookDelta, buildVenueUrl, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, formatOutcomeTitle, getWalletAddressFromUserProfile, hasShape, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };