@metamask-previews/assets-controllers 96.0.0-preview-6ae8a59c → 96.0.0-preview-a94732c3

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 (48) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/TokenListController.cjs +353 -78
  3. package/dist/TokenListController.cjs.map +1 -1
  4. package/dist/TokenListController.d.cts +22 -17
  5. package/dist/TokenListController.d.cts.map +1 -1
  6. package/dist/TokenListController.d.mts +22 -17
  7. package/dist/TokenListController.d.mts.map +1 -1
  8. package/dist/TokenListController.mjs +353 -78
  9. package/dist/TokenListController.mjs.map +1 -1
  10. package/dist/TokenRatesController.cjs +8 -1
  11. package/dist/TokenRatesController.cjs.map +1 -1
  12. package/dist/TokenRatesController.d.cts +2 -1
  13. package/dist/TokenRatesController.d.cts.map +1 -1
  14. package/dist/TokenRatesController.d.mts +2 -1
  15. package/dist/TokenRatesController.d.mts.map +1 -1
  16. package/dist/TokenRatesController.mjs +8 -1
  17. package/dist/TokenRatesController.mjs.map +1 -1
  18. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +3 -53
  19. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
  20. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts +1 -12
  21. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -1
  22. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts +1 -12
  23. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -1
  24. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs +3 -53
  25. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
  26. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  27. package/dist/token-prices-service/abstract-token-prices-service.d.cts +12 -1
  28. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  29. package/dist/token-prices-service/abstract-token-prices-service.d.mts +12 -1
  30. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  31. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  32. package/dist/token-prices-service/codefi-v2.cjs +156 -16
  33. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  34. package/dist/token-prices-service/codefi-v2.d.cts +44 -1
  35. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  36. package/dist/token-prices-service/codefi-v2.d.mts +44 -1
  37. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  38. package/dist/token-prices-service/codefi-v2.mjs +153 -16
  39. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  40. package/dist/token-prices-service/index.cjs +4 -1
  41. package/dist/token-prices-service/index.cjs.map +1 -1
  42. package/dist/token-prices-service/index.d.cts +2 -2
  43. package/dist/token-prices-service/index.d.cts.map +1 -1
  44. package/dist/token-prices-service/index.d.mts +2 -2
  45. package/dist/token-prices-service/index.d.mts.map +1 -1
  46. package/dist/token-prices-service/index.mjs +1 -1
  47. package/dist/token-prices-service/index.mjs.map +1 -1
  48. package/package.json +3 -1
@@ -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_chainsLoadedFromStorage, _TokenListController_previousTokensChainsCache, _TokenListController_persistDebounceMs, _TokenListController_storageKeyPrefix, _TokenListController_getChainStorageKey, _TokenListController_intervalId, _TokenListController_intervalDelay, _TokenListController_cacheRefreshThreshold, _TokenListController_chainId, _TokenListController_abortController, _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,48 @@ 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
+ * Tracks chains that were just loaded from storage and should skip
85
+ * the next persistence cycle. This prevents redundant writes where
86
+ * data loaded from storage would be immediately written back.
87
+ * Chains are removed from this set after being skipped once.
88
+ */
89
+ _TokenListController_chainsLoadedFromStorage.set(this, new Set());
90
+ /**
91
+ * Previous tokensChainsCache for detecting which chains changed.
92
+ */
93
+ _TokenListController_previousTokensChainsCache.set(this, {});
94
+ _TokenListController_intervalId.set(this, void 0);
95
+ _TokenListController_intervalDelay.set(this, void 0);
96
+ _TokenListController_cacheRefreshThreshold.set(this, void 0);
97
+ _TokenListController_chainId.set(this, void 0);
98
+ _TokenListController_abortController.set(this, void 0);
99
+ __classPrivateFieldSet(this, _TokenListController_intervalDelay, interval, "f");
62
100
  this.setIntervalLength(interval);
63
- this.cacheRefreshThreshold = cacheRefreshThreshold;
64
- this.chainId = chainId;
101
+ __classPrivateFieldSet(this, _TokenListController_cacheRefreshThreshold, cacheRefreshThreshold, "f");
102
+ __classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
65
103
  this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);
66
- this.abortController = new AbortController();
104
+ __classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
105
+ // Subscribe to state changes to automatically persist tokensChainsCache
106
+ this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
67
107
  if (onNetworkStateChange) {
68
108
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
69
109
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
@@ -80,6 +120,16 @@ export class TokenListController extends StaticIntervalPollingController() {
80
120
  });
81
121
  }
82
122
  }
