@metamask-previews/perps-controller 19.0.0-preview-3b264bf6d → 19.0.0-preview-5e76941

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 (41) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +9 -4
  3. package/dist/PerpsController-method-action-types.d.ts +4 -0
  4. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -1
  6. package/dist/PerpsController.d.ts +4 -0
  7. package/dist/PerpsController.d.ts.map +1 -1
  8. package/dist/PerpsController.js +145 -15
  9. package/dist/PerpsController.js.map +1 -1
  10. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  11. package/dist/providers/HyperLiquidProvider.js +329 -78
  12. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  13. package/dist/services/DataLakeService.d.ts.map +1 -1
  14. package/dist/services/DataLakeService.js +20 -2
  15. package/dist/services/DataLakeService.js.map +1 -1
  16. package/dist/services/HyperLiquidClientService.d.ts +17 -0
  17. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  18. package/dist/services/HyperLiquidClientService.js +44 -1
  19. package/dist/services/HyperLiquidClientService.js.map +1 -1
  20. package/dist/services/HyperLiquidSubscriptionService.d.ts +7 -1
  21. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  22. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  23. package/dist/services/HyperLiquidWalletService.d.ts +7 -3
  24. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
  25. package/dist/services/HyperLiquidWalletService.js +42 -19
  26. package/dist/services/HyperLiquidWalletService.js.map +1 -1
  27. package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
  28. package/dist/services/RewardsIntegrationService.js +50 -41
  29. package/dist/services/RewardsIntegrationService.js.map +1 -1
  30. package/dist/services/missingActionHandler.d.ts +17 -0
  31. package/dist/services/missingActionHandler.d.ts.map +1 -0
  32. package/dist/services/missingActionHandler.js +29 -0
  33. package/dist/services/missingActionHandler.js.map +1 -0
  34. package/dist/types/index.d.ts +34 -6
  35. package/dist/types/index.d.ts.map +1 -1
  36. package/dist/types/index.js.map +1 -1
  37. package/dist/utils/subscriptionFeeWaiver.d.ts +2 -1
  38. package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
  39. package/dist/utils/subscriptionFeeWaiver.js +3 -1
  40. package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
  41. package/package.json +1 -1
@@ -18,6 +18,7 @@ import { DepositService } from './services/DepositService.js';
18
18
  import { EligibilityService } from './services/EligibilityService.js';
19
19
  import { FeatureFlagConfigurationService } from './services/FeatureFlagConfigurationService.js';
20
20
  import { MarketDataService } from './services/MarketDataService.js';
21
+ import { isMissingActionHandlerError } from './services/missingActionHandler.js';
21
22
  import { isProviderOnTestnet } from './services/providerNetwork.js';
22
23
  import { RewardsIntegrationService } from './services/RewardsIntegrationService.js';
23
24
  import { TerminalMarketService } from './services/TerminalMarketService.js';
@@ -81,6 +82,26 @@ export function resolveWatchlistExchangeKey(activeProvider) {
81
82
  };
82
83
  return map[activeProvider] ?? null;
83
84
  }
85
+ /**
86
+ * Apply watchlist toggles, in order, on top of a watchlist.
87
+ *
88
+ * @param watchlist - The watchlist to start from.
89
+ * @param watchlist.testnet - Testnet symbols.
90
+ * @param watchlist.mainnet - Mainnet symbols.
91
+ * @param edits - Toggles to apply.
92
+ * @returns A new watchlist with the toggles applied.
93
+ */
94
+ function applyWatchlistEdits(watchlist, edits) {
95
+ const result = {
96
+ testnet: [...watchlist.testnet],
97
+ mainnet: [...watchlist.mainnet],
98
+ };
99
+ for (const { network, symbol, add } of edits) {
100
+ const rest = result[network].filter((marketSymbol) => marketSymbol !== symbol);
101
+ result[network] = add ? [...rest, symbol] : rest;
102
+ }
103
+ return result;
104
+ }
84
105
  // Re-export error codes from separate file to avoid circular dependencies
85
106
  export { PERPS_ERROR_CODES } from './perpsErrorCodes.js';
