@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488

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.
Files changed (156) hide show
  1. package/CHANGELOG.md +105 -9
  2. package/dist/PerpsController-method-action-types.d.ts +149 -3
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +125 -3
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +787 -31
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +69 -9
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +82 -11
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +15 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +14 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/perpsConfig.d.ts +10 -2
  18. package/dist/constants/perpsConfig.d.ts.map +1 -1
  19. package/dist/constants/perpsConfig.js +11 -3
  20. package/dist/constants/perpsConfig.js.map +1 -1
  21. package/dist/index.d.ts +10 -8
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal/accountReturnOnEquity.d.ts +12 -0
  26. package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
  27. package/dist/internal/accountReturnOnEquity.js +18 -0
  28. package/dist/internal/accountReturnOnEquity.js.map +1 -0
  29. package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
  30. package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
  31. package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
  32. package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
  33. package/dist/internal/marketNumericValues.d.ts +10 -0
  34. package/dist/internal/marketNumericValues.d.ts.map +1 -0
  35. package/dist/internal/marketNumericValues.js +9 -0
  36. package/dist/internal/marketNumericValues.js.map +1 -0
  37. package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
  38. package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
  39. package/dist/internal/perpsDisplaySymbol.js +21 -0
  40. package/dist/internal/perpsDisplaySymbol.js.map +1 -0
  41. package/dist/perpsErrorCodes.d.ts +1 -0
  42. package/dist/perpsErrorCodes.d.ts.map +1 -1
  43. package/dist/perpsErrorCodes.js +1 -0
  44. package/dist/perpsErrorCodes.js.map +1 -1
  45. package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
  46. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  47. package/dist/providers/AggregatedPerpsProvider.js +140 -0
  48. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  49. package/dist/providers/HyperLiquidProvider.d.ts +72 -4
  50. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  51. package/dist/providers/HyperLiquidProvider.js +751 -159
  52. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  53. package/dist/providers/LighterProvider.d.ts +2 -1
  54. package/dist/providers/LighterProvider.d.ts.map +1 -1
  55. package/dist/providers/LighterProvider.js +11 -6
  56. package/dist/providers/LighterProvider.js.map +1 -1
  57. package/dist/selectors.d.ts +15 -5
  58. package/dist/selectors.d.ts.map +1 -1
  59. package/dist/selectors.js +23 -5
  60. package/dist/selectors.js.map +1 -1
  61. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
  62. package/dist/services/AggregatedOrderBookConnection.js +8 -10
  63. package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
  64. package/dist/services/HyperLiquidClientService.d.ts +8 -0
  65. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  66. package/dist/services/HyperLiquidClientService.js +65 -0
  67. package/dist/services/HyperLiquidClientService.js.map +1 -1
  68. package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
  69. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  70. package/dist/services/HyperLiquidSubscriptionService.js +117 -30
  71. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  72. package/dist/services/MarketDataService.d.ts +20 -3
  73. package/dist/services/MarketDataService.d.ts.map +1 -1
  74. package/dist/services/MarketDataService.js +55 -3
  75. package/dist/services/MarketDataService.js.map +1 -1
  76. package/dist/services/StreamChannelManager.d.ts +139 -0
  77. package/dist/services/StreamChannelManager.d.ts.map +1 -0
  78. package/dist/services/StreamChannelManager.js +475 -0
  79. package/dist/services/StreamChannelManager.js.map +1 -0
  80. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  81. package/dist/services/TerminalMarketService.js +7 -0
  82. package/dist/services/TerminalMarketService.js.map +1 -1
  83. package/dist/services/agentSigner.d.ts +8 -0
  84. package/dist/services/agentSigner.d.ts.map +1 -1
  85. package/dist/services/agentSigner.js +13 -0
  86. package/dist/services/agentSigner.js.map +1 -1
  87. package/dist/types/hyperliquid-types.d.ts +9 -1
  88. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  89. package/dist/types/hyperliquid-types.js +10 -0
  90. package/dist/types/hyperliquid-types.js.map +1 -1
  91. package/dist/types/index.d.ts +434 -17
  92. package/dist/types/index.d.ts.map +1 -1
  93. package/dist/types/index.js.map +1 -1
  94. package/dist/utils/accountAggregation.d.ts +17 -0
  95. package/dist/utils/accountAggregation.d.ts.map +1 -1
  96. package/dist/utils/accountAggregation.js +21 -5
  97. package/dist/utils/accountAggregation.js.map +1 -1
  98. package/dist/utils/accountUtils.d.ts +31 -10
  99. package/dist/utils/accountUtils.d.ts.map +1 -1
  100. package/dist/utils/accountUtils.js +68 -28
  101. package/dist/utils/accountUtils.js.map +1 -1
  102. package/dist/utils/closeCalculations.d.ts +17 -4
  103. package/dist/utils/closeCalculations.d.ts.map +1 -1
  104. package/dist/utils/closeCalculations.js +23 -7
  105. package/dist/utils/closeCalculations.js.map +1 -1
  106. package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
  107. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  108. package/dist/utils/hyperLiquidAdapter.js +17 -1
  109. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  110. package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
  111. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  112. package/dist/utils/hyperLiquidPositionPreview.js +264 -29
  113. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  114. package/dist/utils/index.d.ts +4 -2
  115. package/dist/utils/index.d.ts.map +1 -1
  116. package/dist/utils/index.js +1 -0
  117. package/dist/utils/index.js.map +1 -1
  118. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  119. package/dist/utils/lighterAdapter.js +46 -9
  120. package/dist/utils/lighterAdapter.js.map +1 -1
  121. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  122. package/dist/utils/marketDataTransform.js +13 -8
  123. package/dist/utils/marketDataTransform.js.map +1 -1
  124. package/dist/utils/marketUtils.d.ts +1 -2
  125. package/dist/utils/marketUtils.d.ts.map +1 -1
  126. package/dist/utils/marketUtils.js +7 -17
  127. package/dist/utils/marketUtils.js.map +1 -1
  128. package/dist/utils/orderBookGrouping.d.ts +35 -5
  129. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  130. package/dist/utils/orderBookGrouping.js +62 -6
  131. package/dist/utils/orderBookGrouping.js.map +1 -1
  132. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  133. package/dist/utils/perpsClientCopy.js +4 -0
  134. package/dist/utils/perpsClientCopy.js.map +1 -1
  135. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
  136. package/dist/utils/perpsDiskPersistence.js +10 -0
  137. package/dist/utils/perpsDiskPersistence.js.map +1 -1
  138. package/dist/utils/perpsFormatters.d.ts +31 -0
  139. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  140. package/dist/utils/perpsFormatters.js +26 -0
  141. package/dist/utils/perpsFormatters.js.map +1 -1
  142. package/dist/utils/priceDeviation.d.ts +9 -6
  143. package/dist/utils/priceDeviation.d.ts.map +1 -1
  144. package/dist/utils/priceDeviation.js +17 -26
  145. package/dist/utils/priceDeviation.js.map +1 -1
  146. package/dist/utils/sortMarkets.d.ts +13 -5
  147. package/dist/utils/sortMarkets.d.ts.map +1 -1
  148. package/dist/utils/sortMarkets.js +60 -38
  149. package/dist/utils/sortMarkets.js.map +1 -1
  150. package/docs/architecture.md +54 -24
  151. package/docs/client-contract.md +52 -27
  152. package/docs/contracts/events.md +38 -32
  153. package/docs/contracts/feature-flags.md +4 -4
  154. package/docs/formatting.md +2 -0
  155. package/docs/venues/lighter/capabilities.md +18 -15
  156. package/package.json +1 -1
