@metamask-previews/assets-controllers 99.1.0-preview-f12b43c → 99.1.0-preview-6060063
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/AssetsContractController.cjs +22 -22
- package/dist/AssetsContractController.cjs.map +1 -1
- package/dist/AssetsContractController.mjs +22 -22
- package/dist/AssetsContractController.mjs.map +1 -1
- package/dist/TokenListController.cjs +8 -35
- package/dist/TokenListController.cjs.map +1 -1
- package/dist/TokenListController.d.cts.map +1 -1
- package/dist/TokenListController.d.mts.map +1 -1
- package/dist/TokenListController.mjs +8 -35
- package/dist/TokenListController.mjs.map +1 -1
- package/dist/assetsUtil.cjs +23 -22
- package/dist/assetsUtil.cjs.map +1 -1
- package/dist/assetsUtil.d.cts +23 -22
- package/dist/assetsUtil.d.cts.map +1 -1
- package/dist/assetsUtil.d.mts +23 -22
- package/dist/assetsUtil.d.mts.map +1 -1
- package/dist/assetsUtil.mjs +23 -22
- package/dist/assetsUtil.mjs.map +1 -1
- package/dist/constants.cjs +1 -0
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +1 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs +2 -2
- package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs.map +1 -1
- package/dist/multi-chain-accounts-service/api-balance-fetcher.mjs +2 -2
- package/dist/multi-chain-accounts-service/api-balance-fetcher.mjs.map +1 -1
- package/dist/multicall.cjs +1 -0
- package/dist/multicall.cjs.map +1 -1
- package/dist/multicall.d.cts.map +1 -1
- package/dist/multicall.d.mts.map +1 -1
- package/dist/multicall.mjs +1 -0
- package/dist/multicall.mjs.map +1 -1
- package/dist/token-prices-service/codefi-v2.cjs +1 -1
- package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
- package/dist/token-prices-service/codefi-v2.d.cts +1 -1
- package/dist/token-prices-service/codefi-v2.d.mts +1 -1
- package/dist/token-prices-service/codefi-v2.mjs +1 -1
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -10,7 +10,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
11
11
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
12
12
|
};
|
|
13
|
-
var _TokenListController_instances, _a, _TokenListController_persistDebounceTimer, _TokenListController_persistInFlightPromise, _TokenListController_changedChainsToPersist,
|
|
13
|
+
var _TokenListController_instances, _a, _TokenListController_persistDebounceTimer, _TokenListController_persistInFlightPromise, _TokenListController_changedChainsToPersist, _TokenListController_previousTokensChainsCache, _TokenListController_persistDebounceMs, _TokenListController_storageKeyPrefix, _TokenListController_getChainStorageKey, _TokenListController_intervalId, _TokenListController_intervalDelay, _TokenListController_cacheRefreshThreshold, _TokenListController_chainId, _TokenListController_abortController, _TokenListController_onCacheChanged, _TokenListController_debouncePersist, _TokenListController_persistChangedChains, _TokenListController_synchronizeCacheWithStorage, _TokenListController_saveChainCacheToStorage, _TokenListController_onNetworkControllerStateChange, _TokenListController_stopPolling, _TokenListController_startDeprecatedPolling;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.TokenListController = exports.getDefaultTokenListState = void 0;
|
|
16
16
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
@@ -72,13 +72,6 @@ class TokenListController extends (0, polling_controller_1.StaticIntervalPolling
|
|
|
72
72
|
* Only changed chains are persisted to reduce write amplification.
|
|
73
73
|
*/
|
|
74
74
|
_TokenListController_changedChainsToPersist.set(this, new Set());
|
|
75
|
-
/**
|
|
76
|
-
* Tracks chains that were just loaded from storage and should skip
|
|
77
|
-
* the next persistence cycle. This prevents redundant writes where
|
|
78
|
-
* data loaded from storage would be immediately written back.
|
|
79
|
-
* Chains are removed from this set after being skipped once.
|
|
80
|
-
*/
|
|
81
|
-
_TokenListController_chainsLoadedFromStorage.set(this, new Set());
|
|
82
75
|
/**
|
|
83
76
|
* Previous tokensChainsCache for detecting which chains changed.
|
|
84
77
|
*/
|
|
@@ -93,8 +86,6 @@ class TokenListController extends (0, polling_controller_1.StaticIntervalPolling
|
|
|
93
86
|
__classPrivateFieldSet(this, _TokenListController_cacheRefreshThreshold, cacheRefreshThreshold, "f");
|
|
94
87
|
__classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
|
|
95
88
|
__classPrivateFieldSet(this, _TokenListController_abortController, new AbortController(), "f");
|
|
96
|
-
// Subscribe to state changes to automatically persist tokensChainsCache
|
|
97
|
-
this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
|
|
98
89
|
if (onNetworkStateChange) {
|
|
99
90
|
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
100
91
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
@@ -119,6 +110,8 @@ class TokenListController extends (0, polling_controller_1.StaticIntervalPolling
|
|
|
119
110
|
*/
|
|
120
111
|
async initialize() {
|
|
121
112
|
await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_synchronizeCacheWithStorage).call(this);
|
|
113
|
+
// Subscribe to state changes to automatically persist tokensChainsCache
|
|
114
|
+
this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
|
|
122
115
|
}
|
|
123
116
|
// Eventually we want to remove start/restart/stop controls in favor of new _executePoll API
|
|
124
117
|
// Maintaining these functions for now until we can safely deprecate them for backwards compatibility
|
|
@@ -168,7 +161,6 @@ class TokenListController extends (0, polling_controller_1.StaticIntervalPolling
|
|
|
168
161
|
__classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
|
|
169
162
|
}
|
|
170
163
|
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
|
|
171
|
-
__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").clear();
|
|
172
164
|
}
|
|
173
165
|
/**
|
|
174
166
|
* This starts a new polling loop for any given chain. Under the hood it is deduping polls
|
|
@@ -240,7 +232,7 @@ class TokenListController extends (0, polling_controller_1.StaticIntervalPolling
|
|
|
240
232
|
}
|
|
241
233
|
}
|
|
242
234
|
exports.TokenListController = TokenListController;
|
|
243
|
-
_a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(),
|
|
235
|
+
_a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(), _TokenListController_previousTokensChainsCache = new WeakMap(), _TokenListController_intervalId = new WeakMap(), _TokenListController_intervalDelay = new WeakMap(), _TokenListController_cacheRefreshThreshold = new WeakMap(), _TokenListController_chainId = new WeakMap(), _TokenListController_abortController = new WeakMap(), _TokenListController_instances = new WeakSet(), _TokenListController_getChainStorageKey = function _TokenListController_getChainStorageKey(chainId) {
|
|
244
236
|
return `${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:${chainId}`;
|
|
245
237
|
}, _TokenListController_onCacheChanged = function _TokenListController_onCacheChanged(newCache) {
|
|
246
238
|
// Detect which chains changed by comparing with previous cache
|
|
@@ -249,14 +241,7 @@ _a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMa
|
|
|
249
241
|
const prevData = __classPrivateFieldGet(this, _TokenListController_previousTokensChainsCache, "f")[chainId];
|
|
250
242
|
// Chain is new or timestamp changed (indicating data update)
|
|
251
243
|
if (!prevData || prevData.timestamp !== newData.timestamp) {
|
|
252
|
-
|
|
253
|
-
// (they don't need to be written back immediately)
|
|
254
|
-
if (__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").has(chainId)) {
|
|
255
|
-
__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").delete(chainId); // Clean up - future updates should persist
|
|
256
|
-
}
|
|
257
|
-
else {
|
|
258
|
-
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
259
|
-
}
|
|
244
|
+
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
260
245
|
}
|
|
261
246
|
}
|
|
262
247
|
// Update previous cache reference
|
|
@@ -342,16 +327,11 @@ async function _TokenListController_synchronizeCacheWithStorage() {
|
|
|
342
327
|
loadedCache[chainCache.chainId] = chainCache.data;
|
|
343
328
|
}
|
|
344
329
|
});
|
|
330
|
+
// Chains in state _before loading persisted state_, from a recent update
|
|
331
|
+
const chainsInState = new Set(Object.keys(this.state.tokensChainsCache));
|
|
345
332
|
// Merge loaded cache with existing state, preferring existing data
|
|
346
333
|
// (which may be fresher if fetched during initialization)
|
|
347
334
|
if (Object.keys(loadedCache).length > 0) {
|
|
348
|
-
// Track which chains we're actually loading from storage
|
|
349
|
-
// These will be skipped in the next #onCacheChanged to avoid redundant writes
|
|
350
|
-
for (const chainId of Object.keys(loadedCache)) {
|
|
351
|
-
if (!this.state.tokensChainsCache[chainId]) {
|
|
352
|
-
__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").add(chainId);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
335
|
this.update((state) => {
|
|
356
336
|
// Only load chains that don't already exist in state
|
|
357
337
|
// This prevents overwriting fresh API data with stale cached data
|
|
@@ -361,20 +341,13 @@ async function _TokenListController_synchronizeCacheWithStorage() {
|
|
|
361
341
|
}
|
|
362
342
|
}
|
|
363
343
|
});
|
|
364
|
-
// Note: The update() call above only triggers #onCacheChanged if chains
|
|
365
|
-
// were actually added to state. If initial state already contains chains
|
|
366
|
-
// from storage, the update() is a no-op and #onCacheChanged is never called.
|
|
367
344
|
}
|
|
368
345
|
// Persist chains that exist in state but were not loaded from storage.
|
|
369
346
|
// This handles the case where initial state contains chains that don't exist
|
|
370
347
|
// in storage yet (e.g., fresh data from API). Without this, those chains
|
|
371
348
|
// would be lost on the next app restart.
|
|
372
|
-
const loadedChainIds = new Set(Object.keys(loadedCache));
|
|
373
|
-
const chainsInState = new Set(Object.keys(this.state.tokensChainsCache));
|
|
374
349
|
for (const chainId of chainsInState) {
|
|
375
|
-
|
|
376
|
-
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
377
|
-
}
|
|
350
|
+
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
378
351
|
}
|
|
379
352
|
// Persist any chains that need to be saved
|
|
380
353
|
if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenListController.cjs","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,iEAA2D;AAO3D,qEAA+E;AAQ/E,iDAIsB;AACtB,uDAAwE;AAExE,0CAA0C;AAC1C,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC5C,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAuDnC,MAAM,QAAQ,GAAkC;IAC9C,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK,EAAE,0CAA0C;QAC1D,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEK,MAAM,wBA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I,EAAE;QACxC,MAAM,IAAA,gCAAa,EAAC,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,kBAAe,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"]}
|
|
1
|
+
{"version":3,"file":"TokenListController.cjs","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,iEAA2D;AAO3D,qEAA+E;AAQ/E,iDAIsB;AACtB,uDAAwE;AAExE,0CAA0C;AAC1C,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC5C,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAuDnC,MAAM,QAAQ,GAAkC;IAC9C,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK,EAAE,0CAA0C;QAC1D,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEK,MAAM,wBAAwB,GAAG,GAAmB,EAAE;IAC3D,OAAO;QACL,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC,CAAC;AAJW,QAAA,wBAAwB,4BAInC;AAOF;;GAEG;AACH,MAAa,mBAAoB,SAAQ,I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AAC,CAAC;IAClC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,mDAAmD;IACnD,MAAM,IAAA,gCAAa,EAAC,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,IAAA,gCAAa,EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,uBAAA,IAAI,oCAAS,CAAC,CAAC,CAAC;IAChE,CAAC,EAAE,uBAAA,IAAI,0CAAe,CAAC,MAAA,CAAC;AAC1B,CAAC;AA/ZD;;GAEG;AACa,kDAAqB,GAAG,EAAN,CAAO;AAEzC,yCAAyC;AACzB,iDAAoB,mBAAmB,EAAtB,CAAuB;AA+e1D,kBAAe,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 * 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 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 // 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\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 this.#changedChainsToPersist.add(chainId);\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 // Chains in state _before loading persisted state_, from a recent update\n const chainsInState = new Set(\n Object.keys(this.state.tokensChainsCache) as Hex[],\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 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\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 for (const chainId of chainsInState) {\n this.#changedChainsToPersist.add(chainId);\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 }\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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TokenListController.d.cts","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EACV,iCAAiC,EACjC,YAAY,EACZ,2CAA2C,EAC5C,qCAAqC;AAEtC,OAAO,KAAK,EACV,2BAA2B,EAC3B,2BAA2B,EAC3B,8BAA8B,EAC/B,kCAAkC;AACnC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAO3C,OAAO,EAAE,YAAY,EAA2B,4BAAwB;AAMxE,QAAA,MAAM,IAAI,wBAAwB,CAAC;AAEnC,MAAM,MAAM,cAAc,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,YAAY,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AAE1D,MAAM,MAAM,SAAS,GAAG;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,YAAY,CAAC;CACpB,CAAC;AACF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,CAAC,OAAO,EAAE,GAAG,GAAG,SAAS,CAAC;CAC3B,CAAC;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V,OAAO,EACP,oBAAoB,EACpB,QAA2B,EAC3B,qBAAyC,EACzC,SAAS,EACT,KAAK,GACN,EAAE;QACD,OAAO,EAAE,GAAG,CAAC;QACb,oBAAoB,CAAC,EAAE,CACrB,QAAQ,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,KAC3C,IAAI,CAAC;QACV,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,qBAAqB,CAAC,EAAE,MAAM,CAAC;QAC/B,SAAS,EAAE,4BAA4B,CAAC;QACxC,KAAK,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;KACjC;IAgCD;;;;;OAKG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAoPjC;;;;;OAKG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;;;OAKG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;;OAKG;IACH,IAAI,IAAI,IAAI;IAIZ;;;;;OAKG;IACM,OAAO,IAAI,IAAI;IAwCxB;;;;;;OAMG;IACG,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrE;;;;;OAKG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAyDjD,YAAY,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO;CAQpC;AAED,eAAe,mBAAmB,CAAC"}
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
9
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
10
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
11
11
|
};
|
|
12
|
-
var _TokenListController_instances, _a, _TokenListController_persistDebounceTimer, _TokenListController_persistInFlightPromise, _TokenListController_changedChainsToPersist,
|
|
12
|
+
var _TokenListController_instances, _a, _TokenListController_persistDebounceTimer, _TokenListController_persistInFlightPromise, _TokenListController_changedChainsToPersist, _TokenListController_previousTokensChainsCache, _TokenListController_persistDebounceMs, _TokenListController_storageKeyPrefix, _TokenListController_getChainStorageKey, _TokenListController_intervalId, _TokenListController_intervalDelay, _TokenListController_cacheRefreshThreshold, _TokenListController_chainId, _TokenListController_abortController, _TokenListController_onCacheChanged, _TokenListController_debouncePersist, _TokenListController_persistChangedChains, _TokenListController_synchronizeCacheWithStorage, _TokenListController_saveChainCacheToStorage, _TokenListController_onNetworkControllerStateChange, _TokenListController_stopPolling, _TokenListController_startDeprecatedPolling;
|
|
13
13
|
import { safelyExecute } from "@metamask/controller-utils";
|
|
14
14
|
import { StaticIntervalPollingController } from "@metamask/polling-controller";
|
|
15
15
|
import { isTokenListSupportedForNetwork, formatAggregatorNames, formatIconUrlWithProxy } from "./assetsUtil.mjs";
|
|
@@ -68,13 +68,6 @@ export class TokenListController extends StaticIntervalPollingController() {
|
|
|
68
68
|
* Only changed chains are persisted to reduce write amplification.
|
|
69
69
|
*/
|
|
70
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
71
|
/**
|
|
79
72
|
* Previous tokensChainsCache for detecting which chains changed.
|
|
80
73
|
*/
|
|
@@ -89,8 +82,6 @@ export class TokenListController extends StaticIntervalPollingController() {
|
|
|
89
82
|
__classPrivateFieldSet(this, _TokenListController_cacheRefreshThreshold, cacheRefreshThreshold, "f");
|
|
90
83
|
__classPrivateFieldSet(this, _TokenListController_chainId, chainId, "f");
|
|
91
84
|
__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);
|
|
94
85
|
if (onNetworkStateChange) {
|
|
95
86
|
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
96
87
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
@@ -115,6 +106,8 @@ export class TokenListController extends StaticIntervalPollingController() {
|
|
|
115
106
|
*/
|
|
116
107
|
async initialize() {
|
|
117
108
|
await __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_synchronizeCacheWithStorage).call(this);
|
|
109
|
+
// Subscribe to state changes to automatically persist tokensChainsCache
|
|
110
|
+
this.messenger.subscribe('TokenListController:stateChange', (newCache) => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onCacheChanged).call(this, newCache), (controllerState) => controllerState.tokensChainsCache);
|
|
118
111
|
}
|
|
119
112
|
// Eventually we want to remove start/restart/stop controls in favor of new _executePoll API
|
|
120
113
|
// Maintaining these functions for now until we can safely deprecate them for backwards compatibility
|
|
@@ -164,7 +157,6 @@ export class TokenListController extends StaticIntervalPollingController() {
|
|
|
164
157
|
__classPrivateFieldSet(this, _TokenListController_persistDebounceTimer, undefined, "f");
|
|
165
158
|
}
|
|
166
159
|
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").clear();
|
|
167
|
-
__classPrivateFieldGet(this, _TokenListController_chainsLoadedFromStorage, "f").clear();
|
|
168
160
|
}
|
|
169
161
|
/**
|
|
170
162
|
* This starts a new polling loop for any given chain. Under the hood it is deduping polls
|
|
@@ -235,7 +227,7 @@ export class TokenListController extends StaticIntervalPollingController() {
|
|
|
235
227
|
return (timestamp !== undefined && now - timestamp < __classPrivateFieldGet(this, _TokenListController_cacheRefreshThreshold, "f"));
|
|
236
228
|
}
|
|
237
229
|
}
|
|
238
|
-
_a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(),
|
|
230
|
+
_a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMap(), _TokenListController_persistInFlightPromise = new WeakMap(), _TokenListController_changedChainsToPersist = new WeakMap(), _TokenListController_previousTokensChainsCache = new WeakMap(), _TokenListController_intervalId = new WeakMap(), _TokenListController_intervalDelay = new WeakMap(), _TokenListController_cacheRefreshThreshold = new WeakMap(), _TokenListController_chainId = new WeakMap(), _TokenListController_abortController = new WeakMap(), _TokenListController_instances = new WeakSet(), _TokenListController_getChainStorageKey = function _TokenListController_getChainStorageKey(chainId) {
|
|
239
231
|
return `${__classPrivateFieldGet(_a, _a, "f", _TokenListController_storageKeyPrefix)}:${chainId}`;
|
|
240
232
|
}, _TokenListController_onCacheChanged = function _TokenListController_onCacheChanged(newCache) {
|
|
241
233
|
// Detect which chains changed by comparing with previous cache
|
|
@@ -244,14 +236,7 @@ _a = TokenListController, _TokenListController_persistDebounceTimer = new WeakMa
|
|
|
244
236
|
const prevData = __classPrivateFieldGet(this, _TokenListController_previousTokensChainsCache, "f")[chainId];
|
|
245
237
|
// Chain is new or timestamp changed (indicating data update)
|
|
246
238
|
if (!prevData || prevData.timestamp !== newData.timestamp) {
|
|
247
|
-
|
|
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
|
-
}
|
|
239
|
+
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
255
240
|
}
|
|
256
241
|
}
|
|
257
242
|
// Update previous cache reference
|
|
@@ -337,16 +322,11 @@ async function _TokenListController_synchronizeCacheWithStorage() {
|
|
|
337
322
|
loadedCache[chainCache.chainId] = chainCache.data;
|
|
338
323
|
}
|
|
339
324
|
});
|
|
325
|
+
// Chains in state _before loading persisted state_, from a recent update
|
|
326
|
+
const chainsInState = new Set(Object.keys(this.state.tokensChainsCache));
|
|
340
327
|
// Merge loaded cache with existing state, preferring existing data
|
|
341
328
|
// (which may be fresher if fetched during initialization)
|
|
342
329
|
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
330
|
this.update((state) => {
|
|
351
331
|
// Only load chains that don't already exist in state
|
|
352
332
|
// This prevents overwriting fresh API data with stale cached data
|
|
@@ -356,20 +336,13 @@ async function _TokenListController_synchronizeCacheWithStorage() {
|
|
|
356
336
|
}
|
|
357
337
|
}
|
|
358
338
|
});
|
|
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
339
|
}
|
|
363
340
|
// Persist chains that exist in state but were not loaded from storage.
|
|
364
341
|
// This handles the case where initial state contains chains that don't exist
|
|
365
342
|
// in storage yet (e.g., fresh data from API). Without this, those chains
|
|
366
343
|
// 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
344
|
for (const chainId of chainsInState) {
|
|
370
|
-
|
|
371
|
-
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
372
|
-
}
|
|
345
|
+
__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").add(chainId);
|
|
373
346
|
}
|
|
374
347
|
// Persist any chains that need to be saved
|
|
375
348
|
if (__classPrivateFieldGet(this, _TokenListController_changedChainsToPersist, "f").size > 0) {
|
|
@@ -1 +1 @@
|
|
|
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,EAC9B,qBAAqB,EACrB,sBAAsB,EACvB,yBAAqB;AACtB,OAAO,EAAgB,uBAAuB,EAAE,4BAAwB;AAExE,0CAA0C;AAC1C,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC5C,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAuDnC,MAAM,QAAQ,GAAkC;IAC9C,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK,EAAE,0CAA0C;QAC1D,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAmB,EAAE;IAC3D,OAAO;QACL,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC,CAAC;AAOF;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,+BAA+B,EAIvE;IA2DC;;;;;;;;;;OAUG;IACH,YAAY,EACV,OAAO,EACP,oBAAoB,EACpB,QAAQ,GAAG,gBAAgB,EAC3B,qBAAqB,GAAG,iBAAiB,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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"]}
|
|
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,EAC9B,qBAAqB,EACrB,sBAAsB,EACvB,yBAAqB;AACtB,OAAO,EAAgB,uBAAuB,EAAE,4BAAwB;AAExE,0CAA0C;AAC1C,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC5C,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAuDnC,MAAM,QAAQ,GAAkC;IAC9C,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK,EAAE,0CAA0C;QAC1D,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAmB,EAAE;IAC3D,OAAO;QACL,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC,CAAC;AAOF;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,+BAA+B,EAIvE;IAmDC;;;;;;;;;;OAUG;IACH,YAAY,EACV,OAAO,EACP,oBAAoB,EACpB,QAAQ,GAAG,gBAAgB,EAC3B,qBAAqB,GAAG,iBAAiB,EACzC,SAAS,EACT,KAAK,GAUN;QACC,KAAK,CAAC;YACJ,IAAI;YACJ,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,wBAAw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AI,CAAC,cAAc,CAAC,uBAAA,IAAI,oCAAS,CAAC,CAAC,CAAC;IAChE,CAAC,EAAE,uBAAA,IAAI,0CAAe,CAAC,MAAA,CAAC;AAC1B,CAAC;AA/ZD;;GAEG;AACa,kDAAqB,GAAG,EAAN,CAAO;AAEzC,yCAAyC;AACzB,iDAAoB,mBAAmB,EAAtB,CAAuB;AA+e1D,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 * 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 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 // 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\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 this.#changedChainsToPersist.add(chainId);\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 // Chains in state _before loading persisted state_, from a recent update\n const chainsInState = new Set(\n Object.keys(this.state.tokensChainsCache) as Hex[],\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 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\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 for (const chainId of chainsInState) {\n this.#changedChainsToPersist.add(chainId);\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 }\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"]}
|