@agg-build/hooks 1.2.0 → 1.2.12

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.
@@ -370,6 +370,12 @@ var enUsLabels = {
370
370
  max: "Max",
371
371
  tokenLabel: "Receive token",
372
372
  networkLabel: "Receive network",
373
+ estimatedFees: "Est. fees",
374
+ networkReserve: "Network reserve",
375
+ networkReserveTooltipAria: "Network reserve details",
376
+ networkReserveTooltipLineOne: "This reserve helps cover network and bridge costs.",
377
+ networkReserveTooltipLineTwo: "Any unused amount stays in your balance.",
378
+ youReceive: "You'll receive",
373
379
  confirm: "Confirm withdrawal",
374
380
  successTitle: "Withdrawal submitted",
375
381
  successDescription: (tokenSymbol) => `Your ${tokenSymbol} withdrawal is being processed and will arrive shortly.`,
@@ -378,12 +384,16 @@ var enUsLabels = {
378
384
  // terminal status — otherwise a finished withdrawal would keep showing
379
385
  // "submitted / processing" forever and force the user to hard-refresh.
380
386
  successTitleCompleted: "Withdrawal complete",
381
- successDescriptionCompleted: (tokenSymbol) => `Your ${tokenSymbol} withdrawal has been delivered.`,
387
+ successDescriptionCompleted: (tokenSymbol) => `Your ${tokenSymbol} has been successfully sent to your wallet.`,
382
388
  successTitlePartial: "Withdrawal partially completed",
383
- successDescriptionPartial: (tokenSymbol) => `Some legs of your ${tokenSymbol} withdrawal completed; see details below.`,
389
+ successDescriptionPartial: () => "Part of your withdrawal was completed successfully, but the remaining funds failed to transfer and were returned to your balance.",
384
390
  successTitleFailed: "Withdrawal failed",
385
- successDescriptionFailed: (tokenSymbol) => `Your ${tokenSymbol} withdrawal could not be completed.`,
391
+ successDescriptionFailed: () => "We couldn't complete your withdrawal. Your funds were returned to your balance.",
392
+ retry: "Try Again",
393
+ close: "Close",
394
+ loadingDescription: "This may take a few minutes. You can safely close this window and check the status later in your activity.",
386
395
  summary: {
396
+ requestedWithdrawal: "Requested withdrawal",
387
397
  // The response is `pricingStatus: "unquoted"` — we don't know net
388
398
  // output until on-chain settlement. Calling this "Amount received"
389
399
  // would imply receipt before the lifecycle has confirmed. Keep it
@@ -401,6 +411,12 @@ var enUsLabels = {
401
411
  completed: "Withdrawal complete.",
402
412
  partial: "Withdrawal partially completed \u2014 see details below.",
403
413
  failed: "Withdrawal failed.",
414
+ loadingSteps: {
415
+ preparing: "Preparing funds",
416
+ bridging: "Bridging between networks",
417
+ sending: "Sending to your wallet",
418
+ confirming: "Waiting for network confirmation"
419
+ },
404
420
  steps: {
405
421
  bridge: (sourceChainName, destChainName) => `Bridging from ${sourceChainName} to ${destChainName}`,
406
422
  transfer: (destChainName) => `Transferring on ${destChainName}`
@@ -456,10 +472,37 @@ var enUsLabels = {
456
472
  externalWallet: "Deposit from external wallet",
457
473
  card: "Deposit with card"
458
474
  },
475
+ depositStatusTitles: {
476
+ connectedWallet: {
477
+ pending: "Processing deposit from connected wallet",
478
+ completed: "Successful deposit from connected wallet",
479
+ failed: "Failed deposit from connected wallet",
480
+ canceled: "Canceled deposit from connected wallet"
481
+ },
482
+ externalWallet: {
483
+ pending: "Processing deposit from external wallet",
484
+ completed: "Successful deposit from external wallet",
485
+ failed: "Failed deposit from external wallet",
486
+ canceled: "Canceled deposit from external wallet"
487
+ },
488
+ card: {
489
+ pending: "Processing deposit with card",
490
+ completed: "Successful deposit with card",
491
+ failed: "Failed deposit with card",
492
+ canceled: "Canceled deposit with card"
493
+ }
494
+ },
495
+ withdrawalStatusTitles: {
496
+ pending: "Processing withdrawal",
497
+ completed: "Successful withdrawal",
498
+ failed: "Failed withdrawal",
499
+ canceled: "Canceled withdrawal"
500
+ },
459
501
  // Activity-row title for any withdrawal regardless of lifecycle
460
- // state (pending / completed / failed) — render the asset rather
461
- // than implying success. The ActivityRow renders a separate status
462
- // chip when the row is failed.
502
+ // state — render the asset rather than implying success. The
503
+ // ActivityRow renders a separate status chip when the row is
504
+ // failed. Retained for partner overrides that still want a
505
+ // status-agnostic title.
463
506
  withdrawalTitle: (tokenSymbol) => `Withdraw ${tokenSymbol}`
464
507
  },
465
508
  positions: {
@@ -494,6 +537,15 @@ var enUsLabels = {
494
537
  eventList: {
495
538
  matchedTab: "Matched",
496
539
  allTab: "All",
540
+ sortByLabel: "Sort by",
541
+ sortBy24hVolume: "24h volume",
542
+ sortByTopArbitrage: "Top arbitrage",
543
+ sortByTotalVolume: "Total volume",
544
+ sortByEndingSoon: "Ending soon",
545
+ subcategoriesLabel: "Subcategories",
546
+ subcategoriesAll: "All",
547
+ subcategoriesOpenAria: "Open subcategories",
548
+ subcategoriesCloseAria: "Close subcategories",
497
549
  loading: (title) => `Loading ${title}`,
498
550
  tabsAria: (title) => `${title} tabs`,
499
551
  emptyAria: "No events found",
@@ -680,6 +732,19 @@ var enUsLabels = {
680
732
  noMarketSelected: "Select a market to place an order.",
681
733
  noOrderbooks: "No live orderbooks are available for this market right now.",
682
734
  quoteUnavailable: "Quote temporarily unavailable. Please try again.",
735
+ quoteBalanceMismatch: "Quote balance mismatch. Try a different amount.",
736
+ serviceTemporarilyUnavailable: "Service temporarily unavailable. Please try again in a moment.",
737
+ orderDeadlineExpiredBeforeSubmission: "Order deadline expired before submission. Please try again.",
738
+ sellNoOnchainPosition: "You don't currently hold any on-chain shares of this outcome. If you just sold or redeemed elsewhere, your position display will refresh shortly \u2014 try again after that.",
739
+ venueQuoteUnfillable: "The venue couldn't fill this order at the quoted price right now. Try a smaller size, a higher slippage tolerance, or wait a moment and re-quote.",
740
+ venueMinOrderSize: "Order size is below the venue minimum. Try a larger amount.",
741
+ sourceBalanceChanged: "Your balance changed since the quote. Refresh and try again, or pick a smaller amount.",
742
+ venueMarketResolved: "This market just resolved. Pick a different market or wait for the next round.",
743
+ dflowWalletUnverified: "Your Solana wallet needs to be verified with dFlow before you can trade Kalshi markets. Verify at https://dflow.net/proof, then try again.",
744
+ venueNoQuotePath: "No active quote path for this market right now. Try a different size, or wait a moment and re-quote.",
745
+ solanaBlockhashExpired: "Solana transaction expired before submission. Please re-quote and try again.",
746
+ venueRateLimited: "The venue is rate-limiting requests right now. Please wait a moment and try again.",
747
+ serviceBlockedOrder: "Something on our side blocked this order. Please contact support if it keeps happening \u2014 retrying with the same quote will hit the same issue.",
683
748
  selectedVenueUnavailable: "The venue you selected is no longer available on this route. Review the updated options and try again.",
684
749
  engineUnavailable: "The routing engine is temporarily unavailable. Please try again in a moment.",
685
750
  insufficientInputAmount: "Trade amount is too small to cover bridging and execution costs. Increase your spend or deposit funds on the destination chain.",
@@ -693,6 +758,7 @@ var enUsLabels = {
693
758
  deposit: "Deposit",
694
759
  kycRequired: "Verify to trade Kalshi",
695
760
  kycNotVerifiedTooltip: "You have not been verified yet",
761
+ kycVerify: "Verify Identity",
696
762
  kycVerifyModalTitle: "Verify Your Identity",
697
763
  kycVerifyModalDescription: "To start trading on Kalshi, you'll need to complete identity verification through dFlow. It only takes a few minutes and helps us stay compliant with regulations.",
698
764
  kycStartVerification: "Start Verification",
@@ -706,6 +772,7 @@ var enUsLabels = {
706
772
  splitOrderDescription: "We split your order for the best price:",
707
773
  viewAllRoutes: (count) => `View all (${count})`,
708
774
  venueUnavailableInRegion: "Unavailable in your region",
775
+ verified: "Verified",
709
776
  platformFee: "0% platform fees",
710
777
  estimatedFees: "Estimated fees",
711
778
  estimatedFeesTooltipAria: "Estimated fees breakdown",
@@ -717,6 +784,7 @@ var enUsLabels = {
717
784
  buyingOutcome: (label) => `Buying ${label}`,
718
785
  sellingOutcome: (label) => `Selling ${label}`,
719
786
  findingBestRoute: "Finding the best route...",
787
+ checkingBalance: "Checking balance",
720
788
  submittingOrderProgress: "Submitting order...",
721
789
  orderSubmittedProgress: (orderId) => `Order #${orderId.replace(/^#/, "")} submitted`,
722
790
  executingOnVenue: (venueLabel) => `Executing on ${venueLabel}...`,
@@ -896,6 +964,57 @@ var enUsLabels = {
896
964
  header: {
897
965
  bannerAria: "Site header",
898
966
  logoAria: "Home"
967
+ },
968
+ notifications: {
969
+ order: {
970
+ filledTitle: "Order filled",
971
+ filledMessage: ({ venueLabel, sideLabel, amountLabel, priceLabel }) => {
972
+ const action = sideLabel ? `${sideLabel} filled` : "Filled";
973
+ const amount = amountLabel ? ` ${amountLabel}` : "";
974
+ const price = priceLabel ? ` at ${priceLabel}` : "";
975
+ const venue = venueLabel ? ` on ${venueLabel}` : "";
976
+ return `${action}${amount}${price}${venue}`.trim();
977
+ },
978
+ partialFilledTitle: "Order partially filled",
979
+ partialFilledMessage: ({ venueLabel, sideLabel, amountLabel, priceLabel }) => {
980
+ const action = sideLabel ? `${sideLabel} partially filled` : "Partially filled";
981
+ const amount = amountLabel ? ` ${amountLabel}` : "";
982
+ const price = priceLabel ? ` at ${priceLabel}` : "";
983
+ const venue = venueLabel ? ` on ${venueLabel}` : "";
984
+ return `${action}${amount}${price}${venue}`.trim();
985
+ },
986
+ failedTitle: "Order failed",
987
+ failedMessage: (errorReason) => errorReason && errorReason.length > 0 ? errorReason : "Your order could not be completed. Please try again."
988
+ },
989
+ deposit: {
990
+ completedTitle: "Deposit complete",
991
+ completedMessage: ({ amountLabel, tokenLabel }) => {
992
+ if (amountLabel && tokenLabel) return `${amountLabel} ${tokenLabel} added to your balance.`;
993
+ if (tokenLabel) return `Your ${tokenLabel} has been added to your balance.`;
994
+ return "Your funds have been added to your balance.";
995
+ },
996
+ failedTitle: "Deposit failed",
997
+ failedMessage: ({ amountLabel, tokenLabel }) => {
998
+ const what = amountLabel && tokenLabel ? `${amountLabel} ${tokenLabel}` : "deposit";
999
+ return `We couldn't complete your ${what}.`;
1000
+ }
1001
+ },
1002
+ withdrawal: {
1003
+ completedTitle: "Withdrawal complete",
1004
+ completedMessage: ({ amountLabel, tokenLabel }) => {
1005
+ if (amountLabel && tokenLabel) return `${amountLabel} ${tokenLabel} sent to your wallet.`;
1006
+ if (tokenLabel) return `Your ${tokenLabel} has been sent to your wallet.`;
1007
+ return "Your withdrawal has been sent to your wallet.";
1008
+ },
1009
+ partialTitle: "Withdrawal partially completed",
1010
+ partialMessage: ({ amountLabel, tokenLabel }) => {
1011
+ if (amountLabel && tokenLabel)
1012
+ return `Part of your ${tokenLabel} was sent. The remainder was returned to your balance.`;
1013
+ return "Part of your withdrawal was sent. The remainder was returned to your balance.";
1014
+ },
1015
+ failedTitle: "Withdrawal failed",
1016
+ failedMessage: (errorReason) => errorReason && errorReason.length > 0 ? errorReason : "Your funds have been returned to your balance."
1017
+ }
899
1018
  }
900
1019
  };
901
1020
  var defaultAggUiLabelsByLocale = {
@@ -975,6 +1094,7 @@ var defaultAggUiSearchConfig = {
975
1094
  var defaultAggUiConfig = {
976
1095
  enableLogs: false,
977
1096
  enableWebsocketsLogs: false,
1097
+ enableDebug: false,
978
1098
  general: {
979
1099
  locale: DEFAULT_LOCALE,
980
1100
  theme: "light",
@@ -985,7 +1105,9 @@ var defaultAggUiConfig = {
985
1105
  enableAnimations: true,
986
1106
  enableLiveUpdates: true,
987
1107
  showFeesBreakdown: false,
988
- enableGradients: false
1108
+ enableGradients: false,
1109
+ enableVenueEventDiscoveryFilters: false,
1110
+ enableNotifications: true
989
1111
  },
990
1112
  market: {
991
1113
  arbitrageThreshold: 0
@@ -1012,7 +1134,7 @@ var mergeAggUiSearchConfig = (config) => {
1012
1134
  };
1013
1135
  };
1014
1136
  var mergeAggUiConfig = (persisted, config) => {
1015
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M;
1137
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R;
1016
1138
  const locale = (_d = (_c = (_a = config == null ? void 0 : config.general) == null ? void 0 : _a.locale) != null ? _c : (_b = persisted.general) == null ? void 0 : _b.locale) != null ? _d : DEFAULT_LOCALE;
1017
1139
  const theme = (_h = (_g = (_e = config == null ? void 0 : config.general) == null ? void 0 : _e.theme) != null ? _g : (_f = persisted.general) == null ? void 0 : _f.theme) != null ? _h : defaultAggUiConfig.general.theme;
1018
1140
  const formatters = createFormatters(locale);
@@ -1020,32 +1142,35 @@ var mergeAggUiConfig = (persisted, config) => {
1020
1142
  return {
1021
1143
  enableLogs: (_i = config == null ? void 0 : config.enableLogs) != null ? _i : defaultAggUiConfig.enableLogs,
1022
1144
  enableWebsocketsLogs: (_j = config == null ? void 0 : config.enableWebsocketsLogs) != null ? _j : defaultAggUiConfig.enableWebsocketsLogs,
1145
+ enableDebug: (_k = config == null ? void 0 : config.enableDebug) != null ? _k : defaultAggUiConfig.enableDebug,
1023
1146
  general: {
1024
1147
  locale,
1025
1148
  theme,
1026
- rootClassName: (_l = (_k = config == null ? void 0 : config.general) == null ? void 0 : _k.rootClassName) != null ? _l : defaultAggUiConfig.general.rootClassName,
1027
- labels: mergeAggUiLabels(defaultLabels, (_m = config == null ? void 0 : config.general) == null ? void 0 : _m.labels)
1149
+ rootClassName: (_m = (_l = config == null ? void 0 : config.general) == null ? void 0 : _l.rootClassName) != null ? _m : defaultAggUiConfig.general.rootClassName,
1150
+ labels: mergeAggUiLabels(defaultLabels, (_n = config == null ? void 0 : config.general) == null ? void 0 : _n.labels)
1028
1151
  },
1029
1152
  features: {
1030
- enableAnimations: (_o = (_n = config == null ? void 0 : config.features) == null ? void 0 : _n.enableAnimations) != null ? _o : defaultAggUiConfig.features.enableAnimations,
1031
- enableLiveUpdates: (_q = (_p = config == null ? void 0 : config.features) == null ? void 0 : _p.enableLiveUpdates) != null ? _q : defaultAggUiConfig.features.enableLiveUpdates,
1032
- showFeesBreakdown: (_s = (_r = config == null ? void 0 : config.features) == null ? void 0 : _r.showFeesBreakdown) != null ? _s : defaultAggUiConfig.features.showFeesBreakdown,
1033
- enableGradients: (_u = (_t = config == null ? void 0 : config.features) == null ? void 0 : _t.enableGradients) != null ? _u : defaultAggUiConfig.features.enableGradients
1153
+ enableAnimations: (_p = (_o = config == null ? void 0 : config.features) == null ? void 0 : _o.enableAnimations) != null ? _p : defaultAggUiConfig.features.enableAnimations,
1154
+ enableLiveUpdates: (_r = (_q = config == null ? void 0 : config.features) == null ? void 0 : _q.enableLiveUpdates) != null ? _r : defaultAggUiConfig.features.enableLiveUpdates,
1155
+ showFeesBreakdown: (_t = (_s = config == null ? void 0 : config.features) == null ? void 0 : _s.showFeesBreakdown) != null ? _t : defaultAggUiConfig.features.showFeesBreakdown,
1156
+ enableGradients: (_v = (_u = config == null ? void 0 : config.features) == null ? void 0 : _u.enableGradients) != null ? _v : defaultAggUiConfig.features.enableGradients,
1157
+ enableVenueEventDiscoveryFilters: (_x = (_w = config == null ? void 0 : config.features) == null ? void 0 : _w.enableVenueEventDiscoveryFilters) != null ? _x : defaultAggUiConfig.features.enableVenueEventDiscoveryFilters,
1158
+ enableNotifications: (_z = (_y = config == null ? void 0 : config.features) == null ? void 0 : _y.enableNotifications) != null ? _z : defaultAggUiConfig.features.enableNotifications
1034
1159
  },
1035
1160
  market: {
1036
- arbitrageThreshold: (_w = (_v = config == null ? void 0 : config.market) == null ? void 0 : _v.arbitrageThreshold) != null ? _w : defaultAggUiConfig.market.arbitrageThreshold
1161
+ arbitrageThreshold: (_B = (_A = config == null ? void 0 : config.market) == null ? void 0 : _A.arbitrageThreshold) != null ? _B : defaultAggUiConfig.market.arbitrageThreshold
1037
1162
  },
1038
1163
  chart: {
1039
- defaultChartTimeRange: (_y = (_x = config == null ? void 0 : config.chart) == null ? void 0 : _x.defaultChartTimeRange) != null ? _y : defaultAggUiConfig.chart.defaultChartTimeRange,
1040
- selectedChartTimeRange: (_C = (_B = (_z = persisted.chart) == null ? void 0 : _z.selectedChartTimeRange) != null ? _B : (_A = config == null ? void 0 : config.chart) == null ? void 0 : _A.defaultChartTimeRange) != null ? _C : defaultAggUiConfig.chart.defaultChartTimeRange,
1164
+ defaultChartTimeRange: (_D = (_C = config == null ? void 0 : config.chart) == null ? void 0 : _C.defaultChartTimeRange) != null ? _D : defaultAggUiConfig.chart.defaultChartTimeRange,
1165
+ selectedChartTimeRange: (_H = (_G = (_E = persisted.chart) == null ? void 0 : _E.selectedChartTimeRange) != null ? _G : (_F = config == null ? void 0 : config.chart) == null ? void 0 : _F.defaultChartTimeRange) != null ? _H : defaultAggUiConfig.chart.defaultChartTimeRange,
1041
1166
  setSelectedChartTimeRange: defaultAggUiConfig.chart.setSelectedChartTimeRange
1042
1167
  },
1043
1168
  formatting: {
1044
- formatNumber: (_E = (_D = config == null ? void 0 : config.formatting) == null ? void 0 : _D.formatNumber) != null ? _E : formatters.formatNumber,
1045
- formatPercent: (_G = (_F = config == null ? void 0 : config.formatting) == null ? void 0 : _F.formatPercent) != null ? _G : formatters.formatPercent,
1046
- formatCurrency: (_I = (_H = config == null ? void 0 : config.formatting) == null ? void 0 : _H.formatCurrency) != null ? _I : formatters.formatCurrency,
1047
- formatCompactCurrency: (_K = (_J = config == null ? void 0 : config.formatting) == null ? void 0 : _J.formatCompactCurrency) != null ? _K : formatters.formatCompactCurrency,
1048
- formatDate: (_M = (_L = config == null ? void 0 : config.formatting) == null ? void 0 : _L.formatDate) != null ? _M : formatters.formatDate
1169
+ formatNumber: (_J = (_I = config == null ? void 0 : config.formatting) == null ? void 0 : _I.formatNumber) != null ? _J : formatters.formatNumber,
1170
+ formatPercent: (_L = (_K = config == null ? void 0 : config.formatting) == null ? void 0 : _K.formatPercent) != null ? _L : formatters.formatPercent,
1171
+ formatCurrency: (_N = (_M = config == null ? void 0 : config.formatting) == null ? void 0 : _M.formatCurrency) != null ? _N : formatters.formatCurrency,
1172
+ formatCompactCurrency: (_P = (_O = config == null ? void 0 : config.formatting) == null ? void 0 : _O.formatCompactCurrency) != null ? _P : formatters.formatCompactCurrency,
1173
+ formatDate: (_R = (_Q = config == null ? void 0 : config.formatting) == null ? void 0 : _Q.formatDate) != null ? _R : formatters.formatDate
1049
1174
  },
1050
1175
  search: mergeAggUiSearchConfig(config == null ? void 0 : config.search),
1051
1176
  walletActions: config == null ? void 0 : config.walletActions,
@@ -1108,6 +1233,26 @@ var shouldInvalidateBalancesForOrderEvent = (event, currentUserId) => {
1108
1233
  if (!currentUserId) return true;
1109
1234
  return event.userId === currentUserId;
1110
1235
  };
1236
+ var userActivityQueryKeys = {
1237
+ all: () => ["user-activity"]
1238
+ };
1239
+ var invalidateUserActivityQueries = (queryClient, options) => {
1240
+ var _a;
1241
+ const strategy = (_a = options == null ? void 0 : options.strategy) != null ? _a : "remove";
1242
+ if (strategy === "remove") {
1243
+ queryClient.removeQueries({ queryKey: userActivityQueryKeys.all() });
1244
+ return;
1245
+ }
1246
+ queryClient.invalidateQueries({
1247
+ queryKey: userActivityQueryKeys.all(),
1248
+ refetchType: "all"
1249
+ });
1250
+ };
1251
+ var invalidateUserMoneyState = (queryClient, options) => {
1252
+ invalidateBalanceQueries(queryClient, { refetchType: options == null ? void 0 : options.refetchType });
1253
+ invalidatePositionQueries(queryClient, { refetchType: options == null ? void 0 : options.refetchType });
1254
+ invalidateUserActivityQueries(queryClient, { strategy: options == null ? void 0 : options.activityStrategy });
1255
+ };
1111
1256
 
1112
1257
  // src/core/providers/balance-provider.tsx
1113
1258
  import { useQuery } from "@tanstack/react-query";
@@ -1128,6 +1273,7 @@ var CHAIN_LABELS = {
1128
1273
  10: "Optimism",
1129
1274
  56: "BNB",
1130
1275
  137: "Polygon",
1276
+ 1337: "Hyperliquid",
1131
1277
  8453: "Base",
1132
1278
  42161: "Arbitrum",
1133
1279
  43114: "Avalanche",
@@ -1167,7 +1313,9 @@ function AggBalanceProvider({ children }) {
1167
1313
  return client.getManagedBalances();
1168
1314
  }),
1169
1315
  enabled: Boolean(client && isAuthenticated),
1170
- staleTime: 1e4
1316
+ staleTime: 60 * 1e3,
1317
+ refetchOnWindowFocus: "always",
1318
+ refetchOnReconnect: "always"
1171
1319
  });
1172
1320
  const managedBalancesData = balancesQuery.data;
1173
1321
  const managedBalances = useMemo(
@@ -1325,6 +1473,9 @@ var useAggClient = () => {
1325
1473
  }
1326
1474
  return client;
1327
1475
  };
1476
+ var useOptionalAggClient = () => {
1477
+ return useContext3(AggClientContext);
1478
+ };
1328
1479
  var useAggUiConfig = () => {
1329
1480
  return useContext3(AggUiContext);
1330
1481
  };
@@ -1365,6 +1516,7 @@ import {
1365
1516
  import { useQueryClient } from "@tanstack/react-query";
1366
1517
 
1367
1518
  // src/market-data/chart-cache.ts
1519
+ var MAX_CACHE_RETENTION_SECONDS = 7 * 30 * 24 * 60 * 60 + 14 * 24 * 60 * 60;
1368
1520
  var getIntervalSeconds = (interval) => {
1369
1521
  switch (interval) {
1370
1522
  case "1m":
@@ -1383,12 +1535,41 @@ var createVenueData = (venue, outcomeIds = []) => ({
1383
1535
  candles: [],
1384
1536
  liveCandle: null,
1385
1537
  lineValue: void 0,
1386
- lastTrade: null
1538
+ lastTrade: null,
1539
+ lastUpdateTs: null
1387
1540
  });
1541
+ var pruneCandlesBefore = (candles, cutoffTs) => {
1542
+ if (cutoffTs <= 0) return candles;
1543
+ let firstKeptIndex = 0;
1544
+ while (firstKeptIndex < candles.length && candles[firstKeptIndex].time < cutoffTs) {
1545
+ firstKeptIndex += 1;
1546
+ }
1547
+ if (firstKeptIndex === 0) return candles;
1548
+ return candles.slice(firstKeptIndex);
1549
+ };
1550
+ var promoteClosedLiveCandle = (candles, liveCandle, expectedCandleTime) => {
1551
+ if (!liveCandle || liveCandle.time >= expectedCandleTime) {
1552
+ return { candles, promoted: false };
1553
+ }
1554
+ if (candles.some((candle) => candle.time === liveCandle.time)) {
1555
+ return { candles, promoted: false };
1556
+ }
1557
+ return { candles: sortCandles([...candles, liveCandle]), promoted: true };
1558
+ };
1559
+ var resolveMaxLastUpdateTs = (venues) => {
1560
+ let max = null;
1561
+ for (const venueData of Object.values(venues)) {
1562
+ if (venueData.lastUpdateTs != null && (max == null || venueData.lastUpdateTs > max)) {
1563
+ max = venueData.lastUpdateTs;
1564
+ }
1565
+ }
1566
+ return max;
1567
+ };
1388
1568
  var sortCandles = (candles) => {
1389
1569
  return [...candles].sort((left, right) => left.time - right.time);
1390
1570
  };
1391
1571
  var createMarketChartData = (params) => {
1572
+ var _a;
1392
1573
  const candles = sortCandles(
1393
1574
  params.response.data.map((candle) => ({
1394
1575
  time: Math.floor(candle.t / 1e3),
@@ -1401,6 +1582,7 @@ var createMarketChartData = (params) => {
1401
1582
  }))
1402
1583
  );
1403
1584
  const lastCandle = candles[candles.length - 1];
1585
+ const lastUpdateTs = (_a = lastCandle == null ? void 0 : lastCandle.time) != null ? _a : null;
1404
1586
  const venues = {
1405
1587
  [params.response.venue]: {
1406
1588
  venue: params.response.venue,
@@ -1408,7 +1590,8 @@ var createMarketChartData = (params) => {
1408
1590
  candles,
1409
1591
  liveCandle: null,
1410
1592
  lineValue: lastCandle == null ? void 0 : lastCandle.close,
1411
- lastTrade: null
1593
+ lastTrade: null,
1594
+ lastUpdateTs
1412
1595
  }
1413
1596
  };
1414
1597
  return {
@@ -1418,7 +1601,8 @@ var createMarketChartData = (params) => {
1418
1601
  interval: params.interval,
1419
1602
  startTs: params.startTs,
1420
1603
  endTs: params.endTs,
1421
- venues
1604
+ venues,
1605
+ lastUpdateTs
1422
1606
  };
1423
1607
  };
1424
1608
  var mergeMarketChartData = (params) => {
@@ -1452,9 +1636,75 @@ var mergeMarketChartData = (params) => {
1452
1636
  interval: params.interval,
1453
1637
  startTs: params.startTs,
1454
1638
  endTs: params.endTs,
1455
- venues
1639
+ venues,
1640
+ lastUpdateTs: resolveMaxLastUpdateTs(venues)
1456
1641
  };
1457
1642
  };
1643
+ var applyMidpointToMarketChart = (data, update) => {
1644
+ var _a;
1645
+ if (!data || !Number.isFinite(update.midpoint)) {
1646
+ return data;
1647
+ }
1648
+ const targetVenueEntry = Object.entries(data.venues).find(
1649
+ ([, venueData]) => venueData.outcomeIds.includes(update.outcomeId)
1650
+ );
1651
+ if (!targetVenueEntry && data.marketId !== update.outcomeId) {
1652
+ return data;
1653
+ }
1654
+ const [targetVenueName, currentVenue] = targetVenueEntry != null ? targetVenueEntry : [
1655
+ data.primaryVenue,
1656
+ (_a = data.venues[data.primaryVenue]) != null ? _a : createVenueData(data.primaryVenue, [update.outcomeId])
1657
+ ];
1658
+ const intervalSeconds = getIntervalSeconds(data.interval);
1659
+ const expectedCandleTime = update.timestamp - update.timestamp % intervalSeconds;
1660
+ let liveCandle = currentVenue.liveCandle;
1661
+ const { candles: promotedCandles } = promoteClosedLiveCandle(
1662
+ currentVenue.candles,
1663
+ liveCandle,
1664
+ expectedCandleTime
1665
+ );
1666
+ const nextCandles = pruneCandlesBefore(
1667
+ promotedCandles,
1668
+ update.timestamp - MAX_CACHE_RETENTION_SECONDS
1669
+ );
1670
+ if (liveCandle && liveCandle.time === expectedCandleTime) {
1671
+ if (liveCandle.source === "trade") {
1672
+ liveCandle = __spreadProps(__spreadValues({}, liveCandle), {
1673
+ close: update.midpoint
1674
+ });
1675
+ } else {
1676
+ liveCandle = __spreadProps(__spreadValues({}, liveCandle), {
1677
+ close: update.midpoint,
1678
+ high: Math.max(liveCandle.high, update.midpoint),
1679
+ low: Math.min(liveCandle.low, update.midpoint),
1680
+ source: "midpoint"
1681
+ });
1682
+ }
1683
+ } else {
1684
+ liveCandle = {
1685
+ time: expectedCandleTime,
1686
+ open: update.midpoint,
1687
+ high: update.midpoint,
1688
+ low: update.midpoint,
1689
+ close: update.midpoint,
1690
+ volume: 0,
1691
+ source: "midpoint"
1692
+ };
1693
+ }
1694
+ const nextVenues = __spreadProps(__spreadValues({}, data.venues), {
1695
+ [targetVenueName]: __spreadProps(__spreadValues({}, currentVenue), {
1696
+ outcomeIds: currentVenue.outcomeIds.includes(update.outcomeId) ? currentVenue.outcomeIds : [...currentVenue.outcomeIds, update.outcomeId],
1697
+ candles: nextCandles,
1698
+ liveCandle,
1699
+ lineValue: update.midpoint,
1700
+ lastUpdateTs: update.timestamp
1701
+ })
1702
+ });
1703
+ return __spreadProps(__spreadValues({}, data), {
1704
+ venues: nextVenues,
1705
+ lastUpdateTs: resolveMaxLastUpdateTs(nextVenues)
1706
+ });
1707
+ };
1458
1708
  var applyTradeToMarketChart = (data, trade) => {
1459
1709
  var _a, _b, _c;
1460
1710
  if (!data || data.marketId !== trade.outcomeId) {
@@ -1464,6 +1714,15 @@ var applyTradeToMarketChart = (data, trade) => {
1464
1714
  const intervalSeconds = getIntervalSeconds(data.interval);
1465
1715
  const expectedCandleTime = trade.timestamp - trade.timestamp % intervalSeconds;
1466
1716
  let liveCandle = currentVenue.liveCandle;
1717
+ const { candles: promotedCandles } = promoteClosedLiveCandle(
1718
+ currentVenue.candles,
1719
+ liveCandle,
1720
+ expectedCandleTime
1721
+ );
1722
+ const nextCandles = pruneCandlesBefore(
1723
+ promotedCandles,
1724
+ trade.timestamp - MAX_CACHE_RETENTION_SECONDS
1725
+ );
1467
1726
  if (liveCandle && liveCandle.time === expectedCandleTime) {
1468
1727
  liveCandle = __spreadProps(__spreadValues({}, liveCandle), {
1469
1728
  close: trade.price,
@@ -1483,16 +1742,20 @@ var applyTradeToMarketChart = (data, trade) => {
1483
1742
  source: "trade"
1484
1743
  };
1485
1744
  }
1486
- return __spreadProps(__spreadValues({}, data), {
1487
- venues: __spreadProps(__spreadValues({}, data.venues), {
1488
- [trade.venue]: __spreadProps(__spreadValues({}, currentVenue), {
1489
- outcomeIds: currentVenue.outcomeIds.includes(trade.outcomeId) ? currentVenue.outcomeIds : [...currentVenue.outcomeIds, trade.outcomeId],
1490
- liveCandle,
1491
- lineValue: (_c = liveCandle == null ? void 0 : liveCandle.close) != null ? _c : trade.price,
1492
- lastTrade: trade
1493
- })
1745
+ const nextVenues = __spreadProps(__spreadValues({}, data.venues), {
1746
+ [trade.venue]: __spreadProps(__spreadValues({}, currentVenue), {
1747
+ outcomeIds: currentVenue.outcomeIds.includes(trade.outcomeId) ? currentVenue.outcomeIds : [...currentVenue.outcomeIds, trade.outcomeId],
1748
+ candles: nextCandles,
1749
+ liveCandle,
1750
+ lineValue: (_c = liveCandle == null ? void 0 : liveCandle.close) != null ? _c : trade.price,
1751
+ lastTrade: trade,
1752
+ lastUpdateTs: trade.timestamp
1494
1753
  })
1495
1754
  });
1755
+ return __spreadProps(__spreadValues({}, data), {
1756
+ venues: nextVenues,
1757
+ lastUpdateTs: resolveMaxLastUpdateTs(nextVenues)
1758
+ });
1496
1759
  };
1497
1760
 
1498
1761
  // src/market-data/live-cache.ts
@@ -1683,7 +1946,15 @@ var marketDataKeys = {
1683
1946
  orderbook: (marketId, selectionKey, depth) => ["market-data", "orderbook", marketId, selectionKey != null ? selectionKey : null, depth != null ? depth : null],
1684
1947
  orderbookPrefix: (marketId) => marketId == null ? ["market-data", "orderbook"] : ["market-data", "orderbook", marketId],
1685
1948
  orderbookQuote: (marketId, side, size) => ["market-data", "orderbook-quote", marketId, side, size],
1686
- chart: (marketId, interval, startTs, endTs, countBack) => ["market-data", "chart", marketId, interval, startTs, endTs, countBack != null ? countBack : null],
1949
+ /**
1950
+ * Stable per `{marketId, interval, rangeKey}`. Deliberately excludes the
1951
+ * concrete `startTs`/`endTs` of the rolling window — those advance every
1952
+ * candle bucket, and including them would mint a fresh key on every
1953
+ * rollover, defeating React Query's cache on tab/page revisits. The
1954
+ * current window is passed to `queryFn` via closure instead, and
1955
+ * `refetchInterval` advances the data under the stable key.
1956
+ */
1957
+ chart: (marketId, interval, rangeKey, countBack) => ["market-data", "chart", marketId, interval, rangeKey, countBack != null ? countBack : null],
1687
1958
  chartPrefix: (marketId, interval) => {
1688
1959
  if (!marketId) return ["market-data", "chart"];
1689
1960
  if (!interval) return ["market-data", "chart", marketId];
@@ -1892,6 +2163,9 @@ function AggWebSocketProvider({ children }) {
1892
2163
  const invalidatePositionCaches = useCallback3(() => {
1893
2164
  invalidatePositionQueries(queryClient);
1894
2165
  }, [queryClient]);
2166
+ const invalidateActivityCaches = useCallback3(() => {
2167
+ invalidateUserActivityQueries(queryClient);
2168
+ }, [queryClient]);
1895
2169
  const callbacks = useMemo2(
1896
2170
  () => ({
1897
2171
  onSnapshot: (marketId, book) => {
@@ -1910,6 +2184,14 @@ function AggWebSocketProvider({ children }) {
1910
2184
  syncLiveQuery(marketId, (previous) => withLiveOrderbook(previous, book, "snapshot"));
1911
2185
  if (book.midpoint != null) {
1912
2186
  getOrCreateBuilder(marketId).addMidpoint(book.midpoint, book.timestamp);
2187
+ syncChartQueries(
2188
+ marketId,
2189
+ (_queryKey, previous) => applyMidpointToMarketChart(previous, {
2190
+ outcomeId: marketId,
2191
+ midpoint: book.midpoint,
2192
+ timestamp: book.timestamp
2193
+ })
2194
+ );
1913
2195
  }
1914
2196
  },
1915
2197
  onDelta: (marketId, book) => {
@@ -1955,6 +2237,14 @@ function AggWebSocketProvider({ children }) {
1955
2237
  });
1956
2238
  if (book.midpoint != null) {
1957
2239
  getOrCreateBuilder(marketId).addMidpoint(book.midpoint, book.timestamp);
2240
+ syncChartQueries(
2241
+ marketId,
2242
+ (_queryKey, previous) => applyMidpointToMarketChart(previous, {
2243
+ outcomeId: marketId,
2244
+ midpoint: book.midpoint,
2245
+ timestamp: book.timestamp
2246
+ })
2247
+ );
1958
2248
  }
1959
2249
  },
1960
2250
  onTrade: (trade) => {
@@ -1992,6 +2282,7 @@ function AggWebSocketProvider({ children }) {
1992
2282
  onBalanceUpdate: (msg) => {
1993
2283
  if (isClientAuthenticated) {
1994
2284
  invalidateBalanceCaches();
2285
+ invalidateActivityCaches();
1995
2286
  }
1996
2287
  for (const listener of balanceUpdateListenersRef.current) {
1997
2288
  listener(msg);
@@ -2057,6 +2348,7 @@ function AggWebSocketProvider({ children }) {
2057
2348
  [
2058
2349
  client,
2059
2350
  enableWebsocketsLogs,
2351
+ invalidateActivityCaches,
2060
2352
  invalidateBalanceCaches,
2061
2353
  invalidatePositionCaches,
2062
2354
  isClientAuthenticated,
@@ -2120,9 +2412,26 @@ var resolveTradingStateKind = (status) => {
2120
2412
  return "closed";
2121
2413
  };
2122
2414
  var resolveMarketWinningOutcome = (market) => {
2123
- var _a;
2415
+ var _a, _b, _c, _d;
2124
2416
  if (!market) return null;
2125
- return (_a = market.venueMarketOutcomes.find((outcome) => outcome.winner === true)) != null ? _a : null;
2417
+ const localWinningOutcome = (_a = market.venueMarketOutcomes.find((outcome) => outcome.winner === true)) != null ? _a : null;
2418
+ if (localWinningOutcome) return localWinningOutcome;
2419
+ const matchedVenueMarkets = (_b = market.matchedVenueMarkets) != null ? _b : [];
2420
+ if (!matchedVenueMarkets.length) return null;
2421
+ for (const outcome of market.venueMarketOutcomes) {
2422
+ const matchedRefs = (_c = outcome.matchedVenueMarketOutcomes) != null ? _c : [];
2423
+ for (const ref of matchedRefs) {
2424
+ const matchedMarket = matchedVenueMarkets.find((item) => item.id === ref.venueMarketId);
2425
+ if (!matchedMarket) continue;
2426
+ const matchedOutcome = (_d = matchedMarket.venueMarketOutcomes) == null ? void 0 : _d.find(
2427
+ (item) => item.id === ref.venueMarketOutcomeId
2428
+ );
2429
+ if ((matchedOutcome == null ? void 0 : matchedOutcome.winner) === true) {
2430
+ return outcome;
2431
+ }
2432
+ }
2433
+ }
2434
+ return null;
2126
2435
  };
2127
2436
  var AFFIRMATIVE_WINNER_LABELS = /* @__PURE__ */ new Set(["yes", "up", "buy", "long", "true"]);
2128
2437
  var isAffirmativeWinnerLabel = (label) => {
@@ -2310,51 +2619,50 @@ function findOutcomeAcrossMarkets(event, outcomeId) {
2310
2619
  }
2311
2620
  return null;
2312
2621
  }
2622
+ var TradeSide = {
2623
+ Buy: "buy",
2624
+ Sell: "sell"
2625
+ };
2313
2626
  function tradingReducer(state, action) {
2314
- var _a, _b;
2627
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2315
2628
  switch (action.type) {
2316
2629
  case "INITIALIZE_EVENT": {
2317
2630
  if (!action.event) {
2318
- return { event: null, market: null, outcome: null };
2631
+ return { event: null, market: null, outcome: null, tradeSide: TradeSide.Buy };
2319
2632
  }
2320
- const market = resolveDefaultMarket(action.event);
2321
2633
  return {
2322
2634
  event: action.event,
2323
- market,
2324
- outcome: resolveDefaultOutcome(market)
2635
+ market: null,
2636
+ outcome: null,
2637
+ tradeSide: TradeSide.Buy
2325
2638
  };
2326
2639
  }
2327
2640
  case "SYNC_EVENT": {
2328
- const nextEvent = action.event;
2329
- const preservedMarket = state.market ? findMarketById(nextEvent, state.market.id) : null;
2330
- if (preservedMarket) {
2331
- const preservedMarketState = resolveMarketTradingState(preservedMarket);
2332
- if (preservedMarketState.isTradingDisabled) {
2333
- const tradableAlternative = resolveDefaultMarket(nextEvent);
2334
- if (tradableAlternative && resolveMarketTradingState(tradableAlternative).isOpen) {
2335
- return {
2336
- event: nextEvent,
2337
- market: tradableAlternative,
2338
- outcome: resolveDefaultOutcome(tradableAlternative)
2339
- };
2340
- }
2341
- }
2342
- const preservedOutcome = state.outcome ? findOutcomeById(preservedMarket, state.outcome.id) : null;
2641
+ const previousMarketId = (_b = (_a = state.market) == null ? void 0 : _a.id) != null ? _b : null;
2642
+ const previousOutcomeId = (_d = (_c = state.outcome) == null ? void 0 : _c.id) != null ? _d : null;
2643
+ const syncedMarket = previousMarketId ? findMarketById(action.event, previousMarketId) : null;
2644
+ if (!syncedMarket || resolveMarketTradingState(syncedMarket).isTradingDisabled) {
2343
2645
  return {
2344
- event: nextEvent,
2345
- market: preservedMarket,
2346
- outcome: preservedOutcome != null ? preservedOutcome : resolveDefaultOutcome(preservedMarket)
2646
+ event: action.event,
2647
+ market: null,
2648
+ outcome: null,
2649
+ tradeSide: (_e = state.tradeSide) != null ? _e : TradeSide.Buy
2347
2650
  };
2348
2651
  }
2349
- const defaultMarket = resolveDefaultMarket(nextEvent);
2652
+ const syncedOutcome = previousOutcomeId ? findOutcomeById(syncedMarket, previousOutcomeId) : null;
2350
2653
  return {
2351
- event: nextEvent,
2352
- market: defaultMarket,
2353
- outcome: resolveDefaultOutcome(defaultMarket)
2654
+ event: action.event,
2655
+ market: syncedMarket,
2656
+ outcome: syncedOutcome,
2657
+ tradeSide: (_f = state.tradeSide) != null ? _f : TradeSide.Buy
2354
2658
  };
2355
2659
  }
2660
+ case "SET_TRADE_SIDE": {
2661
+ if (((_g = state.tradeSide) != null ? _g : TradeSide.Buy) === action.tradeSide) return state;
2662
+ return __spreadProps(__spreadValues({}, state), { tradeSide: action.tradeSide });
2663
+ }
2356
2664
  case "SELECT_MARKET": {
2357
- const market = (_b = (_a = findMarketById(state.event, action.marketId)) != null ? _a : action.market) != null ? _b : null;
2665
+ const market = (_i = (_h = findMarketById(state.event, action.marketId)) != null ? _h : action.market) != null ? _i : null;
2358
2666
  if (!market) return state;
2359
2667
  if (resolveMarketTradingState(market).kind === "resolved") return state;
2360
2668
  return __spreadProps(__spreadValues({}, state), {
@@ -2363,6 +2671,9 @@ function tradingReducer(state, action) {
2363
2671
  });
2364
2672
  }
2365
2673
  case "SELECT_OUTCOME": {
2674
+ if (((_j = state.outcome) == null ? void 0 : _j.id) === action.outcomeId) {
2675
+ return state;
2676
+ }
2366
2677
  if (state.market) {
2367
2678
  const outcomeInCurrentMarket = findOutcomeById(state.market, action.outcomeId);
2368
2679
  if (outcomeInCurrentMarket) {
@@ -2414,7 +2725,8 @@ function logAction(actionType, payload, prev, next, enableLogs) {
2414
2725
  var initialState = {
2415
2726
  event: null,
2416
2727
  market: null,
2417
- outcome: null
2728
+ outcome: null,
2729
+ tradeSide: TradeSide.Buy
2418
2730
  };
2419
2731
  var EventTradingContext = createContext4(void 0);
2420
2732
  var useEventTradingContext = () => {
@@ -2424,9 +2736,15 @@ var EventTradingProvider = ({
2424
2736
  children,
2425
2737
  enableLogs = false
2426
2738
  }) => {
2739
+ var _a, _b;
2427
2740
  const [state, rawDispatch] = useReducer(tradingReducer, initialState);
2428
2741
  const stateRef = useRef3(state);
2742
+ const pendingAtomicSelectionRef = useRef3(null);
2429
2743
  stateRef.current = state;
2744
+ const pendingAtomicSelection = pendingAtomicSelectionRef.current;
2745
+ if (pendingAtomicSelection && ((_a = state.market) == null ? void 0 : _a.id) === pendingAtomicSelection.marketId && ((_b = state.outcome) == null ? void 0 : _b.id) === pendingAtomicSelection.outcomeId) {
2746
+ pendingAtomicSelectionRef.current = null;
2747
+ }
2430
2748
  const dispatch = useCallback4(
2431
2749
  (action) => {
2432
2750
  const prev = stateRef.current;
@@ -2449,24 +2767,45 @@ var EventTradingProvider = ({
2449
2767
  [dispatch]
2450
2768
  );
2451
2769
  const selectOutcome = useCallback4(
2452
- (outcomeId) => dispatch({ type: "SELECT_OUTCOME", outcomeId }),
2770
+ (outcomeId) => {
2771
+ var _a2, _b2;
2772
+ if (((_a2 = stateRef.current.outcome) == null ? void 0 : _a2.id) === outcomeId) return;
2773
+ if (((_b2 = pendingAtomicSelectionRef.current) == null ? void 0 : _b2.outcomeId) === outcomeId) return;
2774
+ dispatch({ type: "SELECT_OUTCOME", outcomeId });
2775
+ },
2453
2776
  [dispatch]
2454
2777
  );
2455
2778
  const selectMarketAndOutcome = useCallback4(
2456
- (marketId, outcomeId) => dispatch({ type: "SELECT_MARKET_AND_OUTCOME", marketId, outcomeId }),
2779
+ (marketId, outcomeId) => {
2780
+ var _a2, _b2, _c, _d;
2781
+ if (((_a2 = stateRef.current.market) == null ? void 0 : _a2.id) === marketId && ((_b2 = stateRef.current.outcome) == null ? void 0 : _b2.id) === outcomeId) {
2782
+ return;
2783
+ }
2784
+ if (((_c = pendingAtomicSelectionRef.current) == null ? void 0 : _c.marketId) === marketId && ((_d = pendingAtomicSelectionRef.current) == null ? void 0 : _d.outcomeId) === outcomeId) {
2785
+ return;
2786
+ }
2787
+ pendingAtomicSelectionRef.current = { marketId, outcomeId };
2788
+ dispatch({ type: "SELECT_MARKET_AND_OUTCOME", marketId, outcomeId });
2789
+ },
2790
+ [dispatch]
2791
+ );
2792
+ const setTradeSide = useCallback4(
2793
+ (tradeSide) => dispatch({ type: "SET_TRADE_SIDE", tradeSide }),
2457
2794
  [dispatch]
2458
2795
  );
2459
2796
  const value = useMemo3(
2460
2797
  () => {
2461
- var _a, _b, _c, _d, _e, _f, _g, _h;
2798
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2462
2799
  return {
2463
2800
  selectedEvent: state.event,
2464
2801
  selectedMarket: state.market,
2465
2802
  selectedOutcome: state.outcome,
2466
- selectedEventId: (_b = (_a = state.event) == null ? void 0 : _a.id) != null ? _b : null,
2803
+ selectedEventId: (_b2 = (_a2 = state.event) == null ? void 0 : _a2.id) != null ? _b2 : null,
2467
2804
  selectedMarketId: (_d = (_c = state.market) == null ? void 0 : _c.id) != null ? _d : null,
2468
2805
  selectedOutcomeId: (_f = (_e = state.outcome) == null ? void 0 : _e.id) != null ? _f : null,
2469
2806
  selectedVenue: (_h = (_g = state.market) == null ? void 0 : _g.venue) != null ? _h : null,
2807
+ tradeSide: (_i = state.tradeSide) != null ? _i : TradeSide.Buy,
2808
+ setTradeSide,
2470
2809
  initializeFromEvent,
2471
2810
  syncEvent,
2472
2811
  selectMarket,
@@ -2474,7 +2813,15 @@ var EventTradingProvider = ({
2474
2813
  selectMarketAndOutcome
2475
2814
  };
2476
2815
  },
2477
- [state, initializeFromEvent, syncEvent, selectMarket, selectOutcome, selectMarketAndOutcome]
2816
+ [
2817
+ state,
2818
+ initializeFromEvent,
2819
+ syncEvent,
2820
+ selectMarket,
2821
+ selectOutcome,
2822
+ selectMarketAndOutcome,
2823
+ setTradeSide
2824
+ ]
2478
2825
  );
2479
2826
  return /* @__PURE__ */ jsx4(EventTradingContext.Provider, { value, children });
2480
2827
  };
@@ -2800,7 +3147,7 @@ var createAuthCallbackSession = (tokens) => {
2800
3147
  };
2801
3148
  };
2802
3149
  var executeWalletAuthFlow = (input) => __async(null, null, function* () {
2803
- var _a, _b;
3150
+ var _a, _b, _c, _d;
2804
3151
  const address = input.options.address.trim();
2805
3152
  const chain = (_a = input.options.chain) != null ? _a : "ethereum";
2806
3153
  const provider = chain === "solana" ? "siws" : "siwe";
@@ -2823,14 +3170,14 @@ var executeWalletAuthFlow = (input) => __async(null, null, function* () {
2823
3170
  uri: location.uri,
2824
3171
  nonce: startResult.nonce,
2825
3172
  chainId: typeof input.options.chainId === "string" ? input.options.chainId : "mainnet",
2826
- statement: input.options.statement
3173
+ statement: (_c = startResult.statement) != null ? _c : input.options.statement
2827
3174
  }) : input.client.buildSiweMessage({
2828
3175
  domain: location.domain,
2829
3176
  address,
2830
3177
  uri: location.uri,
2831
3178
  nonce: startResult.nonce,
2832
3179
  chainId: typeof input.options.chainId === "number" ? input.options.chainId : void 0,
2833
- statement: input.options.statement
3180
+ statement: (_d = startResult.statement) != null ? _d : input.options.statement
2834
3181
  });
2835
3182
  const signature = yield input.options.signMessage(message);
2836
3183
  const result = yield input.client.verify({ message, signature });
@@ -3141,7 +3488,7 @@ function useWithdrawManaged(options) {
3141
3488
  mutationFn: (params) => client.withdrawManaged(params),
3142
3489
  onSuccess: (data) => {
3143
3490
  var _a;
3144
- invalidateBalanceQueries(queryClient);
3491
+ invalidateUserMoneyState(queryClient);
3145
3492
  (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options, data);
3146
3493
  },
3147
3494
  onError: options == null ? void 0 : options.onError
@@ -3253,7 +3600,7 @@ function useSyncBalances(options) {
3253
3600
  mutationFn: () => client.syncManagedBalances(),
3254
3601
  onSuccess: () => {
3255
3602
  var _a;
3256
- invalidateBalanceQueries(queryClient);
3603
+ invalidateUserMoneyState(queryClient);
3257
3604
  (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options);
3258
3605
  },
3259
3606
  onError: options == null ? void 0 : options.onError
@@ -3262,12 +3609,18 @@ function useSyncBalances(options) {
3262
3609
 
3263
3610
  // src/execution/use-execution-progress.ts
3264
3611
  import { useCallback as useCallback7, useEffect as useEffect5, useRef as useRef5, useState as useState5 } from "react";
3265
- var TERMINAL_ORDER_STATUSES = /* @__PURE__ */ new Set(["filled", "partial_fill", "failed", "cancelled"]);
3612
+ var TERMINAL_ORDER_STATUSES = /* @__PURE__ */ new Set([
3613
+ "filled",
3614
+ "partial_fill",
3615
+ "failed",
3616
+ "cancelled",
3617
+ "expired"
3618
+ ]);
3266
3619
  var ORDER_POLL_INTERVAL_MS = 5e3;
3267
3620
  function mapOrderStatusToTerminalEvent(status) {
3268
3621
  if (status === "filled") return "filled";
3269
3622
  if (status === "partial_fill") return "partial_fill";
3270
- if (status === "failed" || status === "cancelled") return "failed";
3623
+ if (status === "failed" || status === "cancelled" || status === "expired") return "failed";
3271
3624
  return null;
3272
3625
  }
3273
3626
  function useExecutionProgress({
@@ -3323,19 +3676,26 @@ function useExecutionProgress({
3323
3676
  submittedOrderVenueByIdRef.current.set(msg.orderId, trimmedVenue);
3324
3677
  }
3325
3678
  const { event } = msg;
3326
- if (event === "filled" || event === "partial_fill" || event === "failed" || event === "bridge_ws_subscribe_failed") {
3327
- const mappedEvent = event === "bridge_ws_subscribe_failed" ? "failed" : event;
3679
+ if (event === "filled" || event === "partial_fill" || event === "failed" || event === "bridge_ws_subscribe_failed" || event === "expired" || event === "dag_cancelled") {
3680
+ const mappedEvent = event === "filled" || event === "partial_fill" ? event : "failed";
3328
3681
  const resolvedVenue = trimmedVenue || submittedOrderVenueByIdRef.current.get(msg.orderId) || "";
3329
3682
  if (resolvedVenue) {
3330
3683
  submittedOrderVenueByIdRef.current.set(msg.orderId, resolvedVenue);
3331
3684
  }
3685
+ const fallbackErrorReason = event === "bridge_ws_subscribe_failed" ? "Bridge event subscription failed." : event === "expired" ? "Order expired before it could be submitted." : event === "dag_cancelled" ? "Order was cancelled before submission." : void 0;
3332
3686
  const nextTerminalEvent = {
3333
3687
  orderId: msg.orderId,
3334
3688
  venue: resolvedVenue,
3335
3689
  event: mappedEvent,
3336
3690
  filledAmountRaw: msg.filledAmountRaw,
3337
3691
  remainingAmountRaw: msg.remainingAmountRaw,
3338
- errorReason: event === "bridge_ws_subscribe_failed" ? (_a = msg.errorReason) != null ? _a : "Bridge event subscription failed." : msg.errorReason,
3692
+ actualSharesRaw: msg.actualSharesRaw,
3693
+ actualToWinRaw: msg.actualToWinRaw,
3694
+ quotedSharesRaw: msg.quotedSharesRaw,
3695
+ quotedToWinRaw: msg.quotedToWinRaw,
3696
+ executionPriceRaw: msg.executionPriceRaw,
3697
+ quotedPriceRaw: msg.quotedPriceRaw,
3698
+ errorReason: (_a = msg.errorReason) != null ? _a : fallbackErrorReason,
3339
3699
  timestamp: msg.timestamp
3340
3700
  };
3341
3701
  setTerminalOrderEvents((prev) => {
@@ -3413,15 +3773,29 @@ function useExecutionProgress({
3413
3773
  });
3414
3774
  return;
3415
3775
  }
3776
+ const buildFailedProgress = (prev) => {
3777
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l;
3778
+ const seq = (_b2 = (_a2 = msg.sequence) != null ? _a2 : prev == null ? void 0 : prev.currentSequence) != null ? _b2 : 0;
3779
+ const stepType = (_d = (_c2 = msg.stepType) != null ? _c2 : prev == null ? void 0 : prev.currentStepType) != null ? _d : null;
3780
+ const baseStepTypes = (_e = prev == null ? void 0 : prev.stepTypes) != null ? _e : {};
3781
+ const stepTypes = seq && stepType ? __spreadProps(__spreadValues({}, baseStepTypes), { [seq]: stepType }) : baseStepTypes;
3782
+ return {
3783
+ dagRunId: (_g = (_f = msg.dagRunId) != null ? _f : prev == null ? void 0 : prev.dagRunId) != null ? _g : "",
3784
+ totalSteps: (_i = (_h = msg.totalSteps) != null ? _h : prev == null ? void 0 : prev.totalSteps) != null ? _i : 0,
3785
+ currentSequence: seq,
3786
+ currentStepType: stepType,
3787
+ completedSequences: (_j = prev == null ? void 0 : prev.completedSequences) != null ? _j : [],
3788
+ stepTypes,
3789
+ status: "failed",
3790
+ errorReason: (_l = (_k = msg.errorReason) != null ? _k : prev == null ? void 0 : prev.errorReason) != null ? _l : null
3791
+ };
3792
+ };
3793
+ if (event === "step_failed") {
3794
+ setDagProgress((prev) => buildFailedProgress(prev));
3795
+ return;
3796
+ }
3416
3797
  if (event === "dag_failed") {
3417
- setDagProgress((prev) => {
3418
- var _a2;
3419
- if (!prev) return prev;
3420
- return __spreadProps(__spreadValues({}, prev), {
3421
- status: "failed",
3422
- errorReason: (_a2 = msg.errorReason) != null ? _a2 : null
3423
- });
3424
- });
3798
+ setDagProgress((prev) => buildFailedProgress(prev));
3425
3799
  return;
3426
3800
  }
3427
3801
  }, []);
@@ -3446,7 +3820,7 @@ function useExecutionProgress({
3446
3820
  }
3447
3821
  };
3448
3822
  const reconcile = () => __async(null, null, function* () {
3449
- var _a, _b, _c;
3823
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3450
3824
  if (cancelled || pollInFlightRef.current) return;
3451
3825
  const pending = orderIds.filter((id) => !terminalOrderIdsRef.current.has(id));
3452
3826
  if (pending.length === 0) {
@@ -3478,7 +3852,13 @@ function useExecutionProgress({
3478
3852
  venue: (_a = order.venue) != null ? _a : "",
3479
3853
  event: mapped,
3480
3854
  filledAmountRaw: (_b = order.filledAmountRaw) != null ? _b : void 0,
3481
- errorReason: (_c = order.errorMessage) != null ? _c : void 0,
3855
+ actualSharesRaw: (_c = order.actualSharesRaw) != null ? _c : void 0,
3856
+ actualToWinRaw: (_d = order.actualToWinRaw) != null ? _d : void 0,
3857
+ quotedSharesRaw: (_e = order.quotedSharesRaw) != null ? _e : void 0,
3858
+ quotedToWinRaw: (_f = order.quotedToWinRaw) != null ? _f : void 0,
3859
+ executionPriceRaw: (_g = order.executionPrice) != null ? _g : void 0,
3860
+ quotedPriceRaw: (_h = order.quotedPriceRaw) != null ? _h : void 0,
3861
+ errorReason: (_i = order.errorMessage) != null ? _i : void 0,
3482
3862
  timestamp: new Date(order.updatedAt).getTime() || Date.now()
3483
3863
  });
3484
3864
  }
@@ -3558,11 +3938,27 @@ var computeClosedPositionTotals = (group) => {
3558
3938
 
3559
3939
  // src/execution/use-redeem.ts
3560
3940
  import { useMutation as useMutation5, useQueryClient as useQueryClient6 } from "@tanstack/react-query";
3941
+ var RedeemRejectedError = class extends Error {
3942
+ constructor(message, response) {
3943
+ super(message);
3944
+ this.name = "RedeemRejectedError";
3945
+ this.response = response;
3946
+ }
3947
+ };
3948
+ var isLegRejected = (status) => status === "ineligible" || status === "rejected";
3561
3949
  var useRedeem = () => {
3562
3950
  const client = useAggClient();
3563
3951
  const queryClient = useQueryClient6();
3564
3952
  return useMutation5({
3565
- mutationFn: (body) => client.redeem(body),
3953
+ mutationFn: (body) => __async(null, null, function* () {
3954
+ const response = yield client.redeem(body);
3955
+ if (response.results.length > 0 && response.results.every((r) => isLegRejected(r.status))) {
3956
+ const reasons = response.results.map((r) => r.reason).filter((r) => Boolean(r));
3957
+ const message = reasons.length > 0 ? reasons.join("; ") : "Redeem rejected";
3958
+ throw new RedeemRejectedError(message, response);
3959
+ }
3960
+ return response;
3961
+ }),
3566
3962
  onSuccess: () => {
3567
3963
  queryClient.invalidateQueries({ queryKey: executionKeys.positionsPrefix() });
3568
3964
  queryClient.invalidateQueries({ queryKey: executionKeys.balances() });
@@ -3613,6 +4009,142 @@ var useRedeemEligibleCount = () => {
3613
4009
  return (_a = query.data) != null ? _a : 0;
3614
4010
  };
3615
4011
 
4012
+ // src/execution/use-redeem-lifecycles.ts
4013
+ import { useEffect as useEffect6, useMemo as useMemo7, useState as useState6 } from "react";
4014
+ var computeDerivedState = (legs, expectedCount) => {
4015
+ const legCount = Object.keys(legs).length;
4016
+ let allTerminal = legCount === expectedCount;
4017
+ let allConfirmed = allTerminal;
4018
+ let anyFailed = false;
4019
+ let errorMessage = null;
4020
+ for (const leg of Object.values(legs)) {
4021
+ if (leg.status === "submitted") allTerminal = false;
4022
+ if (leg.status !== "confirmed") allConfirmed = false;
4023
+ if (leg.status === "failed") {
4024
+ anyFailed = true;
4025
+ if (errorMessage === null && leg.errorMessage) errorMessage = leg.errorMessage;
4026
+ }
4027
+ }
4028
+ return {
4029
+ terminal: allTerminal,
4030
+ allConfirmed: allTerminal && allConfirmed,
4031
+ anyFailed,
4032
+ errorMessage
4033
+ };
4034
+ };
4035
+ var seedState = (input) => {
4036
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4037
+ const legs = {};
4038
+ for (const id of (_a = input.preFailedOutcomeIds) != null ? _a : []) {
4039
+ legs[id] = {
4040
+ status: "failed",
4041
+ txHash: null,
4042
+ errorMessage: (_c = (_b = input.preFailedReasons) == null ? void 0 : _b[id]) != null ? _c : null
4043
+ };
4044
+ }
4045
+ for (const id of (_d = input.preConfirmedOutcomeIds) != null ? _d : []) {
4046
+ legs[id] = {
4047
+ status: "confirmed",
4048
+ txHash: (_f = (_e = input.preConfirmedTxHashes) == null ? void 0 : _e[id]) != null ? _f : null,
4049
+ errorMessage: null
4050
+ };
4051
+ }
4052
+ const expectedCount = input.expectedOutcomeIds.length + ((_h = (_g = input.preFailedOutcomeIds) == null ? void 0 : _g.length) != null ? _h : 0) + ((_j = (_i = input.preConfirmedOutcomeIds) == null ? void 0 : _i.length) != null ? _j : 0);
4053
+ const derived = computeDerivedState(legs, expectedCount);
4054
+ return {
4055
+ pending: !derived.terminal,
4056
+ terminal: derived.terminal,
4057
+ allConfirmed: derived.allConfirmed,
4058
+ anyFailed: derived.anyFailed,
4059
+ errorMessage: derived.errorMessage,
4060
+ legs
4061
+ };
4062
+ };
4063
+ function useRedeemLifecycles(inputs) {
4064
+ const inputsByRedeemId = useMemo7(() => {
4065
+ const map = {};
4066
+ for (const input of inputs) {
4067
+ map[input.redeemId] = input;
4068
+ }
4069
+ return map;
4070
+ }, [inputs]);
4071
+ const [stateMap, setStateMap] = useState6(() => {
4072
+ const next = {};
4073
+ for (const [id, input] of Object.entries(inputsByRedeemId)) {
4074
+ next[id] = seedState(input);
4075
+ }
4076
+ return next;
4077
+ });
4078
+ useEffect6(() => {
4079
+ setStateMap((prev) => {
4080
+ let changed = false;
4081
+ const next = {};
4082
+ for (const [id, input] of Object.entries(inputsByRedeemId)) {
4083
+ const existing = prev[id];
4084
+ if (existing) {
4085
+ next[id] = existing;
4086
+ } else {
4087
+ next[id] = seedState(input);
4088
+ changed = true;
4089
+ }
4090
+ }
4091
+ if (Object.keys(next).length !== Object.keys(prev).length) changed = true;
4092
+ return changed ? next : prev;
4093
+ });
4094
+ }, [inputsByRedeemId]);
4095
+ useOnRedeemEvent(
4096
+ useMemo7(() => {
4097
+ if (Object.keys(inputsByRedeemId).length === 0) return null;
4098
+ return (event) => {
4099
+ const input = inputsByRedeemId[event.redeemId];
4100
+ if (!input) return;
4101
+ setStateMap((prev) => {
4102
+ var _a, _b, _c, _d;
4103
+ const existing = prev[event.redeemId];
4104
+ if (!existing) return prev;
4105
+ const nextLegs = __spreadProps(__spreadValues({}, existing.legs), {
4106
+ [event.venueMarketOutcomeId]: {
4107
+ status: event.status,
4108
+ txHash: event.txHash,
4109
+ errorMessage: event.errorMessage
4110
+ }
4111
+ });
4112
+ const expectedCount = input.expectedOutcomeIds.length + ((_b = (_a = input.preFailedOutcomeIds) == null ? void 0 : _a.length) != null ? _b : 0) + ((_d = (_c = input.preConfirmedOutcomeIds) == null ? void 0 : _c.length) != null ? _d : 0);
4113
+ const derived = computeDerivedState(nextLegs, expectedCount);
4114
+ const nextState = {
4115
+ pending: !derived.terminal,
4116
+ terminal: derived.terminal,
4117
+ allConfirmed: derived.allConfirmed,
4118
+ anyFailed: derived.anyFailed,
4119
+ errorMessage: derived.errorMessage,
4120
+ legs: nextLegs
4121
+ };
4122
+ return __spreadProps(__spreadValues({}, prev), { [event.redeemId]: nextState });
4123
+ });
4124
+ };
4125
+ }, [inputsByRedeemId])
4126
+ );
4127
+ return stateMap;
4128
+ }
4129
+
4130
+ // src/execution/use-redeem-lifecycle.ts
4131
+ import { useMemo as useMemo8 } from "react";
4132
+ var INITIAL_STATE = {
4133
+ pending: true,
4134
+ terminal: false,
4135
+ allConfirmed: false,
4136
+ anyFailed: false,
4137
+ errorMessage: null,
4138
+ legs: {}
4139
+ };
4140
+ function useRedeemLifecycle(input) {
4141
+ var _a;
4142
+ const inputs = useMemo8(() => input ? [input] : [], [input]);
4143
+ const map = useRedeemLifecycles(inputs);
4144
+ if (!input) return INITIAL_STATE;
4145
+ return (_a = map[input.redeemId]) != null ? _a : INITIAL_STATE;
4146
+ }
4147
+
3616
4148
  export {
3617
4149
  __spreadValues,
3618
4150
  __spreadProps,
@@ -3637,9 +4169,13 @@ export {
3637
4169
  executionKeys,
3638
4170
  invalidateBalanceQueries,
3639
4171
  invalidatePositionQueries,
4172
+ userActivityQueryKeys,
4173
+ invalidateUserActivityQueries,
4174
+ invalidateUserMoneyState,
3640
4175
  AggBalanceProvider,
3641
4176
  EventListStateProvider,
3642
4177
  useEventListState,
4178
+ getIntervalSeconds,
3643
4179
  createMarketChartData,
3644
4180
  mergeMarketChartData,
3645
4181
  createMarketLiveState,
@@ -3649,6 +4185,7 @@ export {
3649
4185
  applyOrderbookDepth,
3650
4186
  marketDataKeys,
3651
4187
  useAggClient,
4188
+ useOptionalAggClient,
3652
4189
  useAggUiConfig,
3653
4190
  useAggLabels,
3654
4191
  useAggAuthContext,
@@ -3663,6 +4200,7 @@ export {
3663
4200
  useAggWebSocketConnectionState,
3664
4201
  useOnOrderSubmitted,
3665
4202
  useOnBalanceUpdate,
4203
+ useOnOrderEvent,
3666
4204
  useOnWithdrawalLifecycle,
3667
4205
  DEFAULT_AGG_ROOT_CLASS_NAME,
3668
4206
  CHART_TIME_RANGES,
@@ -3672,6 +4210,7 @@ export {
3672
4210
  resolveEventTradingState,
3673
4211
  resolveOrderEligibility,
3674
4212
  resolveDefaultMarket,
4213
+ TradeSide,
3675
4214
  tradingReducer,
3676
4215
  useEventTradingContext,
3677
4216
  AggUiProvider,
@@ -3686,7 +4225,10 @@ export {
3686
4225
  useSyncBalances,
3687
4226
  useExecutionProgress,
3688
4227
  computeClosedPositionTotals,
4228
+ RedeemRejectedError,
3689
4229
  useRedeem,
3690
4230
  useOnRedeemEvent2 as useOnRedeemEvent,
3691
- useRedeemEligibleCount
4231
+ useRedeemEligibleCount,
4232
+ useRedeemLifecycles,
4233
+ useRedeemLifecycle
3692
4234
  };