@metamask-previews/perps-controller 24.0.0-preview-e92ccc12d → 24.0.0-preview-d94a14f45

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_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_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';
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,6 +957,59 @@ 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
+ };
960
1013
  // ============================================================================
961
1014
  // LighterProvider
962
1015
  // ============================================================================
@@ -1008,12 +1061,16 @@ export class LighterProvider {
1008
1061
  #connectionState = WebSocketConnectionState.Disconnected;
1009
1062
  /** Consecutive reconnect attempts since the last successful open. */
1010
1063
  #wsReconnectAttempts = 0;
1064
+ /** The attempt connection listeners last received with a state. */
1065
+ #notifiedReconnectAttempts = 0;
1011
1066
  #connectionListeners = new Set();
1012
1067
  #setConnectionState = (state) => {
1013
- if (this.#connectionState === state) {
1068
+ if (this.#connectionState === state &&
1069
+ this.#notifiedReconnectAttempts === this.#wsReconnectAttempts) {
1014
1070
  return;
1015
1071
  }
1016
1072
  this.#connectionState = state;
1073
+ this.#notifiedReconnectAttempts = this.#wsReconnectAttempts;
1017
1074
  for (const listener of this.#connectionListeners) {
1018
1075
  try {
1019
1076
  listener(state, this.#wsReconnectAttempts);
@@ -1022,8 +1079,25 @@ export class LighterProvider {
1022
1079
  this.#logSubscriberError('connection-state', error);
1023
1080
  }
1024
1081
  }
1082
+ this.#emitHealth();
1025
1083
  };
1026
1084
  #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;
1027
1101
  /** Merged latest price per symbol, replayed to late price subscribers. */
1028
1102
  #lastPriceBySymbol = new Map();
1029
1103
  /** Merged live position state from account_all_positions (keyed marketId). */
@@ -1087,8 +1161,14 @@ export class LighterProvider {
1087
1161
  options.lighterAuthConfig?.apiKeyIndex ?? LIGHTER_DEFAULT_API_KEY_INDEX;
1088
1162
  this.#preferredApiKeyIndex = this.#apiKeyIndex;
1089
1163
  this.#configuredAccountIndex = options.lighterAuthConfig?.accountIndex;
1164
+ this.#socketIdleCloseMs =
1165
+ options.socketIdleCloseMs ?? LIGHTER_SOCKET_IDLE_CLOSE_MS;
1090
1166
  this.#clientService = new LighterClientService(this.#deps, {
1091
1167
  isTestnet: this.#isTestnet,
1168
+ onRequestHealthChange: () => {
1169
+ this.#scheduleCooldownReport();
1170
+ this.#emitHealth();
1171
+ },
1092
1172
  });
1093
1173
  this.#walletService = new LighterWalletService(this.#deps, {
1094
1174
  isTestnet: this.#isTestnet,
@@ -1195,9 +1275,16 @@ export class LighterProvider {
1195
1275
  // fences instead of submitting after the provider was torn down.
1196
1276
  this.#interruptChase();
1197
1277
  this.#isDisconnected = true;
1278
+ this.#clientService.cancelHeldRequests();
1198
1279
  this.#invalidateSessionState();
1199
1280
  this.#removeSignerResetListener();
1200
1281
  this.#teardownStream();
1282
+ if (this.#cooldownTimer !== null) {
1283
+ clearTimeout(this.#cooldownTimer);
1284
+ this.#cooldownTimer = null;
1285
+ }
1286
+ this.#healthListeners.clear();
1287
+ this.#lastHealthSignature = null;
1201
1288
  this.#priceSubscribers.clear();
1202
1289
  this.#oiCapSubscribers.clear();
1203
1290
  this.#accountSubscribers.clear();
@@ -1511,13 +1598,20 @@ export class LighterProvider {
1511
1598
  if (this.#priceSubscribers.size > 0 || this.#oiCapSubscribers.size > 0) {
1512
1599
  this.#requestChannel('market_stats/all');
1513
1600
  }
1514
- for (const marketId of this.#orderBookSubscribers.keys()) {
1515
- this.#requestChannel(`order_book/${marketId}`);
1601
+ for (const [marketId, subscribers] of this.#orderBookSubscribers) {
1602
+ if (subscribers.size > 0) {
1603
+ this.#requestChannel(`order_book/${marketId}`);
1604
+ }
1516
1605
  }
1517
- for (const marketId of this.#publicTradeSubscribers.keys()) {
1518
- this.#requestChannel(`trade/${marketId}`);
1606
+ for (const [marketId, subscribers] of this.#publicTradeSubscribers) {
1607
+ if (subscribers.size > 0) {
1608
+ this.#requestChannel(`trade/${marketId}`);
1609
+ }
1519
1610
  }
1520
- for (const seriesKey of this.#candleSubscribers.keys()) {
1611
+ for (const [seriesKey, subscribers] of this.#candleSubscribers) {
1612
+ if (subscribers.size === 0) {
1613
+ continue;
1614
+ }
1521
1615
  // Series keys are `${marketId}:${resolution}`; the channel form uses
1522
1616
  // slashes. The teardown cleared the series state, and the message
1523
1617
  // router drops updates for unknown series — recreate an empty series
@@ -1525,10 +1619,7 @@ export class LighterProvider {
1525
1619
  this.#candleSeries.set(seriesKey, new Map());
1526
1620
  this.#requestChannel(`candle/${seriesKey.replace(':', '/')}`);
1527
1621
  }
1528
- if (this.#accountSubscribers.size > 0 ||
1529
- this.#positionSubscribers.size > 0 ||
1530
- this.#orderSubscribers.size > 0 ||
1531
- this.#fillSubscribers.size > 0) {
1622
+ if (this.#hasAccountSubscriber()) {
1532
1623
  // The promise was cleared by the teardown, so this re-resolves the
1533
1624
  // account channels against the newly bound address.
1534
1625
  this.#ensureAccountChannels();
@@ -5727,7 +5818,7 @@ export class LighterProvider {
5727
5818
  // INNERMOST: the bridge mutex — the WASM client is a singleton
5728
5819
  // per bridge, so ensure-correct-client + every sign of a section
5729
5820
  // are serialized across ALL providers sharing the bridge.
5730
- async () => await withProcessMutex(bridgeMutexKey(this.#rawSignerBridge()), criticalSection));
5821
+ async () => await withProcessMutex(bridgeMutexKey(this.#rawSignerBridge()), async () => await this.#clientService.runTradingSection(criticalSection)));
5731
5822
  const run = this.#writeChain.then(guardedSection, guardedSection);
5732
5823
  this.#writeChain = run.then(() => undefined, () => undefined);
5733
5824
  return await run;
@@ -7926,7 +8017,22 @@ export class LighterProvider {
7926
8017
  }
7927
8018
  }
7928
8019
  }
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
+ }
7929
8032
  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) {
7930
8036
  const deferProviderErrorReport = input.deferProviderErrorReport === true;
7931
8037
  const params = { ...input };
7932
8038
  delete params.deferProviderErrorReport;
@@ -9685,6 +9791,9 @@ export class LighterProvider {
9685
9791
  throw new Error('Lighter native TWAP lifecycle is unavailable: authoritative parent fills and termination are not established');
9686
9792
  }
9687
9793
  async cancelOrder(params, inheritedGeneration) {
9794
+ return await this.#runTradingFlow(async () => await this.#cancelOrder(params, inheritedGeneration));
9795
+ }
9796
+ async #cancelOrder(params, inheritedGeneration) {
9688
9797
  if (params.orderType === 'chase') {
9689
9798
  try {
9690
9799
  return await this.#cancelChase(params);
@@ -9778,6 +9887,9 @@ export class LighterProvider {
9778
9887
  * @returns Truthful durable same-order outcome, never a placement receipt.
9779
9888
  */
9780
9889
  async editOrder(params) {
9890
+ return await this.#runTradingFlow(async () => await this.#editOrder(params));
9891
+ }
9892
+ async #editOrder(params) {
9781
9893
  try {
9782
9894
  this.#ensureSessionBinding();
9783
9895
  const generation = this.#sessionGeneration;
@@ -10227,6 +10339,9 @@ export class LighterProvider {
10227
10339
  return held > 0 && requestedSize >= held * (1 - 1e-9);
10228
10340
  };
10229
10341
  async closePosition(rawParams) {
10342
+ return await this.#runTradingFlow(async () => await this.#closePosition(rawParams));
10343
+ }
10344
+ async #closePosition(rawParams) {
10230
10345
  const params = this.#normalizeCloseParams(rawParams);
10231
10346
  try {
10232
10347
  // One intent identity from the position read through the final write:
@@ -10280,7 +10395,7 @@ export class LighterProvider {
10280
10395
  }
10281
10396
  }
10282
10397
  async updatePositionTPSL(params) {
10283
- return this.#updatePositionTPSL(params);
10398
+ return await this.#runTradingFlow(async () => await this.#updatePositionTPSL(params));
10284
10399
  }
10285
10400
  /**
10286
10401
  * Lighter settles position protection as one journaled TP/SL pair, so it
@@ -10301,7 +10416,7 @@ export class LighterProvider {
10301
10416
  * @returns Settled successor result; failure retains the source obligation.
10302
10417
  */
10303
10418
  async resolveRecoveryProtection(params) {
10304
- const result = await this.#resolveRecoveryProtection(params);
10419
+ const result = await this.#runTradingFlow(async () => await this.#resolveRecoveryProtection(params));
10305
10420
  return {
10306
10421
  ...result,
10307
10422
  status: result.success ? 'settled' : 'unresolved',
@@ -11883,6 +11998,9 @@ export class LighterProvider {
11883
11998
  };
11884
11999
  };
11885
12000
  async updateMargin(input) {
12001
+ return await this.#runTradingFlow(async () => await this.#updateMargin(input));
12002
+ }
12003
+ async #updateMargin(input) {
11886
12004
  const params = { ...input };
11887
12005
  try {
11888
12006
  this.#ensureSessionBinding();
@@ -11961,6 +12079,9 @@ export class LighterProvider {
11961
12079
  }
11962
12080
  }
11963
12081
  async withdraw(params) {
12082
+ return await this.#runTradingFlow(async () => await this.#withdraw(params));
12083
+ }
12084
+ async #withdraw(params) {
11964
12085
  try {
11965
12086
  this.#ensureSessionBinding();
11966
12087
  const generationAtIntent = this.#sessionGeneration;
@@ -12990,7 +13111,7 @@ export class LighterProvider {
12990
13111
  this.#ensureStream();
12991
13112
  return () => {
12992
13113
  this.#priceSubscribers.delete(params);
12993
- this.#releaseChannelIfUnused();
13114
+ this.#onListenerRemoved('market_stats/all');
12994
13115
  };
12995
13116
  }
12996
13117
  subscribeToOICaps(params) {
@@ -13002,7 +13123,7 @@ export class LighterProvider {
13002
13123
  this.#ensureStream();
13003
13124
  return () => {
13004
13125
  this.#oiCapSubscribers.delete(params);
13005
- this.#releaseChannelIfUnused();
13126
+ this.#onListenerRemoved('market_stats/all');
13006
13127
  };
13007
13128
  }
13008
13129
  subscribeToAccount(params) {
@@ -13013,7 +13134,7 @@ export class LighterProvider {
13013
13134
  this.#ensureAccountChannels();
13014
13135
  return () => {
13015
13136
  this.#accountSubscribers.delete(params);
13016
- this.#releaseChannelIfUnused();
13137
+ this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13017
13138
  };
13018
13139
  }
13019
13140
  subscribeToPositions(params) {
@@ -13027,7 +13148,7 @@ export class LighterProvider {
13027
13148
  this.#ensureAccountChannels();
13028
13149
  return () => {
13029
13150
  this.#positionSubscribers.delete(params);
13030
- this.#releaseChannelIfUnused();
13151
+ this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13031
13152
  };
13032
13153
  }
13033
13154
  subscribeToOrders(params) {
@@ -13041,7 +13162,7 @@ export class LighterProvider {
13041
13162
  this.#ensureAccountChannels();
13042
13163
  return () => {
13043
13164
  this.#orderSubscribers.delete(params);
13044
- this.#releaseChannelIfUnused();
13165
+ this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13045
13166
  };
13046
13167
  }
13047
13168
  subscribeToOrderFills(params) {
@@ -13066,7 +13187,7 @@ export class LighterProvider {
13066
13187
  .catch(() => undefined);
13067
13188
  return () => {
13068
13189
  this.#fillSubscribers.delete(params);
13069
- this.#releaseChannelIfUnused();
13190
+ this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
13070
13191
  };
13071
13192
  }
13072
13193
  // ============================================================================
@@ -13103,6 +13224,7 @@ export class LighterProvider {
13103
13224
  if (this.#isDisconnected) {
13104
13225
  return;
13105
13226
  }
13227
+ this.#cancelChannelRelease(LIGHTER_ACCOUNT_CHANNELS_KEY);
13106
13228
  if (this.#accountChannelsPromise) {
13107
13229
  this.#ensureStream();
13108
13230
  return;
@@ -13123,6 +13245,10 @@ export class LighterProvider {
13123
13245
  // Fails closed when no wallet account is bound — a configured
13124
13246
  // account index alone must never subscribe user channels.
13125
13247
  this.#assertSession(generation);
13248
+ // Released (no account listener left) or replaced while resolving.
13249
+ if (this.#accountChannelsPromise !== setupPromise) {
13250
+ return;
13251
+ }
13126
13252
  this.#requestChannel(`user_stats/${accountIndex}`);
13127
13253
  this.#requestChannel(`account_all_positions/${accountIndex}`);
13128
13254
  this.#requestChannel(`account_all_trades/${accountIndex}`);
@@ -13131,6 +13257,9 @@ export class LighterProvider {
13131
13257
  try {
13132
13258
  const auth = await this.#getAuthToken();
13133
13259
  this.#assertSession(generation);
13260
+ if (this.#accountChannelsPromise !== setupPromise) {
13261
+ return;
13262
+ }
13134
13263
  this.#requestChannel(`account_all_orders/${accountIndex}`, auth);
13135
13264
  }
13136
13265
  catch (error) {
@@ -13191,18 +13320,47 @@ export class LighterProvider {
13191
13320
  #hasAnySubscriber = () => {
13192
13321
  return (this.#priceSubscribers.size > 0 ||
13193
13322
  this.#oiCapSubscribers.size > 0 ||
13194
- this.#accountSubscribers.size > 0 ||
13195
- this.#positionSubscribers.size > 0 ||
13196
- this.#orderSubscribers.size > 0 ||
13197
- this.#fillSubscribers.size > 0 ||
13323
+ this.#hasAccountSubscriber() ||
13198
13324
  [...this.#orderBookSubscribers.values()].some((subscribers) => subscribers.size > 0) ||
13199
13325
  [...this.#publicTradeSubscribers.values()].some((subscribers) => subscribers.size > 0) ||
13200
13326
  [...this.#candleSubscribers.values()].some((subscribers) => subscribers.size > 0));
13201
13327
  };
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
+ };
13202
13359
  #requestChannel = (channel, auth) => {
13203
13360
  if (this.#isDisconnected) {
13204
13361
  return;
13205
13362
  }
13363
+ this.#cancelChannelRelease(channel);
13206
13364
  if (this.#wsWantedChannels.has(channel)) {
13207
13365
  return;
13208
13366
  }
@@ -13210,19 +13368,194 @@ export class LighterProvider {
13210
13368
  if (this.#priceWs?.readyState === 1) {
13211
13369
  this.#sendSubscribe(channel, auth);
13212
13370
  }
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
+ }
13213
13514
  };
13214
13515
  #sendSubscribe = (channel, auth) => {
13215
13516
  this.#priceWs?.send(JSON.stringify(auth
13216
13517
  ? { type: 'subscribe', channel, auth }
13217
13518
  : { type: 'subscribe', channel }));
13218
13519
  };
13219
- #releaseChannelIfUnused = () => {
13220
- if (!this.#hasAnySubscriber()) {
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.
13221
13529
  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;
13222
13546
  }
13223
13547
  };
13224
13548
  #ensureStream = () => {
13225
- if (this.#isDisconnected || this.#priceWs || this.#pricePollTimer) {
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) {
13226
13559
  return;
13227
13560
  }
13228
13561
  if (this.#webSocketCtor) {
@@ -13259,7 +13592,9 @@ export class LighterProvider {
13259
13592
  }
13260
13593
  const generationAtOpen = this.#sessionGeneration;
13261
13594
  this.#wsReconnectAttempts = 0;
13595
+ this.#clearSocketDown();
13262
13596
  this.#setConnectionState(WebSocketConnectionState.Connected);
13597
+ this.#pruneUnwatchedChannels();
13263
13598
  for (const [channel, meta] of this.#wsWantedChannels) {
13264
13599
  if (meta.auth) {
13265
13600
  // Auth tokens are short-lived; a reconnect after the deadline must
@@ -13298,7 +13633,11 @@ export class LighterProvider {
13298
13633
  // Socket closing; onclose handles recovery.
13299
13634
  }
13300
13635
  }, 60_000);
13301
- this.#deps.debugLogger.log('[LighterProvider] price stream connected (ws)', { url, channels: [...this.#wsWantedChannels.keys()] });
13636
+ this.#deps.debugLogger.log('[LighterProvider] price stream connected (ws)', {
13637
+ url,
13638
+ channels: [...this.#wsWantedChannels.keys()],
13639
+ subscribedChannels: this.#wsWantedChannels.size,
13640
+ });
13302
13641
  };
13303
13642
  ws.onmessage = (event) => {
13304
13643
  try {
@@ -13330,15 +13669,29 @@ export class LighterProvider {
13330
13669
  }
13331
13670
  this.#priceWs = null;
13332
13671
  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
+ });
13333
13687
  this.#setConnectionState(WebSocketConnectionState.Disconnected);
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;
13688
+ this.#startSocketDownGrace();
13689
+ this.#wsReconnectTimer = setTimeout(() => {
13690
+ this.#wsReconnectTimer = null;
13691
+ if (this.#hasAnySubscriber()) {
13339
13692
  this.#ensureStream();
13340
- }, 5_000);
13341
- }
13693
+ }
13694
+ }, delayMs);
13342
13695
  };
13343
13696
  ws.onerror = () => {
13344
13697
  this.#deps.debugLogger.log('[LighterProvider] price stream ws error');
@@ -13354,6 +13707,9 @@ export class LighterProvider {
13354
13707
  return;
13355
13708
  }
13356
13709
  const type = message.type ?? '';
13710
+ if (!this.#isStreamFrameWanted(type)) {
13711
+ return;
13712
+ }
13357
13713
  if (type.includes('market_stats') && message.marketStats) {
13358
13714
  const timestamp = message.timestamp ?? Date.now();
13359
13715
  const updates = Object.values(message.marketStats).map((stat) => adaptPriceUpdateFromLighterWsStat(stat, timestamp));
@@ -13477,6 +13833,11 @@ export class LighterProvider {
13477
13833
  if (!Number.isFinite(marketId) || !message.orderBook) {
13478
13834
  return;
13479
13835
  }
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
+ }
13480
13841
  const { nonce, beginNonce } = message.orderBook;
13481
13842
  if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce)) {
13482
13843
  return;
@@ -13841,13 +14202,19 @@ export class LighterProvider {
13841
14202
  clearTimeout(this.#wsReconnectTimer);
13842
14203
  this.#wsReconnectTimer = null;
13843
14204
  }
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();
13844
14215
  this.#clearKeepalive();
13845
14216
  this.#wsWantedChannels.clear();
13846
- this.#accountChannelsPromise = null;
13847
- this.#wsPositions.clear();
13848
- this.#hasOrdersSnapshot = false;
13849
- this.#wsFills = null;
13850
- this.#wsOrders.clear();
14217
+ this.#resetAccountStreamState();
13851
14218
  this.#orderBookState.clear();
13852
14219
  this.#candleSeries.clear();
13853
14220
  this.#lastPriceBySymbol.clear();
@@ -13861,7 +14228,9 @@ export class LighterProvider {
13861
14228
  // Socket may already be closed.
13862
14229
  }
13863
14230
  }
14231
+ this.#wsReconnectAttempts = 0;
13864
14232
  this.#setConnectionState(WebSocketConnectionState.Disconnected);
14233
+ this.#emitHealth();
13865
14234
  };
13866
14235
  subscribeToCandles(params) {
13867
14236
  if (this.#isDisconnected) {
@@ -13914,7 +14283,7 @@ export class LighterProvider {
13914
14283
  if (seriesKey !== null) {
13915
14284
  this.#candleSubscribers.get(seriesKey)?.delete(params);
13916
14285
  }
13917
- this.#releaseChannelIfUnused();
14286
+ this.#onListenerRemoved(seriesKey === null ? null : `candle/${seriesKey.replace(':', '/')}`);
13918
14287
  };
13919
14288
  }
13920
14289
  fetchHistoricalCandles = async (options) => {
@@ -13983,7 +14352,7 @@ export class LighterProvider {
13983
14352
  if (marketId !== null) {
13984
14353
  this.#orderBookSubscribers.get(marketId)?.delete(params);
13985
14354
  }
13986
- this.#releaseChannelIfUnused();
14355
+ this.#onListenerRemoved(marketId === null ? null : `order_book/${marketId}`);
13987
14356
  };
13988
14357
  }
13989
14358
  async getPublicTrades(params) {
@@ -14026,20 +14395,9 @@ export class LighterProvider {
14026
14395
  return () => {
14027
14396
  released = true;
14028
14397
  if (marketId !== null) {
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
- }
14398
+ this.#publicTradeSubscribers.get(marketId)?.delete(params);
14041
14399
  }
14042
- this.#releaseChannelIfUnused();
14400
+ this.#onListenerRemoved(marketId === null ? null : `trade/${marketId}`);
14043
14401
  };
14044
14402
  }
14045
14403
  setLiveDataConfig(_config) {
@@ -14065,13 +14423,136 @@ export class LighterProvider {
14065
14423
  this.#connectionListeners.delete(listener);
14066
14424
  };
14067
14425
  }
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
+ };
14068
14549
  async reconnect() {
14069
14550
  if (this.#isDisconnected) {
14070
14551
  return;
14071
14552
  }
14072
14553
  const ws = this.#priceWs;
14073
14554
  if (ws) {
14074
- // Detach first so the onclose handler's 5s backoff never races the
14555
+ // Detach first so the onclose handler's backoff never races the
14075
14556
  // immediate reconnect below.
14076
14557
  this.#priceWs = null;
14077
14558
  this.#clearKeepalive();