86
107
  /**
@@ -610,6 +631,9 @@ export class PerpsController extends BaseController {
610
631
  *
611
632
  * - A toggle that fires immediately after init() always runs *after* the
612
633
  * init hydration finishes (Bug 3).
634
+ * - A hydration started by a re-initialization (`toggleTestnet`,
635
+ * `switchProvider`) waits for earlier toggles' writes, so its read sees
636
+ * them instead of overwriting them.
613
637
  * - Concurrent toggles are serialised so the last PUT reflects all changes
614
638
  * rather than racing with each other (Bug 4).
615
639
  *
@@ -617,6 +641,18 @@ export class PerpsController extends BaseController {
617
641
  * a failed operation does not stall subsequent ones.
618
642
  */
619
643
  #ausQueue = Promise.resolve();
644
+ /**
645
+ * Toggles made while an AUS hydration is queued or in flight, one list per
646
+ * hydration. They are replayed onto the remote watchlist when it arrives,
647
+ * so a late read does not drop changes the user already sees.
648
+ */
649
+ #watchlistEditsDuringHydration = new Set();
650
+ /**
651
+ * Latest toggle number per `network:symbol` whose write is still pending,
652
+ * so a failed write is undone only when no later toggle of the same market
653
+ * has superseded it.
654
+ */
655
+ #pendingWatchlistToggles = new Map();
620
656
  #userDiskWrite = Promise.resolve();
621
657
  // Store options for dependency injection (allows core package to inject platform-specific services)
622
658
  #options;
@@ -1505,10 +1541,19 @@ export class PerpsController extends BaseController {
1505
1541
  });
1506
1542
  // Hydrate watchlist from AUS (non-blocking — transient failures are
1507
1543
  // caught inside and must not prevent init from completing).
1508
- // Assigning to #ausQueue ensures subsequent toggleWatchlistMarket
1509
- // calls wait for hydration before running their own GET-merge-PUT.
1510
- this.#ausQueue = this.#syncWatchlistFromRemote().catch(() => {
1544
+ // Chaining onto #ausQueue makes the read wait for earlier toggles'
1545
+ // writes, and makes later toggles wait for hydration before running
1546
+ // their own GET-merge-PUT. Toggles are recorded from the moment the
1547
+ // hydration is queued, so one made while it waits is replayed too.
1548
+ const editsDuringHydration = [];
1549
+ this.#watchlistEditsDuringHydration.add(editsDuringHydration);
1550
+ this.#ausQueue = this.#ausQueue
1551
+ .then(() => this.#syncWatchlistFromRemote(editsDuringHydration))
1552
+ .catch(() => {
1511
1553
  // Errors are already logged inside #syncWatchlistFromRemote.
1554
+ })
1555
+ .finally(() => {
1556
+ this.#watchlistEditsDuringHydration.delete(editsDuringHydration);
1512
1557
  });
1513
1558
  return; // Exit retry loop on success
1514
1559
  }
@@ -4568,6 +4613,10 @@ export class PerpsController extends BaseController {
4568
4613
  * - `NO_ACCOUNT_SELECTED` when no account is selected;
4569
4614
  * - `PROVIDER_LIFECYCLE_STALE` when the provider disconnected or the account
4570
4615
  * changed during setup;
4616
+ * - the venue's message when HyperLiquid refused the builder fee approval
4617
+ * for a reason signing again cannot fix (for example "Builder has
4618
+ * insufficient balance to be approved"); it is not logged, and the
4619
+ * approval is not asked for again until the provider disconnects;
4571
4620
  * - otherwise the message of the error that stopped setup, which is logged.
4572
4621
  * @throws Like the other provider-backed actions, `CLIENT_NOT_INITIALIZED`
4573
4622
  * before `init`, and `CLIENT_REINITIALIZING` or `PROVIDER_NOT_AVAILABLE`
@@ -5396,6 +5445,13 @@ export class PerpsController extends BaseController {
5396
5445
  state.watchlistMarkets[currentNetwork] = [...currentWatchlist, symbol];
5397
5446
  }
5398
5447
  });
5448
+ for (const edits of this.#watchlistEditsDuringHydration) {
5449
+ edits.push({ network: currentNetwork, symbol, add: !isWatchlisted });
5450
+ }
5451
+ const toggleKey = `${currentNetwork}:${symbol}`;
5452
+ const toggleNumber = (this.#pendingWatchlistToggles.get(toggleKey) ?? 0) + 1;
5453
+ this.#pendingWatchlistToggles.set(toggleKey, toggleNumber);
5454
+ const isLatestToggle = () => this.#pendingWatchlistToggles.get(toggleKey) === toggleNumber;
5399
5455
  this.#getMetrics().trackPerpsEvent(PerpsAnalyticsEvent.UiInteraction, {
5400
5456
  [PERPS_EVENT_PROPERTY.INTERACTION_TYPE]: PERPS_EVENT_VALUE.INTERACTION_TYPE.FAVORITE_TOGGLED,
5401
5457
  [PERPS_EVENT_PROPERTY.ASSET]: symbol,
@@ -5423,11 +5479,33 @@ export class PerpsController extends BaseController {
5423
5479
  network: currentNetwork,
5424
5480
  action: isWatchlisted ? 'remove' : 'add',
5425
5481
  }));
