@metamask/assets-controllers 97.0.0 → 99.0.0

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.
@@ -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_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_synchronizeCacheWithStorage, _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,21 +21,14 @@ 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
  },
23
- preventPollingOnNetworkRestart: {
24
- includeInStateLogs: false,
25
- persist: true,
26
- includeInDebugSnapshot: true,
27
- usedInUi: false,
28
- },
29
28
  };
30
29
  export const getDefaultTokenListState = () => {
31
30
  return {
32
31
  tokensChainsCache: {},
33
- preventPollingOnNetworkRestart: false,
34
32
  };
35
33
  };
36
34
  /**
@@ -47,9 +45,8 @@ export class TokenListController extends StaticIntervalPollingController() {
47
45
  * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds.
48
46
  * @param options.messenger - A restricted messenger.
49
47
  * @param options.state - Initial state to set on this controller.
50
- * @param options.preventPollingOnNetworkRestart - Determines whether to prevent poilling on network restart in extension.
51
48
  */
52
- constructor({ chainId, preventPollingOnNetworkRestart = false, onNetworkStateChange, interval = DEFAULT_INTERVAL, cacheRefreshThreshold = DEFAULT_THRESHOLD, messenger, state, }) {
49
+ constructor({ chainId, onNetworkStateChange, interval = DEFAULT_INTERVAL, cacheRefreshThreshold = DEFAULT_THRESHOLD, messenger, state, }) {
53
50
  super({
54
51
  name,
55
52
  metadata,
@@ -57,13 +54,43 @@ export class TokenListController extends StaticIntervalPollingController() {
57
54
  state: { ...getDefaultTokenListState(), ...state },
58
55
  });
59
56
  _TokenListController_instances.add(this);
60
- this.mutex = new Mutex();
61
- this.intervalDelay = interval;
57
+ /**
58
+ * Debounce timer for persisting state changes to storage.
59
+ */
60
+ _TokenListController_persistDebounceTimer.set(this, void 0);
61
+ /**
62
+ * Promise that resolves when the current persist operation completes.
63
+ * Used to prevent race conditions between persist operations.
64
+ */
65
+ _TokenListController_persistInFlightPromise.set(this, void 0);
66
+ /**
67
+ * Tracks which chains have pending changes to persist.
68
+ * Only changed chains are persisted to reduce write amplification.
69
+ */
70
+ _TokenListController_changedChainsToPersist.set(this, new Set());
71
+ /**
72
+ * Tracks chains that were just loaded from storage and should skip
73
+ * the next persistence cycle. This prevents redundant writes where
74
+ * data loaded from storage would be immediately written back.
75
+ * Chains are removed from this set after being skipped once.
76
+ */
77
+ _TokenListController_chainsLoadedFromStorage.set(this, new Set());
78
+ /**
79
+ * Previous tokensChainsCache for detecting which chains changed.
80
+ */
81
+ _TokenListController_previousTokensChainsCache.set(this, {});
82
+ _TokenListController_intervalId.set(this, void 0);
83
+ _TokenListController_intervalDelay.set(this, void 0);
84
+ _TokenListController_cacheRefreshThreshold.set(this, void 0);
85
+ _TokenListController_chainId.set(this, void 0);
86
+ _TokenListController_abortController.set(this, void 0);
87
+ __classPrivateFieldSet(this, _TokenListController_intervalDelay, interval, "f");
62
88
  this.setIntervalLength(interval);
63
- this.cacheRefreshThreshold = cacheRefreshThreshold;
64
- this.chainId = chainId;
65
- this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);
66
- this.abortController = new AbortController();
89
+ __classPrivateFieldSet(this, _TokenListController_cacheRefreshThreshold, cacheRefreshThreshold, "f");
90
+ __classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
91
+ __classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
92
+ // Subscribe to state changes to automatically persist tokensChainsCache
93
+ this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
67
94
  if (onNetworkStateChange) {
68
95
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
69
96
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
@@ -80,6 +107,15 @@ export class TokenListController extends StaticIntervalPollingController() {
80
107
  });
81
108
  }
82
109
  }
110
+ /**
111
+ * Initialize the controller by loading cache from storage and running migration.
112
+ * This method should be called by clients after construction.
113
+ *
114
+ * @returns A promise that resolves when initialization is complete.
115
+ */
116
+ async initialize() {
117
+ await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_synchronizeCacheWithStorage).call(this);
118
+ }
83
119
  // Eventually we want to remove start/restart/stop controls in favor of new _executePoll API
84
120
  // Maintaining these functions for now until we can safely deprecate them for backwards compatibility
85
121
  /**
@@ -89,7 +125,7 @@ export class TokenListController extends StaticIntervalPollingController() {
89
125
  * Consider using the new polling approach instead
90
126
  */
91
127
  async start() {
92
- if (!isTokenListSupportedForNetwork(this.chainId)) {
128
+ if (!isTokenListSupportedForNetwork(__classPrivateFieldGet(this, _TokenListController_chainId, "f"))) {
93
129
  return;
94
130
  }
95
131
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
@@ -101,7 +137,7 @@ export class TokenListController extends StaticIntervalPollingController() {
101
137
  * Consider using the new polling approach instead
102
138
  */
103
139
  async restart() {
104
- this.stopPolling();
140
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
105
141
  await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_startDeprecatedPolling).call(this);
106
142
  }
107
143
  /**
@@ -111,7 +147,7 @@ export class TokenListController extends StaticIntervalPollingController() {
111
147
  * Consider using the new polling approach instead
112
148
  */
113
149
  stop() {
114
- this.stopPolling();
150
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
115
151
  }
116
152
  /**
117
153
  * This stops any active polling.
@@ -121,18 +157,14 @@ export class TokenListController extends StaticIntervalPollingController() {
121
157
  */
122
158
  destroy() {
123
159
  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);
160
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_stopPolling).call(this);
161
+ // Cancel any pending debounced persistence operations
162
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
163
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
164
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
135
165
  }
166
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
167
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").clear();
136
168
  }
