@metamask-previews/perps-controller 26.2.0-preview-2cd622db9 → 26.2.0-preview-53b9b7d11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/PerpsController-method-action-types.d.ts +11 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +8 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +45 -13
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
  10. package/dist/aggregation/SubscriptionMultiplexer.js +10 -2
  11. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
  12. package/dist/constants/eventNames.d.ts +2 -0
  13. package/dist/constants/eventNames.d.ts.map +1 -1
  14. package/dist/constants/eventNames.js +3 -0
  15. package/dist/constants/eventNames.js.map +1 -1
  16. package/dist/constants/lighterConfig.d.ts +11 -0
  17. package/dist/constants/lighterConfig.d.ts.map +1 -1
  18. package/dist/constants/lighterConfig.js +11 -0
  19. package/dist/constants/lighterConfig.js.map +1 -1
  20. package/dist/constants/perpsConfig.d.ts +6 -0
  21. package/dist/constants/perpsConfig.d.ts.map +1 -1
  22. package/dist/constants/perpsConfig.js +6 -0
  23. package/dist/constants/perpsConfig.js.map +1 -1
  24. package/dist/errors.d.ts +7 -0
  25. package/dist/errors.d.ts.map +1 -1
  26. package/dist/errors.js +10 -0
  27. package/dist/errors.js.map +1 -1
  28. package/dist/index.d.ts +3 -3
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/perpsErrorCodes.d.ts +1 -0
  33. package/dist/perpsErrorCodes.d.ts.map +1 -1
  34. package/dist/perpsErrorCodes.js +1 -0
  35. package/dist/perpsErrorCodes.js.map +1 -1
  36. package/dist/providers/AggregatedPerpsProvider.d.ts +6 -1
  37. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  38. package/dist/providers/AggregatedPerpsProvider.js +14 -0
  39. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  40. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  41. package/dist/providers/HyperLiquidProvider.js +1 -3
  42. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  43. package/dist/providers/LighterProvider.d.ts +6 -1
  44. package/dist/providers/LighterProvider.d.ts.map +1 -1
  45. package/dist/providers/LighterProvider.js +458 -149
  46. package/dist/providers/LighterProvider.js.map +1 -1
  47. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  48. package/dist/services/HyperLiquidClientService.js +13 -1
  49. package/dist/services/HyperLiquidClientService.js.map +1 -1
  50. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  51. package/dist/services/HyperLiquidSubscriptionService.js +1 -0
  52. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  53. package/dist/services/StreamChannelManager.d.ts +12 -2
  54. package/dist/services/StreamChannelManager.d.ts.map +1 -1
  55. package/dist/services/StreamChannelManager.js +18 -0
  56. package/dist/services/StreamChannelManager.js.map +1 -1
  57. package/dist/types/index.d.ts +21 -2
  58. package/dist/types/index.d.ts.map +1 -1
  59. package/dist/types/index.js.map +1 -1
  60. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  61. package/dist/utils/perpsClientCopy.js +4 -0
  62. package/dist/utils/perpsClientCopy.js.map +1 -1
  63. package/docs/architecture.md +5 -4
  64. package/docs/venues/lighter/api-keys.md +8 -0
  65. package/package.json +3 -3
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import { hexToBytes } from '@metamask/utils';
17
17
  import { BigNumber } from 'bignumber.js';
18
- 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, getLighterMakerMinimums, getLighterChainId, getLighterTransactionOutcome, LIGHTER_RESOLUTION_MS, LIGHTER_MAX_WIRE_PRICE, LIGHTER_MAX_DECIMALS, 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_TRANSFER, 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, isLighterOrderSizeDecimals, toLighterInteger, } from '../constants/lighterConfig.js';
18
+ 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, getLighterMakerMinimums, getLighterChainId, getLighterTransactionOutcome, LIGHTER_RESOLUTION_MS, LIGHTER_MAX_WIRE_PRICE, LIGHTER_MAX_DECIMALS, 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_TRANSFER, 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, LIGHTER_ACCOUNT_DISCOVERY_CONFIG, LIGHTER_ORDERS_RESUBSCRIBE_RETRY, parseLighterStrictDecimal, isLighterOrderSizeDecimals, toLighterInteger, } from '../constants/lighterConfig.js';
19
19
  import { createTpslLegReplaceUnsupportedError, PerpsControllerError, } from '../errors.js';
20
20
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
21
21
  import { hasErrorInCauseChain } from '../services/causeChain.js';
@@ -967,9 +967,10 @@ const USER_REJECTED_MESSAGE_PATTERN = /user (rejected|denied|cancell?ed)/iu;
967
967
  const isDeclinedRegistration = (error) => hasErrorInCauseChain(error, (current) => current.code === USER_REJECTED_REQUEST_CODE ||
968
968
  USER_REJECTED_MESSAGE_PATTERN.test(current.message));
969
969
  /**
970
- * Empty account state returned when reads fail or no account exists.
970
+ * Empty account state returned only for a venue-confirmed missing account.
971
971
  */
