@metamask-previews/perps-controller 8.0.0-preview-7bc7196a6 → 8.0.0-preview-86a6309a0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,15 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ### Added
11
-
12
- - Sync `watchlistMarkets` with `AuthenticatedUserStorageService` so the watchlist is persisted server-side per authenticated user account ([#9010](https://github.com/MetaMask/core/pull/9010))
13
- - `toggleWatchlistMarket` now performs an optimistic local-state update followed by an async AUS read-merge-write; on failure the local state is reverted.
14
- - On `init()`, `state.watchlistMarkets` is hydrated from AUS (source of truth). If no remote watchlist exists yet for the active exchange, any existing local markets are migrated to AUS in a one-time push.
15
- - When unauthenticated, or when the active provider is not mapped to an AUS exchange key (e.g. `'aggregated'`), the controller falls back to local-only state without surfacing errors to callers.
16
- - `toggleWatchlistMarket` return type changed from `void` to `Promise<void>` to allow callers to await the remote write.
17
- - Add `resolveWatchlistExchangeKey(activeProvider)` helper that maps a `PerpsActiveProviderMode` to the corresponding `PerpsWatchlistMarkets` exchange key, returning `null` for unsupported modes ([#9010](https://github.com/MetaMask/core/pull/9010))
18
-
19
10
  ### Changed
20
11
 
21
12
  - Bump `@metamask/controller-utils` from `^12.1.0` to `^12.1.1` ([#9058](https://github.com/MetaMask/core/pull/9058))
@@ -10,9 +10,9 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
11
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
12
  };
13
- var _PerpsController_instances, _a, _PerpsController_initializationPromise, _PerpsController_isReinitializing, _PerpsController_myxRegistrationPromise, _PerpsController_blockedRegionListVersion, _PerpsController_hip3Enabled, _PerpsController_hip3AllowlistMarkets, _PerpsController_hip3BlocklistMarkets, _PerpsController_hip3ConfigSource, _PerpsController_isMYXProviderEnabled, _PerpsController_standaloneProvider, _PerpsController_handlersRegistered, _PerpsController_standaloneProviderIsTestnet, _PerpsController_standaloneProviderHip3Version, _PerpsController_eligibilityCheckDeferred, _PerpsController_options, _PerpsController_tradingService, _PerpsController_marketDataService, _PerpsController_accountService, _PerpsController_eligibilityService, _PerpsController_dataLakeService, _PerpsController_depositService, _PerpsController_featureFlagConfigurationService, _PerpsController_rewardsIntegrationService, _PerpsController_logError, _PerpsController_debugLog, _PerpsController_getAggregatedCacheProviderIds, _PerpsController_getOrCreateStandaloneProvider, _PerpsController_cleanupStandaloneProvider, _PerpsController_getMetrics, _PerpsController_findNetworkClientIdForChain, _PerpsController_submitTransaction, _PerpsController_migrateRequestsIfNeeded, _PerpsController_withStreamPause, _PerpsController_performInitialization, _PerpsController_createProviders, _PerpsController_assignActiveProvider, _PerpsController_getErrorContext, _PerpsController_getControllerState, _PerpsController_createServiceContext, _PerpsController_ensureTradingServiceDeps, _PerpsController_preloadWatchedPaths, _PerpsController_preloadTimer, _PerpsController_isPreloading, _PerpsController_isPreloadingUserData, _PerpsController_preloadStateUnsubscribe, _PerpsController_accountChangeUnsubscribe, _PerpsController_previousIsTestnet, _PerpsController_previousHip3ConfigVersion, _PerpsController_preloadRefreshMs, _PerpsController_preloadGuardMs, _PerpsController_hydrateCacheFromDiskSync, _PerpsController_performMarketDataPreload, _PerpsController_performUserDataPreload, _PerpsController_persistWatchlistToRemote, _PerpsController_syncWatchlistFromRemote;
13
+ var _PerpsController_instances, _a, _PerpsController_initializationPromise, _PerpsController_isReinitializing, _PerpsController_myxRegistrationPromise, _PerpsController_blockedRegionListVersion, _PerpsController_hip3Enabled, _PerpsController_hip3AllowlistMarkets, _PerpsController_hip3BlocklistMarkets, _PerpsController_hip3ConfigSource, _PerpsController_isMYXProviderEnabled, _PerpsController_standaloneProvider, _PerpsController_handlersRegistered, _PerpsController_standaloneProviderIsTestnet, _PerpsController_standaloneProviderHip3Version, _PerpsController_eligibilityCheckDeferred, _PerpsController_options, _PerpsController_tradingService, _PerpsController_marketDataService, _PerpsController_accountService, _PerpsController_eligibilityService, _PerpsController_dataLakeService, _PerpsController_depositService, _PerpsController_featureFlagConfigurationService, _PerpsController_rewardsIntegrationService, _PerpsController_logError, _PerpsController_debugLog, _PerpsController_getAggregatedCacheProviderIds, _PerpsController_getOrCreateStandaloneProvider, _PerpsController_cleanupStandaloneProvider, _PerpsController_getMetrics, _PerpsController_findNetworkClientIdForChain, _PerpsController_submitTransaction, _PerpsController_migrateRequestsIfNeeded, _PerpsController_withStreamPause, _PerpsController_performInitialization, _PerpsController_createProviders, _PerpsController_assignActiveProvider, _PerpsController_getErrorContext, _PerpsController_getControllerState, _PerpsController_createServiceContext, _PerpsController_ensureTradingServiceDeps, _PerpsController_preloadWatchedPaths, _PerpsController_preloadTimer, _PerpsController_isPreloading, _PerpsController_isPreloadingUserData, _PerpsController_preloadStateUnsubscribe, _PerpsController_accountChangeUnsubscribe, _PerpsController_previousIsTestnet, _PerpsController_previousHip3ConfigVersion, _PerpsController_preloadRefreshMs, _PerpsController_preloadGuardMs, _PerpsController_hydrateCacheFromDiskSync, _PerpsController_performMarketDataPreload, _PerpsController_performUserDataPreload;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.PerpsController = exports.getDefaultPerpsControllerState = exports.InitializationState = exports.PERPS_ERROR_CODES = exports.resolveMyxAuthConfig = exports.resolveWatchlistExchangeKey = exports.firstNonEmpty = void 0;
15
+ exports.PerpsController = exports.getDefaultPerpsControllerState = exports.InitializationState = exports.PERPS_ERROR_CODES = exports.resolveMyxAuthConfig = exports.firstNonEmpty = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
17
17
  const controller_utils_1 = require("@metamask/controller-utils");
18
18
  const uuid_1 = require("uuid");
@@ -49,26 +49,6 @@ function firstNonEmpty(...vals) {
49
49
  return (vals.find((val) => val !== null && val !== undefined && val !== '') ?? '');
50
50
  }
51
51
  exports.firstNonEmpty = firstNonEmpty;
52
- /**
53
- * Maps an active provider mode to the corresponding exchange key used in the
54
- * AUS {@link PerpsWatchlistMarkets} schema.
55
- *
56
- * Returns `null` for modes that are not yet represented in the AUS schema
57
- * (e.g. `'aggregated'`), which signals callers to skip remote sync and fall
58
- * back to local state only. Add new entries here as additional DEX providers
59
- * gain AUS watchlist support.
60
- *
61
- * @param activeProvider - The current active provider mode from controller state.
62
- * @returns The matching `PerpsWatchlistMarkets` key, or `null` if unsupported.
63
- */
64
- function resolveWatchlistExchangeKey(activeProvider) {
65
- const map = {
66
- hyperliquid: 'hyperliquid',
67
- myx: 'myx',
68
- };
69
- return map[activeProvider] ?? null;
70
- }
71
- exports.resolveWatchlistExchangeKey = resolveWatchlistExchangeKey;
72
52
  /**
73
53
  * Resolves MYX auth config from provider credentials, handling
74
54
  * testnet/mainnet fallback logic.
@@ -2951,21 +2931,12 @@ class PerpsController extends base_controller_1.BaseController {
2951
2931
  });
2952
2932
  }
2953
2933
  /**
2954
- * Toggle watchlist status for a market.
2955
- *
2956
- * Updates local state immediately (optimistic UI) and then syncs the new
2957
- * watchlist to AuthenticatedUserStorageService. If the remote write fails,
2958
- * the local state is reverted so it stays consistent with AUS.
2959
- *
2960
- * When the user is unauthenticated, or the active provider is not yet
2961
- * supported by the AUS schema, the controller continues operating with
2962
- * local-persisted state only — no error is surfaced to the caller.
2963
- *
2964
- * Watchlist markets are stored per network (testnet/mainnet).
2934
+ * Toggle watchlist status for a market
2935
+ * Watchlist markets are stored per network (testnet/mainnet)
2965
2936
  *
2966
2937
  * @param symbol - The trading pair symbol.
2967
2938
  */
2968
- async toggleWatchlistMarket(symbol) {
2939
+ toggleWatchlistMarket(symbol) {
2969
2940
  const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2970
2941
  const currentWatchlist = this.state.watchlistMarkets[currentNetwork];
2971
2942
  const isWatchlisted = currentWatchlist.includes(symbol);
@@ -2975,38 +2946,16 @@ class PerpsController extends base_controller_1.BaseController {
2975
2946
  symbol,
2976
2947
  action: isWatchlisted ? 'remove' : 'add',
2977
2948
  });
2978
- // Step 1: Optimistic local state update — UI reflects change immediately.
2979
2949
  this.update((state) => {
2980
2950
  if (isWatchlisted) {
2951
+ // Remove from watchlist
2981
2952
  state.watchlistMarkets[currentNetwork] = currentWatchlist.filter((marketSymbol) => marketSymbol !== symbol);
2982
2953
  }
2983
2954
  else {
2955
+ // Add to watchlist
2984
2956
  state.watchlistMarkets[currentNetwork] = [...currentWatchlist, symbol];
2985
2957
  }
2986
2958
  });
2987
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getMetrics).call(this).trackPerpsEvent(types_1.PerpsAnalyticsEvent.UiInteraction, {
2988
- [eventNames_1.PERPS_EVENT_PROPERTY.INTERACTION_TYPE]: eventNames_1.PERPS_EVENT_VALUE.INTERACTION_TYPE.FAVORITE_TOGGLED,
2989
- [eventNames_1.PERPS_EVENT_PROPERTY.ASSET]: symbol,
2990
- [eventNames_1.PERPS_EVENT_PROPERTY.ACTION_TYPE]: isWatchlisted
2991
- ? eventNames_1.PERPS_EVENT_VALUE.ACTION_TYPE.UNFAVORITE_MARKET
2992
- : eventNames_1.PERPS_EVENT_VALUE.ACTION_TYPE.FAVORITE_MARKET,
2993
- [eventNames_1.PERPS_EVENT_PROPERTY.FAVORITES_COUNT]: this.state.watchlistMarkets[currentNetwork].length,
2994
- });
2995
- // Step 2: Persist to AUS; revert local state if the write fails.
2996
- try {
2997
- await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_persistWatchlistToRemote).call(this, currentNetwork);
2998
- }
2999
- catch (error) {
3000
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.toggleWatchlistMarket'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'toggleWatchlistMarket', {
3001
- symbol,
3002
- network: currentNetwork,
3003
- action: isWatchlisted ? 'remove' : 'add',
3004
- }));
3005
- // Revert the optimistic update.
3006
- this.update((state) => {
3007
- state.watchlistMarkets[currentNetwork] = currentWatchlist;
3008
- });
3009
- }
3010
2959
  }
