@metamask-previews/assets-controllers 95.1.0-preview-22f11ed5 → 95.1.0-preview-821afcb8

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 (44) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/TokenDetectionController.cjs +6 -3
  3. package/dist/TokenDetectionController.cjs.map +1 -1
  4. package/dist/TokenDetectionController.d.cts.map +1 -1
  5. package/dist/TokenDetectionController.d.mts.map +1 -1
  6. package/dist/TokenDetectionController.mjs +6 -3
  7. package/dist/TokenDetectionController.mjs.map +1 -1
  8. package/dist/TokenListController.cjs +353 -78
  9. package/dist/TokenListController.cjs.map +1 -1
  10. package/dist/TokenListController.d.cts +22 -17
  11. package/dist/TokenListController.d.cts.map +1 -1
  12. package/dist/TokenListController.d.mts +22 -17
  13. package/dist/TokenListController.d.mts.map +1 -1
  14. package/dist/TokenListController.mjs +353 -78
  15. package/dist/TokenListController.mjs.map +1 -1
  16. package/dist/TokenRatesController.cjs.map +1 -1
  17. package/dist/TokenRatesController.d.cts +2 -0
  18. package/dist/TokenRatesController.d.cts.map +1 -1
  19. package/dist/TokenRatesController.d.mts +2 -0
  20. package/dist/TokenRatesController.d.mts.map +1 -1
  21. package/dist/TokenRatesController.mjs.map +1 -1
  22. package/dist/TokensController.cjs +5 -2
  23. package/dist/TokensController.cjs.map +1 -1
  24. package/dist/TokensController.d.cts +1 -0
  25. package/dist/TokensController.d.cts.map +1 -1
  26. package/dist/TokensController.d.mts +1 -0
  27. package/dist/TokensController.d.mts.map +1 -1
  28. package/dist/TokensController.mjs +5 -2
  29. package/dist/TokensController.mjs.map +1 -1
  30. package/dist/selectors/token-selectors.cjs +1 -0
  31. package/dist/selectors/token-selectors.cjs.map +1 -1
  32. package/dist/selectors/token-selectors.d.cts +2 -0
  33. package/dist/selectors/token-selectors.d.cts.map +1 -1
  34. package/dist/selectors/token-selectors.d.mts +2 -0
  35. package/dist/selectors/token-selectors.d.mts.map +1 -1
  36. package/dist/selectors/token-selectors.mjs +1 -0
  37. package/dist/selectors/token-selectors.mjs.map +1 -1
  38. package/dist/token-service.cjs +4 -4
  39. package/dist/token-service.cjs.map +1 -1
  40. package/dist/token-service.d.cts.map +1 -1
  41. package/dist/token-service.d.mts.map +1 -1
  42. package/dist/token-service.mjs +4 -4
  43. package/dist/token-service.mjs.map +1 -1
  44. package/package.json +6 -5
@@ -3,10 +3,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
3
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _TokenListController_instances, _TokenListController_onNetworkControllerStateChange, _TokenListController_startDeprecatedPolling;
6
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
+ if (kind === "m") throw new TypeError("Private method is not writable");
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
9
+ 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");
10
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
+ };
12
+ var _TokenListController_instances, _a, _TokenListController_initializationPromise, _TokenListController_persistDebounceTimer, _TokenListController_persistInFlightPromise, _TokenListController_changedChainsToPersist, _TokenListController_previousTokensChainsCache, _TokenListController_persistDebounceMs, _TokenListController_storageKeyPrefix, _TokenListController_getChainStorageKey, _TokenListController_intervalId, _TokenListController_intervalDelay, _TokenListController_cacheRefreshThreshold, _TokenListController_chainId, _TokenListController_abortController, _TokenListController_initializeFromStorage, _TokenListController_onCacheChanged, _TokenListController_debouncePersist, _TokenListController_persistChangedChains, _TokenListController_loadCacheFromStorage, _TokenListController_saveChainCacheToStorage, _TokenListController_onNetworkControllerStateChange, _TokenListController_stopPolling, _TokenListController_startDeprecatedPolling;
7
13
  import { safelyExecute } from "@metamask/controller-utils";