123
+ /**
124
+ * Initialize the controller by loading cache from storage and running migration.
125
+ * This method should be called by clients after construction.
126
+ *
127
+ * @returns A promise that resolves when initialization is complete.
128
+ */
129
+ async initialize() {
130
+ __classPrivateFieldSet(this, _TokenListController_initializationPromise, __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_loadCacheFromStorage).call(this), "f");
131
+ await __classPrivateFieldGet(this, _TokenListController_initializationPromise, "f");
132
+ }
83
133
  // Eventually we want to remove start/restart/stop controls in favor of new _executePoll API
84
134
  // Maintaining these functions for now until we can safely deprecate them for backwards compatibility
85
135
  /**
@@ -89,7 +139,7 @@ export class TokenListController extends StaticIntervalPollingController() {
89
139
  * Consider using the new polling approach instead
90
140
  */
91
141
  async start() {
92
- if (!isTokenListSupportedForNetwork(this.chainId)) {
142
+ if (!isTokenListSupportedForNetwork(__classPrivateFieldGet(this, _TokenListController_chainId, "f"))) {
93
143
  return;
94
144
  }
95
145
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
@@ -101,7 +151,7 @@ export class TokenListController extends StaticIntervalPollingController() {
101
151
  * Consider using the new polling approach instead
102
152
  */
103
153
  async restart() {
104
- this.stopPolling();
154
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
105
155
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
106
156
  }
107
157
  /**
@@ -111,7 +161,7 @@ export class TokenListController extends StaticIntervalPollingController() {
111
161
  * Consider using the new polling approach instead
112
162
  */
113
163
  stop() {
114
- this.stopPolling();
164
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
115
165
  }
116
166
  /**
117
167
  * This stops any active polling.
@@ -121,18 +171,14 @@ export class TokenListController extends StaticIntervalPollingController() {
121
171
  */
122
172
  destroy() {
123
173
  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);
174
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
175
+ // Cancel any pending debounced persistence operations
176
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
177
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
178
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
135
179
  }
180
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
181
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").clear();
136
182
  }
137
183
  /**
138
184
  * This starts a new polling loop for any given chain. Under the hood it is deduping polls
@@ -145,71 +191,142 @@ export class TokenListController extends StaticIntervalPollingController() {
145
191
  return this.fetchTokenList(chainId);
146
192
  }
147
193
  /**
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)
194
+ * Fetching token list from the Token Service API. This will fetch tokens across chains.
195
+ * State changes are automatically persisted via the stateChange subscription.
149
196
  *
150
197
  * @param chainId - The chainId of the current chain triggering the fetch.
151
198
  */
152
199
  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;
200
+ if (this.isCacheValid(chainId)) {
201
+ return;
202
+ }
203
+ // Fetch fresh token list from the API
204
+ const tokensFromAPI = await safelyExecute(() => fetchTokenListByChainId(chainId, __classPrivateFieldGet(this, _TokenListController_abortController, "f").signal));
205
+ // Have response - process and update list
206
+ if (tokensFromAPI) {
207
+ // Format tokens from API (HTTP) and update tokenList
208
+ const tokenList = {};
209
+ for (const token of tokensFromAPI) {
210
+ tokenList[token.address] = {
211
+ ...token,
212
+ aggregators: formatAggregatorNames(token.aggregators),
213
+ iconUrl: formatIconUrlWithProxy({
214
+ chainId,
215
+ tokenAddress: token.address,
216
+ }),
217
+ };
182
218
  }
183
- // No response - fallback to previous state, or initialise empty
184
- if (!tokensFromAPI) {
219
+ // Update state - persistence happens automatically via subscription
220
+ const newDataCache = {
221
+ data: tokenList,
222
+ timestamp: Date.now(),
223
+ };
224
+ this.update((state) => {
225
+ state.tokensChainsCache[chainId] = newDataCache;
226
+ });
227
+ return;
228
+ }
229
+ // No response - fallback to previous state, or initialise empty.
230
+ // Only initialize with a new timestamp if there's no existing cache.
231
+ // If there's existing cache, keep it as-is without updating the timestamp
232
+ // to avoid making stale data appear "fresh" and preventing retry attempts.
233
+ if (!tokensFromAPI) {
234
+ const existingCache = this.state.tokensChainsCache[chainId];
235
+ if (!existingCache) {
236
+ // No existing cache - initialize empty (persistence happens automatically)
237
+ const newDataCache = { data: {}, timestamp: Date.now() };
185
238
  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();
239
+ state.tokensChainsCache[chainId] = newDataCache;
190
240
  });
191
241
  }
192
- }
193
- finally {
194
- releaseLock();
242
+ // If there's existing cache, keep it as-is (don't update timestamp or persist)
195
243
  }
196
244
  }
197
245
  isCacheValid(chainId) {
198
246
  const { tokensChainsCache } = this.state;
199
247
  const timestamp = tokensChainsCache[chainId]?.timestamp;
200
248
  const now = Date.now();
201
- return (timestamp !== undefined && now - timestamp < this.cacheRefreshThreshold);
249
+ return (timestamp !== undefined && now - timestamp < __classPrivateFieldGet(this, _TokenListController_cacheRefreshThreshold, "f"));
202
250
  }
