@metamask-previews/perps-controller 24.0.0-preview-df8dca72c → 24.0.0-preview-c62310f6e

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.
@@ -14,7 +14,7 @@
14
14
  * order-book, and candle streams, with price polling as a fallback.
15
15
  */
16
16
  import { BigNumber } from 'bignumber.js';
17
- import { computeLighterMinOrderSize, LIGHTER_MAX_BASE_AMOUNT, LIGHTER_RECENT_TRADES_MAX_LIMIT, LIGHTER_NATIVE_PROBE_MAX_NOTIONAL, LIGHTER_NATIVE_PROBE_PAGE_LIMIT, LIGHTER_NATIVE_PROBE_PAGE_SIZE, LIGHTER_CHASE_DEFAULT_INTERVAL_MS, LIGHTER_CHASE_DEFAULT_DURATION_MS, LIGHTER_CHASE_DEFAULT_REPRICINGS, LIGHTER_CHASE_DEFAULT_DISTANCE_BPS, LIGHTER_CHASE_MIN_INTERVAL_MS, LIGHTER_CHASE_MAX_DURATION_MS, LIGHTER_CHASE_MAX_REPRICINGS, LIGHTER_CHASE_MAX_DISTANCE_BPS, LIGHTER_CHASE_QUOTE_MAX_AGE_MS, LIGHTER_POST_ONLY_QUOTE_MAX_AGE_MS, fromLighterInteger, getLighterChainId, getLighterTransactionOutcome, LIGHTER_RESOLUTION_MS, LIGHTER_MAX_WIRE_PRICE, LIGHTER_RECOVERY_ACCOUNT_INDEX_LIMIT, LIGHTER_SUPPORTED_RESOLUTIONS, LIGHTER_CHANNEL_RELEASE_DELAY_MS, LIGHTER_RECONNECT_BASE_DELAY_MS, LIGHTER_RECONNECT_MAX_DELAY_MS, LIGHTER_SERVER_ERROR_DEGRADED_THRESHOLD, LIGHTER_SOCKET_DOWN_GRACE_MS, LIGHTER_SOCKET_IDLE_CLOSE_MS, LIGHTER_DEFAULT_API_KEY_INDEX, LIGHTER_MIN_TRADING_API_KEY_INDEX, LIGHTER_TX_EXPIRY_SLACK_MS, LIGHTER_MAX_TRADING_API_KEY_INDEX, LIGHTER_TRADING_API_KEY_COUNT, LIGHTER_KEY_REGISTRATION_VISIBILITY_TIMEOUT_MS, LIGHTER_KEY_REGISTRATION_VISIBILITY_POLL_MS, LIGHTER_KEY_REGISTRATION_VISIBILITY_MAX_ATTEMPTS, LIGHTER_FILL_REPLAY_LIMIT, LIGHTER_NO_TRIGGER_PRICE, LIGHTER_ORDER_EXPIRY_NONE, LIGHTER_ORDER_TYPE_LIMIT, LIGHTER_ORDER_TYPE_MARKET, LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME, LIGHTER_TIME_IN_FORCE_POST_ONLY, getLighterWsEndpoint, LIGHTER_PRICE_POLLING_INTERVAL_MS, LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL, LIGHTER_BRIDGE_CONFIG, LIGHTER_TX_TYPE_CANCEL_ORDER, LIGHTER_TX_TYPE_MODIFY_ORDER, LIGHTER_TX_TYPE_CHANGE_PUB_KEY, LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER, LIGHTER_GROUPING_ONE_TRIGGERS_THE_OTHER, LIGHTER_GROUPING_ONE_TRIGGERS_OCO, LIGHTER_ORDER_TYPE_STOP_LOSS, LIGHTER_ORDER_TYPE_STOP_LOSS_LIMIT, LIGHTER_ORDER_TYPE_TAKE_PROFIT, LIGHTER_ORDER_TYPE_TAKE_PROFIT_LIMIT, LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS, LIGHTER_TX_TYPE_CREATE_ORDER, LIGHTER_TX_TYPE_UPDATE_LEVERAGE, LIGHTER_TX_TYPE_UPDATE_MARGIN, LIGHTER_TX_TYPE_WITHDRAW, LIGHTER_MARGIN_MODE_CROSS, LIGHTER_MARGIN_MODE_ISOLATED, LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX, LIGHTER_USDC_ASSET_INDEX, LIGHTER_DATA_INTEGRITY_PREFIX, LIGHTER_MARGIN_METADATA_TTL_MS, LIGHTER_SCALE_SETTLEMENT_WINDOW_MS, LIGHTER_SCALE_SETTLEMENT_POLL_MS, parseLighterStrictDecimal, toLighterInteger, } from '../constants/lighterConfig.js';
17
+ import { computeLighterMinOrderSize, LIGHTER_MAX_BASE_AMOUNT, LIGHTER_RECENT_TRADES_MAX_LIMIT, LIGHTER_NATIVE_PROBE_MAX_NOTIONAL, LIGHTER_NATIVE_PROBE_PAGE_LIMIT, LIGHTER_NATIVE_PROBE_PAGE_SIZE, LIGHTER_CHASE_DEFAULT_INTERVAL_MS, LIGHTER_CHASE_DEFAULT_DURATION_MS, LIGHTER_CHASE_DEFAULT_REPRICINGS, LIGHTER_CHASE_DEFAULT_DISTANCE_BPS, LIGHTER_CHASE_MIN_INTERVAL_MS, LIGHTER_CHASE_MAX_DURATION_MS, LIGHTER_CHASE_MAX_REPRICINGS, LIGHTER_CHASE_MAX_DISTANCE_BPS, LIGHTER_CHASE_QUOTE_MAX_AGE_MS, LIGHTER_POST_ONLY_QUOTE_MAX_AGE_MS, fromLighterInteger, getLighterChainId, getLighterTransactionOutcome, LIGHTER_RESOLUTION_MS, LIGHTER_MAX_WIRE_PRICE, LIGHTER_RECOVERY_ACCOUNT_INDEX_LIMIT, LIGHTER_SUPPORTED_RESOLUTIONS, LIGHTER_DEFAULT_API_KEY_INDEX, LIGHTER_MIN_TRADING_API_KEY_INDEX, LIGHTER_TX_EXPIRY_SLACK_MS, LIGHTER_MAX_TRADING_API_KEY_INDEX, LIGHTER_TRADING_API_KEY_COUNT, LIGHTER_KEY_REGISTRATION_VISIBILITY_TIMEOUT_MS, LIGHTER_KEY_REGISTRATION_VISIBILITY_POLL_MS, LIGHTER_KEY_REGISTRATION_VISIBILITY_MAX_ATTEMPTS, LIGHTER_FILL_REPLAY_LIMIT, LIGHTER_NO_TRIGGER_PRICE, LIGHTER_ORDER_EXPIRY_NONE, LIGHTER_ORDER_TYPE_LIMIT, LIGHTER_ORDER_TYPE_MARKET, LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME, LIGHTER_TIME_IN_FORCE_POST_ONLY, getLighterWsEndpoint, LIGHTER_PRICE_POLLING_INTERVAL_MS, LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL, LIGHTER_BRIDGE_CONFIG, LIGHTER_TX_TYPE_CANCEL_ORDER, LIGHTER_TX_TYPE_MODIFY_ORDER, LIGHTER_TX_TYPE_CHANGE_PUB_KEY, LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER, LIGHTER_GROUPING_ONE_TRIGGERS_THE_OTHER, LIGHTER_GROUPING_ONE_TRIGGERS_OCO, LIGHTER_ORDER_TYPE_STOP_LOSS, LIGHTER_ORDER_TYPE_STOP_LOSS_LIMIT, LIGHTER_ORDER_TYPE_TAKE_PROFIT, LIGHTER_ORDER_TYPE_TAKE_PROFIT_LIMIT, LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS, LIGHTER_TX_TYPE_CREATE_ORDER, LIGHTER_TX_TYPE_UPDATE_LEVERAGE, LIGHTER_TX_TYPE_UPDATE_MARGIN, LIGHTER_TX_TYPE_WITHDRAW, LIGHTER_MARGIN_MODE_CROSS, LIGHTER_MARGIN_MODE_ISOLATED, LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX, LIGHTER_USDC_ASSET_INDEX, LIGHTER_DATA_INTEGRITY_PREFIX, LIGHTER_MARGIN_METADATA_TTL_MS, LIGHTER_SCALE_SETTLEMENT_WINDOW_MS, LIGHTER_SCALE_SETTLEMENT_POLL_MS, parseLighterStrictDecimal, toLighterInteger, } from '../constants/lighterConfig.js';
18
18
  import { createTpslLegReplaceUnsupportedError } from '../errors.js';