@@ -3,7 +3,7 @@ import { hasProperty } from '@metamask/utils';
3
3
  import { HYPERLIQUID_CONFIG } from '../constants/hyperLiquidConfig.js';
4
4
  import { TP_SL_CONFIG, ABSTRACTION_MODE_REFRESH_THROTTLE_MS, } from '../constants/perpsConfig.js';
5
5
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
6
- import { HL_UNIFIED_ACCOUNT_MODE, hyperLiquidModeFoldsSpot, } from '../types/hyperliquid-types.js';
6
+ import { HL_UNIFIED_ACCOUNT_MODE, hyperLiquidModeFoldsSpot, isHyperLiquidStandardMode, } from '../types/hyperliquid-types.js';
7
7
  import { WebSocketConnectionState } from '../types/index.js';
8
8
  import { addSpotBalanceToAccountState, aggregateAccountStates, calculateWeightedReturnOnEquity, getCrossMarginSpotCollateral, } from '../utils/accountUtils.js';
9
9
  import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from '../utils/errorContext.js';
@@ -11,6 +11,7 @@ import { ensureError } from '../utils/errorUtils.js';
11
11
  import { adaptPositionFromSDK, adaptOrderFromSDK, adaptAccountStateFromSDK, buildHyperLiquidFillId, parseAssetName, } from '../utils/hyperLiquidAdapter.js';