137
169
  /**
138
170
  * This starts a new polling loop for any given chain. Under the hood it is deduping polls
@@ -145,87 +177,231 @@ export class TokenListController extends StaticIntervalPollingController() {
145
177
  return this.fetchTokenList(chainId);
146
178
  }
147
179
  /**
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)
180
+ * Fetching token list from the Token Service API. This will fetch tokens across chains.
181
+ * State changes are automatically persisted via the stateChange subscription.
149
182
  *
150
183
  * @param chainId - The chainId of the current chain triggering the fetch.
151
184
  */
152
185
  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;
186
+ if (this.isCacheValid(chainId)) {
187
+ return;
188
+ }
189
+ // Fetch fresh token list from the API
190
+ const tokensFromAPI = await safelyExecute(() => fetchTokenListByChainId(chainId, __classPrivateFieldGet(this, _TokenListController_abortController, "f").signal));
191
+ // Have response - process and update list
192
+ if (tokensFromAPI) {
193
+ // Format tokens from API (HTTP) and update tokenList
194
+ const tokenList = {};
195
+ for (const token of tokensFromAPI) {
196
+ tokenList[token.address] = {
197
+ ...token,
198
+ aggregators: formatAggregatorNames(token.aggregators),
199
+ iconUrl: formatIconUrlWithProxy({
200
+ chainId,
201
+ tokenAddress: token.address,
202
+ }),
203
+ };
182
204
  }
183
- // No response - fallback to previous state, or initialise empty
184
- if (!tokensFromAPI) {
205
+ // Update state - persistence happens automatically via subscription
206
+ const newDataCache = {
207
+ data: tokenList,
208
+ timestamp: Date.now(),
209
+ };
210
+ this.update((state) => {
211
+ state.tokensChainsCache[chainId] = newDataCache;
212
+ });
213
+ return;
214
+ }
215
+ // No response - fallback to previous state, or initialise empty.
216
+ // Only initialize with a new timestamp if there's no existing cache.
217
+ // If there's existing cache, keep it as-is without updating the timestamp
218
+ // to avoid making stale data appear "fresh" and preventing retry attempts.
219
+ if (!tokensFromAPI) {
220
+ const existingCache = this.state.tokensChainsCache[chainId];
221
+ if (!existingCache) {
222
+ // No existing cache - initialize empty (persistence happens automatically)
223
+ const newDataCache = { data: {}, timestamp: Date.now() };
185
224
  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();
225
+ state.tokensChainsCache[chainId] = newDataCache;
190
226
  });
191
227
  }
192
- }
193
- finally {
194
- releaseLock();
228
+ // If there's existing cache, keep it as-is (don't update timestamp or persist)
195
229
  }
196
230
  }
197
231
  isCacheValid(chainId) {
198
232
  const { tokensChainsCache } = this.state;
199
233
  const timestamp = tokensChainsCache[chainId]?.timestamp;
200
234
  const now = Date.now();
201
- return (timestamp !== undefined && now - timestamp < this.cacheRefreshThreshold);
235
+ return (timestamp !== undefined && now - timestamp < __classPrivateFieldGet(this, _TokenListController_cacheRefreshThreshold, "f"));
202
236
  }