972
972
  const EMPTY_ACCOUNT_STATE = {
973
+ exchangeAccountStatus: { registered: false },
973
974
  totalBalance: '0',
974
975
  spendableBalance: '0',
975
976
  withdrawableBalance: '0',
@@ -1123,9 +1124,10 @@ export class LighterProvider {
1123
1124
  #lastPriceBySymbol = new Map();
1124
1125
  /** Merged live position state from account_all_positions (keyed marketId). */
1125
1126
  #wsPositions = new Map();
1126
- /** Merged live open orders from account_all_orders (keyed orderId). */
1127
- #wsOrders = new Map();
1128
- #hasOrdersSnapshot = false;
1127
+ /** Null until this session has received a valid initial orders snapshot. */
1128
+ #wsOrders = null;
1129
+ /** A gap stays open until a snapshot; only a failed repair may retry on the next frame. */
1130
+ #ordersSnapshotRepair = null;
1129
1131
  /** Last validated fill history for this wallet session, including empty. */
1130
1132
  #wsFills = null;
1131
1133
  #oiCapSubscribers = new Set();
@@ -1156,8 +1158,13 @@ export class LighterProvider {
1156
1158
  #candleSubscribers = new Map();
1157
1159
  /** Cached candle series per `marketId:resolution` (keyed by open time). */
1158
1160
  #candleSeries = new Map();
1161
+ #lastStreamAccount = null;
1162
+ #accountDiscoveryTimer = null;
1163
+ #ordersResubscribeTimer = null;
1159
1164
  /** Dedup for the async account-channel setup. */
1160
- #accountChannelsPromise = null;
1165
+ #accountChannelSetup = null;
1166
+ // Only a settled absence (not a transport failure) is retried on discovery.
1167
+ #accountChannelsAwaiting = null;
1161
1168
  /** Derived venue public key hex, set after the signer client is created. */
1162
1169
  #venuePublicKey = null;
1163
1170
  /** Signer session dedup. */
@@ -1504,6 +1511,19 @@ export class LighterProvider {
1504
1511
  this.#readyApiKeyIndex = null;
1505
1512
  this.#authToken = null;
1506
1513
  this.#clearBridgeOwnership();
1514
+ // Retire the private orders channel and its replay cache together. Public
1515
+ // balances and positions remain live while waiting for a usable key.
1516
+ this.#wsOrders = null;
1517
+ this.#ordersSnapshotRepair = null;
1518
+ if (this.#accountIndex !== null) {
1519
+ const channel = `account_all_orders/${this.#accountIndex}`;
1520
+ if (this.#wsWantedChannels.has(channel)) {
1521
+ this.#releaseChannel(channel, true);
1522
+ this.#accountChannelSetup = null;
1523
+ this.#accountChannelsAwaiting = 'tradingKey';
1524
+ this.#notifySubscriptionError(new PerpsControllerError(PERPS_ERROR_CODES.ORDERS_STREAM_PAUSED, 'Lighter orders stream paused after signer reset'), ['orders']);
1525
+ }
1526
+ }
1507
1527
  this.#deps.debugLogger.log('[LighterProvider] signer session invalidated (client lost); will re-setup on next call');
1508
1528
  };
1509
1529
  /** Replace this provider's listener on the client-owned signer bridge. */
@@ -1609,6 +1629,7 @@ export class LighterProvider {
1609
1629
  * the empty state only when the venue confirmed this wallet has no account.
1610
1630
  */
1611
1631
  #emitAccountBindingReset = (account) => {
1632
+ this.#lastStreamAccount = account;
1612
1633
  for (const subscriber of this.#accountSubscribers) {
1613
1634
  try {
1614
1635
  subscriber.callback(account);
@@ -1665,7 +1686,7 @@ export class LighterProvider {
1665
1686
  if (this.#hasAccountSubscriber()) {
1666
1687
  // The promise was cleared by the teardown, so this re-resolves the
1667
1688
  // account channels against the newly bound address.
1668
- this.#ensureAccountChannels();
1689
+ this.#ensureAccountChannels({ existingKeysOnly: true });
1669
1690
  }
1670
1691
  this.#ensureStream();
1671
1692
  };
@@ -1682,50 +1703,80 @@ export class LighterProvider {
1682
1703
  if (this.#accountIndex !== null) {
1683
1704
  return this.#accountIndex;
1684
1705
  }
1685
- if (this.#configuredAccountIndex !== undefined) {
1686
- // A configured index must be a Standard (0-fee) account AND owned by
1687
- // the bound wallet address: a signed-in wallet must never read or
1688
- // trade another owner's account just because an env var names it.
1689
- const generationAtCheck = this.#sessionGeneration;
1690
- const configured = await this.#clientService.getAccountByIndex(this.#configuredAccountIndex);
1691
- this.#ensureSessionBinding();
1692
- if (generationAtCheck !== this.#sessionGeneration) {
1693
- return await this.#ensureAccountIndex();
1694
- }
1695
- const configuredAccount = configured.accounts[0];
1696
- this.#assertStandardAccount(configuredAccount?.accountType);
1697
- this.#assertAccountOwnership(configuredAccount);
1698
- this.#accountIndex = this.#configuredAccountIndex;
1699
- return this.#accountIndex;
1700
- }
1701
1706
  const generation = this.#sessionGeneration;
1702
1707
  const address = this.#walletService.getUserAddress();
1703
- let response;
1708
+ const master = await this.#lookupMasterAccount(address);
1709
+ this.#ensureSessionBinding();
1710
+ if (generation !== this.#sessionGeneration) {
1711
+ return await this.#ensureAccountIndex();
1712
+ }
1713
+ if (master === undefined && this.#configuredAccountIndex === undefined) {
1714
+ // A concurrent lookup may have recorded the index while this stale
1715
+ // one was in flight; the cached index wins over an older empty
1716
+ // result, so callers never read a registered wallet as absent.
1717
+ if (this.#accountIndex !== null) {
1718
+ return this.#accountIndex;
1719
+ }
1720
+ throw new LighterAccountNotFoundError(address);
1721
+ }
1722
+ this.#assertStandardAccount(master?.accountType);
1723
+ this.#assertAccountOwnership(master);
1724
+ return this.#recordAccountIndex(master.index);
1725
+ };
1726
+ async #lookupMasterAccount(address) {
1727
+ if (this.#configuredAccountIndex !== undefined) {
1728
+ const response = await this.#clientService.getAccountByIndex(this.#configuredAccountIndex);
1729
+ return response.accounts[0];
1730
+ }
1704
1731
  try {
1705
- response = await this.#clientService.getAccountsByL1Address(address);
1732
+ const { subAccounts } = await this.#clientService.getAccountsByL1Address(address);
1733
+ if (subAccounts.length === 0) {
1734
+ return undefined;
1735
+ }
1736
+ return subAccounts.reduce((master, account) => account.index < master.index ? account : master);
1706
1737
  }
1707
1738
  catch (error) {
1708
1739
  if (error instanceof LighterApiError && error.code === 21100) {
1709
- throw new LighterAccountNotFoundError(address);
1740
+ return undefined;
1710
1741
  }
1711
1742
  throw error;
1712
1743
  }
1713
- // Re-run the binding so an EXTERNAL switch nothing else observed also
1714
- // advances the generation, then compare: caching after any switch
1715
- // would poison the new session with the old account. Retry instead.
1744
+ }
1745
+ #recordAccountIndex(index) {
1746
+ this.#accountIndex = index;
1747
+ this.#cancelAccountDiscovery();
1748
+ if (this.#lastStreamAccount === EMPTY_ACCOUNT_STATE) {
1749
+ this.#lastStreamAccount = null;
1750
+ }
1751
+ this.#resumeAccountChannels();
1752
+ return index;
1753
+ }
1754
+ /**
1755
+ * @param params - Lighter provider route.
1756
+ * @returns Registration status and the registered wallet's master index.
1757
+ */
1758
+ async getExchangeAccountStatus(params) {
1716
1759
  this.#ensureSessionBinding();
1717
- if (generation !== this.#sessionGeneration) {
1718
- return await this.#ensureAccountIndex();
1760
+ const generation = this.#sessionGeneration;
1761
+ let accountIndex;
1762
+ try {
1763
+ accountIndex = await this.#ensureAccountIndex();
1719
1764
  }
1720
- if (!response.subAccounts?.length) {
1721
- throw new LighterAccountNotFoundError(address);
1765
+ catch (error) {
1766
+ if (!(error instanceof LighterAccountNotFoundError)) {
1767
+ throw error;
1768
+ }
1769
+ accountIndex = this.#accountIndex;
1722
1770
  }
1723
- const master = response.subAccounts.reduce((min, account) => account.index < min.index ? account : min);
1724
- this.#assertStandardAccount(master.accountType);
1725
- this.#assertAccountOwnership(master);
1726
- this.#accountIndex = master.index;
1727
- return this.#accountIndex;
1728
- };
1771
+ // Even a cached index or a delayed 21100 can belong to a wallet just left.
1772
+ this.#ensureSessionBinding();
1773
+ if (generation !== this.#sessionGeneration) {
1774
+ return await this.getExchangeAccountStatus(params);
1775
+ }
1776
+ return accountIndex === null
1777
+ ? { registered: false }
1778
+ : { registered: true, accountIndex };
1779
+ }
1729
1780
  /**
1730
1781
  * Account index notify-perps watches for this wallet: the master (lowest)
1731
1782
  * account, the one the provider always trades with.
@@ -1740,7 +1791,7 @@ export class LighterProvider {
1740
1791
  *
1741
1792
  * @param account - Venue account returned for the bound wallet.
1742
1793
  */
1743
- #assertAccountOwnership = (account) => {
1794
+ #assertAccountOwnership(account) {
1744
1795
  if (account === undefined ||
1745
1796
  !Number.isSafeInteger(account.index) ||
1746
1797
  account.index < 0) {
@@ -1753,7 +1804,7 @@ export class LighterProvider {
1753
1804
  if (account.l1Address.toLowerCase() !== this.#boundAddress) {
1754
1805
  throw new Error(`${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} account is not owned by the selected wallet address`);
1755
1806
  }
1756
- };
1807
+ }
1757
1808
  /**
1758
1809
  * Local account identities recorded before any venue mutation.
1759
1810
  *
@@ -1849,19 +1900,11 @@ export class LighterProvider {
1849
1900
  }
1850
1901
  let account;
1851
1902
  try {
1852
- if (this.#configuredAccountIndex === undefined) {
1853
- const response = await this.#clientService.getAccountsByL1Address(this.#walletService.getUserAddress());
1854
- account = response.subAccounts.reduce((selected, next) => selected === undefined || next.index < selected.index
1855
- ? next
1856
- : selected, undefined);
1857
- }
1858
- else {
1859
- const response = await this.#clientService.getAccountByIndex(this.#configuredAccountIndex);
1860
- account = response.accounts[0];
1861
- }
1903
+ account = await this.#lookupMasterAccount(this.#walletService.getUserAddress());
1862
1904
  }
1863
1905
  catch (error) {
1864
1906
  this.#assertSession(generation);
1907
+ // A missing configured index can still have local recovery records.
1865
1908
  if (error instanceof LighterApiError && error.code === 21100) {
1866
1909
  return absent();
1867
1910
  }
@@ -1876,7 +1919,7 @@ export class LighterProvider {
1876
1919
  throw new Error(`${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} recovery account type could not be verified`);
1877
1920
  }
1878
1921
  if (account.accountType === 0) {
1879
- this.#accountIndex = account.index;
1922
+ this.#recordAccountIndex(account.index);
1880
1923
  }
1881
1924
  return {
1882
1925
  accounts: [account.index],
@@ -2904,14 +2947,14 @@ export class LighterProvider {
2904
2947
  .map((key) => key.apiKeyIndex);
2905
2948
  const discover = bridge.getRecoverableKeyIndices?.bind(bridge) ??
2906
2949
  bridge.getStoredKeyIndices?.bind(bridge);
2907
- const discovered = discover
2950
+ const discovered = discover && requested.length > 0
2908
2951
  ? await discover({
2909
2952
  chainId: getLighterChainId(this.#clientService.network),
2910
2953
  accountIndex,
2911
2954
  apiKeyIndices: requested,
2912
2955
  walletAddress: address ?? undefined,
2913
2956
  })
2914
- : [this.#preferredApiKeyIndex];
2957
+ : requested.filter((slot) => slot === this.#preferredApiKeyIndex);
2915
2958
  const local = requiredSlot === undefined
2916
2959
  ? [...new Set([this.#preferredApiKeyIndex, ...discovered])].filter((slot) => discovered.includes(slot))
2917
2960
  : discovered.filter((slot) => slot === requiredSlot);
@@ -5328,8 +5371,11 @@ export class LighterProvider {
5328
5371
  this.#assertSession(generation);
5329
5372
  // Keep discovery and allocation together across provider lifetimes. The
5330
5373
  // inner venue lock separately protects each candidate's financial writes.
5331
- await withProcessMutex(`lighterKeySetup:${this.#clientService.network}:${accountIndex}`, async () => this.#setupSignerForAccount(accountIndex, generation));
5374
+ await this.#withKeySetupLock(accountIndex, async () => await this.#setupSignerForAccount(accountIndex, generation));
5332
5375
  };
5376
+ #withKeySetupLock(accountIndex, operation) {
5377
+ return withProcessMutex(`lighterKeySetup:${this.#clientService.network}:${accountIndex}`, operation);
5378
+ }
5333
5379
  /**
5334
5380
  * Select and settle a key while holding the account setup mutex.
5335
5381
  * @param accountIndex - Venue account bound to this setup.
@@ -5432,6 +5478,7 @@ export class LighterProvider {
5432
5478
  if (ready) {
5433
5479
  this.#assertSession(generation);
5434
5480
  this.#readyApiKeyIndex = apiKeyIndex;
5481
+ this.#resumeAccountChannels();
5435
5482
  this.#kickTpslRecovery();
5436
5483
  return;
5437
5484
  }
@@ -5911,20 +5958,25 @@ export class LighterProvider {
5911
5958
  this.#assertSession(generation);
5912
5959
  bridgeClientOwners.set(this.#rawSignerBridge(), identity);
5913
5960
  };
5914
- #getAuthToken = async () => {
5961
+ // Supplying a ready account mints with the current signer only: never start
5962
+ // key setup or retry under a different wallet on behalf of a stream.
5963
+ #getAuthToken = async (readyAccountIndex) => {
5915
5964
  this.#ensureSessionBinding();
5916
5965
  const nowSeconds = Math.floor(Date.now() / 1000);
5917
5966
  if (this.#authToken && this.#authToken.deadline - nowSeconds > 60) {
5918
5967
  return this.#authToken.token;
5919
5968
  }
5920
5969
  const generation = this.#sessionGeneration;
5921
- await this.#ensureSignerReady();
5922
- const accountIndex = await this.#ensureAccountIndex();
5970
+ if (readyAccountIndex === undefined) {
5971
+ await this.#ensureSignerReady();
5972
+ }
5973
+ const accountIndex = readyAccountIndex ?? (await this.#ensureAccountIndex());
5923
5974
  // The auth-token mint is a singleton-client call like any other sign:
5924
5975
  // it runs under the BRIDGE LEASE, and re-establishes OUR client first
5925
5976
  // when another identity has since overwritten it — otherwise the
5926
5977
  // token would be minted by the wrong account's venue key.
5927
5978
  const token = await withProcessMutex(bridgeMutexKey(this.#rawSignerBridge()), async () => {
5979
+ this.#assertSession(generation);
5928
5980
  if (this.#signerIdentity !== null &&
5929
5981
  this.#signerRecreateParams !== null &&
5930
5982
  bridgeClientOwners.get(this.#rawSignerBridge()) !==
@@ -5948,7 +6000,10 @@ export class LighterProvider {
5948
6000
  // that no longer exists must never be cached — re-mint under the new
5949
6001
  // captured session instead.
5950
6002
  this.#ensureSessionBinding();
5951
- if (generation !== this.#sessionGeneration) {
6003
+ if (readyAccountIndex !== undefined) {
6004
+ this.#assertSession(generation);
6005
+ }
6006
+ else if (generation !== this.#sessionGeneration) {
5952
6007
  return await this.#getAuthToken();
5953
6008
  }
5954
6009
  this.#authToken = { token: token.token, deadline: token.deadline };
@@ -7441,9 +7496,11 @@ export class LighterProvider {
7441
7496
  const accountState = adaptAccountStateFromLighter(account);
7442
7497
  const crossMarginSummary = await this.#readCrossMarginSummary(account, accountState);
7443
7498
  this.#assertSession(generation);
7444
- return crossMarginSummary
7445
- ? { ...accountState, crossMarginSummary }
7446
- : accountState;
7499
+ return {
7500
+ ...accountState,
7501
+ exchangeAccountStatus: { registered: true, accountIndex },
7502
+ ...(crossMarginSummary && { crossMarginSummary }),
7503
+ };
7447
7504
  }
7448
7505
  catch (caughtError) {
7449
7506
  if (this.#isUnsupportedCapabilityError(caughtError) ||
@@ -8800,7 +8857,7 @@ export class LighterProvider {
8800
8857
  if (records.length === 0) {
8801
8858
  return [];
8802
8859
  }
8803
- const authority = await this.#getNativeProbeReadToken(accountIndex, generation);
8860
+ const authority = await this.#getRegisteredReadToken(accountIndex, generation);
8804
8861
  this.#assertSession(generation);
8805
8862
  return await this.#nativeTwapService.observe(owner, this.#clientService, authority.token);
8806
8863
  }
@@ -8827,7 +8884,7 @@ export class LighterProvider {
8827
8884
  return await start();
8828
8885
  });
8829
8886
  }
8830
- async #getNativeProbeReadToken(accountIndex, generation) {
8887
+ async #getRegisteredReadToken(accountIndex, generation) {
8831
8888
  return await withProcessMutex(`lighterVenueWrite:${this.#isTestnet ? 'testnet' : 'mainnet'}:${accountIndex}`, async () => await this.#getRecoveryReadToken(accountIndex, generation));
8832
8889
  }
8833
8890
  #nativeTwapOwner(accountIndex) {
@@ -9088,7 +9145,7 @@ export class LighterProvider {
9088
9145
  nonce.nonce > (dispatch.nonce ?? -1)) {
9089
9146
  return;
9090
9147
  }
9091
- const { token } = await this.#getNativeProbeReadToken(intent.owner.accountIndex, generation);
9148
+ const { token } = await this.#getRegisteredReadToken(intent.owner.accountIndex, generation);
9092
9149
  assertCurrent();
9093
9150
  const exact = await this.#clientService.getOrdersByClientIds(intent.owner.accountIndex, token, [child.clientOrderId]);
9094
9151
  assertCurrent();
@@ -9167,7 +9224,7 @@ export class LighterProvider {
9167
9224
  !new BigNumber(market.minQuoteAmount).eq(intent.minQuoteAmount)) {
9168
9225
  throw new Error('Lighter Chase native market constraints changed');
9169
9226
  }
9170
- const { token } = await this.#getNativeProbeReadToken(intent.owner.accountIndex, generation);
9227
+ const { token } = await this.#getRegisteredReadToken(intent.owner.accountIndex, generation);
9171
9228
  assertSigning();
9172
9229
  await this.#assertChaseProbeExposure(intent, child.size, generation, child.price, token);
9173
9230
  assertSigning();
@@ -9229,7 +9286,7 @@ export class LighterProvider {
9229
9286
  },
9230
9287
  cancel: async (child, hooks) => {
9231
9288
  assertSigning();
9232
- const { token } = await this.#getNativeProbeReadToken(intent.owner.accountIndex, generation);
9289
+ const { token } = await this.#getRegisteredReadToken(intent.owner.accountIndex, generation);
9233
9290
  assertSigning();
9234
9291
  const exact = await this.#clientService.getOrdersByClientIds(intent.owner.accountIndex, token, [child.clientOrderId]);
9235
9292
  assertSigning();
@@ -9284,7 +9341,7 @@ export class LighterProvider {
9284
9341
  if (cancel) {
9285
9342
  await reconcileDispatch(cancel, child, recordEvidence);
9286
9343
  }
9287
- const { token } = await this.#getNativeProbeReadToken(intent.owner.accountIndex, generation);
9344
+ const { token } = await this.#getRegisteredReadToken(intent.owner.accountIndex, generation);
9288
9345
  assertCurrent();
9289
9346
  const exact = await this.#clientService.getOrdersByClientIds(intent.owner.accountIndex, token, [child.clientOrderId]);
9290
9347
  assertCurrent();
@@ -9956,7 +10013,7 @@ export class LighterProvider {
9956
10013
  throw new Error('Native TWAP cancellation requires an exact owned visible parent');
9957
10014
  }
9958
10015
  const record = owned[0];
9959
- const authority = await this.#getNativeProbeReadToken(accountIndex, generation);
10016
+ const authority = await this.#getRegisteredReadToken(accountIndex, generation);
9960
10017
  this.#assertSession(generation);
9961
10018
  const exact = await this.#clientService.getOrdersByClientIds(accountIndex, authority.token, [record.intent.clientOrderId]);
9962
10019
  this.#assertSession(generation);
@@ -13568,8 +13625,12 @@ export class LighterProvider {
13568
13625
  params.callback(account);
13569
13626
  },
13570
13627
  };
13628
+ this.#ensureSessionBinding();
13629
+ if (this.#lastStreamAccount) {
13630
+ scopedParams.callback(this.#lastStreamAccount);
13631
+ }
13571
13632
  this.#accountSubscribers.add(scopedParams);
13572
- this.#ensureAccountChannels();
13633
+ this.#ensureAccountChannels({ existingKeysOnly: true });
13573
13634
  return () => {
13574
13635
  this.#accountSubscribers.delete(scopedParams);
13575
13636
  this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
@@ -13580,10 +13641,15 @@ export class LighterProvider {
13580
13641
  return NOOP_UNSUBSCRIBE;
13581
13642
  }
13582
13643
  this.#positionSubscribers.add(params);
13583
- if (this.#wsPositions.size > 0) {
13644
+ if (this.#lastStreamAccount === EMPTY_ACCOUNT_STATE) {
13645
+ // A venue-confirmed empty account settled earlier listeners; a
13646
+ // listener that joins during the discovery window gets the same base.
13647
+ params.callback([]);
13648
+ }
13649
+ else if (this.#wsPositions.size > 0) {
13584
13650
  params.callback([...this.#wsPositions.values()]);
13585
13651
  }
13586
- this.#ensureAccountChannels();
13652
+ this.#ensureAccountChannels({ existingKeysOnly: true });
13587
13653
  return () => {
13588
13654
  this.#positionSubscribers.delete(params);
13589
13655
  this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
@@ -13594,10 +13660,16 @@ export class LighterProvider {
13594
13660
  return NOOP_UNSUBSCRIBE;
13595
13661
  }
13596
13662
  this.#orderSubscribers.add(params);
13597
- if (this.#hasOrdersSnapshot || this.#wsOrders.size > 0) {
13598
- params.callback([...this.#wsOrders.values()]);
13663
+ const orders = this.#knownStreamOrders();
13664
+ if (orders) {
13665
+ params.callback(orders);
13599
13666
  }
13600
- this.#ensureAccountChannels();
13667
+ else if (this.#lastStreamAccount === EMPTY_ACCOUNT_STATE) {
13668
+ // A venue-confirmed empty account settled earlier listeners; a
13669
+ // listener that joins during the discovery window gets the same base.
13670
+ params.callback([]);
13671
+ }
13672
+ this.#ensureAccountChannels({ existingKeysOnly: false });
13601
13673
  return () => {
13602
13674
  this.#orderSubscribers.delete(params);
13603
13675
  this.#onListenerRemoved(LIGHTER_ACCOUNT_CHANNELS_KEY);
@@ -13608,15 +13680,15 @@ export class LighterProvider {
13608
13680
  return NOOP_UNSUBSCRIBE;
13609
13681
  }
13610
13682
  this.#fillSubscribers.add(params);
13611
- this.#ensureAccountChannels();
13683
+ this.#ensureAccountChannels({ existingKeysOnly: false });
13612
13684
  const generation = this.#sessionGeneration;
13613
- const channelsPromise = this.#accountChannelsPromise;
13685
+ const setup = this.#accountChannelSetup;
13614
13686
  // A late subscriber may join after the venue's one initial trade snapshot.
13615
13687
  // Replay only after authentication succeeds for the same channel session.
13616
- channelsPromise
13617
- ?.then(() => {
13688
+ setup?.promise
13689
+ .then(() => {
13618
13690
  this.#assertSession(generation);
13619
- if (this.#accountChannelsPromise === channelsPromise &&
13691
+ if (this.#accountChannelSetup === setup &&
13620
13692
  this.#fillSubscribers.has(params) &&
13621
13693
  this.#wsFills !== null) {
13622
13694
  params.callback([...this.#wsFills], true);
@@ -13636,11 +13708,21 @@ export class LighterProvider {
13636
13708
  /**
13637
13709
  * Notify each subscriber without allowing one listener to stop others.
13638
13710
  *
13639
- * @param error - Account channel setup failure.
13640
- * @param readers - The streams it failed.
13641
- */
13642
- #notifySubscriptionError = (error, readers) => {
13643
- for (const [label, subscribers] of readers) {
13711
+ * @param error - Reason the channel is unavailable.
13712
+ * @param channels - Streams affected by the failure.
13713
+ */
13714
+ #notifySubscriptionError = (error, channels = [
13715
+ 'orders',
13716
+ 'fills',
13717
+ ]) => {
13718
+ const subscribersByChannel = {
13719
+ orders: this.#orderSubscribers,
13720
+ fills: this.#fillSubscribers,
13721
+ positions: this.#positionSubscribers,
13722
+ account: this.#accountSubscribers,
13723
+ };
13724
+ for (const label of channels) {
13725
+ const subscribers = subscribersByChannel[label];
13644
13726
  for (const subscriber of subscribers) {
13645
13727
  try {
13646
13728
  subscriber.onError?.(error);
@@ -13651,25 +13733,105 @@ export class LighterProvider {
13651
13733
  }
13652
13734
  }
13653
13735
  };
13736
+ async #getAccountChannelReadToken(accountIndex, generation) {
13737
+ this.#assertSession(generation);
13738
+ if (this.#readyApiKeyIndex !== null) {
13739
+ return await this.#getAuthToken(accountIndex);
13740
+ }
13741
+ // Decide under the setup lock: a signer can become ready while a stream
13742
+ // refresh is queued. A temporary read client would displace it.
13743
+ return await this.#withKeySetupLock(accountIndex, async () => {
13744
+ this.#assertSession(generation);
13745
+ if (this.#readyApiKeyIndex !== null) {
13746
+ return await this.#getAuthToken(accountIndex);
13747
+ }
13748
+ return (await this.#getRegisteredReadToken(accountIndex, generation))
13749
+ .token;
13750
+ });
13751
+ }
13752
+ #cancelAccountDiscovery() {
13753
+ if (this.#accountDiscoveryTimer !== null) {
13754
+ clearTimeout(this.#accountDiscoveryTimer);
13755
+ this.#accountDiscoveryTimer = null;
13756
+ }
13757
+ }
13758
+ #cancelOrdersResubscribe() {
13759
+ if (this.#ordersResubscribeTimer !== null) {
13760
+ clearTimeout(this.#ordersResubscribeTimer);
13761
+ this.#ordersResubscribeTimer = null;
13762
+ }
13763
+ }
13764
+ // One outstanding discovery per account stream. Keep the timer identity
13765
+ // across the await so an old lookup cannot re-arm a released stream.
13766
+ #scheduleAccountDiscovery(deadline = Date.now() + LIGHTER_ACCOUNT_DISCOVERY_CONFIG.DeadlineMs, interval = LIGHTER_ACCOUNT_DISCOVERY_CONFIG.InitialIntervalMs) {
13767
+ const remaining = deadline - Date.now();
13768
+ if (remaining <= 0 ||
13769
+ this.#accountDiscoveryTimer !== null ||
13770
+ !this.#hasAccountSubscriber() ||
13771
+ this.#accountChannelsAwaiting !== 'account') {
13772
+ return;
13773
+ }
13774
+ const timer = setTimeout(() => {
13775
+ if (Date.now() > deadline) {
13776
+ this.#cancelAccountDiscovery();
13777
+ return;
13778
+ }
13779
+ // A validated index immediately resumes the waiting channels.
13780
+ this.#ensureAccountIndex().catch((error) => {
13781
+ this.#ensureSessionBinding();
13782
+ if (this.#accountDiscoveryTimer !== timer) {
13783
+ return;
13784
+ }
13785
+ this.#accountDiscoveryTimer = null;
13786
+ if (!(error instanceof LighterAccountNotFoundError)) {
13787
+ this.#deps.debugLogger.log('[LighterProvider] account discovery failed', { error: String(error) });
13788
+ }
13789
+ this.#scheduleAccountDiscovery(deadline, Math.min(2 * interval, LIGHTER_ACCOUNT_DISCOVERY_CONFIG.MaxIntervalMs));
13790
+ });
13791
+ }, Math.min(interval, remaining));
13792
+ this.#accountDiscoveryTimer = timer;
13793
+ }
13794
+ #resumeAccountChannels() {
13795
+ if (!this.#isDisconnected &&
13796
+ this.#hasAccountSubscriber() &&
13797
+ !this.#accountChannelSetup &&
13798
+ ((this.#accountChannelsAwaiting === 'account' &&
13799
+ this.#accountIndex !== null) ||
13800
+ (this.#accountChannelsAwaiting === 'tradingKey' &&
13801
+ this.#readyApiKeyIndex !== null))) {
13802
+ this.#ensureAccountChannels({ existingKeysOnly: true });
13803
+ }
13804
+ }
13654
13805
  /**
13655
13806
  * Resolve the Lighter account index and request the account-scoped
13656
13807
  * channels. When the venue definitively reports no Lighter account,
13657
13808
  * account-scoped subscribers receive an empty emission.
13809
+ *
13810
+ * @param options - Automatic rebuilds must not initiate key registration.
13811
+ * @param options.existingKeysOnly - Authenticate only with an existing key.
13658
13812
  */
13659
- #ensureAccountChannels = () => {
13813
+ #ensureAccountChannels = (options) => {
13660
13814
  if (this.#isDisconnected) {
13661
13815
  return;
13662
13816
  }
13663
13817
  this.#cancelChannelRelease(LIGHTER_ACCOUNT_CHANNELS_KEY);
13664
- if (this.#accountChannelsPromise) {
13818
+ if (this.#accountChannelSetup) {
13819
+ // A private listener can join while a public listener's lookup is in
13820
+ // flight. Use its explicit setup permission for this request only.
13821
+ if (!options.existingKeysOnly) {
13822
+ this.#accountChannelSetup.options.existingKeysOnly = false;
13823
+ }
13824
+ this.#ensureStream();
13825
+ return;
13826
+ }
13827
+ if (this.#accountDiscoveryTimer !== null) {
13665
13828
  this.#ensureStream();
13666
13829
  return;
13667
13830
  }
13668
13831
  const generation = this.#sessionGeneration;
13832
+ this.#accountChannelsAwaiting = null;
13669
13833
  let channelsRequested = false;
13670
- // Auth setup crosses awaits before consulting this promise identity.
13671
- let setupPromise = undefined;
13672
- setupPromise = (async () => {
13834
+ const open = async () => {
13673
13835
  try {
13674
13836
  // Warm the margin cache before any WS position frame is adapted.
13675
13837
  await this.#ensureMarketMargins().catch(() => undefined);
@@ -13682,21 +13844,55 @@ export class LighterProvider {
13682
13844
  // account index alone must never subscribe user channels.
13683
13845
  this.#assertSession(generation);
13684
13846
  // Released (no account listener left) or replaced while resolving.
13685
- if (this.#accountChannelsPromise !== setupPromise) {
13847
+ if (this.#accountChannelSetup?.options !== options) {
13686
13848
  return;
13687
13849
  }
13688
13850
  this.#requestChannel(`user_stats/${accountIndex}`);
13689
13851
  this.#requestChannel(`account_all_positions/${accountIndex}`);
13690
13852
  this.#requestChannel(`account_all_trades/${accountIndex}`);
13691
13853
  channelsRequested = true;
13854
+ if (this.#orderSubscribers.size === 0 &&
13855
+ this.#fillSubscribers.size === 0 &&
13856
+ this.#readyApiKeyIndex === null) {
13857
+ // A deposit screen needs only public frames. Leave authentication to
13858
+ // a private listener or separately authorized trading session.
13859
+ this.#accountChannelsAwaiting = 'tradingKey';
13860
+ this.#accountChannelSetup = null;
13861
+ return;
13862
+ }
13692
13863
  const channelAddress = this.#boundAddress;
13864
+ // A deposit/status read must not turn an automatic stream rebuild
13865
+ // into a wallet signature. Only explicit trading setup can create a key.
13866
+ const refresh = () => this.#getAccountChannelReadToken(accountIndex, generation);
13867
+ // An explicit listener joining mid-flight can upgrade this setup's
13868
+ // permission; re-read the live permission after a read-only failure
13869
+ // and retry once with mint access instead of failing the upgrade.
13870
+ const authenticate = async () => {
13871
+ const readOnlyAttempt = options.existingKeysOnly;
13872
+ try {
13873
+ return readOnlyAttempt
13874
+ ? await refresh()
13875
+ : await this.#getAuthToken();
13876
+ }
13877
+ catch (error) {
13878
+ if (readOnlyAttempt &&
13879
+ !options.existingKeysOnly &&
13880
+ error instanceof LighterRecoveryReadAuthorityError) {
13881
+ return await this.#getAuthToken();
13882
+ }
13883
+ throw error;
13884
+ }
13885
+ };
13693
13886
  try {
13694
- const auth = await this.#getAuthToken();
13887
+ const auth = await authenticate();
13695
13888
  this.#assertSession(generation);
13696
- if (this.#accountChannelsPromise !== setupPromise) {
13889
+ if (this.#accountChannelSetup?.options !== options) {
13697
13890
  return;
13698
13891
  }
13699
- this.#requestChannel(`account_all_orders/${accountIndex}`, auth);
13892
+ this.#requestChannel(`account_all_orders/${accountIndex}`, {
13893
+ token: auth,
13894
+ refresh,
13895
+ });
13700
13896
  }
13701
13897
  catch (error) {
13702
13898
  this.#deps.debugLogger.log('[LighterProvider] orders channel skipped (no auth token)', { error: String(error) });
@@ -13706,12 +13902,22 @@ export class LighterProvider {
13706
13902
  if (!this.#isDisconnected &&
13707
13903
  channelAddress !== null &&
13708
13904
  channelAddress === this.#boundAddress &&
13709
- this.#accountChannelsPromise === setupPromise) {
13710
- // Positions and balances need no auth token.
13711
- this.#notifySubscriptionError(ensureError(error), [
13712
- ['orders', this.#orderSubscribers],
13713
- ['fills', this.#fillSubscribers],
13714
- ]);
13905
+ this.#accountChannelSetup?.options === options) {
13906
+ // Any auth-step failure while no signer is ready keeps the
13907
+ // resume marker, so a transient failure cannot leave the orders
13908
+ // channel closed after the signer becomes ready.
13909
+ if (this.#readyApiKeyIndex === null) {
13910
+ this.#accountChannelsAwaiting = 'tradingKey';
13911
+ }
13912
+ // No retained key is a waiting state, not a failure: give
13913
+ // clients a code so they need not match on the message. Only
13914
+ // orders wait on the key; the public fills channel stays live.
13915
+ if (error instanceof LighterRecoveryReadAuthorityError) {
13916
+ this.#notifySubscriptionError(new PerpsControllerError(PERPS_ERROR_CODES.ORDERS_STREAM_PAUSED, error.message, undefined, { cause: error }), ['orders']);
13917
+ }
13918
+ else {
13919
+ this.#notifySubscriptionError(ensureError(error));
13920
+ }
13715
13921
  }
13716
13922
  // Setup failures are not authoritative empty order state. Account
13717
13923
  // switches and deselection already emit their synchronous reset.
@@ -13727,18 +13933,23 @@ export class LighterProvider {
13727
13933
  // capability errors cannot prove that the account is empty.
13728
13934
  this.#ensureSessionBinding();
13729
13935
  if (error instanceof LighterAccountNotFoundError &&
13730
- generation === this.#sessionGeneration) {
13731
- this.#emitAccountBindingReset(EMPTY_ACCOUNT_STATE);
13936
+ generation === this.#sessionGeneration &&
13937
+ this.#accountChannelSetup?.options === options) {
13938
+ this.#accountChannelsAwaiting = 'account';
13939
+ if (this.#accountIndex === null) {
13940
+ this.#emitAccountBindingReset(EMPTY_ACCOUNT_STATE);
13941
+ this.#scheduleAccountDiscovery();
13942
+ }
13732
13943
  }
13733
13944
  else if (!this.#isDisconnected &&
13734
13945
  this.#boundAddress !== null &&
13735
13946
  generation === this.#sessionGeneration &&
13736
- this.#accountChannelsPromise === setupPromise) {
13947
+ this.#accountChannelSetup?.options === options) {
13737
13948
  this.#notifySubscriptionError(ensureError(error), [
13738
- ['orders', this.#orderSubscribers],
13739
- ['fills', this.#fillSubscribers],
13740
- ['positions', this.#positionSubscribers],
13741
- ['account', this.#accountSubscribers],
13949
+ 'orders',
13950
+ 'fills',
13951
+ 'positions',
13952
+ 'account',
13742
13953
  ]);
13743
13954
  }
13744
13955
  // An aborted previous-account setup has no authority over the new
@@ -13747,16 +13958,18 @@ export class LighterProvider {
13747
13958
  // authoritative empty account state. Explicit account switches and
13748
13959
  // deselection already emit their synchronous reset.
13749
13960
  }
13750
- })();
13751
- this.#accountChannelsPromise = setupPromise;
13961
+ };
13962
+ const setup = { options, promise: open() };
13963
+ this.#accountChannelSetup = setup;
13752
13964
  // A setup that never requested channels (no wallet account yet, or an
13753
13965
  // aborted switch) must not satisfy future ensure calls — clear it so
13754
13966
  // the next bind retries, without clobbering a newer session's promise.
13755
- setupPromise
13967
+ setup.promise
13756
13968
  .then(() => {
13757
- if (!channelsRequested &&
13758
- this.#accountChannelsPromise === setupPromise) {
13759
- this.#accountChannelsPromise = null;
13969
+ if (!channelsRequested && this.#accountChannelSetup === setup) {
13970
+ this.#accountChannelSetup = null;
13971
+ // A concurrent lookup may have resolved before this setup settled.
13972
+ this.#resumeAccountChannels();
13760
13973
  }
13761
13974
  })
13762
13975
  .catch(() => undefined);
@@ -13812,9 +14025,9 @@ export class LighterProvider {
13812
14025
  if (this.#wsWantedChannels.has(channel)) {
13813
14026
  return;
13814
14027
  }
13815
- this.#wsWantedChannels.set(channel, { auth });
14028
+ this.#wsWantedChannels.set(channel, auth?.refresh);
13816
14029
  if (this.#priceWs?.readyState === 1) {
13817
- this.#sendSubscribe(channel, auth);
14030
+ this.#sendSubscribe(channel, auth?.token);
13818
14031
  }
13819
14032
  this.#logChannelCount('subscribed', channel);
13820
14033
  };
@@ -13856,6 +14069,9 @@ export class LighterProvider {
13856
14069
  if (channel !== null &&
13857
14070
  !this.#isDisconnected &&
13858
14071
  !this.#channelHasListeners(channel)) {
14072
+ if (channel === LIGHTER_ACCOUNT_CHANNELS_KEY) {
14073
+ this.#cancelAccountDiscovery();
14074
+ }
13859
14075
  this.#scheduleChannelRelease(channel);
13860
14076
  }
13861
14077
  if (this.#isSocketDown && !this.#hasAnySubscriber()) {
@@ -13937,11 +14153,15 @@ export class LighterProvider {
13937
14153
  };
13938
14154
  /** Forget the account channel setup and the account data it streamed. */
13939
14155
  #resetAccountStreamState = () => {
13940
- this.#accountChannelsPromise = null;
14156
+ this.#cancelAccountDiscovery();
14157
+ this.#cancelOrdersResubscribe();
14158
+ this.#lastStreamAccount = null;
14159
+ this.#accountChannelSetup = null;
14160
+ this.#accountChannelsAwaiting = null;
13941
14161
  this.#wsPositions.clear();
13942
- this.#hasOrdersSnapshot = false;
14162
+ this.#wsOrders = null;
14163
+ this.#ordersSnapshotRepair = null;
13943
14164
  this.#wsFills = null;
13944
- this.#wsOrders.clear();
13945
14165
  };
13946
14166
  /**
13947
14167
  * Forget channels that lost every listener while the socket was down, so
@@ -13966,6 +14186,64 @@ export class LighterProvider {
13966
14186
  ? { type: 'subscribe', channel, auth }
13967
14187
  : { type: 'subscribe', channel }));
13968
14188
  };
14189
+ #resubscribeAuthenticatedChannel = (ws, channel, getToken, repair, attempt = 0) => {
14190
+ const generation = this.#sessionGeneration;
14191
+ let unsubscribed = false;
14192
+ const isCurrent = () => this.#priceWs === ws &&
14193
+ ws.readyState === 1 &&
14194
+ generation === this.#sessionGeneration &&
14195
+ this.#wsWantedChannels.get(channel) === getToken &&
14196
+ (repair === undefined || this.#ordersSnapshotRepair === repair);
14197
+ getToken()
14198
+ .then((token) => {
14199
+ if (!isCurrent()) {
14200
+ return;
14201
+ }
14202
+ if (repair !== undefined) {
14203
+ ws.send(JSON.stringify({ type: 'unsubscribe', channel }));
14204
+ unsubscribed = true;
14205
+ }
14206
+ this.#sendSubscribe(channel, token);
14207
+ })
14208
+ .catch((error) => {
14209
+ this.#deps.debugLogger.log('[LighterProvider] auth channel resubscribe failed', { channel, error: String(error) });
14210
+ this.#ensureSessionBinding();
14211
+ if (!isCurrent()) {
14212
+ return;
14213
+ }
14214
+ if (repair !== undefined) {
14215
+ this.#ordersSnapshotRepair = 'retry';
14216
+ if (unsubscribed) {
14217
+ this.#wsOrders = null;
14218
+ }
14219
+ // A failed mint leaves the original subscription live. Only evict
14220
+ // its multiplexed orders when direct subscribers cannot replay them.
14221
+ if (!this.#wsOrders?.size) {
14222
+ this.#notifySubscriptionError(ensureError(error), ['orders']);
14223
+ }
14224
+ }
14225
+ else if (channel.startsWith('account_all_orders/')) {
14226
+ // On reconnect the venue never re-subscribed this channel: the
14227
+ // cached orders are stale and no frame will arrive to trigger a
14228
+ // snapshot repair on its own. Notify, then re-mint on a bounded
14229
+ // timer so a transient failure cannot leave orders dead for the
14230
+ // rest of the session on a healthy socket.
14231
+ this.#ordersSnapshotRepair = 'retry';
14232
+ this.#wsOrders = null;
14233
+ this.#notifySubscriptionError(ensureError(error), ['orders']);
14234
+ if (attempt < LIGHTER_ORDERS_RESUBSCRIBE_RETRY.MaxAttempts) {
14235
+ this.#cancelOrdersResubscribe();
14236
+ this.#ordersResubscribeTimer = setTimeout(() => {
14237
+ this.#ordersResubscribeTimer = null;
14238
+ if (this.#isDisconnected || !isCurrent()) {
14239
+ return;
14240
+ }
14241
+ this.#resubscribeAuthenticatedChannel(ws, channel, getToken, undefined, attempt + 1);
14242
+ }, LIGHTER_ORDERS_RESUBSCRIBE_RETRY.DelayMs);
14243
+ }
14244
+ }
14245
+ });
14246
+ };
13969
14247
  /** Close the stream once it has had no listener for the idle period. */
13970
14248
  #scheduleIdleClose = () => {
13971
14249
  if (this.#isDisconnected ||
@@ -14039,37 +14317,22 @@ export class LighterProvider {
14039
14317
  if (this.#priceWs !== ws) {
14040
14318
  return;
14041
14319
  }
14042
- const generationAtOpen = this.#sessionGeneration;
14043
14320
  this.#wsReconnectAttempts = 0;
14044
14321
  this.#clearSocketDown();
14045
14322
  this.#setConnectionState(WebSocketConnectionState.Connected);
14046
14323
  this.#pruneUnwatchedChannels();
14047
- for (const [channel, meta] of this.#wsWantedChannels) {
14048
- if (meta.auth) {
14049
- // Auth tokens are short-lived; a reconnect after the deadline must
14050
- // re-mint instead of replaying the token captured at subscribe
14051
- // time. #getAuthToken reuses the cached token while it is fresh.
14052
- this.#getAuthToken()
14053
- .then((freshToken) => {
14054
- // The async continuation may resolve after an account switch
14055
- // replaced the socket or the channel set: never reinsert a
14056
- // stale channel or pair it with the new session's token.
14057
- if (this.#priceWs !== ws ||
14058
- generationAtOpen !== this.#sessionGeneration ||
14059
- !this.#wsWantedChannels.has(channel)) {
14060
- return;
14061
- }
14062
- this.#wsWantedChannels.set(channel, { auth: freshToken });
14063
- this.#sendSubscribe(channel, freshToken);
14064
- })
14065
- .catch((error) => {
14066
- this.#deps.debugLogger.log('[LighterProvider] auth channel resubscribe failed', { channel, error: String(error) });
14067
- });
14324
+ for (const [channel, getToken] of this.#wsWantedChannels) {
14325
+ if (getToken) {
14326
+ this.#resubscribeAuthenticatedChannel(ws, channel, getToken);
14068
14327
  }
14069
14328
  else {
14070
- this.#sendSubscribe(channel, meta.auth);
14329
+ this.#sendSubscribe(channel);
14071
14330
  }
14072
14331
  }
14332
+ if (this.#accountChannelsAwaiting === 'tradingKey' &&
14333
+ (this.#orderSubscribers.size > 0 || this.#fillSubscribers.size > 0)) {
14334
+ this.#ensureAccountChannels({ existingKeysOnly: true });
14335
+ }
14073
14336
  // The server closes idle sockets; any frame under 2 minutes keeps it up.
14074
14337
  // Unconditional replacement: `??=` would keep a timer bound to a dead
14075
14338
  // socket when a new one opens before the old socket's onclose fired.
@@ -14167,8 +14430,17 @@ export class LighterProvider {
14167
14430
  this.#detectMarketChange(message.marketStats, type.startsWith('subscribed'));
14168
14431
  return;
14169
14432
  }
14170
- if (type.includes('user_stats') && message.stats) {
14171
- const accountState = adaptAccountStateFromLighterUserStats(message.stats);
14433
+ if (type.includes('user_stats') &&
14434
+ message.stats &&
14435
+ this.#accountIndex !== null) {
14436
+ const accountState = {
14437
+ ...adaptAccountStateFromLighterUserStats(message.stats),
14438
+ exchangeAccountStatus: {
14439
+ registered: true,
14440
+ accountIndex: this.#accountIndex,
14441
+ },
14442
+ };
14443
+ this.#lastStreamAccount = accountState;
14172
14444
  for (const subscriber of this.#accountSubscribers) {
14173
14445
  try {
14174
14446
  subscriber.callback(accountState);
@@ -14240,6 +14512,13 @@ export class LighterProvider {
14240
14512
  throw new Error('Invalid Lighter venue data: malformed orders container');
14241
14513
  }
14242
14514
  const isSnapshot = type.startsWith('subscribed');
14515
+ if (!isSnapshot && this.#ordersSnapshotRepair === 'retry') {
14516
+ this.#repairOrdersSnapshot();
14517
+ }
14518
+ // A delta is not a complete list of open orders for this session.
14519
+ if (!isSnapshot && this.#wsOrders === null) {
14520
+ return;
14521
+ }
14243
14522
  const nextOrders = isSnapshot
14244
14523
  ? new Map()
14245
14524
  : new Map(this.#wsOrders);
@@ -14257,20 +14536,50 @@ export class LighterProvider {
14257
14536
  }
14258
14537
  }
14259
14538
  if (isSnapshot) {
14260
- this.#hasOrdersSnapshot = true;
14539
+ this.#ordersSnapshotRepair = null;
14261
14540
  }
14262
- this.#wsOrders.clear();
14263
- for (const [orderId, order] of nextOrders) {
14264
- this.#wsOrders.set(orderId, order);
14541
+ this.#wsOrders = nextOrders;
14542
+ const orders = this.#knownStreamOrders();
14543
+ if (orders) {
14544
+ this.#emitToOrderSubscribers(orders);
14265
14545
  }
14266
- this.#emitToOrderSubscribers([...this.#wsOrders.values()]);
14267
14546
  }
14268
14547
  catch (error) {
14269
- this.#hasOrdersSnapshot = false;
14548
+ if (type.startsWith('subscribed') &&
14549
+ typeof this.#ordersSnapshotRepair === 'symbol') {
14550
+ // The repaired snapshot is bad too: retry on the next delta.
14551
+ this.#ordersSnapshotRepair = 'retry';
14552
+ if (!this.#wsOrders?.size) {
14553
+ this.#notifySubscriptionError(ensureError(error), ['orders']);
14554
+ }
14555
+ }
14556
+ else {
14557
+ this.#repairOrdersSnapshot();
14558
+ }
14270
14559
  throw error;
14271
14560
  }
14272
14561
  }
14273
14562
  };
14563
+ #knownStreamOrders() {
14564
+ if (this.#wsOrders === null ||
14565
+ (this.#ordersSnapshotRepair !== null && this.#wsOrders.size === 0)) {
14566
+ return undefined;
14567
+ }
14568
+ return [...this.#wsOrders.values()];
14569
+ }
14570
+ #repairOrdersSnapshot() {
14571
+ if (typeof this.#ordersSnapshotRepair === 'symbol' ||
14572
+ this.#accountIndex === null) {
14573
+ return;
14574
+ }
14575
+ const channel = `account_all_orders/${this.#accountIndex}`;
14576
+ const getToken = this.#wsWantedChannels.get(channel);
14577
+ if (this.#priceWs && getToken) {
14578
+ const repair = Symbol('orders snapshot repair');
14579
+ this.#ordersSnapshotRepair = repair;
14580
+ this.#resubscribeAuthenticatedChannel(this.#priceWs, channel, getToken, repair);
14581
+ }
14582
+ }
14274
14583
  /**
14275
14584
  * Apply an order_book snapshot/delta and fan the assembled book out.
14276
14585
  *