203
251
  /**
204
252
  * Clearing tokenList and tokensChainsCache explicitly.
253
+ * This clears both state and all per-chain files in StorageService.
254
+ *
255
+ * Uses Promise.allSettled to handle partial failures gracefully.
256
+ * After all removal attempts complete, state is updated to match storage:
257
+ * - Successfully removed chains are cleared from state
258
+ * - Failed removals are kept in state to maintain consistency with storage
259
+ *
260
+ * Note: This method explicitly deletes from storage rather than relying on the
261
+ * stateChange subscription, since the subscription handles saves, not deletes.
205
262
  */
206
- clearingTokenListData() {
207
- this.update(() => {
208
- return {
209
- ...this.state,
210
- tokensChainsCache: {},
211
- };
212
- });
263
+ async clearingTokenListData() {
264
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
265
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
266
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
267
+ }
268
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
269
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").clear();
270
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, {}, "f");
271
+ // Wait for any in-flight persist operation to complete before clearing storage.
272
+ // This prevents race conditions where persist setItem calls interleave with
273
+ // our removeItem calls, potentially re-saving data after we remove it.
274
+ if (__classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f")) {
275
+ try {
276
+ await __classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f");
277
+ }
278
+ catch {
279
+ // Ignore
280
+ }
281
+ }
282
+ try {
283
+ const allKeys = await this.messenger.call('StorageService:getAllKeys', name);
284
+ // Filter and remove all tokensChainsCache keys
285
+ const cacheKeys = allKeys.filter((key) => key.startsWith(`${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:`));
286
+ if (cacheKeys.length === 0) {
287
+ // No storage keys to remove, just clear state
288
+ this.update((state) => {
289
+ state.tokensChainsCache = {};
290
+ });
291
+ return;
292
+ }
293
+ // Use Promise.allSettled to handle partial failures gracefully.
294
+ // This ensures all removals are attempted and we can track which succeeded.
295
+ const results = await Promise.allSettled(cacheKeys.map((key) => this.messenger.call('StorageService:removeItem', name, key)));
296
+ // Identify which chains failed to be removed from storage
297
+ const failedChainIds = new Set();
298
+ results.forEach((result, index) => {
299
+ if (result.status === 'rejected') {
300
+ const key = cacheKeys[index];
301
+ const chainId = key.split(':')[1];
302
+ failedChainIds.add(chainId);
303
+ console.error(`TokenListController: Failed to remove cache for chain ${chainId}:`, result.reason);
304
+ }
305
+ });
306
+ // Update state to match storage: keep only chains that failed to be removed
307
+ this.update((state) => {
308
+ if (failedChainIds.size === 0) {
309
+ state.tokensChainsCache = {};
310
+ }
311
+ else {
312
+ // Keep only chains that failed to be removed from storage
313
+ const preservedCache = {};
314
+ for (const chainId of failedChainIds) {
315
+ if (state.tokensChainsCache[chainId]) {
316
+ preservedCache[chainId] = state.tokensChainsCache[chainId];
317
+ }
318
+ }
319
+ state.tokensChainsCache = preservedCache;
320
+ }
321
+ });
322
+ }
323
+ catch (error) {
324
+ console.error('TokenListController: Failed to clear cache from storage:', error);
325
+ // Still clear state even if storage access fails
326
+ this.update((state) => {
327
+ state.tokensChainsCache = {};
328
+ });
329
+ }
213
330
  }