203
- /**
204
- * Clearing tokenList and tokensChainsCache explicitly.
205
- */
206
- clearingTokenListData() {
207
- this.update(() => {
208
- return {
209
- ...this.state,
210
- tokensChainsCache: {},
211
- };
212
- });
237
+ }
238
+ _a = TokenListController, _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) {
239
+ return `${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:${chainId}`;
240
+ }, _TokenListController_onCacheChanged = function _TokenListController_onCacheChanged(newCache) {
241
+ // Detect which chains changed by comparing with previous cache
242
+ for (const chainId of Object.keys(newCache)) {
243
+ const newData = newCache[chainId];
244
+ const prevData = __classPrivateFieldGet(this, _TokenListController_previousTokensChainsCache, "f")[chainId];
245
+ // Chain is new or timestamp changed (indicating data update)
246
+ if (!prevData || prevData.timestamp !== newData.timestamp) {
247
+ // Skip persistence for chains that were just loaded from storage
248
+ // (they don't need to be written back immediately)
249
+ if (__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").has(chainId)) {
250
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").delete(chainId); // Clean up - future updates should persist
251
+ }
252
+ else {
253
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
254
+ }
255
+ }
213
256
  }
214
- /**
215
- * Updates preventPollingOnNetworkRestart from extension.
216
- *
217
- * @param shouldPreventPolling - Determine whether to prevent polling on network change
218
- */
219
- updatePreventPollingOnNetworkRestart(shouldPreventPolling) {
220
- this.update(() => {
221
- return {
222
- ...this.state,
223
- preventPollingOnNetworkRestart: shouldPreventPolling,
224
- };
257
+ // Update previous cache reference
258
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, { ...newCache }, "f");
259
+ // Schedule persistence if there are changes
260
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
261
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
262
+ }
263
+ }, _TokenListController_debouncePersist = function _TokenListController_debouncePersist() {
264
+ if (__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f")) {
265
+ clearTimeout(__classPrivateFieldGet(this, _TokenListController_persistDebounceTimer, "f"));
266
+ }
267
+ __classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, setTimeout(() => {
268
+ // Note: #persistChangedChains handles errors internally via #saveChainCacheToStorage,
269
+ // so this promise will not reject.
270
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
271
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_persistChangedChains).call(this);
272
+ }, __classPrivateFieldGet(_a, _a, "f", _TokenListController_persistDebounceMs)), "f");
273
+ }, _TokenListController_persistChangedChains =
274
+ /**
275
+ * Persist only the chains that have changed to storage.
276
+ * Reduces write amplification by skipping unchanged chains.
277
+ *
278
+ * If a persist operation is already in-flight, this method returns early
279
+ * and reschedules the debounce to ensure accumulated changes are retried
280
+ * after the current operation completes.
281
+ *
282
+ * @returns A promise that resolves when changed chains are persisted.
283
+ */
284
+ async function _TokenListController_persistChangedChains() {
285
+ if (__classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f")) {
286
+ // Reschedule debounce to retry accumulated changes after in-flight persist completes
287
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
288
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
289
+ }
290
+ return;
291
+ }
292
+ const chainsToPersist = [...__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f")];
293
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
294
+ if (chainsToPersist.length === 0) {
295
+ return;
296
+ }
297
+ __classPrivateFieldSet(this, _TokenListController_persistInFlightPromise, Promise.all(chainsToPersist.map((chainId) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_saveChainCacheToStorage).call(this, chainId))).then(() => undefined), "f");
298
+ try {
299
+ await __classPrivateFieldGet(this, _TokenListController_persistInFlightPromise, "f");
300
+ }
301
+ finally {
302
+ __classPrivateFieldSet(this, _TokenListController_persistInFlightPromise, undefined, "f");
303
+ }
304
+ }, _TokenListController_synchronizeCacheWithStorage =
305
+ /**
306
+ * Synchronize tokensChainsCache between state and storage bidirectionally.
307
+ *
308
+ * This method:
309
+ * 1. Loads cached chains from storage (per-chain files) in parallel
310
+ * 2. Merges loaded data into state (preferring existing state to avoid overwriting fresh data)
311
+ * 3. Persists any chains that exist in state but not in storage
312
+ *
313
+ * Called during initialization to ensure state and storage are consistent.
314
+ *
315
+ * @returns A promise that resolves when synchronization is complete.
316
+ */
317
+ async function _TokenListController_synchronizeCacheWithStorage() {
318
+ try {
319
+ const allKeys = await this.messenger.call('StorageService:getAllKeys', name);
320
+ // Filter keys that belong to tokensChainsCache (per-chain files)
321
+ const cacheKeys = allKeys.filter((key) => key.startsWith(`${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:`));
322
+ // Load all chains in parallel
323
+ const chainCaches = await Promise.all(cacheKeys.map(async (key) => {
324
+ // Extract chainId from key: 'tokensChainsCache:0x1' → '0x1'
325
+ const chainId = key.split(':')[1];
326
+ const { result, error } = await this.messenger.call('StorageService:getItem', name, key);
327
+ if (error) {
328
+ console.error(`TokenListController: Error loading cache for ${chainId}:`, error);
329
+ return null;
330
+ }
331
+ return result ? { chainId, data: result } : null;
332
+ }));
333
+ // Build complete cache from loaded chains
334
+ const loadedCache = {};
335
+ chainCaches.forEach((chainCache) => {
336
+ if (chainCache) {
337
+ loadedCache[chainCache.chainId] = chainCache.data;
338
+ }
225
339
  });
340
+ // Merge loaded cache with existing state, preferring existing data
341
+ // (which may be fresher if fetched during initialization)
342
+ if (Object.keys(loadedCache).length > 0) {
343
+ // Track which chains we're actually loading from storage
344
+ // These will be skipped in the next #onCacheChanged to avoid redundant writes
345
+ for (const chainId of Object.keys(loadedCache)) {
346
+ if (!this.state.tokensChainsCache[chainId]) {
347
+ __classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").add(chainId);
348
+ }
349
+ }
350
+ this.update((state) => {
351
+ // Only load chains that don't already exist in state
352
+ // This prevents overwriting fresh API data with stale cached data
353
+ for (const [chainId, cacheData] of Object.entries(loadedCache)) {
354
+ if (!state.tokensChainsCache[chainId]) {
355
+ state.tokensChainsCache[chainId] = cacheData;
356
+ }
357
+ }
358
+ });
359
+ // Note: The update() call above only triggers #onCacheChanged if chains
360
+ // were actually added to state. If initial state already contains chains
361
+ // from storage, the update() is a no-op and #onCacheChanged is never called.
362
+ }
363
+ // Persist chains that exist in state but were not loaded from storage.
364
+ // This handles the case where initial state contains chains that don't exist
365
+ // in storage yet (e.g., fresh data from API). Without this, those chains
366
+ // would be lost on the next app restart.
367
+ const loadedChainIds = new Set(Object.keys(loadedCache));
368
+ const chainsInState = new Set(Object.keys(this.state.tokensChainsCache));
369
+ for (const chainId of chainsInState) {
370
+ if (!loadedChainIds.has(chainId)) {
371
+ __classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
372
+ }
373
+ }
374
+ // Persist any chains that need to be saved
375
+ if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
376
+ __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_debouncePersist).call(this);
377
+ }
378
+ __classPrivateFieldSet(this, _TokenListController_previousTokensChainsCache, { ...this.state.tokensChainsCache }, "f");
226
379
  }
227
- }
228
- _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkControllerStateChange =
380
+ catch (error) {
381
+ console.error('TokenListController: Failed to load cache from storage:', error);
382
+ }
383
+ }, _TokenListController_saveChainCacheToStorage =
384
+ /**
385
+ * Save a specific chain's cache to StorageService.
386
+ * This persists only the updated chain's data, reducing write amplification.
387
+ *
388
+ * @param chainId - The chain ID to save.
389
+ * @returns A promise that resolves when saving is complete.
390
+ */
391
+ async function _TokenListController_saveChainCacheToStorage(chainId) {
392
+ try {
393
+ const chainData = this.state.tokensChainsCache[chainId];
394
+ if (!chainData) {
395
+ console.warn(`TokenListController: No cache data for chain ${chainId}`);
396
+ return;
397
+ }
398
+ const storageKey = __classPrivateFieldGet(_a, _a, "m", _TokenListController_getChainStorageKey).call(_a, chainId);
399
+ await this.messenger.call('StorageService:setItem', name, storageKey, chainData);
400
+ }
401
+ catch (error) {
402
+ console.error(`TokenListController: Failed to save cache for ${chainId}:`, error);
403
+ }
404
+ }, _TokenListController_onNetworkControllerStateChange =
229
405
  /**
230
406
  * Updates state and restarts polling on changes to the network controller
231
407
  * state.
@@ -235,13 +411,14 @@ _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkCo
235
411
  async function _TokenListController_onNetworkControllerStateChange(networkControllerState) {
236
412
  const selectedNetworkClient = this.messenger.call('NetworkController:getNetworkClientById', networkControllerState.selectedNetworkClientId);
237
413
  const { chainId } = selectedNetworkClient.configuration;
238
- if (this.chainId !== chainId) {
239
- this.abortController.abort();
240
- this.abortController = new AbortController();
241
- this.chainId = chainId;
242
- if (this.state.preventPollingOnNetworkRestart) {
243
- this.clearingTokenListData();
244
- }
414
+ if (__classPrivateFieldGet(this, _TokenListController_chainId, "f") !== chainId) {
415
+ __classPrivateFieldGet(this, _TokenListController_abortController, "f").abort();
416
+ __classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
417
+ __classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
418
+ }
419
+ }, _TokenListController_stopPolling = function _TokenListController_stopPolling() {
420
+ if (__classPrivateFieldGet(this, _TokenListController_intervalId, "f")) {
421
+ clearInterval(__classPrivateFieldGet(this, _TokenListController_intervalId, "f"));
245
422
  }
246
423
  }, _TokenListController_startDeprecatedPolling =
247
424
  /**
@@ -252,12 +429,18 @@ async function _TokenListController_onNetworkControllerStateChange(networkContro
252
429
  */
