@metamask-previews/perps-controller 25.0.0-preview-d8b2a69a9 → 25.0.0-preview-a7bdec3

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 (86) hide show
  1. package/CHANGELOG.md +40 -2
  2. package/dist/constants/eventNames.d.ts +32 -0
  3. package/dist/constants/eventNames.d.ts.map +1 -1
  4. package/dist/constants/eventNames.js +38 -0
  5. package/dist/constants/eventNames.js.map +1 -1
  6. package/dist/constants/hyperLiquidConfig.d.ts +4 -0
  7. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  8. package/dist/constants/hyperLiquidConfig.js +2 -0
  9. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  10. package/dist/constants/perpsConfig.d.ts +25 -0
  11. package/dist/constants/perpsConfig.d.ts.map +1 -1
  12. package/dist/constants/perpsConfig.js +26 -0
  13. package/dist/constants/perpsConfig.js.map +1 -1
  14. package/dist/index.d.ts +13 -9
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -6
  17. package/dist/index.js.map +1 -1
  18. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  19. package/dist/providers/HyperLiquidProvider.js +39 -70
  20. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  21. package/dist/providers/LighterProvider.d.ts.map +1 -1
  22. package/dist/providers/LighterProvider.js +10 -0
  23. package/dist/providers/LighterProvider.js.map +1 -1
  24. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  25. package/dist/services/HyperLiquidClientService.js +4 -5
  26. package/dist/services/HyperLiquidClientService.js.map +1 -1
  27. package/dist/services/HyperLiquidSubscriptionService.d.ts +1 -13
  28. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  29. package/dist/services/HyperLiquidSubscriptionService.js +50 -296
  30. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  31. package/dist/types/index.d.ts +18 -10
  32. package/dist/types/index.d.ts.map +1 -1
  33. package/dist/types/index.js.map +1 -1
  34. package/dist/utils/accountUtils.d.ts +10 -0
  35. package/dist/utils/accountUtils.d.ts.map +1 -1
  36. package/dist/utils/accountUtils.js +17 -0
  37. package/dist/utils/accountUtils.js.map +1 -1
  38. package/dist/utils/closeCalculations.d.ts +41 -0
  39. package/dist/utils/closeCalculations.d.ts.map +1 -1
  40. package/dist/utils/closeCalculations.js +44 -0
  41. package/dist/utils/closeCalculations.js.map +1 -1
  42. package/dist/utils/feeAmounts.d.ts +55 -0
  43. package/dist/utils/feeAmounts.d.ts.map +1 -0
  44. package/dist/utils/feeAmounts.js +92 -0
  45. package/dist/utils/feeAmounts.js.map +1 -0
  46. package/dist/utils/hyperLiquidScaleOrders.d.ts +73 -0
  47. package/dist/utils/hyperLiquidScaleOrders.d.ts.map +1 -0
  48. package/dist/utils/hyperLiquidScaleOrders.js +195 -0
  49. package/dist/utils/hyperLiquidScaleOrders.js.map +1 -0
  50. package/dist/utils/index.d.ts +13 -4
  51. package/dist/utils/index.d.ts.map +1 -1
  52. package/dist/utils/index.js +9 -2
  53. package/dist/utils/index.js.map +1 -1
  54. package/dist/utils/orderBookGrouping.d.ts +62 -1
  55. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  56. package/dist/utils/orderBookGrouping.js +96 -1
  57. package/dist/utils/orderBookGrouping.js.map +1 -1
  58. package/dist/utils/orderBookSlippage.d.ts +39 -0
  59. package/dist/utils/orderBookSlippage.d.ts.map +1 -0
  60. package/dist/utils/orderBookSlippage.js +72 -0
  61. package/dist/utils/orderBookSlippage.js.map +1 -0
  62. package/dist/utils/orderFills.d.ts +24 -0
  63. package/dist/utils/orderFills.d.ts.map +1 -0
  64. package/dist/utils/orderFills.js +71 -0
  65. package/dist/utils/orderFills.js.map +1 -0
  66. package/dist/utils/positionCalculations.d.ts +22 -0
  67. package/dist/utils/positionCalculations.d.ts.map +1 -0
  68. package/dist/utils/positionCalculations.js +54 -0
  69. package/dist/utils/positionCalculations.js.map +1 -0
  70. package/dist/utils/priceDeviation.d.ts +27 -0
  71. package/dist/utils/priceDeviation.d.ts.map +1 -0
  72. package/dist/utils/priceDeviation.js +58 -0
  73. package/dist/utils/priceDeviation.js.map +1 -0
  74. package/dist/utils/pricePrecision.d.ts +20 -0
  75. package/dist/utils/pricePrecision.d.ts.map +1 -0
  76. package/dist/utils/pricePrecision.js +52 -0
  77. package/dist/utils/pricePrecision.js.map +1 -0
  78. package/dist/utils/tpslCalculations.d.ts +22 -0
  79. package/dist/utils/tpslCalculations.d.ts.map +1 -1
  80. package/dist/utils/tpslCalculations.js +29 -0
  81. package/dist/utils/tpslCalculations.js.map +1 -1
  82. package/docs/client-contract.md +31 -8
  83. package/docs/contracts/events.md +33 -31
  84. package/docs/venues/hyperliquid/init-flow.md +8 -25
  85. package/docs/venues/lighter/capabilities.md +1 -0
  86. 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 { hyperLiquidModeFoldsSpot } 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';