214
331
  /**
215
332
  * Updates preventPollingOnNetworkRestart from extension.
@@ -225,7 +342,154 @@ export class TokenListController extends StaticIntervalPollingController() {
225
342
  });
226
343
  }
227
344
  }
228
- _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkControllerStateChange =
345
+ _a = TokenListController, _TokenListController_initializationPromise = new WeakMap(), _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(), _TokenListController_chainsLoadedFromStorage = 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) {
346
+ return `${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:${chainId}`;
347
+ }, _TokenListController_onCacheChanged = function _TokenListController_onCacheChanged(newCache) {
348
+ // Detect which chains changed by comparing with previous cache
349
+ for (const chainId of Object.keys(newCache)) {
350
+ const newData = newCache[chainId];
351
+ const prevData = __classPrivateFieldGet(this, _TokenListController_previousTokensChainsCache, "f")[chainId];
352
+ // Chain is new or timestamp changed (indicating data update)
353
+ if (!prevData || prevData.timestamp !== newData.timestamp) {
354
+ // Skip persistence for chains that were just loaded from storage
355
+ // (they don't need to be written back immediately)
356
+ if (__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").has(chainId)) {
357
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").delete(chainId); // Clean up - future updates should persist
358
+ }
359
+ else {
360
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
361
+ }
362
+ }
363
+ }
364
+ // Update previous cache reference
365
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, { ...newCache }, "f");
366
+ // Schedule persistence if there are changes
367
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
368
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
369
+ }
370
+ }, _TokenListController_debouncePersist = function _TokenListController_debouncePersist() {
371
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
372
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
373
+ }
374
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, setTimeout(() => {
375
+ // Note: #persistChangedChains handles errors internally via #saveChainCacheToStorage,
376
+ // so this promise will not reject.
377
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
378
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_persistChangedChains).call(this);
379
+ }, __classPrivateFieldGet(_a, _a, "f", _TokenListController_persistDebounceMs)), "f");
380
+ }, _TokenListController_persistChangedChains =
381
+ /**
382
+ * Persist only the chains that have changed to storage.
383
+ * Reduces write amplification by skipping unchanged chains.
384
+ *
385
+ * Tracks the in-flight operation via #persistInFlightPromise so that
386
+ * clearingTokenListData() can wait for it to complete before removing
387
+ * items from storage, preventing race conditions.
388
+ *
389
+ * @returns A promise that resolves when changed chains are persisted.
390
+ */
391
+ async function _TokenListController_persistChangedChains() {
392
+ const chainsToPersist = [...__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f")];
393
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
394
+ if (chainsToPersist.length === 0) {
395
+ return;
396
+ }
397
+ __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>
398
+ try {
399
+ await __classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f");
400
+ }
401
+ finally {
402
+ __classPrivateFieldSet(this, _TokenListController_persistInFlightPromise, undefined, "f");
403
+ }
404
+ }, _TokenListController_loadCacheFromStorage =
405
+ /**
406
+ * Load tokensChainsCache from StorageService into state.
407
+ * Loads all cached chains from separate per-chain files in parallel.
408
+ * Called during initialization to restore cached data.
409
+ *
410
+ * Note: This method merges loaded data with existing state to avoid
411
+ * overwriting any fresh data that may have been fetched concurrently.
412
+ * Caller must hold the mutex.
413
+ *
414
+ * @returns A promise that resolves when loading is complete.
415
+ */
416
+ async function _TokenListController_loadCacheFromStorage() {
417
+ try {
418
+ const allKeys = await this.messenger.call('StorageService:getAllKeys', name);
419
+ // Filter keys that belong to tokensChainsCache (per-chain files)
420
+ const cacheKeys = allKeys.filter((key) => key.startsWith(`${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:`));
421
+ if (cacheKeys.length === 0) {
422
+ return;
423
+ }
424
+ // Load all chains in parallel
425
+ const chainCaches = await Promise.all(cacheKeys.map(async (key) => {
426
+ // Extract chainId from key: 'tokensChainsCache:0x1' → '0x1'
427
+ const chainId = key.split(':')[1];
428
+ const { result, error } = await this.messenger.call('StorageService:getItem', name, key);
429
+ if (error) {
430
+ console.error(`TokenListController: Error loading cache for ${chainId}:`, error);
431
+ return null;
432
+ }
433
+ return result ? { chainId, data: result } : null;
434
+ }));
435
+ // Build complete cache from loaded chains
436
+ const loadedCache = {};
437
+ chainCaches.forEach((chainCache) => {
438
+ if (chainCache) {
439
+ loadedCache[chainCache.chainId] = chainCache.data;
440
+ }
441
+ });
442
+ // Merge loaded cache with existing state, preferring existing data
443
+ // (which may be fresher if fetched during initialization)
444
+ if (Object.keys(loadedCache).length > 0) {
445
+ // Track which chains we're actually loading from storage
446
+ // These will be skipped in the next #onCacheChanged to avoid redundant writes
447
+ for (const chainId of Object.keys(loadedCache)) {
448
+ if (!this.state.tokensChainsCache[chainId]) {
449
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").add(chainId);
450
+ }
451
+ }
452
+ this.update((state) => {
453
+ // Only load chains that don't already exist in state
454
+ // This prevents overwriting fresh API data with stale cached data
455
+ for (const [chainId, cacheData] of Object.entries(loadedCache)) {
456
+ if (!state.tokensChainsCache[chainId]) {
457
+ state.tokensChainsCache[chainId] = cacheData;
458
+ }
459
+ }
460
+ });
461
+ // Note: The update() call above triggers #onCacheChanged. Chains that were
462
+ // just loaded from storage are tracked in #chainsLoadedFromStorage and will
463
+ // be skipped from persistence (since they're already in storage).
464
+ // Chains from initial state that were NOT overwritten will still be persisted
465
+ // correctly, as they're not in #chainsLoadedFromStorage.
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