@metamask-previews/perps-controller 25.0.0-preview-a7bdec3 → 25.0.0-preview-2be370e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -15
- package/dist/PerpsController-method-action-types.d.ts +17 -7
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +20 -10
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +196 -99
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/lighterConfig.js +2 -2
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +14 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +46 -6
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +60 -35
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +5 -4
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +13 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +296 -50
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +5 -2
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +211 -55
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +12 -7
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +64 -22
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/types/index.d.ts +36 -6
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +60 -1
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +151 -3
- package/dist/utils/marketUtils.js.map +1 -1
- package/docs/architecture.md +9 -1
- package/docs/contracts/feature-flags.md +5 -5
- package/docs/venues/hyperliquid/init-flow.md +25 -8
- package/docs/venues/lighter/capabilities.md +4 -0
- package/docs/venues/lighter/signer-provenance.md +52 -0
- 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 { hyperLiquidModeFoldsSpot } from '../types/hyperliquid-types.js';
|
|
6
|
+
import { HL_UNIFIED_ACCOUNT_MODE, 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
|
-
//
|
|
154
|
+
// Shared webData3 subscription for account mode and open-interest caps.
|
|
155
155
|
#webData3Subscriptions = new Map(); // Key: dex name ('' for main)
|
|
156
156
|
#webData3SubscriptionPromise;
|
|
157
157
|
#positionSubscriberCount = 0;
|
|
@@ -179,6 +179,11 @@ 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;
|
|
182
187
|
// HL abstraction mode (Unified / Standard / Portfolio / DEX-abstraction).
|
|
183
188
|
// Gates spot→perps folding in addSpotBalanceToAccountState. Keyed by user
|
|
184
189
|
// address so an in-flight refresh or late response for one wallet cannot
|
|
@@ -196,10 +201,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
196
201
|
#cachedSpotStateUserAddress = null;
|
|
197
202
|
#spotStatePromise;
|
|
198
203
|
#spotStatePromiseUserAddress;
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
// discards its result, preventing cross-account cache contamination
|
|
202
|
-
// when accounts are switched mid-fetch.
|
|
204
|
+
// Invalidate in-flight spot reads on cleanup, mode changes, new reads,
|
|
205
|
+
// and WebSocket spot updates.
|
|
203
206
|
#spotStateGeneration = 0;
|
|
204
207
|
#cachedPositions = null; // Aggregated positions
|
|
205
208
|
#cachedOrders = null; // Aggregated orders
|
|
@@ -691,9 +694,13 @@ export class HyperLiquidSubscriptionService {
|
|
|
691
694
|
// JSON keeps the main DEX ('') distinct from a complete account.
|
|
692
695
|
const unavailable = JSON.stringify(account.unavailableSubAccounts ?? null);
|
|
693
696
|
const breakdown = JSON.stringify(account.subAccountBreakdown ?? null);
|
|
694
|
-
return `${account.spendableBalance}:${account.withdrawableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}:${account.returnOnEquity}:${spotCollateral}:${summaryHash}:${unavailable}:${breakdown}`;
|
|
697
|
+
return `${account.spendableBalance}:${account.withdrawableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}:${account.returnOnEquity}:${spotCollateral}:${account.accountMode ?? ''}:${summaryHash}:${unavailable}:${breakdown}`;
|
|
695
698
|
}
|
|
696
699
|
// Cache hashes to avoid recomputation
|
|
700
|
+
#completePositionSubscribers = new Set();
|
|
701
|
+
#completeOrderSubscribers = new Set();
|
|
702
|
+
#completePositionsHash = '';
|
|
703
|
+
#completeOrdersHash = '';
|
|
697
704
|
#cachedPositionsHash = '';
|
|
698
705
|
#cachedOrdersHash = '';
|
|
699
706
|
#cachedAccountHash = '';
|
|
@@ -1036,11 +1043,13 @@ export class HyperLiquidSubscriptionService {
|
|
|
1036
1043
|
// Configured DEXs whose account state has not arrived (late, or the
|
|
1037
1044
|
// subscription failed): the totals exclude them, so say which.
|
|
1038
1045
|
const unavailableSubAccounts = Array.from(this.#accountSnapshotDexs).filter((dex) => !this.#dexAccountCache.has(dex) || !this.#isPositionDexFresh(dex));
|
|
1046
|
+
const accountMode = this.#getStreamedAccountMode();
|
|
1039
1047
|
return addSpotBalanceToAccountState({
|
|
1040
1048
|
...firstDexBase,
|
|
1041
1049
|
...aggregatedAccountState,
|
|
1042
1050
|
subAccountBreakdown,
|
|
1043
1051
|
returnOnEquity,
|
|
1052
|
+
...(accountMode !== undefined && { accountMode }),
|
|
1044
1053
|
...(unavailableSubAccounts.length > 0 && { unavailableSubAccounts }),
|
|
1045
1054
|
}, this.#hasSpotForBoundWallet() ? this.#cachedSpotState : null, this.#getSpotBalanceOptions());
|
|
1046
1055
|
}
|
|
@@ -1092,12 +1101,46 @@ export class HyperLiquidSubscriptionService {
|
|
|
1092
1101
|
* @param mode - The current abstraction mode for this user.
|
|
1093
1102
|
*/
|
|
1094
1103
|
setUserAbstractionMode(userAddress, mode) {
|
|
1095
|
-
|
|
1096
|
-
this.#
|
|
1104
|
+
this.#abstractionModeRevision += 1;
|
|
1105
|
+
this.#recordAbstractionMode(userAddress.toLowerCase(), mode);
|
|
1097
1106
|
if (this.#dexAccountCache.size > 0) {
|
|
1098
1107
|
this.#aggregateAndNotifySubscribers();
|
|
1099
1108
|
}
|
|
1100
1109
|
}
|
|
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
|
+
}
|
|
1101
1144
|
/**
|
|
1102
1145
|
* Fetch userAbstraction and update the cache, throttled so the long-lived
|
|
1103
1146
|
* spotState WebSocket can trigger a background refresh on every tick
|
|
@@ -1123,16 +1166,27 @@ export class HyperLiquidSubscriptionService {
|
|
|
1123
1166
|
if (now - lastWsRefreshAt < ABSTRACTION_MODE_REFRESH_THROTTLE_MS) {
|
|
1124
1167
|
return undefined;
|
|
1125
1168
|
}
|
|
1169
|
+
const binding = this.#userDataBinding;
|
|
1170
|
+
const revision = this.#abstractionModeRevision;
|
|
1171
|
+
const epoch = this.#clientService.getConnectionEpoch();
|
|
1126
1172
|
const inflight = (async () => {
|
|
1127
1173
|
try {
|
|
1128
1174
|
const infoClient = this.#clientService.getInfoClient();
|
|
1129
1175
|
const mode = await infoClient.userAbstraction({ user: userAddress });
|
|
1130
|
-
|
|
1131
|
-
|
|
1176
|
+
if (binding !== this.#userDataBinding ||
|
|
1177
|
+
epoch !== this.#clientService.getConnectionEpoch()) {
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1132
1180
|
// Set timestamp only on success; a hanging/failed fetch must not
|
|
1133
1181
|
// ratchet the throttle window forward (which would silence every
|
|
1134
1182
|
// subsequent spot WS tick for the full throttle duration).
|
|
1135
1183
|
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);
|
|
1136
1190
|
// Re-aggregate when the published account changes. The fold covers
|
|
1137
1191
|
// spendable and withdrawable. Spot collateral also changes when an
|
|
1138
1192
|
// unknown mode resolves to Standard: both fail closed to no-fold, so
|
|
@@ -1145,7 +1199,9 @@ export class HyperLiquidSubscriptionService {
|
|
|
1145
1199
|
getCrossMarginSpotCollateral(this.#cachedSpotState, mode);
|
|
1146
1200
|
const foldChanged = hyperLiquidModeFoldsSpot(previousMode) !==
|
|
1147
1201
|
hyperLiquidModeFoldsSpot(mode);
|
|
1148
|
-
if ((foldChanged ||
|
|
1202
|
+
if ((foldChanged ||
|
|
1203
|
+
collateralChanged ||
|
|
1204
|
+
previousStreamedMode !== this.#getStreamedAccountMode()) &&
|
|
1149
1205
|
this.#dexAccountCache.size > 0) {
|
|
1150
1206
|
this.#aggregateAndNotifySubscribers();
|
|
1151
1207
|
}
|
|
@@ -1188,15 +1244,17 @@ export class HyperLiquidSubscriptionService {
|
|
|
1188
1244
|
// A pending fetch for a different user is stale after an account switch —
|
|
1189
1245
|
// start a fresh fetch; the stale one will self-discard via generation check.
|
|
1190
1246
|
if (this.#spotStatePromise &&
|
|
1191
|
-
this.#spotStatePromiseUserAddress ===
|
|
1247
|
+
this.#spotStatePromiseUserAddress === lowerUserAddress) {
|
|
1192
1248
|
await this.#spotStatePromise;
|
|
1193
1249
|
return;
|
|
1194
1250
|
}
|
|
1195
1251
|
this.#spotStateGeneration += 1;
|
|
1196
1252
|
const generation = this.#spotStateGeneration;
|
|
1197
|
-
|
|
1253
|
+
await this.#trackSpotStateRefresh(userAddress, this.#refreshSpotState(userAddress, generation));
|
|
1254
|
+
}
|
|
1255
|
+
async #trackSpotStateRefresh(userAddress, promise) {
|
|
1198
1256
|
this.#spotStatePromise = promise;
|
|
1199
|
-
this.#spotStatePromiseUserAddress = userAddress;
|
|
1257
|
+
this.#spotStatePromiseUserAddress = userAddress.toLowerCase();
|
|
1200
1258
|
try {
|
|
1201
1259
|
await promise;
|
|
1202
1260
|
}
|
|
@@ -1210,6 +1268,7 @@ export class HyperLiquidSubscriptionService {
|
|
|
1210
1268
|
}
|
|
1211
1269
|
}
|
|
1212
1270
|
async #refreshSpotState(userAddress, generation) {
|
|
1271
|
+
const binding = this.#userDataBinding;
|
|
1213
1272
|
try {
|
|
1214
1273
|
// Cold-start safety: getInfoClient() throws until the SDK has been
|
|
1215
1274
|
// initialized via ensureSubscriptionClient. On a fresh service
|
|
@@ -1229,6 +1288,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
1229
1288
|
// Register the userAbstraction call in `#abstractionModeInflightByUser`
|
|
1230
1289
|
// so a concurrent WS-driven `#refreshAbstractionModeThrottled` awaits
|
|
1231
1290
|
// this fetch instead of duplicating the REST round-trip.
|
|
1291
|
+
const revision = this.#abstractionModeRevision;
|
|
1292
|
+
const epoch = this.#clientService.getConnectionEpoch();
|
|
1232
1293
|
const abstractionFetch = infoClient.userAbstraction({
|
|
1233
1294
|
user: userAddress,
|
|
1234
1295
|
});
|
|
@@ -1242,16 +1303,16 @@ export class HyperLiquidSubscriptionService {
|
|
|
1242
1303
|
trackedAbstraction) {
|
|
1243
1304
|
this.#abstractionModeInflightByUser.delete(lowerUserAddress);
|
|
1244
1305
|
}
|
|
1245
|
-
//
|
|
1246
|
-
//
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
if (
|
|
1252
|
-
this.#
|
|
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);
|
|
1253
1314
|
}
|
|
1254
|
-
else {
|
|
1315
|
+
else if (abstractionResult.status === 'rejected') {
|
|
1255
1316
|
this.#deps.debugLogger.log('User abstraction fetch failed during spot refresh; spot fold disabled until the mode resolves', {
|
|
1256
1317
|
error: ensureError(abstractionResult.reason, 'HyperLiquidSubscriptionService.refreshSpotState.abstraction').message,
|
|
1257
1318
|
});
|
|
@@ -1263,7 +1324,7 @@ export class HyperLiquidSubscriptionService {
|
|
|
1263
1324
|
// for the user whose spot is cached (strict match — null cache
|
|
1264
1325
|
// owner could mean cleanUp ran for a different user), re-aggregate
|
|
1265
1326
|
// now so the active subscribers immediately see the correct fold.
|
|
1266
|
-
if (
|
|
1327
|
+
if (resolvedMode &&
|
|
1267
1328
|
this.#cachedSpotState &&
|
|
1268
1329
|
this.#cachedSpotStateUserAddress === lowerUserAddress) {
|
|
1269
1330
|
if (this.#dexAccountCache.size > 0) {
|
|
@@ -1272,8 +1333,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
1272
1333
|
}
|
|
1273
1334
|
return;
|
|
1274
1335
|
}
|
|
1275
|
-
const boundAddress =
|
|
1276
|
-
if (
|
|
1336
|
+
const boundAddress = binding?.address.toLowerCase();
|
|
1337
|
+
if (binding !== this.#userDataBinding ||
|
|
1338
|
+
epoch !== this.#clientService.getConnectionEpoch() ||
|
|
1339
|
+
(boundAddress !== undefined && boundAddress !== lowerUserAddress)) {
|
|
1277
1340
|
return;
|
|
1278
1341
|
}
|
|
1279
1342
|
if (spotResult.status === 'rejected') {
|
|
@@ -1286,6 +1349,9 @@ export class HyperLiquidSubscriptionService {
|
|
|
1286
1349
|
// a transient abstraction failure leaves the user out of the map and
|
|
1287
1350
|
// the next #ensureSpotState retries both fetches.
|
|
1288
1351
|
this.#cachedSpotStateUserAddress = lowerUserAddress;
|
|
1352
|
+
if (binding) {
|
|
1353
|
+
this.#crossMarginSpot = { binding, epoch };
|
|
1354
|
+
}
|
|
1289
1355
|
if (this.#dexAccountCache.size > 0) {
|
|
1290
1356
|
this.#aggregateAndNotifySubscribers();
|
|
1291
1357
|
}
|
|
@@ -1318,6 +1384,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
1318
1384
|
const boundAddress = this.#userDataBinding?.address.toLowerCase();
|
|
1319
1385
|
const address = userAddress.toLowerCase();
|
|
1320
1386
|
if (startGeneration !== this.#spotStateSubscriptionGeneration ||
|
|
1387
|
+
subscriptionClient !==
|
|
1388
|
+
this.#clientService.getSubscriptionClient() ||
|
|
1321
1389
|
event.user.toLowerCase() !== address ||
|
|
1322
1390
|
(boundAddress !== undefined && boundAddress !== address)) {
|
|
1323
1391
|
return;
|
|
@@ -1326,6 +1394,12 @@ export class HyperLiquidSubscriptionService {
|
|
|
1326
1394
|
// its result instead of overwriting this fresher WS snapshot.
|
|
1327
1395
|
this.#spotStateGeneration += 1;
|
|
1328
1396
|
this.#cachedSpotState = event.spotState;
|
|
1397
|
+
if (this.#userDataBinding) {
|
|
1398
|
+
this.#crossMarginSpot = {
|
|
1399
|
+
binding: this.#userDataBinding,
|
|
1400
|
+
epoch: this.#clientService.getConnectionEpoch(),
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1329
1403
|
// Always record the spot owner so subsequent generation guards
|
|
1330
1404
|
// and recovery branches can identify whose data is cached.
|
|
1331
1405
|
// Fast-path eligibility is gated separately in #ensureSpotState
|
|
@@ -1536,11 +1610,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
1536
1610
|
/**
|
|
1537
1611
|
* Create WebSocket subscription for user data (positions, orders, account).
|
|
1538
1612
|
*
|
|
1539
|
-
*
|
|
1540
|
-
*
|
|
1541
|
-
*
|
|
1542
|
-
*
|
|
1543
|
-
* used (TAT-3332).
|
|
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.
|
|
1544
1617
|
*
|
|
1545
1618
|
* - HIP-3 disabled: subscribe to the main DEX only (`dexsToSubscribe = ['']`).
|
|
1546
1619
|
* - HIP-3 enabled: subscribe to the main DEX plus each enabled HIP-3 DEX.
|
|
@@ -1586,8 +1659,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
1586
1659
|
}
|
|
1587
1660
|
return new Promise((resolve, reject) => {
|
|
1588
1661
|
// Use per-DEX clearinghouseState + openOrders subscriptions for
|
|
1589
|
-
// positions/orders/account on every path. webData3
|
|
1590
|
-
//
|
|
1662
|
+
// positions/orders/account on every path. webData3 supplies the account
|
|
1663
|
+
// mode and OI caps.
|
|
1591
1664
|
// Determine which DEXs to subscribe to:
|
|
1592
1665
|
// - HIP-3 enabled: main DEX + each enabled HIP-3 DEX.
|
|
1593
1666
|
// - HIP-3 disabled: main DEX only.
|
|
@@ -1620,15 +1693,30 @@ export class HyperLiquidSubscriptionService {
|
|
|
1620
1693
|
// Set up openOrders subscription for orders
|
|
1621
1694
|
subscriptionPromises.push(this.#ensureOpenOrdersSubscription(userAddress, currentDexName));
|
|
1622
1695
|
}
|
|
1623
|
-
//
|
|
1696
|
+
// webData3 provides the account mode and OI caps.
|
|
1624
1697
|
const webData3Promise = subscriptionClient
|
|
1625
1698
|
.webData3({ user: userAddress }, (data) => {
|
|
1626
1699
|
if (!this.#isCurrentUserDataStream(binding, subscriptionClient)) {
|
|
1627
1700
|
return;
|
|
1628
1701
|
}
|
|
1629
1702
|
try {
|
|
1630
|
-
|
|
1631
|
-
|
|
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.
|
|
1632
1720
|
const allOICaps = [];
|
|
1633
1721
|
data.perpDexStates.forEach((dexState, index) => {
|
|
1634
1722
|
// Map webData3 index to DEX name
|
|
@@ -1787,6 +1875,7 @@ export class HyperLiquidSubscriptionService {
|
|
|
1787
1875
|
this.#userDataDexBindings.get(dexName) !== dexBinding) {
|
|
1788
1876
|
return;
|
|
1789
1877
|
}
|
|
1878
|
+
this.#crossMarginAccountDexs.delete(cacheKey);
|
|
1790
1879
|
if (!Array.isArray(data.clearinghouseState?.assetPositions)) {
|
|
1791
1880
|
this.#dexAccountCache.delete(cacheKey);
|
|
1792
1881
|
this.#dexPositionsEpoch.delete(cacheKey);
|
|
@@ -1826,6 +1915,7 @@ export class HyperLiquidSubscriptionService {
|
|
|
1826
1915
|
}
|
|
1827
1916
|
this.#dexPositionsCache.set(cacheKey, positionsWithTPSL);
|
|
1828
1917
|
this.#cacheDexAccount(cacheKey, data.clearinghouseState);
|
|
1918
|
+
this.#crossMarginAccountDexs.add(cacheKey);
|
|
1829
1919
|
// Mark this DEX as initialized (has sent first data)
|
|
1830
1920
|
this.#initializedDexs.add(cacheKey);
|
|
1831
1921
|
// Stamp at delivery, not subscription creation. The SDK keeps this
|
|
@@ -2009,6 +2099,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
2009
2099
|
if (binding !== this.#userDataBinding) {
|
|
2010
2100
|
return;
|
|
2011
2101
|
}
|
|
2102
|
+
this.#notifyCompleteSnapshots(binding);
|
|
2103
|
+
if (binding !== this.#userDataBinding) {
|
|
2104
|
+
return;
|
|
2105
|
+
}
|
|
2012
2106
|
// Wait for all expected DEXs to send initial data before notifying
|
|
2013
2107
|
// This ensures positions from all DEXs appear simultaneously
|
|
2014
2108
|
if (this.#expectedDexs.size > 0) {
|
|
@@ -2045,6 +2139,51 @@ export class HyperLiquidSubscriptionService {
|
|
|
2045
2139
|
});
|
|
2046
2140
|
}
|
|
2047
2141
|
}
|
|
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
|
+
}
|
|
2048
2187
|
#invalidateDexProtectionCoverage(dex) {
|
|
2049
2188
|
const markOrders = (orders) => orders?.map((order) => ({ ...order, coverageUnavailable: true }));
|
|
2050
2189
|
const markPosition = (position) => ({
|
|
@@ -2186,6 +2325,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
2186
2325
|
this.#cachedPositions = null;
|
|
2187
2326
|
this.#cachedOrders = null;
|
|
2188
2327
|
this.#cachedSpotState = null;
|
|
2328
|
+
this.#crossMarginSpot = null;
|
|
2329
|
+
this.#streamedAbstraction = null;
|
|
2330
|
+
this.#crossMarginAccountDexs.clear();
|
|
2331
|
+
this.#abstractionModeRevision += 1;
|
|
2189
2332
|
this.#cachedSpotStateUserAddress = null;
|
|
2190
2333
|
this.#abstractionModeByUser.clear();
|
|
2191
2334
|
this.#abstractionModeLastWsRefreshAtByUser.clear();
|
|
@@ -2201,6 +2344,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
2201
2344
|
this.#positionsCacheInitialized = false; // Reset cache initialization flag
|
|
2202
2345
|
// Clear hash caches
|
|
2203
2346
|
this.#cachedPositionsHash = '';
|
|
2347
|
+
this.#completePositionsHash = '';
|
|
2348
|
+
this.#completeOrdersHash = '';
|
|
2204
2349
|
this.#cachedOrdersHash = '';
|
|
2205
2350
|
this.#cachedAccountHash = '';
|
|
2206
2351
|
this.#deps.debugLogger.log('All multi-DEX subscriptions cleaned up (webData3 + individual subscriptions)');
|
|
@@ -2213,8 +2358,18 @@ export class HyperLiquidSubscriptionService {
|
|
|
2213
2358
|
* @returns A cleanup function to unsubscribe from position updates.
|
|
2214
2359
|
*/
|
|
2215
2360
|
subscribeToPositions(params) {
|
|
2216
|
-
const { callback, accountId } = params;
|
|
2217
|
-
const
|
|
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));
|
|
2218
2373
|
this.#positionSubscriberCount += 1;
|
|
2219
2374
|
const unsubscribe = () => {
|
|
2220
2375
|
removeListener();
|
|
@@ -2223,7 +2378,13 @@ export class HyperLiquidSubscriptionService {
|
|
|
2223
2378
|
};
|
|
2224
2379
|
// Replay is synchronous. A failed callback has no cleanup handle yet.
|
|
2225
2380
|
try {
|
|
2226
|
-
if (
|
|
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) {
|
|
2227
2388
|
callback(this.#cachedPositions);
|
|
2228
2389
|
}
|
|
2229
2390
|
}
|
|
@@ -2654,23 +2815,47 @@ export class HyperLiquidSubscriptionService {
|
|
|
2654
2815
|
* @returns A cleanup function to unsubscribe from order updates.
|
|
2655
2816
|
*/
|
|
2656
2817
|
subscribeToOrders(params) {
|
|
2657
|
-
const { callback, accountId } = params;
|
|
2658
|
-
const
|
|
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);
|
|
2659
2829
|
// Increment order subscriber count
|
|
2660
2830
|
this.#orderSubscriberCount += 1;
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
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;
|
|
2664
2853
|
}
|
|
2665
2854
|
// Ensure shared subscription is active
|
|
2666
2855
|
this.#ensureSharedWebData3Subscription(accountId).catch((error) => {
|
|
2667
2856
|
this.#logErrorUnlessClearing(ensureError(error, 'HyperLiquidSubscriptionService.subscribeToOrders'), this.#getErrorContext('subscribeToOrders'));
|
|
2668
2857
|
});
|
|
2669
|
-
return
|
|
2670
|
-
unsubscribe();
|
|
2671
|
-
this.#orderSubscriberCount -= 1;
|
|
2672
|
-
this.#cleanupSharedWebData3ISubscription();
|
|
2673
|
-
};
|
|
2858
|
+
return unsubscribe;
|
|
2674
2859
|
}
|
|
2675
2860
|
/**
|
|
2676
2861
|
* Subscribe to live account updates
|
|
@@ -2763,6 +2948,59 @@ export class HyperLiquidSubscriptionService {
|
|
|
2763
2948
|
isPositionsCacheInitialized() {
|
|
2764
2949
|
return this.#positionsCacheInitialized;
|
|
2765
2950
|
}
|
|
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
|
+
}
|
|
2766
3004
|
/**
|
|
2767
3005
|
* Get one complete position snapshot from current-connection DEX slices.
|
|
2768
3006
|
*
|
|
@@ -4379,10 +4617,12 @@ export class HyperLiquidSubscriptionService {
|
|
|
4379
4617
|
// Clear all local subscriber collections
|
|
4380
4618
|
this.#priceSubscribers.clear();
|
|
4381
4619
|
this.#positionSubscribers.clear();
|
|
4620
|
+
this.#completePositionSubscribers.clear();
|
|
4382
4621
|
this.#orderFillSubscribers.clear();
|
|
4383
4622
|
this.#twapOrderSubscribers.clear();
|
|
4384
4623
|
this.#twapOrderAdapters.clear();
|
|
4385
4624
|
this.#orderSubscribers.clear();
|
|
4625
|
+
this.#completeOrderSubscribers.clear();
|
|
4386
4626
|
this.#accountSubscribers.clear();
|
|
4387
4627
|
this.#marketDataSubscribers.clear();
|
|
4388
4628
|
this.#orderBookSubscribers.clear();
|
|
@@ -4433,6 +4673,8 @@ export class HyperLiquidSubscriptionService {
|
|
|
4433
4673
|
this.#dexSubscriberCounts.clear();
|
|
4434
4674
|
// Clear hash caches
|
|
4435
4675
|
this.#cachedPositionsHash = '';
|
|
4676
|
+
this.#completePositionsHash = '';
|
|
4677
|
+
this.#completeOrdersHash = '';
|
|
4436
4678
|
this.#cachedOrdersHash = '';
|
|
4437
4679
|
this.#cachedAccountHash = '';
|
|
4438
4680
|
// Clear multi-DEX caches
|
|
@@ -4451,6 +4693,10 @@ export class HyperLiquidSubscriptionService {
|
|
|
4451
4693
|
this.#dexAccountCache.clear();
|
|
4452
4694
|
this.#dexPositionsEpoch.clear();
|
|
4453
4695
|
this.#cachedSpotState = null;
|
|
4696
|
+
this.#crossMarginSpot = null;
|
|
4697
|
+
this.#streamedAbstraction = null;
|
|
4698
|
+
this.#crossMarginAccountDexs.clear();
|
|
4699
|
+
this.#abstractionModeRevision += 1;
|
|
4454
4700
|
this.#cachedSpotStateUserAddress = null;
|
|
4455
4701
|
this.#abstractionModeByUser.clear();
|
|
4456
4702
|
this.#abstractionModeLastWsRefreshAtByUser.clear();
|