@@ -151,7 +151,7 @@ export class HyperLiquidSubscriptionService {
151
151
  #spotStateSubscriptionGeneration = 0;
152
152
  #symbolSubscriberCounts = new Map();
153
153
  #dexSubscriberCounts = new Map(); // Track subscribers per DEX for assetCtxs
154
- // Shared webData3 subscription for account mode and open-interest caps.
154
+ // Multi-DEX webData3 subscription for all user data (positions, orders, account, OI caps)
155
155
  #webData3Subscriptions = new Map(); // Key: dex name ('' for main)
156
156
  #webData3SubscriptionPromise;
157
157
  #positionSubscriberCount = 0;
@@ -179,11 +179,6 @@ export class HyperLiquidSubscriptionService {
179
179
  #dexRawOrdersCache = new Map();
180
180
  #dexAccountCache = new Map(); // Per-DEX account state
181
181
  #cachedSpotState = null;
182
- #crossMarginSpot = null;
183
- #streamedAbstraction = null;
184
- // Account slices from before a mode change can belong to a different pool.
185
- #crossMarginAccountDexs = new Set();
186
- #abstractionModeRevision = 0;
187
182
  // HL abstraction mode (Unified / Standard / Portfolio / DEX-abstraction).
188
183
  // Gates spot→perps folding in addSpotBalanceToAccountState. Keyed by user
189
184
  // address so an in-flight refresh or late response for one wallet cannot
@@ -201,8 +196,10 @@ export class HyperLiquidSubscriptionService {
201
196
  #cachedSpotStateUserAddress = null;
202
197
  #spotStatePromise;
203
198
  #spotStatePromiseUserAddress;
204
- // Invalidate in-flight spot reads on cleanup, mode changes, new reads,
205
- // and WebSocket spot updates.
199
+ // Monotonic token bumped on cleanUp/clearAll and on each new fetch.
200
+ // Any in-flight #refreshSpotState that resolves with a stale token
201
+ // discards its result, preventing cross-account cache contamination
202
+ // when accounts are switched mid-fetch.
206
203
  #spotStateGeneration = 0;
207
204
  #cachedPositions = null; // Aggregated positions
208
205
  #cachedOrders = null; // Aggregated orders
@@ -694,13 +691,9 @@ export class HyperLiquidSubscriptionService {
694
691
  // JSON keeps the main DEX ('') distinct from a complete account.
695
692
  const unavailable = JSON.stringify(account.unavailableSubAccounts ?? null);
696
693
  const breakdown = JSON.stringify(account.subAccountBreakdown ?? null);
697
- return `${account.spendableBalance}:${account.withdrawableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}:${account.returnOnEquity}:${spotCollateral}:${account.accountMode ?? ''}:${summaryHash}:${unavailable}:${breakdown}`;
694
+ return `${account.spendableBalance}:${account.withdrawableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}:${account.returnOnEquity}:${spotCollateral}:${summaryHash}:${unavailable}:${breakdown}`;
698
695
  }
699
696
  // Cache hashes to avoid recomputation
700
- #completePositionSubscribers = new Set();
701
- #completeOrderSubscribers = new Set();
702
- #completePositionsHash = '';
703
- #completeOrdersHash = '';
704
697
  #cachedPositionsHash = '';
705
698
  #cachedOrdersHash = '';
706
699
  #cachedAccountHash = '';
@@ -1043,13 +1036,11 @@ export class HyperLiquidSubscriptionService {
1043
1036
  // Configured DEXs whose account state has not arrived (late, or the
1044
1037
  // subscription failed): the totals exclude them, so say which.
1045
1038
  const unavailableSubAccounts = Array.from(this.#accountSnapshotDexs).filter((dex) => !this.#dexAccountCache.has(dex) || !this.#isPositionDexFresh(dex));
1046
- const accountMode = this.#getStreamedAccountMode();
1047
1039
  return addSpotBalanceToAccountState({
1048
1040
  ...firstDexBase,
1049
1041
  ...aggregatedAccountState,
1050
1042
  subAccountBreakdown,
1051
1043
  returnOnEquity,
1052
- ...(accountMode !== undefined && { accountMode }),
1053
1044
  ...(unavailableSubAccounts.length > 0 && { unavailableSubAccounts }),
1054
1045
  }, this.#hasSpotForBoundWallet() ? this.#cachedSpotState : null, this.#getSpotBalanceOptions());
1055
1046
  }
@@ -1101,46 +1092,12 @@ export class HyperLiquidSubscriptionService {
1101
1092
  * @param mode - The current abstraction mode for this user.
1102
1093
  */
1103
1094
  setUserAbstractionMode(userAddress, mode) {
1104
- this.#abstractionModeRevision += 1;
1105
- this.#recordAbstractionMode(userAddress.toLowerCase(), mode);
1095
+ const lower = userAddress.toLowerCase();
1096
+ this.#abstractionModeByUser.set(lower, mode);
1106
1097
  if (this.#dexAccountCache.size > 0) {
1107
1098
  this.#aggregateAndNotifySubscribers();
1108
1099
  }
1109
1100
  }
1110
- #recordAbstractionMode(userAddress, mode) {
1111
- const previousMode = this.#abstractionModeByUser.get(userAddress);
1112
- this.#abstractionModeByUser.set(userAddress, mode);
1113
- const binding = this.#userDataBinding;
1114
- if (previousMode !== undefined &&
1115
- previousMode !== mode &&
1116
- binding?.address.toLowerCase() === userAddress) {
1117
- this.#crossMarginAccountDexs.clear();
1118
- this.#crossMarginSpot = null;
1119
- this.#streamedAbstraction = null;
1120
- this.#spotStateGeneration += 1;
1121
- if (mode === HL_UNIFIED_ACCOUNT_MODE) {
1122
- // The live spot channel may stay quiet across a mode change.
1123
- this.#trackSpotStateRefresh(binding.address, this.#refreshCrossMarginSpot(binding, this.#spotStateGeneration)).catch((error) => {
1124
- this.#logErrorUnlessClearing(ensureError(error, 'HyperLiquidSubscriptionService.refreshCrossMarginSpot'), this.#getErrorContext('refreshCrossMarginSpot'));
1125
- });
1126
- }
1127
- }
1128
- }
1129
- async #refreshCrossMarginSpot(binding, generation) {
1130
- const epoch = this.#clientService.getConnectionEpoch();
1131
- const spotState = await this.#clientService
1132
- .getInfoClient({ useHttp: true })
1133
- .spotClearinghouseState({ user: binding.address });
1134
- if (generation !== this.#spotStateGeneration ||
1135
- binding !== this.#userDataBinding ||
1136
- epoch !== this.#clientService.getConnectionEpoch()) {
1137
- return;
1138
- }
1139
- this.#cachedSpotState = spotState;
1140
- this.#cachedSpotStateUserAddress = binding.address.toLowerCase();
1141
- this.#crossMarginSpot = { binding, epoch };
1142
- this.#notifyAccountSubscribers();
1143
- }
1144
1101
  /**
1145
1102
  * Fetch userAbstraction and update the cache, throttled so the long-lived
1146
1103
  * spotState WebSocket can trigger a background refresh on every tick
@@ -1166,27 +1123,16 @@ export class HyperLiquidSubscriptionService {
1166
1123
  if (now - lastWsRefreshAt < ABSTRACTION_MODE_REFRESH_THROTTLE_MS) {
1167
1124
  return undefined;
1168
1125
  }
1169
- const binding = this.#userDataBinding;
1170
- const revision = this.#abstractionModeRevision;
1171
- const epoch = this.#clientService.getConnectionEpoch();
1172
1126
  const inflight = (async () => {
1173
1127
  try {
1174
1128
  const infoClient = this.#clientService.getInfoClient();
1175
1129
  const mode = await infoClient.userAbstraction({ user: userAddress });
1176
- if (binding !== this.#userDataBinding ||
1177
- epoch !== this.#clientService.getConnectionEpoch()) {
1178
- return;
1179
- }
1130
+ const previousMode = this.#abstractionModeByUser.get(normalizedUser) ?? null;
1131
+ this.#abstractionModeByUser.set(normalizedUser, mode);
1180
1132
  // Set timestamp only on success; a hanging/failed fetch must not
1181
1133
  // ratchet the throttle window forward (which would silence every
1182
1134
  // subsequent spot WS tick for the full throttle duration).
1183
1135
  this.#abstractionModeLastWsRefreshAtByUser.set(normalizedUser, Date.now());
1184
- if (revision !== this.#abstractionModeRevision) {
1185
- return;
1186
- }
1187
- const previousMode = this.#abstractionModeByUser.get(normalizedUser) ?? null;
1188
- const previousStreamedMode = this.#getStreamedAccountMode();
1189
- this.#recordAbstractionMode(normalizedUser, mode);
1190
1136
  // Re-aggregate when the published account changes. The fold covers
1191
1137
  // spendable and withdrawable. Spot collateral also changes when an
1192
1138
  // unknown mode resolves to Standard: both fail closed to no-fold, so
@@ -1199,9 +1145,7 @@ export class HyperLiquidSubscriptionService {
1199
1145
  getCrossMarginSpotCollateral(this.#cachedSpotState, mode);
1200
1146
  const foldChanged = hyperLiquidModeFoldsSpot(previousMode) !==
1201
1147
  hyperLiquidModeFoldsSpot(mode);
1202
- if ((foldChanged ||
1203
- collateralChanged ||
1204
- previousStreamedMode !== this.#getStreamedAccountMode()) &&
1148
+ if ((foldChanged || collateralChanged) &&
1205
1149
  this.#dexAccountCache.size > 0) {
1206
1150
  this.#aggregateAndNotifySubscribers();
1207
1151
  }
@@ -1244,17 +1188,15 @@ export class HyperLiquidSubscriptionService {
1244
1188
  // A pending fetch for a different user is stale after an account switch —
1245
1189
  // start a fresh fetch; the stale one will self-discard via generation check.
1246
1190
  if (this.#spotStatePromise &&
1247
- this.#spotStatePromiseUserAddress === lowerUserAddress) {
1191
+ this.#spotStatePromiseUserAddress === userAddress) {
1248
1192
  await this.#spotStatePromise;
1249
1193
  return;
1250
1194
  }
1251
1195
  this.#spotStateGeneration += 1;
1252
1196
  const generation = this.#spotStateGeneration;
1253
- await this.#trackSpotStateRefresh(userAddress, this.#refreshSpotState(userAddress, generation));
1254
- }
1255
- async #trackSpotStateRefresh(userAddress, promise) {
1197
+ const promise = this.#refreshSpotState(userAddress, generation);
1256
1198
  this.#spotStatePromise = promise;
1257
- this.#spotStatePromiseUserAddress = userAddress.toLowerCase();
1199
+ this.#spotStatePromiseUserAddress = userAddress;
1258
1200
  try {
1259
1201
  await promise;
1260
1202
  }
@@ -1268,7 +1210,6 @@ export class HyperLiquidSubscriptionService {
1268
1210
  }
1269
1211
  }
1270
1212
  async #refreshSpotState(userAddress, generation) {
1271
- const binding = this.#userDataBinding;
1272
1213
  try {
1273
1214
  // Cold-start safety: getInfoClient() throws until the SDK has been
1274
1215
  // initialized via ensureSubscriptionClient. On a fresh service
@@ -1288,8 +1229,6 @@ export class HyperLiquidSubscriptionService {
1288
1229
  // Register the userAbstraction call in `#abstractionModeInflightByUser`
1289
1230
  // so a concurrent WS-driven `#refreshAbstractionModeThrottled` awaits
1290
1231
  // this fetch instead of duplicating the REST round-trip.
1291
- const revision = this.#abstractionModeRevision;
1292
- const epoch = this.#clientService.getConnectionEpoch();
1293
1232
  const abstractionFetch = infoClient.userAbstraction({
1294
1233
  user: userAddress,
1295
1234
  });
@@ -1303,16 +1242,16 @@ export class HyperLiquidSubscriptionService {
1303
1242
  trackedAbstraction) {
1304
1243
  this.#abstractionModeInflightByUser.delete(lowerUserAddress);
1305
1244
  }
1306
- // A newer account-mode confirmation supersedes this REST read even
1307
- // if the spot balance itself did not change during the request.
1308
- const resolvedMode = abstractionResult.status === 'fulfilled' &&
1309
- revision === this.#abstractionModeRevision &&
1310
- binding === this.#userDataBinding &&
1311
- epoch === this.#clientService.getConnectionEpoch();
1312
- if (resolvedMode) {
1313
- this.#recordAbstractionMode(lowerUserAddress, abstractionResult.value);
1245
+ // Record the abstraction mode regardless of generation. The mode is
1246
+ // user-keyed (independent of the spot snapshot generation) so a WS
1247
+ // push that bumped generation while we awaited cannot make this
1248
+ // result wrong for this user. Discarding it would strand
1249
+ // Unified / Portfolio Margin users at fail-closed until another
1250
+ // subscribe runs — exactly the race the WS-vs-REST guard creates.
1251
+ if (abstractionResult.status === 'fulfilled') {
1252
+ this.#abstractionModeByUser.set(lowerUserAddress, abstractionResult.value);
1314
1253
  }
1315
- else if (abstractionResult.status === 'rejected') {
1254
+ else {
1316
1255
  this.#deps.debugLogger.log('User abstraction fetch failed during spot refresh; spot fold disabled until the mode resolves', {
1317
1256
  error: ensureError(abstractionResult.reason, 'HyperLiquidSubscriptionService.refreshSpotState.abstraction').message,
1318
1257
  });
@@ -1324,7 +1263,7 @@ export class HyperLiquidSubscriptionService {
1324
1263
  // for the user whose spot is cached (strict match — null cache
1325
1264
  // owner could mean cleanUp ran for a different user), re-aggregate
1326
1265
  // now so the active subscribers immediately see the correct fold.
1327
- if (resolvedMode &&
1266
+ if (abstractionResult.status === 'fulfilled' &&
1328
1267
  this.#cachedSpotState &&
1329
1268
  this.#cachedSpotStateUserAddress === lowerUserAddress) {
1330
1269
  if (this.#dexAccountCache.size > 0) {
@@ -1333,10 +1272,8 @@ export class HyperLiquidSubscriptionService {
1333
1272
  }
1334
1273
  return;
1335
1274
  }
1336
- const boundAddress = binding?.address.toLowerCase();
1337
- if (binding !== this.#userDataBinding ||
1338
- epoch !== this.#clientService.getConnectionEpoch() ||
1339
- (boundAddress !== undefined && boundAddress !== lowerUserAddress)) {
1275
+ const boundAddress = this.#userDataBinding?.address.toLowerCase();
1276
+ if (boundAddress !== undefined && boundAddress !== lowerUserAddress) {
1340
1277
  return;
1341
1278
  }
1342
1279
  if (spotResult.status === 'rejected') {
@@ -1349,9 +1286,6 @@ export class HyperLiquidSubscriptionService {
1349
1286
  // a transient abstraction failure leaves the user out of the map and
1350
1287
  // the next #ensureSpotState retries both fetches.
1351
1288
  this.#cachedSpotStateUserAddress = lowerUserAddress;
1352
- if (binding) {
1353
- this.#crossMarginSpot = { binding, epoch };
1354
- }
1355
1289
  if (this.#dexAccountCache.size > 0) {
1356
1290
  this.#aggregateAndNotifySubscribers();
1357
1291
  }
@@ -1384,8 +1318,6 @@ export class HyperLiquidSubscriptionService {
1384
1318
  const boundAddress = this.#userDataBinding?.address.toLowerCase();
1385
1319
  const address = userAddress.toLowerCase();
1386
1320
  if (startGeneration !== this.#spotStateSubscriptionGeneration ||
1387
- subscriptionClient !==
1388
- this.#clientService.getSubscriptionClient() ||
1389
1321
  event.user.toLowerCase() !== address ||
1390
1322
  (boundAddress !== undefined && boundAddress !== address)) {
1391
1323
  return;
@@ -1394,12 +1326,6 @@ export class HyperLiquidSubscriptionService {
1394
1326
  // its result instead of overwriting this fresher WS snapshot.
1395
1327
  this.#spotStateGeneration += 1;
1396
1328
  this.#cachedSpotState = event.spotState;
1397
- if (this.#userDataBinding) {
1398
- this.#crossMarginSpot = {
1399
- binding: this.#userDataBinding,
1400
- epoch: this.#clientService.getConnectionEpoch(),
1401
- };
1402
- }
1403
1329
  // Always record the spot owner so subsequent generation guards
1404
1330
  // and recovery branches can identify whose data is cached.
1405
1331
  // Fast-path eligibility is gated separately in #ensureSpotState
@@ -1610,10 +1536,11 @@ export class HyperLiquidSubscriptionService {
1610
1536
  /**
1611
1537
  * Create WebSocket subscription for user data (positions, orders, account).
1612
1538
  *
1613
- * Per-DEX `clearinghouseState` supplies positions and account data, and
1614
- * `openOrders` supplies orders. `spotState` supplies spot balances.
1615
- * `webData3` supplies open-interest caps and the bound wallet's account
1616
- * mode, which Cross previews use only on the current connection.
1539
+ * Positions, orders, and account/spot balance are always delivered via
1540
+ * per-DEX `clearinghouseState` + `openOrders` subscriptions (sub-second
1541
+ * updates). webData3 is used only for OI caps extraction (not
1542
+ * latency-sensitive). The deprecated webData2 snapshot channel is no longer
1543
+ * used (TAT-3332).
1617
1544
  *
1618
1545
  * - HIP-3 disabled: subscribe to the main DEX only (`dexsToSubscribe = ['']`).
1619
1546
  * - HIP-3 enabled: subscribe to the main DEX plus each enabled HIP-3 DEX.
@@ -1659,8 +1586,8 @@ export class HyperLiquidSubscriptionService {
1659
1586
  }
1660
1587
  return new Promise((resolve, reject) => {
1661
1588
  // Use per-DEX clearinghouseState + openOrders subscriptions for
1662
- // positions/orders/account on every path. webData3 supplies the account
1663
- // mode and OI caps.
1589
+ // positions/orders/account on every path. webData3 is used only for OI
1590
+ // caps extraction. The deprecated webData2 channel is no longer used.
1664
1591
  // Determine which DEXs to subscribe to:
1665
1592
  // - HIP-3 enabled: main DEX + each enabled HIP-3 DEX.
1666
1593
  // - HIP-3 disabled: main DEX only.
@@ -1693,30 +1620,15 @@ export class HyperLiquidSubscriptionService {
1693
1620
  // Set up openOrders subscription for orders
1694
1621
  subscriptionPromises.push(this.#ensureOpenOrdersSubscription(userAddress, currentDexName));
1695
1622
  }
1696
- // webData3 provides the account mode and OI caps.
1623
+ // Also set up webData3 for OI caps only
1697
1624
  const webData3Promise = subscriptionClient
1698
1625
  .webData3({ user: userAddress }, (data) => {
1699
1626
  if (!this.#isCurrentUserDataStream(binding, subscriptionClient)) {
1700
1627
  return;
1701
1628
  }
1702
1629
  try {
1703
- const previousMode = this.#getStreamedAccountMode();
1704
- const { user, abstraction } = data.userState ?? {};
1705
- const address = userAddress.toLowerCase();
1706
- if (user?.toLowerCase() === address && abstraction) {
1707
- this.#abstractionModeRevision += 1;
1708
- this.#recordAbstractionMode(address, abstraction);
1709
- this.#streamedAbstraction = {
1710
- binding,
1711
- epoch: this.#clientService.getConnectionEpoch(),
1712
- mode: abstraction,
1713
- };
1714
- }
1715
- if (this.#accountSubscribers.size > 0 &&
1716
- previousMode !== this.#getStreamedAccountMode()) {
1717
- this.#notifyAccountSubscribers();
1718
- }
1719
- // Position and order data come from the individual subscriptions.
1630
+ // webData3 is ONLY used for OI caps extraction
1631
+ // Positions, orders, and account data come from individual subscriptions
1720
1632
  const allOICaps = [];
1721
1633
  data.perpDexStates.forEach((dexState, index) => {
1722
1634
  // Map webData3 index to DEX name
@@ -1875,7 +1787,6 @@ export class HyperLiquidSubscriptionService {
1875
1787
  this.#userDataDexBindings.get(dexName) !== dexBinding) {
1876
1788
  return;
1877
1789
  }
1878
- this.#crossMarginAccountDexs.delete(cacheKey);
1879
1790
  if (!Array.isArray(data.clearinghouseState?.assetPositions)) {
1880
1791
  this.#dexAccountCache.delete(cacheKey);
1881
1792
  this.#dexPositionsEpoch.delete(cacheKey);
@@ -1915,7 +1826,6 @@ export class HyperLiquidSubscriptionService {
1915
1826
  }
1916
1827
  this.#dexPositionsCache.set(cacheKey, positionsWithTPSL);
1917
1828
  this.#cacheDexAccount(cacheKey, data.clearinghouseState);
1918
- this.#crossMarginAccountDexs.add(cacheKey);
1919
1829
  // Mark this DEX as initialized (has sent first data)
1920
1830
  this.#initializedDexs.add(cacheKey);
1921
1831
  // Stamp at delivery, not subscription creation. The SDK keeps this
@@ -2099,10 +2009,6 @@ export class HyperLiquidSubscriptionService {
2099
2009
  if (binding !== this.#userDataBinding) {
2100
2010
  return;
2101
2011
  }
2102
- this.#notifyCompleteSnapshots(binding);
2103
- if (binding !== this.#userDataBinding) {
2104
- return;
2105
- }
2106
2012
  // Wait for all expected DEXs to send initial data before notifying
2107
2013
  // This ensures positions from all DEXs appear simultaneously
2108
2014
  if (this.#expectedDexs.size > 0) {
@@ -2139,51 +2045,6 @@ export class HyperLiquidSubscriptionService {
2139
2045
  });
2140
2046
  }
2141
2047
  }
2142
- #notifyCompleteSnapshots(binding) {
2143
- if (this.#completePositionSubscribers.size === 0 &&
2144
- this.#completeOrderSubscribers.size === 0) {
2145
- return;
2146
- }
2147
- const scope = [
2148
- this.#clientService.getConnectionEpoch(),
2149
- [...this.#accountSnapshotDexs],
2150
- ];
2151
- // Complete snapshots also carry identity and order details that the
2152
- // legacy display hashes skip.
2153
- if (this.#completePositionSubscribers.size > 0) {
2154
- const positions = this.getFreshPositionsForAllDexs();
2155
- if (positions !== null) {
2156
- const hash = JSON.stringify([scope, positions]);
2157
- if (hash !== this.#completePositionsHash) {
2158
- this.#completePositionsHash = hash;
2159
- for (const callback of this.#completePositionSubscribers) {
2160
- if (binding !== this.#userDataBinding) {
2161
- return;
2162
- }
2163
- callback(positions);
2164
- }
2165
- }
2166
- }
2167
- }
2168
- if (binding !== this.#userDataBinding ||
2169
- this.#completeOrderSubscribers.size === 0) {
2170
- return;
2171
- }
2172
- const orders = this.getOrdersCacheIfInitialized(true);
2173
- if (orders === null) {
2174
- return;
2175
- }
2176
- const hash = JSON.stringify([scope, orders]);
2177
- if (hash !== this.#completeOrdersHash) {
2178
- this.#completeOrdersHash = hash;
2179
- for (const callback of this.#completeOrderSubscribers) {
2180
- if (binding !== this.#userDataBinding) {
2181
- return;
2182
- }
2183
- callback(orders);
2184
- }
2185
- }
2186
- }
2187
2048
  #invalidateDexProtectionCoverage(dex) {
2188
2049
  const markOrders = (orders) => orders?.map((order) => ({ ...order, coverageUnavailable: true }));
2189
2050
  const markPosition = (position) => ({
@@ -2325,10 +2186,6 @@ export class HyperLiquidSubscriptionService {
2325
2186
  this.#cachedPositions = null;
2326
2187
  this.#cachedOrders = null;
2327
2188
  this.#cachedSpotState = null;
2328
- this.#crossMarginSpot = null;
2329
- this.#streamedAbstraction = null;
2330
- this.#crossMarginAccountDexs.clear();
2331
- this.#abstractionModeRevision += 1;
2332
2189
  this.#cachedSpotStateUserAddress = null;
2333
2190
  this.#abstractionModeByUser.clear();
2334
2191
  this.#abstractionModeLastWsRefreshAtByUser.clear();
@@ -2344,8 +2201,6 @@ export class HyperLiquidSubscriptionService {
2344
2201
  this.#positionsCacheInitialized = false; // Reset cache initialization flag
2345
2202
  // Clear hash caches
2346
2203
  this.#cachedPositionsHash = '';
2347
- this.#completePositionsHash = '';
2348
- this.#completeOrdersHash = '';
2349
2204
  this.#cachedOrdersHash = '';
2350
2205
  this.#cachedAccountHash = '';
2351
2206
  this.#deps.debugLogger.log('All multi-DEX subscriptions cleaned up (webData3 + individual subscriptions)');
@@ -2358,18 +2213,8 @@ export class HyperLiquidSubscriptionService {
2358
2213
  * @returns A cleanup function to unsubscribe from position updates.
2359
2214
  */
2360
2215
  subscribeToPositions(params) {
2361
- const { callback, accountId, includeSnapshotStatus } = params;
2362
- const scopedUserAddress = includeSnapshotStatus
2363
- ? this.#walletService.getAccountStreamAddress(accountId)
2364
- : undefined;
2365
- const removeListener = includeSnapshotStatus
2366
- ? this.#createSubscription(this.#completePositionSubscribers, (positions) => {
2367
- if (scopedUserAddress &&
2368
- this.#hasUserDataWallet(scopedUserAddress)) {
2369
- callback(positions, true);
2370
- }
2371
- })
2372
- : this.#createSubscription(this.#positionSubscribers, (positions) => callback(positions));
2216
+ const { callback, accountId } = params;
2217
+ const removeListener = this.#createSubscription(this.#positionSubscribers, (positions) => callback(positions));
2373
2218
  this.#positionSubscriberCount += 1;
2374
2219
  const unsubscribe = () => {
2375
2220
  removeListener();
@@ -2378,13 +2223,7 @@ export class HyperLiquidSubscriptionService {
2378
2223
  };
2379
2224
  // Replay is synchronous. A failed callback has no cleanup handle yet.
2380
2225
  try {
2381
- if (includeSnapshotStatus) {
2382
- const positions = this.getFreshPositionsForAllDexs(false, scopedUserAddress);
2383
- if (positions !== null) {
2384
- callback(positions, true);
2385
- }
2386
- }
2387
- else if (this.#cachedPositions) {
2226
+ if (this.#cachedPositions) {
2388
2227
  callback(this.#cachedPositions);
2389
2228
  }
2390
2229
  }
@@ -2815,47 +2654,23 @@ export class HyperLiquidSubscriptionService {
2815
2654
  * @returns A cleanup function to unsubscribe from order updates.
2816
2655
  */
2817
2656
  subscribeToOrders(params) {
2818
- const { callback, accountId, includeSnapshotStatus } = params;
2819
- const scopedUserAddress = includeSnapshotStatus
2820
- ? this.#walletService.getAccountStreamAddress(accountId)
2821
- : undefined;
2822
- const removeListener = includeSnapshotStatus
2823
- ? this.#createSubscription(this.#completeOrderSubscribers, (orders) => {
2824
- if (scopedUserAddress && this.#hasUserDataWallet(scopedUserAddress)) {
2825
- callback(orders, undefined, true);
2826
- }
2827
- })
2828
- : this.#createSubscription(this.#orderSubscribers, callback);
2657
+ const { callback, accountId } = params;
2658
+ const unsubscribe = this.#createSubscription(this.#orderSubscribers, callback);
2829
2659
  // Increment order subscriber count
2830
2660
  this.#orderSubscriberCount += 1;
2831
- const unsubscribe = () => {
2832
- removeListener();
2833
- this.#orderSubscriberCount -= 1;
2834
- this.#cleanupSharedWebData3ISubscription();
2835
- };
2836
- // Replay is synchronous. A failed callback has no cleanup handle yet.
2837
- try {
2838
- if (includeSnapshotStatus) {
2839
- const orders = this.getOrdersCacheIfInitialized(true, {
2840
- userAddress: scopedUserAddress,
2841
- });
2842
- if (orders !== null) {
2843
- callback(orders, undefined, true);
2844
- }
2845
- }
2846
- else if (this.#cachedOrders) {
2847
- callback(this.#cachedOrders);
2848
- }
2849
- }
2850
- catch (error) {
2851
- unsubscribe();
2852
- throw error;
2661
+ // Immediately provide cached data if available
2662
+ if (this.#cachedOrders) {
2663
+ callback(this.#cachedOrders);
2853
2664
  }
2854
2665
  // Ensure shared subscription is active
2855
2666
  this.#ensureSharedWebData3Subscription(accountId).catch((error) => {
2856
2667
  this.#logErrorUnlessClearing(ensureError(error, 'HyperLiquidSubscriptionService.subscribeToOrders'), this.#getErrorContext('subscribeToOrders'));
2857
2668
  });
2858
- return unsubscribe;
2669
+ return () => {
2670
+ unsubscribe();
2671
+ this.#orderSubscriberCount -= 1;
2672
+ this.#cleanupSharedWebData3ISubscription();
2673
+ };
2859
2674
  }
2860
2675
  /**
2861
2676
  * Subscribe to live account updates
@@ -2948,59 +2763,6 @@ export class HyperLiquidSubscriptionService {
2948
2763
  isPositionsCacheInitialized() {
2949
2764
  return this.#positionsCacheInitialized;
2950
2765
  }
2951
- #getStreamedAccountMode() {
2952
- const mode = this.#streamedAbstraction;
2953
- return mode &&
2954
- mode.binding === this.#userDataBinding &&
2955
- mode.epoch === this.#clientService.getConnectionEpoch()
2956
- ? mode.mode
2957
- : undefined;
2958
- }
2959
- /**
2960
- * Read Cross preview inputs from the current wallet's live account data.
2961
- *
2962
- * @param userAddress - The account the caller is pricing.
2963
- * @param asset - The proposed position's market.
2964
- * @returns Preview inputs or null when the caller needs a venue read.
2965
- */
2966
- getFreshCrossMarginContext(userAddress, asset) {
2967
- const mode = this.#getStreamedAccountMode();
2968
- const binding = this.#userDataBinding;
2969
- const epoch = this.#clientService.getConnectionEpoch();
2970
- if (!mode || !this.#hasUserDataWallet(userAddress)) {
2971
- return null;
2972
- }
2973
- const { dex } = parseAssetName(asset);
2974
- const dexName = dex ?? '';
2975
- const positions = this.getCachedPositionsForDex(dexName, userAddress);
2976
- if (positions === null || !this.#crossMarginAccountDexs.has(dexName)) {
2977
- return null;
2978
- }
2979
- let summary;
2980
- let spotCollateral;
2981
- if (mode === HL_UNIFIED_ACCOUNT_MODE &&
2982
- this.#positionSnapshotDexs.has(dexName) &&
2983
- this.#crossMarginSpot?.binding === binding &&
2984
- this.#crossMarginSpot?.epoch === epoch &&
2985
- Array.from(this.#positionSnapshotDexs).every((key) => this.#crossMarginAccountDexs.has(key)) &&
2986
- this.#isAccountSnapshotComplete()) {
2987
- const account = this.#aggregateAccountStates();
2988
- summary = account?.crossMarginSummary;
2989
- spotCollateral = account?.spotCollateral;
2990
- }
2991
- else if ((mode === 'disabled' || mode === 'default') && dex === null) {
2992
- summary = this.#dexAccountCache.get('')?.crossMarginSummary;
2993
- spotCollateral = '0';
2994
- }
2995
- if (summary === undefined || spotCollateral === undefined) {
2996
- return null;
2997
- }
2998
- return {
2999
- summary,
3000
- spotCollateral,
3001
- hasPosition: positions.some(({ symbol }) => symbol === asset),
3002
- };
3003
- }
3004
2766
  /**
3005
2767
  * Get one complete position snapshot from current-connection DEX slices.
3006
2768
  *
@@ -4617,12 +4379,10 @@ export class HyperLiquidSubscriptionService {
4617
4379
  // Clear all local subscriber collections
4618
4380
  this.#priceSubscribers.clear();
4619
4381
  this.#positionSubscribers.clear();
4620
- this.#completePositionSubscribers.clear();
4621
4382
  this.#orderFillSubscribers.clear();
4622
4383
  this.#twapOrderSubscribers.clear();
4623
4384
  this.#twapOrderAdapters.clear();
4624
4385
  this.#orderSubscribers.clear();
4625
- this.#completeOrderSubscribers.clear();
4626
4386
  this.#accountSubscribers.clear();
4627
4387
  this.#marketDataSubscribers.clear();
4628
4388
  this.#orderBookSubscribers.clear();
@@ -4673,8 +4433,6 @@ export class HyperLiquidSubscriptionService {
4673
4433
  this.#dexSubscriberCounts.clear();
4674
4434
  // Clear hash caches
4675
4435
  this.#cachedPositionsHash = '';
4676
- this.#completePositionsHash = '';
4677
- this.#completeOrdersHash = '';
4678
4436
  this.#cachedOrdersHash = '';
4679
4437
  this.#cachedAccountHash = '';
4680
4438
  // Clear multi-DEX caches
@@ -4693,10 +4451,6 @@ export class HyperLiquidSubscriptionService {
4693
4451
  this.#dexAccountCache.clear();
4694
4452
  this.#dexPositionsEpoch.clear();
4695
4453
  this.#cachedSpotState = null;
4696
- this.#crossMarginSpot = null;
4697
- this.#streamedAbstraction = null;
4698
- this.#crossMarginAccountDexs.clear();
4699
- this.#abstractionModeRevision += 1;
4700
4454
  this.#cachedSpotStateUserAddress = null;
4701
4455
  this.#abstractionModeByUser.clear();
4702
4456
  this.#abstractionModeLastWsRefreshAtByUser.clear();