12
12
  import { processBboData } from '../utils/hyperLiquidOrderBookProcessor.js';
13
13
  import { calculateOpenInterestUSD, isMarketTradable, } from '../utils/marketDataTransform.js';
14
+ import { calculateOrderBookSpread } from '../utils/orderBookGrouping.js';
14
15
  import { buildPositionTriggerOrderFromOrder, hashTriggerOrders, resolvePositionTriggerSummaryPrice, } from '../utils/orderTypes.js';
15
16
  import { parseFiniteDecimal } from '../utils/stringParseUtils.js';
16
17
  /**
@@ -132,6 +133,9 @@ export class HyperLiquidSubscriptionService {
132
133
  // Merged TWAP state per account. The venue sends a snapshot then deltas, so
133
134
  // the full set the public callback promises is accumulated here.
134
135
  #cachedTwapOrders = new Map();
136
+ // Wallet and connection epoch of the snapshot each TWAP cache entry was
137
+ // built from, so a read can tell whether the cache is the live set.
138
+ #cachedTwapOrderSources = new Map();
135
139
  // Bumped per account by teardown and reconnect so an in-flight open for
136
140
  // that account discards its subscription instead of rehydrating a cleared
137
141
  // map. Keyed rather than global: every other TWAP map is per-account, so a
@@ -2373,6 +2377,11 @@ export class HyperLiquidSubscriptionService {
2373
2377
  this.#positionSubscriberCount += 1;
2374
2378
  const unsubscribe = () => {
2375
2379
  removeListener();
2380
+ // An empty opt-in set stops refreshing the dedup hash, so a stale hash
2381
+ // could suppress the next resubscriber's first change.
2382
+ if (this.#completePositionSubscribers.size === 0) {
2383
+ this.#completePositionsHash = '';
2384
+ }
2376
2385
  this.#positionSubscriberCount -= 1;
2377
2386
  this.#cleanupSharedWebData3ISubscription();
2378
2387
  };
@@ -2675,6 +2684,7 @@ export class HyperLiquidSubscriptionService {
2675
2684
  this.#pendingTwapOrderSubscriptions.delete(normalizedAccountId);
2676
2685
  this.#twapOrderAdapters.delete(normalizedAccountId);
2677
2686
  this.#cachedTwapOrders.delete(normalizedAccountId);
2687
+ this.#cachedTwapOrderSources.delete(normalizedAccountId);
2678
2688
  }
2679
2689
  };
2680
2690
  }
@@ -2755,6 +2765,12 @@ export class HyperLiquidSubscriptionService {
2755
2765
  // receives the complete list its contract promises.
2756
2766
  const previous = this.#cachedTwapOrders.get(normalizedAccountId) ??
2757
2767
  new Map();
2768
+ if (data.isSnapshot) {
2769
+ this.#cachedTwapOrderSources.set(normalizedAccountId, {
2770
+ userAddress,
2771
+ epoch: this.#clientService.getConnectionEpoch(),
2772
+ });
2773
+ }
2758
2774
  const merged = data.isSnapshot
2759
2775
  ? new Map()
2760
2776
  : previous;
@@ -2830,6 +2846,10 @@ export class HyperLiquidSubscriptionService {
2830
2846
  this.#orderSubscriberCount += 1;
2831
2847
  const unsubscribe = () => {
2832
2848
  removeListener();
2849
+ // See subscribeToPositions: keep the dedup hash from going stale.
2850
+ if (this.#completeOrderSubscribers.size === 0) {
2851
+ this.#completeOrdersHash = '';
2852
+ }
2833
2853
  this.#orderSubscriberCount -= 1;
2834
2854
  this.#cleanupSharedWebData3ISubscription();
2835
2855
  };
@@ -2988,7 +3008,7 @@ export class HyperLiquidSubscriptionService {
2988
3008
  summary = account?.crossMarginSummary;
2989
3009
  spotCollateral = account?.spotCollateral;
2990
3010
  }
2991
- else if ((mode === 'disabled' || mode === 'default') && dex === null) {
3011
+ else if (isHyperLiquidStandardMode(mode) && dex === null) {
2992
3012
  summary = this.#dexAccountCache.get('')?.crossMarginSummary;
2993
3013
  spotCollateral = '0';
2994
3014
  }
@@ -3106,6 +3126,64 @@ export class HyperLiquidSubscriptionService {
3106
3126
  getCachedOrders() {
3107
3127
  return this.#cachedOrders;
3108
3128
  }
3129
+ /**
3130
+ * Get a DEX's live open orders as the venue sent them, or null when that
3131
+ * DEX has not published orders for this wallet on the current connection.
3132
+ *
3133
+ * @param dexName - DEX identifier, or '' for the main DEX.
3134
+ * @param userAddress - Wallet the orders must belong to.
3135
+ * @returns The venue's open orders for that DEX, or null.
3136
+ */
3137
+ getCachedOpenOrdersForDex(dexName, userAddress) {
3138
+ if (!this.#hasUserDataWallet(userAddress) ||
3139
+ this.#dexOrdersEpoch.get(dexName) !==
3140
+ this.#clientService.getConnectionEpoch()) {
3141
+ return null;
3142
+ }
3143
+ return this.#dexRawOrdersCache.get(dexName) ?? null;
3144
+ }
3145
+ /**
3146
+ * Get the wallet's active TWAP schedules from the live `userTwapHistory`
3147
+ * stream, or null when no stream for that wallet has delivered its
3148
+ * snapshot on the current connection.
3149
+ *
3150
+ * @param userAddress - Wallet the schedules must belong to.
3151
+ * @returns Active schedules (possibly empty), or null.
3152
+ */
3153
+ getCachedActiveTwapOrders(userAddress) {
3154
+ const epoch = this.#clientService.getConnectionEpoch();
3155
+ for (const [accountKey, orders] of this.#cachedTwapOrders) {
3156
+ const source = this.#cachedTwapOrderSources.get(accountKey);
3157
+ if (source?.epoch === epoch &&
3158
+ source.userAddress.toLowerCase() === userAddress.toLowerCase()) {
3159
+ return [...orders.values()].filter((order) => order.status === 'active');
3160
+ }
3161
+ }
3162
+ return null;
3163
+ }
3164
+ /**
3165
+ * Get a market's leverage setting (type and value) from a live
3166
+ * `activeAssetData` stream for that wallet, such as an order form's
3167
+ * available-to-trade subscription, or null when no such stream has
3168
+ * delivered a frame on the current connection.
3169
+ *
3170
+ * @param symbol - Market symbol, including any DEX prefix.
3171
+ * @param userAddress - Wallet the frame must belong to.
3172
+ * @returns The venue's leverage setting for the market, or null.
3173
+ */
3174
+ getCachedActiveAssetLeverage(symbol, userAddress) {
3175
+ const epoch = this.#clientService.getConnectionEpoch();
3176
+ const user = userAddress.toLowerCase();
3177
+ for (const stream of this.#activeAssetDataStreams) {
3178
+ const latest = stream.getLatest();
3179
+ if (latest?.coin === symbol &&
3180
+ latest.user === user &&
3181
+ latest.epoch === epoch) {
3182
+ return latest.leverage;
3183
+ }
3184
+ }
3185
+ return null;
3186
+ }
3109
3187
  #hasUserDataWallet(userAddress) {