253
430
  async function _TokenListController_startDeprecatedPolling() {
254
431
  // renaming this to avoid collision with base class
255
- await safelyExecute(() => this.fetchTokenList(this.chainId));
432
+ await safelyExecute(() => this.fetchTokenList(__classPrivateFieldGet(this, _TokenListController_chainId, "f")));
256
433
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
257
434
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
258
- this.intervalId = setInterval(async () => {
259
- await safelyExecute(() => this.fetchTokenList(this.chainId));
260
- }, this.intervalDelay);
435
+ __classPrivateFieldSet(this, _TokenListController_intervalId, setInterval(async () => {
436
+ await safelyExecute(() => this.fetchTokenList(__classPrivateFieldGet(this, _TokenListController_chainId, "f")));
437
+ }, __classPrivateFieldGet(this, _TokenListController_intervalDelay, "f")), "f");
261
438
  };
439
+ /**
440
+ * Debounce delay for persisting state changes (in milliseconds).
441
+ */
442
+ _TokenListController_persistDebounceMs = { value: 500 };
443
+ // Storage key prefix for per-chain files
444
+ _TokenListController_storageKeyPrefix = { value: 'tokensChainsCache' };
262
445
  export default TokenListController;
263
446
  //# sourceMappingURL=TokenListController.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"TokenListController.mjs","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings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C,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/D,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;AACzB,CAAC;AA2GH,eAAe,mBAAmB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerStateChangeEvent,\n NetworkState,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport {\n isTokenListSupportedForNetwork,\n formatAggregatorNames,\n formatIconUrlWithProxy,\n} from './assetsUtil';\nimport { TokenRwaData, fetchTokenListByChainId } from './token-service';\n\n// 4 Hour Interval Cache Refresh Threshold\nconst DEFAULT_INTERVAL = 4 * 60 * 60 * 1000;\nconst DEFAULT_THRESHOLD = 4 * 60 * 60 * 1000;\n\nconst name = 'TokenListController';\n\nexport type TokenListToken = {\n name: string;\n symbol: string;\n decimals: number;\n address: string;\n occurrences: number;\n aggregators: string[];\n iconUrl: string;\n rwaData?: TokenRwaData;\n};\n\nexport type TokenListMap = Record<string, TokenListToken>;\n\ntype DataCache = {\n timestamp: number;\n data: TokenListMap;\n};\nexport type TokensChainsCache = {\n [chainId: Hex]: DataCache;\n};\n\nexport type TokenListState = {\n tokensChainsCache: TokensChainsCache;\n preventPollingOnNetworkRestart: boolean;\n};\n\nexport type TokenListStateChange = ControllerStateChangeEvent<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerEvents = TokenListStateChange;\n\nexport type GetTokenListState = ControllerGetStateAction<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerActions = GetTokenListState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype AllowedEvents = NetworkControllerStateChangeEvent;\n\nexport type TokenListControllerMessenger = Messenger<\n typeof name,\n TokenListControllerActions | AllowedActions,\n TokenListControllerEvents | AllowedEvents\n>;\n\nconst metadata: StateMetadata<TokenListState> = {\n tokensChainsCache: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n preventPollingOnNetworkRestart: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n};\n\nexport const getDefaultTokenListState = (): TokenListState => {\n return {\n tokensChainsCache: {},\n preventPollingOnNetworkRestart: false,\n };\n};\n\n/** The input to start polling for the {@link TokenListController} */\ntype TokenListPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval for the list of tokens from metaswaps api\n */\nexport class TokenListController extends StaticIntervalPollingController<TokenListPollingInput>()<\n typeof name,\n TokenListState,\n TokenListControllerMessenger\n> {\n private readonly mutex = new Mutex();\n\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay: number;\n\n private readonly cacheRefreshThreshold: number;\n\n private chainId: Hex;\n\n private abortController: AbortController;\n\n /**\n * Creates a TokenListController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for network state changes.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.preventPollingOnNetworkRestart - Determines whether to prevent poilling on network restart in extension.\n */\n constructor({\n chainId,\n preventPollingOnNetworkRestart = false,\n onNetworkStateChange,\n interval = DEFAULT_INTERVAL,\n cacheRefreshThreshold = DEFAULT_THRESHOLD,\n messenger,\n state,\n }: {\n chainId: Hex;\n preventPollingOnNetworkRestart?: boolean;\n onNetworkStateChange?: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n interval?: number;\n cacheRefreshThreshold?: number;\n messenger: TokenListControllerMessenger;\n state?: Partial<TokenListState>;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...getDefaultTokenListState(), ...state },\n });\n this.intervalDelay = interval;\n this.setIntervalLength(interval);\n this.cacheRefreshThreshold = cacheRefreshThreshold;\n this.chainId = chainId;\n this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);\n this.abortController = new AbortController();\n if (onNetworkStateChange) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onNetworkStateChange(async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n });\n } else {\n this.messenger.subscribe(\n 'NetworkController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n },\n );\n }\n }\n\n /**\n * Updates state and restarts polling on changes to the network controller\n * state.\n *\n * @param networkControllerState - The updated network controller state.\n */\n async #onNetworkControllerStateChange(\n networkControllerState: NetworkState,\n ): Promise<void> {\n const selectedNetworkClient = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkControllerState.selectedNetworkClientId,\n );\n const { chainId } = selectedNetworkClient.configuration;\n\n if (this.chainId !== chainId) {\n this.abortController.abort();\n this.abortController = new AbortController();\n this.chainId = chainId;\n if (this.state.preventPollingOnNetworkRestart) {\n this.clearingTokenListData();\n }\n }\n }\n\n // Eventually we want to remove start/restart/stop controls in favor of new _executePoll API\n // Maintaining these functions for now until we can safely deprecate them for backwards compatibility\n /**\n * Start polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async start(): Promise<void> {\n if (!isTokenListSupportedForNetwork(this.chainId)) {\n return;\n }\n await this.#startDeprecatedPolling();\n }\n\n /**\n * Restart polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async restart(): Promise<void> {\n this.stopPolling();\n await this.#startDeprecatedPolling();\n }\n\n /**\n * Stop polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n stop(): void {\n this.stopPolling();\n }\n\n /**\n * This stops any active polling.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n override destroy(): void {\n super.destroy();\n this.stopPolling();\n }\n\n /**\n * This stops any active polling intervals.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n private stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n }\n\n /**\n * Starts a new polling interval for a given chainId (this should be deprecated in favor of _executePoll)\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async #startDeprecatedPolling(): Promise<void> {\n // renaming this to avoid collision with base class\n await safelyExecute(() => this.fetchTokenList(this.chainId));\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this.fetchTokenList(this.chainId));\n }, this.intervalDelay);\n }\n\n /**\n * This starts a new polling loop for any given chain. Under the hood it is deduping polls\n *\n * @param input - The input for the poll.\n * @param input.chainId - The chainId of the chain to trigger the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll({ chainId }: TokenListPollingInput): Promise<void> {\n return this.fetchTokenList(chainId);\n }\n\n /**\n * 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)\n *\n * @param chainId - The chainId of the current chain triggering the fetch.\n */\n async fetchTokenList(chainId: Hex): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n try {\n if (this.isCacheValid(chainId)) {\n return;\n }\n\n // Fetch fresh token list from the API\n const tokensFromAPI = await safelyExecute(\n () =>\n fetchTokenListByChainId(\n chainId,\n this.abortController.signal,\n ) as Promise<TokenListToken[]>,\n );\n\n // Have response - process and update list\n if (tokensFromAPI) {\n // Format tokens from API (HTTP) and update tokenList\n const tokenList: TokenListMap = {};\n for (const token of tokensFromAPI) {\n tokenList[token.address] = {\n ...token,\n aggregators: formatAggregatorNames(token.aggregators),\n iconUrl: formatIconUrlWithProxy({\n chainId,\n tokenAddress: token.address,\n }),\n };\n }\n\n this.update((state) => {\n const newDataCache: DataCache = { data: {}, timestamp: Date.now() };\n state.tokensChainsCache[chainId] ??= newDataCache;\n state.tokensChainsCache[chainId].data = tokenList;\n state.tokensChainsCache[chainId].timestamp = Date.now();\n });\n return;\n }\n\n // No response - fallback to previous state, or initialise empty\n if (!tokensFromAPI) {\n this.update((state) => {\n const newDataCache: DataCache = { data: {}, timestamp: Date.now() };\n state.tokensChainsCache[chainId] ??= newDataCache;\n state.tokensChainsCache[chainId].timestamp = Date.now();\n });\n }\n } finally {\n releaseLock();\n }\n }\n\n isCacheValid(chainId: Hex): boolean {\n const { tokensChainsCache }: TokenListState = this.state;\n const timestamp: number | undefined = tokensChainsCache[chainId]?.timestamp;\n const now = Date.now();\n return (\n timestamp !== undefined && now - timestamp < this.cacheRefreshThreshold\n );\n }\n\n /**\n * Clearing tokenList and tokensChainsCache explicitly.\n */\n clearingTokenListData(): void {\n this.update(() => {\n return {\n ...this.state,\n tokensChainsCache: {},\n };\n });\n }\n\n /**\n * Updates preventPollingOnNetworkRestart from extension.\n *\n * @param shouldPreventPolling - Determine whether to prevent polling on network change\n */\n updatePreventPollingOnNetworkRestart(shouldPreventPolling: boolean): void {\n this.update(() => {\n return {\n ...this.state,\n preventPollingOnNetworkRestart: shouldPreventPolling,\n };\n });\n }\n}\n\nexport default TokenListController;\n"]}