19
19
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
20
20
  import { hasErrorInCauseChain } from '../services/causeChain.js';
@@ -957,59 +957,6 @@ const EMPTY_ACCOUNT_STATE = {
957
957
  returnOnEquity: '0',
958
958
  providerId: 'lighter',
959
959
  };
960
- /** Channels owned by the bound account; they are released as one group. */
961
- const LIGHTER_ACCOUNT_CHANNEL_PREFIXES = [
962
- 'user_stats/',
963
- 'account_all_positions/',
964
- 'account_all_trades/',
965
- 'account_all_orders/',
966
- ];
967
- /** Channel prefixes whose frames are dropped once the channel is released. */
968
- const LIGHTER_STREAM_FRAME_PREFIXES = [
969
- 'market_stats/',
970
- ...LIGHTER_ACCOUNT_CHANNEL_PREFIXES,
971
- ];
972
- /** Release key for the account channel group. */
973
- const LIGHTER_ACCOUNT_CHANNELS_KEY = 'account';
974
- const isLighterAccountChannel = (channel) => LIGHTER_ACCOUNT_CHANNEL_PREFIXES.some((prefix) => channel.startsWith(prefix));
975
- /**
976
- * Split a per-market channel name (`order_book/{id}`, `trade/{id}`,
977
- * `candle/{id}/{resolution}`) into its registry keys.
978
- *
979
- * @param channel - Venue channel name.
980
- * @returns The channel kind, market ID and candle series key.
981
- */
982
- const parseLighterMarketChannel = (channel) => {
983
- const [kind, marketId, resolution] = channel.split('/');
984
- return {
985
- kind,
986
- marketId: Number(marketId),
987
- seriesKey: `${marketId}:${resolution}`,
988
- };
989
- };
990
- /**
991
- * Drop registry entries whose subscriber set is empty.
992
- *
993
- * @param registry - Subscribers keyed by market or series.
994
- */
995
- const deleteEmptyRegistries = (registry) => {
996
- for (const [key, subscribers] of registry) {
997
- if (subscribers.size === 0) {
998
- registry.delete(key);
999
- }
1000
- }
1001
- };
1002
- /**
1003
- * Reconnect delay with equal jitter: 1 s doubling per attempt, capped at
1004
- * 30 s, then a random point in the upper half of that window.
1005
- *
1006
- * @param attempt - Reconnect attempt since the last successful open (1-based).
1007
- * @returns Delay in milliseconds, between half and all of the window.
1008
- */
1009
- export const getLighterReconnectDelayMs = (attempt) => {
1010
- const windowMs = Math.min(LIGHTER_RECONNECT_MAX_DELAY_MS, LIGHTER_RECONNECT_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1));
1011
- return Math.round(windowMs / 2 + (Math.random() * windowMs) / 2);
1012
- };
1013
960
  // ============================================================================
1014
961
  // LighterProvider
1015
962
  // ============================================================================