3110
3188
  return (this.#userDataBinding?.address.toLowerCase() === userAddress.toLowerCase());
3111
3189
  }
@@ -3236,36 +3314,34 @@ export class HyperLiquidSubscriptionService {
3236
3314
  const change = ((currentPrice - marketData.prevDayPx) / marketData.prevDayPx) * 100;
3237
3315
  percentChange24h = change.toFixed(2);
3238
3316
  }
3239
- // Check if any subscriber for this symbol wants market data
3240
- const hasMarketDataSubscribers = this.#marketDataSubscribers.has(symbol) &&
3241
- (this.#marketDataSubscribers.get(symbol)?.size ?? 0) > 0;
3242
3317
  const priceUpdate = {
3243
3318
  symbol,
3244
3319
  price,
3245
3320
  timestamp: Date.now(),
3246
3321
  percentChange24h,
3247
- // Add mark price from activeAssetCtx
3248
- markPrice: marketData?.oraclePrice
3249
- ? marketData.oraclePrice.toString()
3250
- : undefined,
3322
+ // Venue mark price (markPx) and oracle price (oraclePx) from the
3323
+ // asset contexts. They differ: mark blends oracle and book prices.
3324
+ markPrice: marketData?.markPrice,
3325
+ oraclePrice: marketData?.oraclePrice,
3251
3326
  // Add order book data if available
3252
3327
  bestBid: orderBookData?.bestBid,
3253
3328
  bestAsk: orderBookData?.bestAsk,
3254
3329
  spread: orderBookData?.spread,
3255
3330
  // Always include funding when available (don't default to 0, preserve undefined)
3256
3331
  funding: marketData?.funding,
3257
- // Add market data only if requested by at least one subscriber
3258
- openInterest: hasMarketDataSubscribers
3259
- ? marketData?.openInterest
3260
- : undefined,
3261
- volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,
3332
+ // The per-DEX assetCtxs feed every price subscription keeps open caches
3333
+ // these for every market, so list readers get them too.
3334
+ openInterest: marketData?.openInterest,
3335
+ volume24h: marketData?.volume24h,
3262
3336
  // Flag markets that are currently untradable because the mid price has drifted
3263
3337
  // too far from the oracle price (HyperLiquid rejects such orders). Lets clients
3264
3338
  // warn the user before they attempt an order that would fail. Defaults to tradable
3265
3339
  // when the oracle price isn't yet cached.
3266
3340
  isTradable: isMarketTradable({
3267
3341
  midPrice: currentPrice,
3268
- oraclePrice: marketData?.oraclePrice,
3342
+ oraclePrice: marketData?.oraclePrice === undefined
3343
+ ? undefined
3344
+ : parseFloat(marketData.oraclePrice),
3269
3345
  deviationLimit: this.#priceDeviationLimit,
3270
3346
  }),
3271
3347
  };
@@ -3578,8 +3654,9 @@ export class HyperLiquidSubscriptionService {
3578
3654
  ? parseFloat(ctx.dayNtlVlm.toString())
3579
3655
  : undefined,
3580
3656
  oraclePrice: isPerpsContext(data)
3581
- ? parseFloat(data.ctx.oraclePx.toString())
3657
+ ? data.ctx.oraclePx.toString()
3582
3658
  : undefined,
3659
+ markPrice: ctx.markPx ? ctx.markPx.toString() : undefined,
3583
3660
  lastUpdated: now,
3584
3661
  // Store fast-stream price for per-subscriber projection in
3585
3662
  // #notifyAllPriceSubscribers. Used only for focused subscribers.
@@ -3846,7 +3923,8 @@ export class HyperLiquidSubscriptionService {
3846
3923
  volume24h: ctx.dayNtlVlm
3847
3924
  ? parseFloat(ctx.dayNtlVlm.toString())
3848
3925
  : undefined,
3849
- oraclePrice: parseFloat(ctx.oraclePx.toString()),
3926
+ oraclePrice: ctx.oraclePx.toString(),
3927
+ markPrice: ctx.markPx ? ctx.markPx.toString() : undefined,
3850
3928
  lastUpdated: Date.now(),
3851
3929
  activeAssetCtxPrice: existingMarketData?.activeAssetCtxPrice,
3852
3930
  priceLastUpdated: existingMarketData?.priceLastUpdated,
@@ -4140,6 +4218,8 @@ export class HyperLiquidSubscriptionService {
4140
4218
  // Bumped on every open, failure and retirement: a subscription, frame or
4141
4219
  // error that an older attempt delivers afterwards is dropped.
4142
4220
  let generation = 0;
4221
+ // Leverage from the last frame on the current open.
4222
+ let latest;
4143
4223
  // Consecutive failures, at open or after it, since the last frame. One
4144
4224
  // budget for both paths, so a venue that accepts the subscribe and then
4145
4225
  // fails it cannot retry forever.
@@ -4164,6 +4244,7 @@ export class HyperLiquidSubscriptionService {
4164
4244
  const open = () => {
4165
4245
  release();
4166
4246
  generation += 1;
4247
+ latest = undefined;
4167
4248
  const thisGeneration = generation;
4168
4249
  const isCurrent = () => !retired && thisGeneration === generation;
4169
4250
  // A transient SDK failure retries on the same transport with the
@@ -4219,6 +4300,12 @@ export class HyperLiquidSubscriptionService {
4219
4300
  return;
4220
4301
  }
4221
4302
  failures = 0;
4303
+ latest = {
4304
+ user: user.toLowerCase(),
4305
+ coin: symbol,
4306
+ leverage: data.leverage,
4307
+ epoch: this.#clientService.getConnectionEpoch(),
4308
+ };
4222
4309
  callback(data);
4223
4310
  }, {
4224
4311
  // A failure after the open (a rejected resubscription, a
@@ -4234,6 +4321,7 @@ export class HyperLiquidSubscriptionService {
4234
4321
  })().catch(fail);
4235
4322
  };
4236
4323
  const stream = {
4324
+ getLatest: () => latest,
4237
4325
  reopen: () => {
4238
4326
  // A replacement transport starts a fresh retry budget.
4239
4327
  failures = 0;
@@ -4295,22 +4383,18 @@ export class HyperLiquidSubscriptionService {
4295
4383
  totalNotional: askCumulativeNotional.toFixed(2),
4296
4384
  };
4297
4385
  });
4298
- // Calculate spread and mid price
4299
- const bestBid = bids[0];
4300
- const bestAsk = asks[0];
4301
- const bidPrice = bestBid ? parseFloat(bestBid.price) : 0;
4302
- const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;
4303
- const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
4304
- const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
4305
- const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
4386
+ const top = calculateOrderBookSpread({
4387
+ bestBid: bids[0]?.price,
4388
+ bestAsk: asks[0]?.price,
4389
+ });
4306
4390
  // Calculate max total for depth chart scaling
4307
4391
  const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
4308
4392
  return {
4309
4393
  bids,
4310
4394
  asks,
4311
- spread: spread.toFixed(5),
4312
- spreadPercentage,
4313
- midPrice: midPrice.toFixed(5),
4395
+ spread: (top?.spread ?? 0).toFixed(5),
4396
+ spreadPercentage: top ? top.spreadPercentage.toFixed(4) : '0',
4397
+ midPrice: (top?.midPrice ?? 0).toFixed(5),
4314
4398
  lastUpdated: Date.now(),
4315
4399
  maxTotal,
4316
4400
  };
@@ -4454,6 +4538,7 @@ export class HyperLiquidSubscriptionService {
4454
4538
  this.#pendingTwapOrderSubscriptions.clear();
4455
4539
  // Drop merged state: the fresh socket opens with a new snapshot.
4456
4540
  this.#cachedTwapOrders.clear();
4541
+ this.#cachedTwapOrderSources.clear();
4457
4542
  // Pair each account with its retained adapter first, so the restore map
4458
4543
  // has no absent-adapter case to represent.
4459
4544
  const restorable = Array.from(this.#twapOrderSubscribers.keys()).flatMap((normalizedAccountId) => {
@@ -4476,8 +4561,9 @@ export class HyperLiquidSubscriptionService {
4476
4561
  // reaches the caller's onError.
4477
4562
  this.#activeAssetDataStreams.forEach((stream) => stream.reopen());
4478
4563
  // Re-establish user data subscriptions if there are user data subscribers
4479
- if (this.#positionSubscribers.size > 0 ||
4480
- this.#orderSubscribers.size > 0 ||
4564
+ // The counts include opt-in complete-snapshot subscribers.
4565
+ if (this.#positionSubscriberCount > 0 ||
4566
+ this.#orderSubscriberCount > 0 ||
4481
4567
  this.#accountSubscribers.size > 0 ||
4482
4568
  this.#oiCapSubscribers.size > 0) {
4483
4569
  // Retire pending opens as well as subscriptions on the old transport.
@@ -4640,6 +4726,7 @@ export class HyperLiquidSubscriptionService {
4640
4726
  // Clear TWAP subscriptions; generations were bumped above, before the
4641
4727
  // subscriber keys naming those accounts were cleared.
4642
4728
  this.#cachedTwapOrders.clear();
4729
+ this.#cachedTwapOrderSources.clear();
4643
4730
  this.#twapOrderSubscriptions.forEach((subscription) => {
4644
4731
  subscription.unsubscribe().catch(() => {
4645
4732
  // Ignore errors during cleanup