1
+ {"version":3,"file":"TokenListController.mjs","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,aAAa,EAAE,mCAAmC;AAO3D,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAQ/E,OAAO,EACL,8BAA8B,EA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C;QAC9C,uBAAA,IAAI,gCAAY,OAAO,MAAA,CAAC;IAC1B,CAAC;AACH,CAAC;IAgEC,IAAI,uBAAA,IAAI,uCAAY,EAAE,CAAC;QACrB,aAAa,CAAC,uBAAA,IAAI,uCAAY,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,mDAAmD;IACnD,MAAM,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,uBAAA,IAAI,oCAAS,CAAC,CAAC,CAAC;IAC9D,gFAAgF;IAChF,kEAAkE;IAClE,uBAAA,IAAI,mCAAe,WAAW,CAAC,KAAK,IAAI,EAAE;QACxC,MAAM,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,uBAAA,IAAI,oCAAS,CAAC,CAAC,CAAC;IAChE,CAAC,EAAE,uBAAA,IAAI,0CAAe,CAAC,MAAA,CAAC;AAC1B,CAAC;AAnbD;;GAEG;AACa,kDAAqB,GAAG,EAAN,CAAO;AAEzC,yCAAyC;AACzB,iDAAoB,mBAAmB,EAAtB,CAAuB;AAmgB1D,eAAe,mBAAmB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerStateChangeEvent,\n NetworkState,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n StorageServiceSetItemAction,\n StorageServiceGetItemAction,\n StorageServiceGetAllKeysAction,\n} from '@metamask/storage-service';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n isTokenListSupportedForNetwork,\n formatAggregatorNames,\n formatIconUrlWithProxy,\n} from './assetsUtil';\nimport { TokenRwaData, fetchTokenListByChainId } from './token-service';\n\n// 4 Hour Interval Cache Refresh Threshold\nconst DEFAULT_INTERVAL = 4 * 60 * 60 * 1000;\nconst DEFAULT_THRESHOLD = 4 * 60 * 60 * 1000;\n\nconst name = 'TokenListController';\n\nexport type TokenListToken = {\n name: string;\n symbol: string;\n decimals: number;\n address: string;\n occurrences: number;\n aggregators: string[];\n iconUrl: string;\n rwaData?: TokenRwaData;\n};\n\nexport type TokenListMap = Record<string, TokenListToken>;\n\nexport type DataCache = {\n timestamp: number;\n data: TokenListMap;\n};\nexport type TokensChainsCache = {\n [chainId: Hex]: DataCache;\n};\n\nexport type TokenListState = {\n tokensChainsCache: TokensChainsCache;\n};\n\nexport type TokenListStateChange = ControllerStateChangeEvent<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerEvents = TokenListStateChange;\n\nexport type GetTokenListState = ControllerGetStateAction<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerActions = GetTokenListState;\n\ntype AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | StorageServiceSetItemAction\n | StorageServiceGetItemAction\n | StorageServiceGetAllKeysAction;\n\ntype AllowedEvents = NetworkControllerStateChangeEvent;\n\nexport type TokenListControllerMessenger = Messenger<\n typeof name,\n TokenListControllerActions | AllowedActions,\n TokenListControllerEvents | AllowedEvents\n>;\n\nconst metadata: StateMetadata<TokenListState> = {\n tokensChainsCache: {\n includeInStateLogs: false,\n persist: false, // Persisted separately via StorageService\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nexport const getDefaultTokenListState = (): TokenListState => {\n return {\n tokensChainsCache: {},\n };\n};\n\n/** The input to start polling for the {@link TokenListController} */\ntype TokenListPollingInput = {\n chainId: Hex;\n};\n\n/**\n * Controller that passively polls on a set interval for the list of tokens from metaswaps api\n */\nexport class TokenListController extends StaticIntervalPollingController<TokenListPollingInput>()<\n typeof name,\n TokenListState,\n TokenListControllerMessenger\n> {\n /**\n * Debounce timer for persisting state changes to storage.\n */\n #persistDebounceTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * Promise that resolves when the current persist operation completes.\n * Used to prevent race conditions between persist operations.\n */\n #persistInFlightPromise?: Promise<void>;\n\n /**\n * Tracks which chains have pending changes to persist.\n * Only changed chains are persisted to reduce write amplification.\n */\n readonly #changedChainsToPersist: Set<Hex> = new Set();\n\n /**\n * Tracks chains that were just loaded from storage and should skip\n * the next persistence cycle. This prevents redundant writes where\n * data loaded from storage would be immediately written back.\n * Chains are removed from this set after being skipped once.\n */\n readonly #chainsLoadedFromStorage: Set<Hex> = new Set();\n\n /**\n * Previous tokensChainsCache for detecting which chains changed.\n */\n #previousTokensChainsCache: TokensChainsCache = {};\n\n /**\n * Debounce delay for persisting state changes (in milliseconds).\n */\n static readonly #persistDebounceMs = 500;\n\n // Storage key prefix for per-chain files\n static readonly #storageKeyPrefix = 'tokensChainsCache';\n\n /**\n * Get storage key for a specific chain.\n *\n * @param chainId - The chain ID.\n * @returns Storage key for the chain.\n */\n static #getChainStorageKey(chainId: Hex): string {\n return `${TokenListController.#storageKeyPrefix}:${chainId}`;\n }\n\n #intervalId?: ReturnType<typeof setTimeout>;\n\n readonly #intervalDelay: number;\n\n readonly #cacheRefreshThreshold: number;\n\n #chainId: Hex;\n\n #abortController: AbortController;\n\n /**\n * Creates a TokenListController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for network state changes.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor({\n chainId,\n onNetworkStateChange,\n interval = DEFAULT_INTERVAL,\n cacheRefreshThreshold = DEFAULT_THRESHOLD,\n messenger,\n state,\n }: {\n chainId: Hex;\n onNetworkStateChange?: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n interval?: number;\n cacheRefreshThreshold?: number;\n messenger: TokenListControllerMessenger;\n state?: Partial<TokenListState>;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...getDefaultTokenListState(), ...state },\n });\n\n this.#intervalDelay = interval;\n this.setIntervalLength(interval);\n this.#cacheRefreshThreshold = cacheRefreshThreshold;\n this.#chainId = chainId;\n this.#abortController = new AbortController();\n\n // Subscribe to state changes to automatically persist tokensChainsCache\n this.messenger.subscribe(\n 'TokenListController:stateChange',\n (newCache: TokensChainsCache) => this.#onCacheChanged(newCache),\n (controllerState) => controllerState.tokensChainsCache,\n );\n\n if (onNetworkStateChange) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onNetworkStateChange(async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n });\n } else {\n this.messenger.subscribe(\n 'NetworkController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n },\n );\n }\n }\n\n /**\n * Initialize the controller by loading cache from storage and running migration.\n * This method should be called by clients after construction.\n *\n * @returns A promise that resolves when initialization is complete.\n */\n async initialize(): Promise<void> {\n await this.#synchronizeCacheWithStorage();\n }\n\n /**\n * Handle tokensChainsCache changes by detecting which chains changed\n * and scheduling debounced persistence.\n *\n * @param newCache - The new tokensChainsCache state.\n */\n #onCacheChanged(newCache: TokensChainsCache): void {\n // Detect which chains changed by comparing with previous cache\n for (const chainId of Object.keys(newCache) as Hex[]) {\n const newData = newCache[chainId];\n const prevData = this.#previousTokensChainsCache[chainId];\n\n // Chain is new or timestamp changed (indicating data update)\n if (!prevData || prevData.timestamp !== newData.timestamp) {\n // Skip persistence for chains that were just loaded from storage\n // (they don't need to be written back immediately)\n if (this.#chainsLoadedFromStorage.has(chainId)) {\n this.#chainsLoadedFromStorage.delete(chainId); // Clean up - future updates should persist\n } else {\n this.#changedChainsToPersist.add(chainId);\n }\n }\n }\n\n // Update previous cache reference\n this.#previousTokensChainsCache = { ...newCache };\n\n // Schedule persistence if there are changes\n if (this.#changedChainsToPersist.size > 0) {\n this.#debouncePersist();\n }\n }\n\n /**\n * Debounce persistence of changed chains to storage.\n */\n #debouncePersist(): void {\n if (this.#persistDebounceTimer) {\n clearTimeout(this.#persistDebounceTimer);\n }\n\n this.#persistDebounceTimer = setTimeout(() => {\n // Note: #persistChangedChains handles errors internally via #saveChainCacheToStorage,\n // so this promise will not reject.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#persistChangedChains();\n }, TokenListController.#persistDebounceMs);\n }\n\n /**\n * Persist only the chains that have changed to storage.\n * Reduces write amplification by skipping unchanged chains.\n *\n * If a persist operation is already in-flight, this method returns early\n * and reschedules the debounce to ensure accumulated changes are retried\n * after the current operation completes.\n *\n * @returns A promise that resolves when changed chains are persisted.\n */\n async #persistChangedChains(): Promise<void> {\n if (this.#persistInFlightPromise) {\n // Reschedule debounce to retry accumulated changes after in-flight persist completes\n if (this.#changedChainsToPersist.size > 0) {\n this.#debouncePersist();\n }\n return;\n }\n\n const chainsToPersist = [...this.#changedChainsToPersist];\n this.#changedChainsToPersist.clear();\n\n if (chainsToPersist.length === 0) {\n return;\n }\n\n this.#persistInFlightPromise = Promise.all(\n chainsToPersist.map((chainId) => this.#saveChainCacheToStorage(chainId)),\n ).then(() => undefined);\n\n try {\n await this.#persistInFlightPromise;\n } finally {\n this.#persistInFlightPromise = undefined;\n }\n }\n\n /**\n * Synchronize tokensChainsCache between state and storage bidirectionally.\n *\n * This method:\n * 1. Loads cached chains from storage (per-chain files) in parallel\n * 2. Merges loaded data into state (preferring existing state to avoid overwriting fresh data)\n * 3. Persists any chains that exist in state but not in storage\n *\n * Called during initialization to ensure state and storage are consistent.\n *\n * @returns A promise that resolves when synchronization is complete.\n */\n async #synchronizeCacheWithStorage(): Promise<void> {\n try {\n const allKeys = await this.messenger.call(\n 'StorageService:getAllKeys',\n name,\n );\n\n // Filter keys that belong to tokensChainsCache (per-chain files)\n const cacheKeys = allKeys.filter((key) =>\n key.startsWith(`${TokenListController.#storageKeyPrefix}:`),\n );\n\n // Load all chains in parallel\n const chainCaches = await Promise.all(\n cacheKeys.map(async (key) => {\n // Extract chainId from key: 'tokensChainsCache:0x1' → '0x1'\n const chainId = key.split(':')[1] as Hex;\n\n const { result, error } = await this.messenger.call(\n 'StorageService:getItem',\n name,\n key,\n );\n\n if (error) {\n console.error(\n `TokenListController: Error loading cache for ${chainId}:`,\n error,\n );\n return null;\n }\n\n return result ? { chainId, data: result as DataCache } : null;\n }),\n );\n\n // Build complete cache from loaded chains\n const loadedCache: TokensChainsCache = {};\n chainCaches.forEach((chainCache) => {\n if (chainCache) {\n loadedCache[chainCache.chainId] = chainCache.data;\n }\n });\n\n // Merge loaded cache with existing state, preferring existing data\n // (which may be fresher if fetched during initialization)\n if (Object.keys(loadedCache).length > 0) {\n // Track which chains we're actually loading from storage\n // These will be skipped in the next #onCacheChanged to avoid redundant writes\n for (const chainId of Object.keys(loadedCache) as Hex[]) {\n if (!this.state.tokensChainsCache[chainId]) {\n this.#chainsLoadedFromStorage.add(chainId);\n }\n }\n\n this.update((state) => {\n // Only load chains that don't already exist in state\n // This prevents overwriting fresh API data with stale cached data\n for (const [chainId, cacheData] of Object.entries(loadedCache)) {\n if (!state.tokensChainsCache[chainId as Hex]) {\n state.tokensChainsCache[chainId as Hex] = cacheData;\n }\n }\n });\n\n // Note: The update() call above only triggers #onCacheChanged if chains\n // were actually added to state. If initial state already contains chains\n // from storage, the update() is a no-op and #onCacheChanged is never called.\n }\n\n // Persist chains that exist in state but were not loaded from storage.\n // This handles the case where initial state contains chains that don't exist\n // in storage yet (e.g., fresh data from API). Without this, those chains\n // would be lost on the next app restart.\n const loadedChainIds = new Set(Object.keys(loadedCache) as Hex[]);\n const chainsInState = new Set(\n Object.keys(this.state.tokensChainsCache) as Hex[],\n );\n for (const chainId of chainsInState) {\n if (!loadedChainIds.has(chainId)) {\n this.#changedChainsToPersist.add(chainId);\n }\n }\n\n // Persist any chains that need to be saved\n if (this.#changedChainsToPersist.size > 0) {\n this.#debouncePersist();\n }\n\n this.#previousTokensChainsCache = { ...this.state.tokensChainsCache };\n } catch (error) {\n console.error(\n 'TokenListController: Failed to load cache from storage:',\n error,\n );\n }\n }\n\n /**\n * Save a specific chain's cache to StorageService.\n * This persists only the updated chain's data, reducing write amplification.\n *\n * @param chainId - The chain ID to save.\n * @returns A promise that resolves when saving is complete.\n */\n async #saveChainCacheToStorage(chainId: Hex): Promise<void> {\n try {\n const chainData = this.state.tokensChainsCache[chainId];\n\n if (!chainData) {\n console.warn(`TokenListController: No cache data for chain ${chainId}`);\n return;\n }\n\n const storageKey = TokenListController.#getChainStorageKey(chainId);\n\n await this.messenger.call(\n 'StorageService:setItem',\n name,\n storageKey,\n chainData,\n );\n } catch (error) {\n console.error(\n `TokenListController: Failed to save cache for ${chainId}:`,\n error,\n );\n }\n }\n\n /**\n * Updates state and restarts polling on changes to the network controller\n * state.\n *\n * @param networkControllerState - The updated network controller state.\n */\n async #onNetworkControllerStateChange(\n networkControllerState: NetworkState,\n ): Promise<void> {\n const selectedNetworkClient = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkControllerState.selectedNetworkClientId,\n );\n const { chainId } = selectedNetworkClient.configuration;\n\n if (this.#chainId !== chainId) {\n this.#abortController.abort();\n this.#abortController = new AbortController();\n this.#chainId = chainId;\n }\n }\n\n // Eventually we want to remove start/restart/stop controls in favor of new _executePoll API\n // Maintaining these functions for now until we can safely deprecate them for backwards compatibility\n /**\n * Start polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async start(): Promise<void> {\n if (!isTokenListSupportedForNetwork(this.#chainId)) {\n return;\n }\n await this.#startDeprecatedPolling();\n }\n\n /**\n * Restart polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async restart(): Promise<void> {\n this.#stopPolling();\n await this.#startDeprecatedPolling();\n }\n\n /**\n * Stop polling for the token list.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n stop(): void {\n this.#stopPolling();\n }\n\n /**\n * This stops any active polling.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n override destroy(): void {\n super.destroy();\n this.#stopPolling();\n\n // Cancel any pending debounced persistence operations\n if (this.#persistDebounceTimer) {\n clearTimeout(this.#persistDebounceTimer);\n this.#persistDebounceTimer = undefined;\n }\n this.#changedChainsToPersist.clear();\n this.#chainsLoadedFromStorage.clear();\n }\n\n /**\n * This stops any active polling intervals.\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n #stopPolling(): void {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval for a given chainId (this should be deprecated in favor of _executePoll)\n *\n * @deprecated This method is deprecated and will be removed in the future.\n * Consider using the new polling approach instead\n */\n async #startDeprecatedPolling(): Promise<void> {\n // renaming this to avoid collision with base class\n await safelyExecute(() => this.fetchTokenList(this.#chainId));\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#intervalId = setInterval(async () => {\n await safelyExecute(() => this.fetchTokenList(this.#chainId));\n }, this.#intervalDelay);\n }\n\n /**\n * This starts a new polling loop for any given chain. Under the hood it is deduping polls\n *\n * @param input - The input for the poll.\n * @param input.chainId - The chainId of the chain to trigger the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll({ chainId }: TokenListPollingInput): Promise<void> {\n return this.fetchTokenList(chainId);\n }\n\n /**\n * Fetching token list from the Token Service API. This will fetch tokens across chains.\n * State changes are automatically persisted via the stateChange subscription.\n *\n * @param chainId - The chainId of the current chain triggering the fetch.\n */\n async fetchTokenList(chainId: Hex): Promise<void> {\n if (this.isCacheValid(chainId)) {\n return;\n }\n\n // Fetch fresh token list from the API\n const tokensFromAPI = await safelyExecute(\n () =>\n fetchTokenListByChainId(\n chainId,\n this.#abortController.signal,\n ) as Promise<TokenListToken[]>,\n );\n\n // Have response - process and update list\n if (tokensFromAPI) {\n // Format tokens from API (HTTP) and update tokenList\n const tokenList: TokenListMap = {};\n for (const token of tokensFromAPI) {\n tokenList[token.address] = {\n ...token,\n aggregators: formatAggregatorNames(token.aggregators),\n iconUrl: formatIconUrlWithProxy({\n chainId,\n tokenAddress: token.address,\n }),\n };\n }\n\n // Update state - persistence happens automatically via subscription\n const newDataCache: DataCache = {\n data: tokenList,\n timestamp: Date.now(),\n };\n this.update((state) => {\n state.tokensChainsCache[chainId] = newDataCache;\n });\n return;\n }\n\n // No response - fallback to previous state, or initialise empty.\n // Only initialize with a new timestamp if there's no existing cache.\n // If there's existing cache, keep it as-is without updating the timestamp\n // to avoid making stale data appear \"fresh\" and preventing retry attempts.\n if (!tokensFromAPI) {\n const existingCache = this.state.tokensChainsCache[chainId];\n if (!existingCache) {\n // No existing cache - initialize empty (persistence happens automatically)\n const newDataCache: DataCache = { data: {}, timestamp: Date.now() };\n this.update((state) => {\n state.tokensChainsCache[chainId] = newDataCache;\n });\n }\n // If there's existing cache, keep it as-is (don't update timestamp or persist)\n }\n }\n\n isCacheValid(chainId: Hex): boolean {\n const { tokensChainsCache }: TokenListState = this.state;\n const timestamp: number | undefined = tokensChainsCache[chainId]?.timestamp;\n const now = Date.now();\n return (\n timestamp !== undefined && now - timestamp < this.#cacheRefreshThreshold\n );\n }\n}\n\nexport default TokenListController;\n"]}