3011
2960
  /**
3012
2961
  * Check if a market is in the watchlist on the current network
@@ -3319,11 +3268,6 @@ async function _PerpsController_performInitialization() {
3319
3268
  timestamp: new Date().toISOString(),
3320
3269
  attempts: attempt,
3321
3270
  });
3322
- // Hydrate watchlist from AUS (non-blocking — transient failures are
3323
- // caught inside and must not prevent init from completing).
3324
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_syncWatchlistFromRemote).call(this).catch(() => {
3325
- // Errors are already logged inside #syncWatchlistFromRemote.
3326
- });
3327
3271
  return; // Exit retry loop on success
3328
3272
  }
3329
3273
  catch (error) {
@@ -3783,135 +3727,6 @@ async function _PerpsController_performUserDataPreload() {
3783
3727
  });
3784
3728
  __classPrivateFieldSet(this, _PerpsController_isPreloadingUserData, false, "f");
3785
3729
  }
3786
- }, _PerpsController_persistWatchlistToRemote =
3787
- /**
3788
- * Writes the current local watchlist to AuthenticatedUserStorageService
3789
- * using a read-merge-write strategy to avoid overwriting other preferences.
3790
- *
3791
- * Skips silently when:
3792
- * - The active provider has no AUS exchange key (e.g. `'aggregated'`).
3793
- * - The remote preferences blob does not yet exist (returns `null` / 404).
3794
- * In that case, `NotificationServicesController.createOnChainTriggers` is
3795
- * the canonical owner that creates the initial blob.
3796
- *
3797
- * Throws on remote write failure so the caller can decide whether to revert.
3798
- *
3799
- * @param network - Which network's list to sync ('testnet' | 'mainnet').
3800
- */
3801
- async function _PerpsController_persistWatchlistToRemote(network) {
3802
- const exchangeKey = resolveWatchlistExchangeKey(this.state.activeProvider);
3803
- if (!exchangeKey) {
3804
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Skipping AUS watchlist sync — provider not mapped', { activeProvider: this.state.activeProvider });
3805
- return;
3806
- }
3807
- const prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
3808
- if (!prefs) {
3809
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Skipping AUS watchlist write — preferences blob not yet initialised', { exchangeKey, network });
3810
- return;
3811
- }
3812
- const existingWatchlist = prefs.perps
3813
- .watchlistMarkets ?? {
3814
- hyperliquid: { testnet: [], mainnet: [] },
3815
- myx: { testnet: [], mainnet: [] },
3816
- };
3817
- const nextWatchlistMarkets = {
3818
- ...existingWatchlist,
3819
- [exchangeKey]: {
3820
- ...existingWatchlist[exchangeKey],
3821
- [network]: this.state.watchlistMarkets[network],
3822
- },
3823
- };
3824
- const nextPrefs = {
3825
- ...prefs,
3826
- perps: {
3827
- ...prefs.perps,
3828
- watchlistMarkets: nextWatchlistMarkets,
3829
- },
3830
- };
3831
- await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
3832
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Watchlist synced to AUS', {
3833
- exchangeKey,
3834
- network,
3835
- count: this.state.watchlistMarkets[network].length,
3836
- });
3837
- }, _PerpsController_syncWatchlistFromRemote =
3838
- /**
3839
- * Hydrates `state.watchlistMarkets` from AuthenticatedUserStorageService on
3840
- * controller initialisation.
3841
- *
3842
- * AUS is the source of truth; local state is used as an offline cache.
3843
- * This method also handles the one-time migration from local-only state to
3844
- * AUS for users who had a watchlist before AUS sync was introduced.
3845
- *
3846
- * All remote errors are swallowed so a transient network failure does not
3847
- * block the rest of `init()`.
3848
- */
3849
- async function _PerpsController_syncWatchlistFromRemote() {
3850
- const exchangeKey = resolveWatchlistExchangeKey(this.state.activeProvider);
3851
- if (!exchangeKey) {
3852
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Skipping AUS watchlist hydration — provider not mapped', { activeProvider: this.state.activeProvider });
3853
- return;
3854
- }
3855
- try {
3856
- const prefs = await this.messenger.call('AuthenticatedUserStorageService:getNotificationPreferences');
3857
- if (!prefs) {
3858
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: No AUS preferences blob — using local watchlist');
3859
- return;
3860
- }
3861
- const remoteExchangeWatchlist = prefs.perps.watchlistMarkets?.[exchangeKey];
3862
- if (remoteExchangeWatchlist) {
3863
- // AUS has data for this exchange — hydrate local state from it.
3864
- this.update((state) => {
3865
- state.watchlistMarkets.testnet = remoteExchangeWatchlist.testnet;
3866
- state.watchlistMarkets.mainnet = remoteExchangeWatchlist.mainnet;
3867
- });
3868
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Watchlist hydrated from AUS', {
3869
- exchangeKey,
3870
- testnetCount: remoteExchangeWatchlist.testnet.length,
3871
- mainnetCount: remoteExchangeWatchlist.mainnet.length,
3872
- });
3873
- }
3874
- else {
3875
- // Blob exists but has no watchlist for this exchange yet.
3876
- // If local state has any markets, push them up as a one-time migration.
3877
- const { testnet, mainnet } = this.state.watchlistMarkets;
3878
- const hasLocalMarkets = testnet.length > 0 || mainnet.length > 0;
3879
- if (hasLocalMarkets) {
3880
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Migrating local watchlist to AUS', {
3881
- exchangeKey,
3882
- testnetCount: testnet.length,
3883
- mainnetCount: mainnet.length,
3884
- });
3885
- // Push testnet and mainnet together via a single read-merge-write.
3886
- // #persistWatchlistToRemote writes the network passed to it; call it
3887
- // for whichever networks have data (or both — duplicate writes are
3888
- // idempotent since we read before each write, but a single combined
3889
- // write is cleaner). We combine both networks in one PUT here.
3890
- const existingWatchlist = {
3891
- hyperliquid: { testnet: [], mainnet: [] },
3892
- myx: { testnet: [], mainnet: [] },
3893
- };
3894
- const nextWatchlistMarkets = {
3895
- ...existingWatchlist,
3896
- [exchangeKey]: { testnet, mainnet },
3897
- };
3898
- const nextPrefs = {
3899
- ...prefs,
3900
- perps: {
3901
- ...prefs.perps,
3902
- watchlistMarkets: nextWatchlistMarkets,
3903
- },
3904
- };
3905
- await this.messenger.call('AuthenticatedUserStorageService:putNotificationPreferences', nextPrefs);
3906
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Local watchlist migrated to AUS', {
3907
- exchangeKey,
3908
- });
3909
- }
3910
- }
3911
- }
3912
- catch (error) {
3913
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.syncWatchlistFromRemote'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'syncWatchlistFromRemote'));
3914
- }
3915
3730
  };
3916
3731
  // ============================================================================
3917
3732
  // Market Data Preload (client-agnostic background caching)