5426
- // Revert the optimistic update.
5482
+ // A later toggle of the same market decides its state; its own write
5483
+ // persists it.
5484
+ if (!isLatestToggle()) {
5485
+ return;
5486
+ }
5487
+ // Undo only this toggle. The list may have changed since it was made
5488
+ // (hydration, other toggles), so restoring the earlier snapshot would
5489
+ // discard those changes.
5427
5490
  this.update((state) => {
5428
- state.watchlistMarkets[currentNetwork] = currentWatchlist;
5491
+ const watchlist = state.watchlistMarkets[currentNetwork];
5492
+ if (isWatchlisted) {
5493
+ if (!watchlist.includes(symbol)) {
5494
+ // Back where it was, as far as the current list allows.
5495
+ const index = Math.min(currentWatchlist.indexOf(symbol), watchlist.length);
5496
+ watchlist.splice(index, 0, symbol);
5497
+ }
5498
+ }
5499
+ else {
5500
+ state.watchlistMarkets[currentNetwork] = watchlist.filter((marketSymbol) => marketSymbol !== symbol);
5501
+ }
5429
5502
  });
5430
5503
  }
5504
+ finally {
5505
+ if (isLatestToggle()) {
5506
+ this.#pendingWatchlistToggles.delete(toggleKey);
5507
+ }
5508
+ }
5431
5509
  }
5432
5510
  /**
5433
5511
  * Check if a market is in the watchlist on the current network
@@ -5495,6 +5573,12 @@ export class PerpsController extends BaseController {
5495
5573
  * - The remote preferences blob does not yet exist (returns `null` / 404).
5496
5574
  * In that case, `NotificationServicesController.createOnChainTriggers` is
5497
5575
  * the canonical owner that creates the initial blob.
5576
+ * - The host does not provide the AUS read or write action. Local state is
5577
+ * then the only copy of the change. With the read but not the write, the
5578
+ * next hydration from AUS (the source of truth) queued after the toggle
5579
+ * replaces it. Every initialization hydrates: `init()` (including after
5580
+ * `disconnect()`), `toggleTestnet()` and `switchProvider()`. A hydration
5581
+ * already queued or in flight when the toggle is made keeps it.
5498
5582
  *
5499
5583
  * Throws on remote write failure so the caller can decide whether to revert.
5500
5584
  *
@@ -5506,7 +5590,17 @@ export class PerpsController extends BaseController {
5506
5590
  this.#debugLog('PerpsController: Skipping AUS watchlist sync — provider not mapped', { activeProvider: this.state.activeProvider });
5507
5591
  return;
5508
5592
  }
5509
- const prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
5593
+ let prefs;
5594
+ try {
5595
+ prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
5596
+ }
5597
+ catch (error) {
5598
+ if (!isMissingActionHandlerError(error, 'AuthenticatedUserStorageService:getNotificationPreferences')) {
5599
+ throw error;
5600
+ }
5601
+ this.#debugLog('PerpsController: Skipping AUS watchlist write — AuthenticatedUserStorageService not provided', { exchangeKey, network });
5602
+ return;
5603
+ }
5510
5604
  if (!prefs) {
5511
5605
  this.#debugLog('PerpsController: Skipping AUS watchlist write — preferences blob not yet initialised', { exchangeKey, network });
5512
5606
  return;
@@ -5529,7 +5623,16 @@ export class PerpsController extends BaseController {
5529
5623
  watchlistMarkets: nextWatchlistMarkets,
5530
5624
  },
5531
5625
  };
5532
- await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
5626
+ try {
5627
+ await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
5628
+ }
5629
+ catch (error) {
5630
+ if (!isMissingActionHandlerError(error, 'AuthenticatedUserStorageService:putNotificationPreferences')) {
5631
+ throw error;
5632
+ }
5633
+ this.#debugLog('PerpsController: Skipping AUS watchlist write — AuthenticatedUserStorageService not provided', { exchangeKey, network });
5634
+ return;
5635
+ }
5533
5636
  this.#debugLog('PerpsController: Watchlist synced to AUS', {
5534
5637
  exchangeKey,
5535
5638
  network,
@@ -5541,20 +5644,35 @@ export class PerpsController extends BaseController {
5541
5644
  * controller initialisation.
5542
5645
  *
5543
5646
  * AUS is the source of truth; local state is used as an offline cache.
5647
+ * Toggles made since the hydration was queued are applied on top of the
5648
+ * remote watchlist rather than overwritten by it.
5544
5649
  * This method also handles the one-time migration from local-only state to
5545
5650
  * AUS for users who had a watchlist before AUS sync was introduced.
5546
5651
  *
5547
5652
  * All remote errors are swallowed so a transient network failure does not
5548
5653
  * block the rest of `init()`.
5654
+ *
5655
+ * @param editsDuringHydration - Toggles recorded since this hydration was
5656
+ * queued; the caller registers and removes the list.
5549
5657
  */