@@ -1061,16 +1008,12 @@ export class LighterProvider {
1061
1008
  #connectionState = WebSocketConnectionState.Disconnected;
1062
1009
  /** Consecutive reconnect attempts since the last successful open. */
1063
1010
  #wsReconnectAttempts = 0;
1064
- /** The attempt connection listeners last received with a state. */
1065
- #notifiedReconnectAttempts = 0;
1066
1011
  #connectionListeners = new Set();
1067
1012
  #setConnectionState = (state) => {
1068
- if (this.#connectionState === state &&
1069
- this.#notifiedReconnectAttempts === this.#wsReconnectAttempts) {
1013
+ if (this.#connectionState === state) {
1070
1014
  return;
1071
1015
  }
1072
1016
  this.#connectionState = state;
1073
- this.#notifiedReconnectAttempts = this.#wsReconnectAttempts;
1074
1017
  for (const listener of this.#connectionListeners) {
1075
1018
  try {
1076
1019
  listener(state, this.#wsReconnectAttempts);
@@ -1079,25 +1022,8 @@ export class LighterProvider {
1079
1022
  this.#logSubscriberError('connection-state', error);
1080
1023
  }
1081
1024
  }
1082
- this.#emitHealth();
1083
1025
  };
1084
1026
  #wsReconnectTimer = null;
1085
- /** Delayed releases keyed by channel, or the account channel group. */
1086
- #channelReleaseTimers = new Map();
1087
- /** Closes the socket once it has had no listener for the idle period. */
1088
- #wsIdleCloseTimer = null;
1089
- #socketIdleCloseMs;
1090
- /**
1091
- * Set once the socket has stayed down past the grace period. Health
1092
- * reports it only while streams wait on the socket.
1093
- */
1094
- #isSocketDown = false;
1095
- #socketDownTimer = null;
1096
- /** Re-reports health when a REST rate-limit cooldown ends. */
1097
- #cooldownTimer = null;
1098
- #healthListeners = new Set();
1099
- /** Last health signature sent to listeners, to skip repeats. */
1100
- #lastHealthSignature = null;
1101
1027
  /** Merged latest price per symbol, replayed to late price subscribers. */
1102
1028
  #lastPriceBySymbol = new Map();
1103
1029
  /** Merged live position state from account_all_positions (keyed marketId). */
@@ -1161,14 +1087,8 @@ export class LighterProvider {
1161
1087
  options.lighterAuthConfig?.apiKeyIndex ?? LIGHTER_DEFAULT_API_KEY_INDEX;
1162
1088
  this.#preferredApiKeyIndex = this.#apiKeyIndex;
1163
1089
  this.#configuredAccountIndex = options.lighterAuthConfig?.accountIndex;
1164
- this.#socketIdleCloseMs =
1165
- options.socketIdleCloseMs ?? LIGHTER_SOCKET_IDLE_CLOSE_MS;
1166
1090
  this.#clientService = new LighterClientService(this.#deps, {
1167
1091
  isTestnet: this.#isTestnet,
1168
- onRequestHealthChange: () => {
1169
- this.#scheduleCooldownReport();
1170
- this.#emitHealth();
1171
- },
1172
1092
  });
1173
1093
  this.#walletService = new LighterWalletService(this.#deps, {
1174
1094
  isTestnet: this.#isTestnet,
@@ -1275,16 +1195,9 @@ export class LighterProvider {
1275
1195
  // fences instead of submitting after the provider was torn down.
1276
1196
  this.#interruptChase();
1277
1197
  this.#isDisconnected = true;
1278
- this.#clientService.cancelHeldRequests();
1279
1198
  this.#invalidateSessionState();
1280
1199
  this.#removeSignerResetListener();
1281
1200
  this.#teardownStream();
1282
- if (this.#cooldownTimer !== null) {
1283
- clearTimeout(this.#cooldownTimer);
1284
- this.#cooldownTimer = null;
1285
- }
1286
- this.#healthListeners.clear();
1287
- this.#lastHealthSignature = null;
1288
1201
  this.#priceSubscribers.clear();
1289
1202
  this.#oiCapSubscribers.clear();
1290
1203
  this.#accountSubscribers.clear();
@@ -1598,20 +1511,13 @@ export class LighterProvider {
1598
1511
  if (this.#priceSubscribers.size > 0 || this.#oiCapSubscribers.size > 0) {
1599
1512
  this.#requestChannel('market_stats/all');
1600
1513
  }
1601
- for (const [marketId, subscribers] of this.#orderBookSubscribers) {
1602
- if (subscribers.size > 0) {
1603
- this.#requestChannel(`order_book/${marketId}`);
1604
- }
1514
+ for (const marketId of this.#orderBookSubscribers.keys()) {
1515
+ this.#requestChannel(`order_book/${marketId}`);
1605
1516
  }
1606
- for (const [marketId, subscribers] of this.#publicTradeSubscribers) {
1607
- if (subscribers.size > 0) {
1608
- this.#requestChannel(`trade/${marketId}`);
1609
- }
1517
+ for (const marketId of this.#publicTradeSubscribers.keys()) {
1518
+ this.#requestChannel(`trade/${marketId}`);
1610
1519
  }
1611
- for (const [seriesKey, subscribers] of this.#candleSubscribers) {
1612
- if (subscribers.size === 0) {
1613
- continue;
1614
- }
1520
+ for (const seriesKey of this.#candleSubscribers.keys()) {
1615
1521
  // Series keys are `${marketId}:${resolution}`; the channel form uses
1616
1522
  // slashes. The teardown cleared the series state, and the message
1617
1523
  // router drops updates for unknown series — recreate an empty series
@@ -1619,7 +1525,10 @@ export class LighterProvider {
1619
1525
  this.#candleSeries.set(seriesKey, new Map());
1620
1526
  this.#requestChannel(`candle/${seriesKey.replace(':', '/')}`);
1621
1527
  }
1622
- if (this.#hasAccountSubscriber()) {
1528
+ if (this.#accountSubscribers.size > 0 ||
1529
+ this.#positionSubscribers.size > 0 ||
1530
+ this.#orderSubscribers.size > 0 ||
1531
+ this.#fillSubscribers.size > 0) {
1623
1532
  // The promise was cleared by the teardown, so this re-resolves the
1624
1533
  // account channels against the newly bound address.
1625
1534
  this.#ensureAccountChannels();
@@ -5818,7 +5727,7 @@ export class LighterProvider {
5818
5727
  // INNERMOST: the bridge mutex — the WASM client is a singleton
5819
5728
  // per bridge, so ensure-correct-client + every sign of a section
5820
5729
  // are serialized across ALL providers sharing the bridge.
5821
- async () => await withProcessMutex(bridgeMutexKey(this.#rawSignerBridge()), async () => await this.#clientService.runTradingSection(criticalSection)));
5730
+ async () => await withProcessMutex(bridgeMutexKey(this.#rawSignerBridge()), criticalSection));
5822
5731
  const run = this.#writeChain.then(guardedSection, guardedSection);
5823
5732
  this.#writeChain = run.then(() => undefined, () => undefined);
5824
5733
  return await run;
@@ -8017,22 +7926,7 @@ export class LighterProvider {
8017
7926
  }
8018
7927
  }
8019
7928
  }
8020
- /**
8021
- * Run a venue write flow as one REST trading section, so the reads it makes
8022
- * before the write lock (fresh prices, the forced market refresh, account
8023
- * and signer checks) never wait behind the read budget or a 429/405
8024
- * cooldown.
8025
- *
8026
- * @param flow - The write flow.
8027
- * @returns The flow's result.
8028
- */
8029
- async #runTradingFlow(flow) {
8030
- return await this.#clientService.runTradingSection(flow);
8031
- }
8032
7929
  async placeOrder(input, inheritedGeneration, reportFailure = true) {
8033
- return await this.#runTradingFlow(async () => await this.#placeOrder(input, inheritedGeneration, reportFailure));
8034
- }
8035
- async #placeOrder(input, inheritedGeneration, reportFailure = true) {
8036
7930
  const deferProviderErrorReport = input.deferProviderErrorReport === true;
8037
7931
  const params = { ...input };
8038
7932
  delete params.deferProviderErrorReport;
@@ -9791,9 +9685,6 @@ export class LighterProvider {
9791
9685
  throw new Error('Lighter native TWAP lifecycle is unavailable: authoritative parent fills and termination are not established');
9792
9686
  }
9793
9687
  async cancelOrder(params, inheritedGeneration) {
9794
- return await this.#runTradingFlow(async () => await this.#cancelOrder(params, inheritedGeneration));
9795
- }
9796
- async #cancelOrder(params, inheritedGeneration) {
9797
9688
  if (params.orderType === 'chase') {
9798
9689
  try {
9799
9690
  return await this.#cancelChase(params);
@@ -9887,9 +9778,6 @@ export class LighterProvider {
9887
9778
  * @returns Truthful durable same-order outcome, never a placement receipt.
9888
9779
  */
9889
9780
  async editOrder(params) {
9890
- return await this.#runTradingFlow(async () => await this.#editOrder(params));
9891
- }
9892
- async #editOrder(params) {
9893
9781
  try {
9894
9782
  this.#ensureSessionBinding();
9895
9783
  const generation = this.#sessionGeneration;
@@ -10339,9 +10227,6 @@ export class LighterProvider {
10339
10227
  return held > 0 && requestedSize >= held * (1 - 1e-9);
10340
10228
  };
10341
10229
  async closePosition(rawParams) {
10342
- return await this.#runTradingFlow(async () => await this.#closePosition(rawParams));
10343
- }
10344
- async #closePosition(rawParams) {
10345
10230
  const params = this.#normalizeCloseParams(rawParams);
10346
10231
  try {
10347
10232
  // One intent identity from the position read through the final write:
@@ -10395,7 +10280,7 @@ export class LighterProvider {
10395
10280
  }
10396
10281
  }
10397
10282
  async updatePositionTPSL(params) {
10398
- return await this.#runTradingFlow(async () => await this.#updatePositionTPSL(params));
10283
+ return this.#updatePositionTPSL(params);
10399
10284
  }
10400
10285
  /**
10401
10286
  * Lighter settles position protection as one journaled TP/SL pair, so it
@@ -10416,7 +10301,7 @@ export class LighterProvider {
10416
10301
  * @returns Settled successor result; failure retains the source obligation.
10417
10302
  */
10418
10303
  async resolveRecoveryProtection(params) {
10419
- const result = await this.#runTradingFlow(async () => await this.#resolveRecoveryProtection(params));
10304
+ const result = await this.#resolveRecoveryProtection(params);
10420
10305
  return {
10421
10306
  ...result,
10422
10307
  status: result.success ? 'settled' : 'unresolved',
@@ -11998,9 +11883,6 @@ export class LighterProvider {
11998
11883
  };
11999
11884
  };
12000
11885
  async updateMargin(input) {
12001
- return await this.#runTradingFlow(async () => await this.#updateMargin(input));
12002
- }
12003
- async #updateMargin(input) {
12004
11886
  const params = { ...input };
12005
11887
  try {
12006
11888
  this.#ensureSessionBinding();
@@ -12079,9 +11961,6 @@ export class LighterProvider {
12079
11961
  }
12080
11962
  }
12081
11963
  async withdraw(params) {
12082
- return await this.#runTradingFlow(async () => await this.#withdraw(params));
12083
- }
12084
- async #withdraw(params) {
12085
11964
  try {
12086
11965
  this.#ensureSessionBinding();
12087
11966
  const generationAtIntent = this.#sessionGeneration;
@@ -13111,7 +12990,7 @@ export class LighterProvider {
13111
12990
  this.#ensureStream();
13112
12991
  return () => {
13113
12992
  this.#priceSubscribers.delete(params);
13114
- this.#onListenerRemoved('market_stats/all');
12993
+ this.#releaseChannelIfUnused();
13115
12994
  };
13116
12995
  }
13117
12996
  subscribeToOICaps(params) {
@@ -13123,7 +13002,7 @@ export class LighterProvider {
13123
13002
  this.#ensureStream();
13124
13003
  return () => {
13125
13004
  this.#oiCapSubscribers.delete(params);
13126
- this.#onListenerRemoved('market_stats/all');
13005
+ this.#releaseChannelIfUnused();
13127
13006
  };
13128
13007
  }
13129
13008
  subscribeToAccount(params) {
@@ -13134,7 +13013,7 @@ export class LighterProvider {
13134
13013
  this.#ensureAccountChannels();
13135
13014
  return () => {
13136
13015
  this.#accountSubscribers.delete(params);
13137
- this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13016
+ this.#releaseChannelIfUnused();
13138
13017
  };
13139
13018
  }
13140
13019
  subscribeToPositions(params) {
@@ -13148,7 +13027,7 @@ export class LighterProvider {
13148
13027
  this.#ensureAccountChannels();
13149
13028
  return () => {
13150
13029
  this.#positionSubscribers.delete(params);
13151
- this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13030
+ this.#releaseChannelIfUnused();
13152
13031
  };
13153
13032
  }
13154
13033
  subscribeToOrders(params) {
@@ -13162,7 +13041,7 @@ export class LighterProvider {
13162
13041
  this.#ensureAccountChannels();
13163
13042
  return () => {
13164
13043
  this.#orderSubscribers.delete(params);
13165
- this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13044
+ this.#releaseChannelIfUnused();
13166
13045
  };
13167
13046
  }
13168
13047
  subscribeToOrderFills(params) {
@@ -13187,7 +13066,7 @@ export class LighterProvider {
13187
13066
  .catch(() => undefined);
13188
13067
  return () => {
13189
13068
  this.#fillSubscribers.delete(params);
13190
- this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13069
+ this.#releaseChannelIfUnused();
13191
13070
  };
13192
13071
  }
13193
13072
  // ============================================================================
@@ -13224,7 +13103,6 @@ export class LighterProvider {
13224
13103
  if (this.#isDisconnected) {
13225
13104
  return;
13226
13105
  }
13227
- this.#cancelChannelRelease(LIGHTER_ACCOUNT_CHANNELS_KEY);
13228
13106
  if (this.#accountChannelsPromise) {
13229
13107
  this.#ensureStream();
13230
13108
  return;
@@ -13245,10 +13123,6 @@ export class LighterProvider {
13245
13123
  // Fails closed when no wallet account is bound — a configured
13246
13124
  // account index alone must never subscribe user channels.
13247
13125
  this.#assertSession(generation);
13248
- // Released (no account listener left) or replaced while resolving.
13249
- if (this.#accountChannelsPromise !== setupPromise) {
13250
- return;
13251
- }
13252
13126
  this.#requestChannel(`user_stats/${accountIndex}`);
13253
13127
  this.#requestChannel(`account_all_positions/${accountIndex}`);
13254
13128
  this.#requestChannel(`account_all_trades/${accountIndex}`);
@@ -13257,9 +13131,6 @@ export class LighterProvider {
13257
13131
  try {
13258
13132
  const auth = await this.#getAuthToken();
13259
13133
  this.#assertSession(generation);
13260
- if (this.#accountChannelsPromise !== setupPromise) {
13261
- return;
13262
- }
13263
13134
  this.#requestChannel(`account_all_orders/${accountIndex}`, auth);
13264
13135
  }
13265
13136
  catch (error) {
@@ -13320,47 +13191,18 @@ export class LighterProvider {
13320
13191
  #hasAnySubscriber = () => {
13321
13192
  return (this.#priceSubscribers.size > 0 ||
13322
13193
  this.#oiCapSubscribers.size > 0 ||
13323
- this.#hasAccountSubscriber() ||
13194
+ this.#accountSubscribers.size > 0 ||
13195
+ this.#positionSubscribers.size > 0 ||
13196
+ this.#orderSubscribers.size > 0 ||
13197
+ this.#fillSubscribers.size > 0 ||
13324
13198
  [...this.#orderBookSubscribers.values()].some((subscribers) => subscribers.size > 0) ||
13325
13199
  [...this.#publicTradeSubscribers.values()].some((subscribers) => subscribers.size > 0) ||
13326
13200
  [...this.#candleSubscribers.values()].some((subscribers) => subscribers.size > 0));
13327
13201
  };
13328
- #hasAccountSubscriber = () => this.#accountSubscribers.size > 0 ||
13329
- this.#positionSubscribers.size > 0 ||
13330
- this.#orderSubscribers.size > 0 ||
13331
- this.#fillSubscribers.size > 0;
13332
- /**
13333
- * Whether a channel (or the account group key) still has a listener.
13334
- *
13335
- * @param channel - Venue channel name, or the account group key.
13336
- * @returns True while some subscriber needs the channel.
13337
- */
13338
- #channelHasListeners = (channel) => {
13339
- if (channel === 'market_stats/all') {
13340
- return this.#priceSubscribers.size > 0 || this.#oiCapSubscribers.size > 0;
13341
- }
13342
- if (channel === LIGHTER_ACCOUNT_CHANNELS_KEY ||
13343
- isLighterAccountChannel(channel)) {
13344
- return this.#hasAccountSubscriber();
13345
- }
13346
- const { kind, marketId, seriesKey } = parseLighterMarketChannel(channel);
13347
- let subscribers;
13348
- if (kind === 'order_book') {
13349
- subscribers = this.#orderBookSubscribers.get(marketId);
13350
- }
13351
- else if (kind === 'trade') {
13352
- subscribers = this.#publicTradeSubscribers.get(marketId);
13353
- }
13354
- else if (kind === 'candle') {
13355
- subscribers = this.#candleSubscribers.get(seriesKey);
13356
- }
13357
- return (subscribers?.size ?? 0) > 0;
13358
- };
13359
13202
  #requestChannel = (channel, auth) => {
13360
13203
  if (this.#isDisconnected) {
13361
13204
  return;
13362
13205
  }
13363
- this.#cancelChannelRelease(channel);
13364
13206
  if (this.#wsWantedChannels.has(channel)) {
13365
13207
  return;
13366
13208
  }
@@ -13368,194 +13210,19 @@ export class LighterProvider {
13368
13210
  if (this.#priceWs?.readyState === 1) {
13369
13211
  this.#sendSubscribe(channel, auth);
13370
13212
  }
13371
- this.#logChannelCount('subscribed', channel);
13372
- };
13373
- /**
13374
- * Whether a price or account frame still has its channel. Frames that
13375
- * arrive after a release would refill caches nobody reads; per-market
13376
- * handlers check their own channel.
13377
- *
13378
- * @param type - Frame type, such as `update/market_stats`.
13379
- * @returns False for a price or account frame whose channel was released.
13380
- */
13381
- #isStreamFrameWanted = (type) => {
13382
- const prefix = LIGHTER_STREAM_FRAME_PREFIXES.find((candidate) => type.includes(candidate.slice(0, -1)));
13383
- if (prefix === undefined) {
13384
- return true;
13385
- }
13386
- for (const channel of this.#wsWantedChannels.keys()) {
13387
- if (channel.startsWith(prefix)) {
13388
- return true;
13389
- }
13390
- }
13391
- return false;
13392
- };
13393
- #logChannelCount = (change, channel) => {
13394
- this.#deps.debugLogger.log('[LighterProvider] stream channels', {
13395
- change,
13396
- channel,
13397
- subscribedChannels: this.#wsWantedChannels.size,
13398
- });
13399
- };
13400
- /**
13401
- * A listener left: release its channel after the wait if nothing else
13402
- * needs it, and close the socket after the idle period if nothing is left.
13403
- *
13404
- * @param channel - Channel (or account group key) the listener used, or
13405
- * null when it never reached a channel.
13406
- */
13407
- #onListenerRemoved = (channel) => {
13408
- if (channel !== null &&
13409
- !this.#isDisconnected &&
13410
- !this.#channelHasListeners(channel)) {
13411
- this.#scheduleChannelRelease(channel);
13412
- }
13413
- if (this.#isSocketDown && !this.#hasAnySubscriber()) {
13414
- // A down socket degrades health only while streams wait on it.
13415
- this.#emitHealth();
13416
- }
13417
- this.#scheduleIdleClose();
13418
- };
13419
- #scheduleChannelRelease = (channel) => {
13420
- if (this.#channelReleaseTimers.has(channel)) {
13421
- return;
13422
- }
13423
- this.#channelReleaseTimers.set(channel, setTimeout(() => {
13424
- this.#channelReleaseTimers.delete(channel);
13425
- if (this.#isDisconnected || this.#channelHasListeners(channel)) {
13426
- return;
13427
- }
13428
- if (channel === LIGHTER_ACCOUNT_CHANNELS_KEY) {
13429
- this.#releaseAccountChannels(true);
13430
- }
13431
- else {
13432
- this.#releaseChannel(channel, true);
13433
- }
13434
- }, LIGHTER_CHANNEL_RELEASE_DELAY_MS));
13435
- };
13436
- #cancelChannelRelease = (channel) => {
13437
- const timer = this.#channelReleaseTimers.get(channel);
13438
- if (timer !== undefined) {
13439
- clearTimeout(timer);
13440
- this.#channelReleaseTimers.delete(channel);
13441
- }
13442
- };
13443
- /**
13444
- * Drop a channel from the wanted set with its cached state.
13445
- *
13446
- * @param channel - Venue channel name.
13447
- * @param notifyVenue - Send `unsubscribe` on the open socket.
13448
- */
13449
- #releaseChannel = (channel, notifyVenue) => {
13450
- this.#wsWantedChannels.delete(channel);
13451
- if (notifyVenue && this.#priceWs?.readyState === 1) {
13452
- this.#priceWs.send(JSON.stringify({ type: 'unsubscribe', channel }));
13453
- }
13454
- const { kind, marketId, seriesKey } = parseLighterMarketChannel(channel);
13455
- if (kind === 'order_book') {
13456
- this.#orderBookState.delete(marketId);
13457
- this.#orderBookSubscribers.delete(marketId);
13458
- }
13459
- else if (kind === 'trade') {
13460
- this.#publicTradeSubscribers.delete(marketId);
13461
- }
13462
- else if (kind === 'candle') {
13463
- this.#candleSeries.delete(seriesKey);
13464
- this.#candleSubscribers.delete(seriesKey);
13465
- }
13466
- else if (channel === 'market_stats/all') {
13467
- this.#lastPriceBySymbol.clear();
13468
- }
13469
- this.#logChannelCount('released', channel);
13470
- };
13471
- /**
13472
- * Drop every account channel and its cached account data. The next
13473
- * account listener resolves and requests them again.
13474
- *
13475
- * @param notifyVenue - Send `unsubscribe` on the open socket.
13476
- */
13477
- #releaseAccountChannels = (notifyVenue) => {
13478
- for (const channel of [...this.#wsWantedChannels.keys()]) {
13479
- if (isLighterAccountChannel(channel)) {
13480
- this.#wsWantedChannels.delete(channel);
13481
- if (notifyVenue && this.#priceWs?.readyState === 1) {
13482
- this.#priceWs.send(JSON.stringify({ type: 'unsubscribe', channel }));
13483
- }
13484
- }
13485
- }
13486
- this.#resetAccountStreamState();
13487
- this.#logChannelCount('released', LIGHTER_ACCOUNT_CHANNELS_KEY);
13488
- };
13489
- /** Forget the account channel setup and the account data it streamed. */
13490
- #resetAccountStreamState = () => {
13491
- this.#accountChannelsPromise = null;
13492
- this.#wsPositions.clear();
13493
- this.#hasOrdersSnapshot = false;
13494
- this.#wsFills = null;
13495
- this.#wsOrders.clear();
13496
- };
13497
- /**
13498
- * Forget channels that lost every listener while the socket was down, so
13499
- * a reconnect subscribes only what is still watched.
13500
- */
13501
- #pruneUnwatchedChannels = () => {
13502
- if (!this.#hasAccountSubscriber() &&
13503
- [...this.#wsWantedChannels.keys()].some(isLighterAccountChannel)) {
13504
- this.#cancelChannelRelease(LIGHTER_ACCOUNT_CHANNELS_KEY);
13505
- this.#releaseAccountChannels(false);
13506
- }
13507
- for (const channel of [...this.#wsWantedChannels.keys()]) {
13508
- if (!isLighterAccountChannel(channel) &&
13509
- !this.#channelHasListeners(channel)) {
13510
- this.#cancelChannelRelease(channel);
13511
- this.#releaseChannel(channel, false);
13512
- }
13513
- }
13514
13213
  };
13515
13214
  #sendSubscribe = (channel, auth) => {
13516
13215
  this.#priceWs?.send(JSON.stringify(auth
13517
13216
  ? { type: 'subscribe', channel, auth }
13518
13217
  : { type: 'subscribe', channel }));
13519
13218
  };
13520
- /** Close the stream once it has had no listener for the idle period. */
13521
- #scheduleIdleClose = () => {
13522
- if (this.#isDisconnected ||
13523
- this.#wsIdleCloseTimer !== null ||
13524
- this.#hasAnySubscriber()) {
13525
- return;
13526
- }
13527
- if (!this.#webSocketCtor) {
13528
- // REST polling has no socket to keep warm: stop it at once.
13219
+ #releaseChannelIfUnused = () => {
13220
+ if (!this.#hasAnySubscriber()) {
13529
13221
  this.#teardownStream();
13530
- return;
13531
- }
13532
- this.#wsIdleCloseTimer = setTimeout(() => {
13533
- this.#wsIdleCloseTimer = null;
13534
- if (!this.#hasAnySubscriber()) {
13535
- this.#deps.debugLogger.log('[LighterProvider] stream idle; closing', {
13536
- idleMs: this.#socketIdleCloseMs,
13537
- });
13538
- this.#teardownStream();
13539
- }
13540
- }, this.#socketIdleCloseMs);
13541
- };
13542
- #cancelIdleClose = () => {
13543
- if (this.#wsIdleCloseTimer !== null) {
13544
- clearTimeout(this.#wsIdleCloseTimer);
13545
- this.#wsIdleCloseTimer = null;
13546
13222
  }
13547
13223
  };
13548
13224
  #ensureStream = () => {
13549
- if (this.#isDisconnected) {
13550
- return;
13551
- }
13552
- this.#cancelIdleClose();
13553
- if (this.#isSocketDown) {
13554
- // Streams are back on a socket that is still down past its grace.
13555
- this.#emitHealth();
13556
- }
13557
- // A pending reconnect keeps its backoff; it resubscribes every channel.
13558
- if (this.#priceWs || this.#pricePollTimer || this.#wsReconnectTimer) {
13225
+ if (this.#isDisconnected || this.#priceWs || this.#pricePollTimer) {
13559
13226
  return;
13560
13227
  }
13561
13228
  if (this.#webSocketCtor) {
@@ -13592,9 +13259,7 @@ export class LighterProvider {
13592
13259
  }
13593
13260
  const generationAtOpen = this.#sessionGeneration;
13594
13261
  this.#wsReconnectAttempts = 0;
13595
- this.#clearSocketDown();
13596
13262
  this.#setConnectionState(WebSocketConnectionState.Connected);
13597
- this.#pruneUnwatchedChannels();
13598
13263
  for (const [channel, meta] of this.#wsWantedChannels) {
13599
13264
  if (meta.auth) {
13600
13265
  // Auth tokens are short-lived; a reconnect after the deadline must
@@ -13633,11 +13298,7 @@ export class LighterProvider {
13633
13298
  // Socket closing; onclose handles recovery.
13634
13299
  }
13635
13300
  }, 60_000);
13636
- this.#deps.debugLogger.log('[LighterProvider] price stream connected (ws)', {
13637
- url,
13638
- channels: [...this.#wsWantedChannels.keys()],
13639
- subscribedChannels: this.#wsWantedChannels.size,
13640
- });
13301
+ this.#deps.debugLogger.log('[LighterProvider] price stream connected (ws)', { url, channels: [...this.#wsWantedChannels.keys()] });
13641
13302
  };
13642
13303
  ws.onmessage = (event) => {
13643
13304
  try {
@@ -13669,29 +13330,15 @@ export class LighterProvider {
13669
13330
  }
13670
13331
  this.#priceWs = null;
13671
13332
  this.#clearKeepalive();
13672
- if (!this.#hasAnySubscriber()) {
13673
- // Nothing listens, so nothing reconnects: report attempt 0.
13674
- this.#wsReconnectAttempts = 0;
13675
- this.#setConnectionState(WebSocketConnectionState.Disconnected);
13676
- return;
13677
- }
13678
- // Counted before the state change, so listeners can tell a pending
13679
- // reconnect (`disconnected` with attempt > 0) from an idle socket.
13680
- this.#wsReconnectAttempts += 1;
13681
- const delayMs = getLighterReconnectDelayMs(this.#wsReconnectAttempts);
13682
- this.#deps.debugLogger.log('[LighterProvider] price stream closed; reconnecting', {
13683
- attempt: this.#wsReconnectAttempts,
13684
- delayMs,
13685
- subscribedChannels: this.#wsWantedChannels.size,
13686
- });
13687
13333
  this.#setConnectionState(WebSocketConnectionState.Disconnected);
13688
- this.#startSocketDownGrace();
13689
- this.#wsReconnectTimer = setTimeout(() => {
13690
- this.#wsReconnectTimer = null;
13691
- if (this.#hasAnySubscriber()) {
13334
+ if (this.#hasAnySubscriber()) {
13335
+ this.#deps.debugLogger.log('[LighterProvider] price stream closed; reconnecting in 5s');
13336
+ this.#wsReconnectAttempts += 1;
13337
+ this.#wsReconnectTimer = setTimeout(() => {
13338
+ this.#wsReconnectTimer = null;
13692
13339
  this.#ensureStream();
13693
- }
13694
- }, delayMs);
13340
+ }, 5_000);
13341
+ }
13695
13342
  };
13696
13343
  ws.onerror = () => {
13697
13344
  this.#deps.debugLogger.log('[LighterProvider] price stream ws error');
@@ -13707,9 +13354,6 @@ export class LighterProvider {
13707
13354
  return;
13708
13355
  }
13709
13356
  const type = message.type ?? '';
13710
- if (!this.#isStreamFrameWanted(type)) {
13711
- return;
13712
- }
13713
13357
  if (type.includes('market_stats') && message.marketStats) {
13714
13358
  const timestamp = message.timestamp ?? Date.now();
13715
13359
  const updates = Object.values(message.marketStats).map((stat) => adaptPriceUpdateFromLighterWsStat(stat, timestamp));
@@ -13833,11 +13477,6 @@ export class LighterProvider {
13833
13477
  if (!Number.isFinite(marketId) || !message.orderBook) {
13834
13478
  return;
13835
13479
  }
13836
- // A frame that arrives after the channel was released does no work and
13837
- // must not trigger a resync, which would subscribe it again.
13838
- if (!this.#wsWantedChannels.has(`order_book/${marketId}`)) {
13839
- return;
13840
- }
13841
13480
  const { nonce, beginNonce } = message.orderBook;
13842
13481
  if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce)) {
13843
13482
  return;
@@ -14202,19 +13841,13 @@ export class LighterProvider {
14202
13841
  clearTimeout(this.#wsReconnectTimer);
14203
13842
  this.#wsReconnectTimer = null;
14204
13843
  }
14205
- this.#cancelIdleClose();
14206
- for (const timer of this.#channelReleaseTimers.values()) {
14207
- clearTimeout(timer);
14208
- }
14209
- this.#channelReleaseTimers.clear();
14210
- // Registries left empty by a pending release would otherwise linger.
14211
- deleteEmptyRegistries(this.#orderBookSubscribers);
14212
- deleteEmptyRegistries(this.#publicTradeSubscribers);
14213
- deleteEmptyRegistries(this.#candleSubscribers);
14214
- this.#clearSocketDown();
14215
13844
  this.#clearKeepalive();
14216
13845
  this.#wsWantedChannels.clear();
14217
- this.#resetAccountStreamState();
13846
+ this.#accountChannelsPromise = null;
13847
+ this.#wsPositions.clear();
13848
+ this.#hasOrdersSnapshot = false;
13849
+ this.#wsFills = null;
13850
+ this.#wsOrders.clear();
14218
13851
  this.#orderBookState.clear();
14219
13852
  this.#candleSeries.clear();
14220
13853
  this.#lastPriceBySymbol.clear();
@@ -14228,9 +13861,7 @@ export class LighterProvider {
14228
13861
  // Socket may already be closed.
14229
13862
  }
14230
13863
  }
14231
- this.#wsReconnectAttempts = 0;
14232
13864
  this.#setConnectionState(WebSocketConnectionState.Disconnected);
14233
- this.#emitHealth();
14234
13865
  };
14235
13866
  subscribeToCandles(params) {
14236
13867
  if (this.#isDisconnected) {
@@ -14283,7 +13914,7 @@ export class LighterProvider {
14283
13914
  if (seriesKey !== null) {
14284
13915
  this.#candleSubscribers.get(seriesKey)?.delete(params);
14285
13916
  }
14286
- this.#onListenerRemoved(seriesKey === null ? null : `candle/${seriesKey.replace(':', '/')}`);
13917
+ this.#releaseChannelIfUnused();
14287
13918
  };
14288
13919
  }
14289
13920
  fetchHistoricalCandles = async (options) => {
@@ -14352,7 +13983,7 @@ export class LighterProvider {
14352
13983
  if (marketId !== null) {
14353
13984
  this.#orderBookSubscribers.get(marketId)?.delete(params);
14354
13985
  }
14355
- this.#onListenerRemoved(marketId === null ? null : `order_book/${marketId}`);
13986
+ this.#releaseChannelIfUnused();
14356
13987
  };
14357
13988
  }
14358
13989
  async getPublicTrades(params) {
@@ -14395,9 +14026,20 @@ export class LighterProvider {
14395
14026
  return () => {
14396
14027
  released = true;
14397
14028
  if (marketId !== null) {
14398
- this.#publicTradeSubscribers.get(marketId)?.delete(params);
14029
+ const subscribers = this.#publicTradeSubscribers.get(marketId);
14030
+ if (subscribers?.delete(params) && subscribers.size === 0) {
14031
+ // Release the market's venue channel even while other streams keep
14032
+ // the socket open, so it stops pushing trades and is not
14033
+ // resubscribed on a reconnect or account rebind.
14034
+ this.#publicTradeSubscribers.delete(marketId);
14035
+ const channel = `trade/${marketId}`;
14036
+ this.#wsWantedChannels.delete(channel);
14037
+ if (this.#priceWs?.readyState === 1) {
14038
+ this.#priceWs.send(JSON.stringify({ type: 'unsubscribe', channel }));
14039
+ }
14040
+ }
14399
14041
  }
14400
- this.#onListenerRemoved(marketId === null ? null : `trade/${marketId}`);
14042
+ this.#releaseChannelIfUnused();
14401
14043
  };
14402
14044
  }
14403
14045
  setLiveDataConfig(_config) {
@@ -14423,136 +14065,13 @@ export class LighterProvider {
14423
14065
  this.#connectionListeners.delete(listener);
14424
14066
  };
14425
14067
  }
14426
- /**
14427
- * Lighter's health: degraded while the socket stays down past its grace
14428
- * period with listeners, after repeated 5xx responses, or during a 429/405
14429
- * cooldown.
14430
- *
14431
- * @returns The current health snapshot.
14432
- */
14433
- getProviderHealth() {
14434
- const connectionState = this.getWebSocketConnectionState();
14435
- if (this.#isDisconnected) {
14436
- return {
14437
- providerId: 'lighter',
14438
- status: 'unavailable',
14439
- reasons: [],
14440
- connectionState,
14441
- reconnectionAttempt: 0,
14442
- updatedAt: Date.now(),
14443
- };
14444
- }
14445
- const { consecutiveServerErrors, cooldownUntil } = this.#clientService.getRequestHealth();
14446
- const reasons = [];
14447
- if (this.#isSocketDown && this.#hasAnySubscriber()) {
14448
- reasons.push('socket_down');
14449
- }
14450
- if (consecutiveServerErrors >= LIGHTER_SERVER_ERROR_DEGRADED_THRESHOLD) {
14451
- reasons.push('server_errors');
14452
- }
14453
- if (cooldownUntil !== null) {
14454
- reasons.push('rate_limited');
14455
- }
14456
- return {
14457
- providerId: 'lighter',
14458
- status: reasons.length > 0 ? 'degraded' : 'healthy',
14459
- reasons,
14460
- connectionState,
14461
- reconnectionAttempt: this.#wsReconnectAttempts,
14462
- ...(cooldownUntil === null ? {} : { cooldownUntil }),
14463
- updatedAt: Date.now(),
14464
- };
14465
- }
14466
- subscribeToProviderHealth(listener) {
14467
- if (this.#isDisconnected) {
14468
- listener(this.getProviderHealth());
14469
- return NOOP_UNSUBSCRIBE;
14470
- }
14471
- this.#healthListeners.add(listener);
14472
- listener(this.getProviderHealth());
14473
- return () => {
14474
- this.#healthListeners.delete(listener);
14475
- if (this.#healthListeners.size === 0) {
14476
- // Changes go unreported with nobody listening; the next subscriber
14477
- // must hear the next change even if it matches the last one sent.
14478
- this.#lastHealthSignature = null;
14479
- }
14480
- };
14481
- }
14482
- /** Notify health listeners when the health snapshot changed. */
14483
- #emitHealth = () => {
14484
- if (this.#healthListeners.size === 0) {
14485
- return;
14486
- }
14487
- const health = this.getProviderHealth();
14488
- const signature = JSON.stringify([
14489
- health.status,
14490
- health.reasons,
14491
- health.connectionState,
14492
- health.reconnectionAttempt,
14493
- health.cooldownUntil,
14494
- ]);
14495
- if (signature === this.#lastHealthSignature) {
14496
- return;
14497
- }
14498
- this.#lastHealthSignature = signature;
14499
- for (const listener of this.#healthListeners) {
14500
- try {
14501
- listener(health);
14502
- }
14503
- catch (error) {
14504
- this.#logSubscriberError('provider-health', error);
14505
- }
14506
- }
14507
- };
14508
- /** Report degraded if the socket is still down after the grace period. */
14509
- #startSocketDownGrace = () => {
14510
- if (this.#socketDownTimer !== null || this.#isSocketDown) {
14511
- return;
14512
- }
14513
- this.#socketDownTimer = setTimeout(() => {
14514
- this.#socketDownTimer = null;
14515
- // Recorded even while nothing listens, so streams that return to the
14516
- // still-down socket report it at once.
14517
- if (this.#connectionState !== WebSocketConnectionState.Connected) {
14518
- this.#isSocketDown = true;
14519
- this.#deps.debugLogger.log('[LighterProvider] stream down past grace', {
14520
- graceMs: LIGHTER_SOCKET_DOWN_GRACE_MS,
14521
- attempt: this.#wsReconnectAttempts,
14522
- });
14523
- this.#emitHealth();
14524
- }
14525
- }, LIGHTER_SOCKET_DOWN_GRACE_MS);
14526
- };
14527
- #clearSocketDown = () => {
14528
- if (this.#socketDownTimer !== null) {
14529
- clearTimeout(this.#socketDownTimer);
14530
- this.#socketDownTimer = null;
14531
- }
14532
- this.#isSocketDown = false;
14533
- };
14534
- /** Re-report health when the current REST cooldown ends. */
14535
- #scheduleCooldownReport = () => {
14536
- if (this.#cooldownTimer !== null) {
14537
- clearTimeout(this.#cooldownTimer);
14538
- this.#cooldownTimer = null;
14539
- }
14540
- const { cooldownUntil } = this.#clientService.getRequestHealth();
14541
- if (cooldownUntil === null || this.#isDisconnected) {
14542
- return;
14543
- }
14544
- this.#cooldownTimer = setTimeout(() => {
14545
- this.#cooldownTimer = null;
14546
- this.#emitHealth();
14547
- }, Math.max(0, cooldownUntil - Date.now()) + 1);
14548
- };
14549
14068
  async reconnect() {
14550
14069
  if (this.#isDisconnected) {
14551
14070
  return;
14552
14071
  }
14553
14072
  const ws = this.#priceWs;
14554
14073
  if (ws) {
14555
- // Detach first so the onclose handler's backoff never races the
14074
+ // Detach first so the onclose handler's 5s backoff never races the
14556
14075
  // immediate reconnect below.
14557
14076
  this.#priceWs = null;
14558
14077
  this.#clearKeepalive();