8
14
  import { StaticIntervalPollingController } from "@metamask/polling-controller";
9
- import { Mutex } from "async-mutex";
10
15
  import { isTokenListSupportedForNetwork, formatAggregatorNames, formatIconUrlWithProxy } from "./assetsUtil.mjs";
11
16
  import { fetchTokenListByChainId } from "./token-service.mjs";
12
17
  // 4 Hour Interval Cache Refresh Threshold
@@ -16,7 +21,7 @@ const name = 'TokenListController';
16
21
  const metadata = {
17
22
  tokensChainsCache: {
18
23
  includeInStateLogs: false,
19
- persist: true,
24
+ persist: false, // Persisted separately via StorageService
20
25
  includeInDebugSnapshot: true,
21
26
  usedInUi: true,
22
27
  },
@@ -57,13 +62,41 @@ export class TokenListController extends StaticIntervalPollingController() {
57
62
  state: { ...getDefaultTokenListState(), ...state },
58
63
  });
59
64
  _TokenListController_instances.add(this);
60
- this.mutex = new Mutex();
61
- this.intervalDelay = interval;
65
+ /**
66
+ * Promise that resolves when initialization (loading cache from storage) is complete.
67
+ */
68
+ _TokenListController_initializationPromise.set(this, Promise.resolve());
69
+ /**
70
+ * Debounce timer for persisting state changes to storage.
71
+ */
72
+ _TokenListController_persistDebounceTimer.set(this, void 0);
73
+ /**
74
+ * Promise that resolves when the current persist operation completes.
75
+ * Used to prevent race conditions between persist and clear operations.
76
+ */
77
+ _TokenListController_persistInFlightPromise.set(this, void 0);
78
+ /**
79
+ * Tracks which chains have pending changes to persist.
80
+ * Only changed chains are persisted to reduce write amplification.
81
+ */
82
+ _TokenListController_changedChainsToPersist.set(this, new Set());
83
+ /**
84
+ * Previous tokensChainsCache for detecting which chains changed.
85
+ */
86
+ _TokenListController_previousTokensChainsCache.set(this, {});
87
+ _TokenListController_intervalId.set(this, void 0);
88
+ _TokenListController_intervalDelay.set(this, void 0);
89
+ _TokenListController_cacheRefreshThreshold.set(this, void 0);
90
+ _TokenListController_chainId.set(this, void 0);
91
+ _TokenListController_abortController.set(this, void 0);
92
+ __classPrivateFieldSet(this, _TokenListController_intervalDelay, interval, "f");
62
93
  this.setIntervalLength(interval);
63
- this.cacheRefreshThreshold = cacheRefreshThreshold;
64
- this.chainId = chainId;
94
+ __classPrivateFieldSet(this, _TokenListController_cacheRefreshThreshold, cacheRefreshThreshold, "f");
95
+ __classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
65
96
  this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);
66
- this.abortController = new AbortController();
97
+ __classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
98
+ // Subscribe to state changes to automatically persist tokensChainsCache
99
+ this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
67
100
  if (onNetworkStateChange) {
68
101
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
69
102
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
@@ -80,6 +113,16 @@ export class TokenListController extends StaticIntervalPollingController() {
80
113
  });
81
114
  }
82
115
  }
116
+ /**
117
+ * Initialize the controller by loading cache from storage and running migration.
118
+ * This method should be called by clients after construction.
119
+ *
120
+ * @returns A promise that resolves when initialization is complete.
121
+ */
122
+ async initialize() {
123
+ __classPrivateFieldSet(this, _TokenListController_initializationPromise, __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_initializeFromStorage).call(this), "f");
124
+ await __classPrivateFieldGet(this, _TokenListController_initializationPromise, "f");
125
+ }
83
126
  // Eventually we want to remove start/restart/stop controls in favor of new _executePoll API
84
127
  // Maintaining these functions for now until we can safely deprecate them for backwards compatibility
85
128
  /**
@@ -89,7 +132,7 @@ export class TokenListController extends StaticIntervalPollingController() {
89
132
  * Consider using the new polling approach instead
90
133
  */