5550
- async #syncWatchlistFromRemote() {
5658
+ async #syncWatchlistFromRemote(editsDuringHydration) {
5551
5659
  const exchangeKey = resolveWatchlistExchangeKey(this.state.activeProvider);
5552
5660
  if (!exchangeKey) {
5553
5661
  this.#debugLog('PerpsController: Skipping AUS watchlist hydration — provider not mapped', { activeProvider: this.state.activeProvider });
5554
5662
  return;
5555
5663
  }
5556
5664
  try {
5557
- const prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
5665
+ let prefs;
5666
+ try {
5667
+ prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
5668
+ }
5669
+ catch (error) {
5670
+ if (!isMissingActionHandlerError(error, 'AuthenticatedUserStorageService:getNotificationPreferences')) {
5671
+ throw error;
5672
+ }
5673
+ this.#debugLog('PerpsController: AuthenticatedUserStorageService not provided — using local watchlist');
5674
+ return;
5675
+ }
5558
5676
  if (!prefs) {
5559
5677
  this.#debugLog('PerpsController: No AUS preferences blob — using local watchlist');
5560
5678
  return;
@@ -5593,22 +5711,34 @@ export class PerpsController extends BaseController {
5593
5711
  watchlistMarkets: nextWatchlistMarkets,
5594
5712
  },
5595
5713
  };
5596
- await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
5714
+ try {
5715
+ await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
5716
+ }
5717
+ catch (error) {
5718
+ if (!isMissingActionHandlerError(error, 'AuthenticatedUserStorageService:putNotificationPreferences')) {
5719
+ throw error;
5720
+ }
5721
+ this.#debugLog('PerpsController: Skipping AUS watchlist migration — putNotificationPreferences not provided', { exchangeKey });
5722
+ return;
5723
+ }
5597
5724
  this.#debugLog('PerpsController: Local watchlist migrated to AUS', {
5598
5725
  exchangeKey,
5599
5726
  });
5600
5727
  }
5601
5728
  }
5602
5729
  else {
5603
- // AUS has an entry for this exchange — hydrate local state from it.
5730
+ // AUS has an entry for this exchange — hydrate local state from it,
5731
+ // keeping any toggle made while the read was in flight.
5732
+ const hydrated = applyWatchlistEdits(remoteExchangeWatchlist, editsDuringHydration);
5604
5733
  this.update((state) => {
5605
- state.watchlistMarkets.testnet = remoteExchangeWatchlist.testnet;
5606
- state.watchlistMarkets.mainnet = remoteExchangeWatchlist.mainnet;
5734
+ state.watchlistMarkets.testnet = hydrated.testnet;
5735
+ state.watchlistMarkets.mainnet = hydrated.mainnet;
5607
5736
  });
5608
5737
  this.#debugLog('PerpsController: Watchlist hydrated from AUS', {
5609
5738
  exchangeKey,
5610
- testnetCount: remoteExchangeWatchlist.testnet.length,
5611
- mainnetCount: remoteExchangeWatchlist.mainnet.length,
5739
+ testnetCount: hydrated.testnet.length,
5740
+ mainnetCount: hydrated.mainnet.length,
5741
+ replayedToggles: editsDuringHydration.length,
5612
5742
  });
5613
5743
  }
5614
5744
  }