91
134
  async start() {
92
- if (!isTokenListSupportedForNetwork(this.chainId)) {
135
+ if (!isTokenListSupportedForNetwork(__classPrivateFieldGet(this, _TokenListController_chainId, "f"))) {
93
136
  return;
94
137
  }
95
138
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
@@ -101,7 +144,7 @@ export class TokenListController extends StaticIntervalPollingController() {
101
144
  * Consider using the new polling approach instead
102
145
  */
103
146
  async restart() {
104
- this.stopPolling();
147
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
105
148
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
106
149
  }
107
150
  /**
@@ -111,7 +154,7 @@ export class TokenListController extends StaticIntervalPollingController() {
111
154
  * Consider using the new polling approach instead
112
155
  */
113
156
  stop() {
114
- this.stopPolling();
157
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
115
158
  }
116
159
  /**
117
160
  * This stops any active polling.
@@ -121,18 +164,13 @@ export class TokenListController extends StaticIntervalPollingController() {
121
164
  */
122
165
  destroy() {
123
166
  super.destroy();
124
- this.stopPolling();
125
- }
126
- /**
127
- * This stops any active polling intervals.
128
- *
129
- * @deprecated This method is deprecated and will be removed in the future.
130
- * Consider using the new polling approach instead
131
- */
132
- stopPolling() {
133
- if (this.intervalId) {
134
- clearInterval(this.intervalId);
167
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
168
+ // Cancel any pending debounced persistence operations
169
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
170
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
171
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
135
172
  }
173
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
136
174
  }
137
175
  /**
138
176
  * This starts a new polling loop for any given chain. Under the hood it is deduping polls
@@ -145,71 +183,141 @@ export class TokenListController extends StaticIntervalPollingController() {
145
183
  return this.fetchTokenList(chainId);
146
184
  }
147
185
  /**
148
- * Fetching token list from the Token Service API. This will fetch tokens across chains. It will update tokensChainsCache (scoped across chains), and also the tokenList (scoped for the selected chain)
186
+ * Fetching token list from the Token Service API. This will fetch tokens across chains.
187
+ * State changes are automatically persisted via the stateChange subscription.
149
188
  *
150
189
  * @param chainId - The chainId of the current chain triggering the fetch.
151
190
  */
152
191
  async fetchTokenList(chainId) {
153
- const releaseLock = await this.mutex.acquire();
154
- try {
155
- if (this.isCacheValid(chainId)) {
156
- return;
157
- }
158
- // Fetch fresh token list from the API
159
- const tokensFromAPI = await safelyExecute(() => fetchTokenListByChainId(chainId, this.abortController.signal));
160
- // Have response - process and update list
161
- if (tokensFromAPI) {
162
- // Format tokens from API (HTTP) and update tokenList
163
- const tokenList = {};
164
- for (const token of tokensFromAPI) {
165
- tokenList[token.address] = {
166
- ...token,
167
- aggregators: formatAggregatorNames(token.aggregators),
168
- iconUrl: formatIconUrlWithProxy({
169
- chainId,
170
- tokenAddress: token.address,
171
- }),
172
- };
173
- }
174
- this.update((state) => {
175
- var _a;
176
- const newDataCache = { data: {}, timestamp: Date.now() };
177
- (_a = state.tokensChainsCache)[chainId] ?? (_a[chainId] = newDataCache);
178
- state.tokensChainsCache[chainId].data = tokenList;
179
- state.tokensChainsCache[chainId].timestamp = Date.now();
180
- });
181
- return;
192
+ if (this.isCacheValid(chainId)) {
193
+ return;
194
+ }
195
+ // Fetch fresh token list from the API
196
+ const tokensFromAPI = await safelyExecute(() => fetchTokenListByChainId(chainId, __classPrivateFieldGet(this, _TokenListController_abortController, "f").signal));
197
+ // Have response - process and update list
198
+ if (tokensFromAPI) {
199
+ // Format tokens from API (HTTP) and update tokenList
200
+ const tokenList = {};
201
+ for (const token of tokensFromAPI) {
202
+ tokenList[token.address] = {
203
+ ...token,
204
+ aggregators: formatAggregatorNames(token.aggregators),
205
+ iconUrl: formatIconUrlWithProxy({
206
+ chainId,
207
+ tokenAddress: token.address,
208
+ }),
209
+ };
182
210
  }
183
- // No response - fallback to previous state, or initialise empty
184
- if (!tokensFromAPI) {
211
+ // Update state - persistence happens automatically via subscription
212
+ const newDataCache = {
213
+ data: tokenList,
214
+ timestamp: Date.now(),
215
+ };
216
+ this.update((state) => {
217
+ state.tokensChainsCache[chainId] = newDataCache;
218
+ });
219
+ return;
220
+ }
221
+ // No response - fallback to previous state, or initialise empty.
222
+ // Only initialize with a new timestamp if there's no existing cache.
223
+ // If there's existing cache, keep it as-is without updating the timestamp
224
+ // to avoid making stale data appear "fresh" and preventing retry attempts.
225
+ if (!tokensFromAPI) {
226
+ const existingCache = this.state.tokensChainsCache[chainId];
227
+ if (!existingCache) {
228
+ // No existing cache - initialize empty (persistence happens automatically)
229
+ const newDataCache = { data: {}, timestamp: Date.now() };
185
230
  this.update((state) => {
186
- var _a;
187
- const newDataCache = { data: {}, timestamp: Date.now() };
188
- (_a = state.tokensChainsCache)[chainId] ?? (_a[chainId] = newDataCache);
189
- state.tokensChainsCache[chainId].timestamp = Date.now();
231
+ state.tokensChainsCache[chainId] = newDataCache;
190
232
  });
191
233
  }
192
- }
193
- finally {
194
- releaseLock();
234
+ // If there's existing cache, keep it as-is (don't update timestamp or persist)
195
235
  }
196
236
  }
197
237
  isCacheValid(chainId) {
198
238
  const { tokensChainsCache } = this.state;
199
239
  const timestamp = tokensChainsCache[chainId]?.timestamp;
200
240
  const now = Date.now();
201
- return (timestamp !== undefined && now - timestamp < this.cacheRefreshThreshold);
241
+ return (timestamp !== undefined && now - timestamp < __classPrivateFieldGet(this, _TokenListController_cacheRefreshThreshold, "f"));
202
242
  }
203
243
  /**
204
244
  * Clearing tokenList and tokensChainsCache explicitly.
245
+ * This clears both state and all per-chain files in StorageService.
246
+ *
247
+ * Uses Promise.allSettled to handle partial failures gracefully.
248
+ * After all removal attempts complete, state is updated to match storage:
249
+ * - Successfully removed chains are cleared from state
250
+ * - Failed removals are kept in state to maintain consistency with storage
251
+ *
252
+ * Note: This method explicitly deletes from storage rather than relying on the
253
+ * stateChange subscription, since the subscription handles saves, not deletes.
205
254
  */
206
- clearingTokenListData() {
207
- this.update(() => {
208
- return {
209
- ...this.state,
210
- tokensChainsCache: {},
211
- };
212
- });
255
+ async clearingTokenListData() {
256
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
257
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
258
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
259
+ }
260
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
261
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, {}, "f");
262
+ // Wait for any in-flight persist operation to complete before clearing storage.
263
+ // This prevents race conditions where persist setItem calls interleave with
264
+ // our removeItem calls, potentially re-saving data after we remove it.
265
+ if (__classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f")) {
266
+ try {
267
+ await __classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f");
268
+ }
269
+ catch {
270
+ // Ignore
271
+ }
272
+ }
273
+ try {
274
+ const allKeys = await this.messenger.call('StorageService:getAllKeys', name);
275
+ // Filter and remove all tokensChainsCache keys
276
+ const cacheKeys = allKeys.filter((key) => key.startsWith(`${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:`));
277
+ if (cacheKeys.length === 0) {
278
+ // No storage keys to remove, just clear state
279
+ this.update((state) => {
280
+ state.tokensChainsCache = {};
281
+ });
282
+ return;
283
+ }
284
+ // Use Promise.allSettled to handle partial failures gracefully.
285
+ // This ensures all removals are attempted and we can track which succeeded.
286
+ const results = await Promise.allSettled(cacheKeys.map((key) => this.messenger.call('StorageService:removeItem', name, key)));
287
+ // Identify which chains failed to be removed from storage
288
+ const failedChainIds = new Set();
289
+ results.forEach((result, index) => {
290
+ if (result.status === 'rejected') {
291
+ const key = cacheKeys[index];
292
+ const chainId = key.split(':')[1];
293
+ failedChainIds.add(chainId);
294
+ console.error(`TokenListController: Failed to remove cache for chain ${chainId}:`, result.reason);
295
+ }
296
+ });
297
+ // Update state to match storage: keep only chains that failed to be removed
298
+ this.update((state) => {
299
+ if (failedChainIds.size === 0) {
300
+ state.tokensChainsCache = {};
301
+ }
302
+ else {
303
+ // Keep only chains that failed to be removed from storage
304
+ const preservedCache = {};
305
+ for (const chainId of failedChainIds) {
306
+ if (state.tokensChainsCache[chainId]) {
307
+ preservedCache[chainId] = state.tokensChainsCache[chainId];
308
+ }
309
+ }
310
+ state.tokensChainsCache = preservedCache;
311
+ }
312
+ });
313
+ }
314
+ catch (error) {
315
+ console.error('TokenListController: Failed to clear cache from storage:', error);
316
+ // Still clear state even if storage access fails
317
+ this.update((state) => {
318
+ state.tokensChainsCache = {};
319
+ });
320
+ }
213
321
  }
214
322
  /**
215
323
  * Updates preventPollingOnNetworkRestart from extension.
@@ -225,7 +333,163 @@ export class TokenListController extends StaticIntervalPollingController() {
225
333
  });
226
334
  }
227
335
  }
228
- _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkControllerStateChange =
336
+ _a = TokenListController, _TokenListController_initializationPromise = new WeakMap(), _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(), _TokenListController_previousTokensChainsCache = new WeakMap(), _TokenListController_intervalId = new WeakMap(), _TokenListController_intervalDelay = new WeakMap(), _TokenListController_cacheRefreshThreshold = new WeakMap(), _TokenListController_chainId = new WeakMap(), _TokenListController_abortController = new WeakMap(), _TokenListController_instances = new WeakSet(), _TokenListController_getChainStorageKey = function _TokenListController_getChainStorageKey(chainId) {
337
+ return `${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:${chainId}`;
338
+ }, _TokenListController_initializeFromStorage =
339
+ /**
340
+ * Internal method to load cache from storage and run migration.
341
+ *
342
+ * @returns A promise that resolves when initialization is complete.
343
+ */
344
+ async function _TokenListController_initializeFromStorage() {
345
+ await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_loadCacheFromStorage).call(this);
346
+ }, _TokenListController_onCacheChanged = function _TokenListController_onCacheChanged(newCache) {
347
+ // Detect which chains changed by comparing with previous cache
348
+ for (const chainId of Object.keys(newCache)) {
349
+ const newData = newCache[chainId];
350
+ const prevData = __classPrivateFieldGet(this, _TokenListController_previousTokensChainsCache, "f")[chainId];
351
+ // Chain is new or timestamp changed (indicating data update)
352
+ if (!prevData || prevData.timestamp !== newData.timestamp) {
353
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
354
+ }
355
+ }
356
+ // Update previous cache reference
357
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, { ...newCache }, "f");
358
+ // Schedule persistence if there are changes
359
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
360
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
361
+ }
362
+ }, _TokenListController_debouncePersist = function _TokenListController_debouncePersist() {
363
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
364
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
365
+ }
366
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, setTimeout(() => {
367
+ // Note: #persistChangedChains handles errors internally via #saveChainCacheToStorage,
368
+ // so this promise will not reject.
369
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
370
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_persistChangedChains).call(this);
371
+ }, __classPrivateFieldGet(_a, _a, "f", _TokenListController_persistDebounceMs)), "f");
372
+ }, _TokenListController_persistChangedChains =
373
+ /**
374
+ * Persist only the chains that have changed to storage.
375
+ * Reduces write amplification by skipping unchanged chains.
376
+ *
377
+ * Tracks the in-flight operation via #persistInFlightPromise so that
378
+ * clearingTokenListData() can wait for it to complete before removing
379
+ * items from storage, preventing race conditions.
380
+ *
381
+ * @returns A promise that resolves when changed chains are persisted.
382
+ */
383
+ async function _TokenListController_persistChangedChains() {
384
+ const chainsToPersist = [...__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f")];
385
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
386
+ if (chainsToPersist.length === 0) {
387
+ return;
388
+ }
389
+ __classPrivateFieldSet(this, _TokenListController_persistInFlightPromise, Promise.all(chainsToPersist.map((chainId) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_saveChainCacheToStorage).call(this, chainId))).then(() => undefined), "f"); // Convert Promise<void[]> to Promise<void>
390
+ try {
391
+ await __classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f");
392
+ }
393
+ finally {
394
+ __classPrivateFieldSet(this, _TokenListController_persistInFlightPromise, undefined, "f");
395
+ }
396
+ }, _TokenListController_loadCacheFromStorage =
397
+ /**
398
+ * Load tokensChainsCache from StorageService into state.
399
+ * Loads all cached chains from separate per-chain files in parallel.
400
+ * Called during initialization to restore cached data.
401
+ *
402
+ * Note: This method merges loaded data with existing state to avoid
403
+ * overwriting any fresh data that may have been fetched concurrently.
404
+ * Caller must hold the mutex.
405
+ *
406
+ * @returns A promise that resolves when loading is complete.
407
+ */
408
+ async function _TokenListController_loadCacheFromStorage() {
409
+ try {
410
+ const allKeys = await this.messenger.call('StorageService:getAllKeys', name);
411
+ // Filter keys that belong to tokensChainsCache (per-chain files)
412
+ const cacheKeys = allKeys.filter((key) => key.startsWith(`${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:`));
413
+ if (cacheKeys.length === 0) {
414
+ return;
415
+ }
416
+ // Load all chains in parallel
417
+ const chainCaches = await Promise.all(cacheKeys.map(async (key) => {
418
+ // Extract chainId from key: 'tokensChainsCache:0x1' → '0x1'
419
+ const chainId = key.split(':')[1];
420
+ const { result, error } = await this.messenger.call('StorageService:getItem', name, key);
421
+ if (error) {
422
+ console.error(`TokenListController: Error loading cache for ${chainId}:`, error);
423
+ return null;
424
+ }
425
+ return result ? { chainId, data: result } : null;
426
+ }));
427
+ // Build complete cache from loaded chains
428
+ const loadedCache = {};
429
+ chainCaches.forEach((chainCache) => {
430
+ if (chainCache) {
431
+ loadedCache[chainCache.chainId] = chainCache.data;
432
+ }
433
+ });
434
+ // Merge loaded cache with existing state, preferring existing data
435
+ // (which may be fresher if fetched during initialization)
436
+ if (Object.keys(loadedCache).length > 0) {
437
+ this.update((state) => {
438
+ // Only load chains that don't already exist in state
439
+ // This prevents overwriting fresh API data with stale cached data
440
+ for (const [chainId, cacheData] of Object.entries(loadedCache)) {
441
+ if (!state.tokensChainsCache[chainId]) {
442
+ state.tokensChainsCache[chainId] = cacheData;
443
+ }
444
+ }
445
+ });
446
+ // Clear persistence for chains loaded from storage only.
447
+ // Data loaded from storage doesn't need to be re-persisted.
448
+ // The update() call above triggers #onCacheChanged which detects all
449
+ // loaded chains as "new" (since #previousTokensChainsCache is empty)
450
+ // and schedules them for persistence. We must clear these to avoid
451
+ // redundant storage writes on every initialization.
452
+ // However, we must NOT clear chains from initial state that were never
453
+ // persisted to storage - those still need their first persist.
454
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
455
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
456
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
457
+ }
458
+ // Only remove loaded chains, not chains from initial state that need first persist
459
+ for (const chainId of Object.keys(loadedCache)) {
460
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").delete(chainId);
461
+ }
462
+ // Re-schedule persistence if there are remaining chains to persist
463
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
464
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
465
+ }
466
+ }
467
+ }
468
+ catch (error) {
469
+ console.error('TokenListController: Failed to load cache from storage:', error);
470
+ }
471
+ }, _TokenListController_saveChainCacheToStorage =
472
+ /**
473
+ * Save a specific chain's cache to StorageService.
474
+ * This persists only the updated chain's data, reducing write amplification.
475
+ *
476
+ * @param chainId - The chain ID to save.
477
+ * @returns A promise that resolves when saving is complete.
478
+ */
479
+ async function _TokenListController_saveChainCacheToStorage(chainId) {
480
+ try {
481
+ const chainData = this.state.tokensChainsCache[chainId];
482
+ if (!chainData) {
483
+ console.warn(`TokenListController: No cache data for chain ${chainId}`);
484
+ return;
485
+ }
486
+ const storageKey = __classPrivateFieldGet(_a, _a, "m", _TokenListController_getChainStorageKey).call(_a, chainId);
487
+ await this.messenger.call('StorageService:setItem', name, storageKey, chainData);
488
+ }
489
+ catch (error) {
490
+ console.error(`TokenListController: Failed to save cache for ${chainId}:`, error);
491
+ }
492
+ }, _TokenListController_onNetworkControllerStateChange =
229
493
  /**
230
494
  * Updates state and restarts polling on changes to the network controller
231
495
  * state.
@@ -235,14 +499,19 @@ _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkCo
235
499
  async function _TokenListController_onNetworkControllerStateChange(networkControllerState) {
236
500
  const selectedNetworkClient = this.messenger.call('NetworkController:getNetworkClientById', networkControllerState.selectedNetworkClientId);
237
501
  const { chainId } = selectedNetworkClient.configuration;
238
- if (this.chainId !== chainId) {
239
- this.abortController.abort();
240
- this.abortController = new AbortController();
241
- this.chainId = chainId;
502
+ if (__classPrivateFieldGet(this, _TokenListController_chainId, "f") !== chainId) {
503
+ __classPrivateFieldGet(this, _TokenListController_abortController, "f").abort();
504
+ __classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
505
+ __classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
242
506
  if (this.state.preventPollingOnNetworkRestart) {
507
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
243
508
  this.clearingTokenListData();
244
509
  }
245
510
  }
511
+ }, _TokenListController_stopPolling = function _TokenListController_stopPolling() {
512
+ if (__classPrivateFieldGet(this, _TokenListController_intervalId, "f")) {
513
+ clearInterval(__classPrivateFieldGet(this, _TokenListController_intervalId, "f"));
514
+ }
246
515
  }, _TokenListController_startDeprecatedPolling =
247
516
  /**
248
517
  * Starts a new polling interval for a given chainId (this should be deprecated in favor of _executePoll)
@@ -252,12 +521,18 @@ async function _TokenListController_onNetworkControllerStateChange(networkContro
252
521
  */
253
522
  async function _TokenListController_startDeprecatedPolling() {
254
523
  // renaming this to avoid collision with base class
255
- await safelyExecute(() => this.fetchTokenList(this.chainId));
524
+ await safelyExecute(() => this.fetchTokenList(__classPrivateFieldGet(this, _TokenListController_chainId, "f")));
256
525
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
257
526
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
258
- this.intervalId = setInterval(async () => {
259
- await safelyExecute(() => this.fetchTokenList(this.chainId));
260
- }, this.intervalDelay);
527
+ __classPrivateFieldSet(this, _TokenListController_intervalId, setInterval(async () => {
528
+ await safelyExecute(() => this.fetchTokenList(__classPrivateFieldGet(this, _TokenListController_chainId, "f")));
529
+ }, __classPrivateFieldGet(this, _TokenListController_intervalDelay, "f")), "f");
261
530
  };
531
+ /**
532
+ * Debounce delay for persisting state changes (in milliseconds).
533
+ */
534
+ _TokenListController_persistDebounceMs = { value: 500 };
535
+ // Storage key prefix for per-chain files
536
+ _TokenListController_storageKeyPrefix = { value: 'tokensChainsCache' };
262
537
  export default TokenListController;
263
538
  //# sourceMappingURL=TokenListController.mjs.map