@metamask-previews/assets-controller 20.2.2-preview-77efa7863 → 20.2.2-preview-9b251c589

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.
@@ -32,10 +32,6 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
32
32
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
33
  done = true;
34
34
  };
35
- var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
36
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
37
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
38
- };
39
35
  import { BaseController } from '@metamask/base-controller';
40
36
  import { clientControllerSelectors } from '@metamask/client-controller';
41
37
  import { isCaipChainId, isStrictHexString, KnownCaipNamespace, parseCaipAssetType, parseCaipChainId, } from '@metamask/utils';
@@ -135,37 +131,37 @@ export function getDefaultAssetsControllerState() {
135
131
  const stateMetadata = {
136
132
  assetsInfo: {
137
133
  persist: true,
138
- includeInStateLogs: false,
134
+ includeInStateLogs: true,
139
135
  includeInDebugSnapshot: false,
140
136
  usedInUi: true,
141
137
  },
142
138
  assetsBalance: {
143
139
  persist: true,
144
- includeInStateLogs: false,
140
+ includeInStateLogs: true,
145
141
  includeInDebugSnapshot: false,
146
142
  usedInUi: true,
147
143
  },
148
144
  assetsPrice: {
149
145
  persist: true,
150
- includeInStateLogs: false,
146
+ includeInStateLogs: true,
151
147
  includeInDebugSnapshot: false,
152
148
  usedInUi: true,
153
149
  },
154
150
  customAssets: {
155
151
  persist: true,
156
- includeInStateLogs: false,
152
+ includeInStateLogs: true,
157
153
  includeInDebugSnapshot: false,
158
154
  usedInUi: true,
159
155
  },
160
156
  assetPreferences: {
161
157
  persist: true,
162
- includeInStateLogs: false,
158
+ includeInStateLogs: true,
163
159
  includeInDebugSnapshot: false,
164
160
  usedInUi: true,
165
161
  },
166
162
  selectedCurrency: {
167
163
  persist: true,
168
- includeInStateLogs: false,
164
+ includeInStateLogs: true,
169
165
  includeInDebugSnapshot: false,
170
166
  usedInUi: true,
171
167
  },
@@ -306,42 +302,45 @@ function effectiveAccountBalancesV6(previousBalances, updatedBalances, undeletab
306
302
  }
307
303
  return { ...keptBalances, ...updatedBalances };
308
304
  }
305
+ // ============================================================================
306
+ // CONTROLLER IMPLEMENTATION
307
+ // ============================================================================
308
+ /**
309
+ * AssetsController provides a unified interface for managing asset balances
310
+ * across all blockchain networks (EVM and non-EVM) and all asset types.
311
+ *
312
+ * ## Core Responsibilities
313
+ *
314
+ * 1. **One-Time Fetch (Sync)**: For initial load, force refresh, or on-demand queries.
315
+ * Uses `getAssets()`, `getAssetsBalance()`, etc. with `forceUpdate: true`.
316
+ *
317
+ * 2. **Async Subscriptions**: Subscribes to data sources for ongoing updates.
318
+ * Data sources push updates via callbacks; the controller updates state.
319
+ *
320
+ * 3. **Dynamic Source Selection**: Routes requests to appropriate data sources
321
+ * based on which chains they support. When active chains change, the controller
322
+ * dynamically adjusts subscriptions.
323
+ *
324
+ * 4. **Client + Keyring Lifecycle**: Starts subscriptions only when both the UI is
325
+ * open (ClientController) and the wallet is unlocked (KeyringController).
326
+ * Stops when either the UI closes or the keyring locks. See client-controller
327
+ * README for the combined pattern.
328
+ *
329
+ * ## Architecture
330
+ *
331
+ * - Data sources declare their supported chains (async, can change over time)
332
+ * - Data sources are responsible for their own update mechanisms (WebSocket, polling, events)
333
+ * - The controller does NOT manage polling - it simply receives pushed updates
334
+ */
309
335
  let AssetsController = (() => {
310
336
  let _classSuper = BaseController;
311
337
  let _instanceExtraInitializers = [];
312
- let _private_getAssetsTracked_decorators;
313
- let _private_getAssetsTracked_descriptor;
338
+ let _getAssets_decorators;
314
339
  return class AssetsController extends _classSuper {
315
340
  static {
316
341
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
317
- _private_getAssetsTracked_decorators = [trackAssetsLoading];
318
- __esDecorate(this, _private_getAssetsTracked_descriptor = { value: __setFunctionName(async function (accounts, options) {
319
- // An omitted list uses the enabled networks. When that state cannot be
320
- // read yet, `undefined` means "do not filter by chain" rather than
321
- // treating a missing read as every network being disabled.
322
- const enabledChains = options?.chainIds === undefined ? this.#readEnabledChains() : undefined;
323
- const chainIds = options?.chainIds ??
324
- (enabledChains === undefined ? undefined : [...enabledChains]);
325
- const assetTypes = options?.assetTypes ?? ['fungible'];
326
- const dataTypes = options?.dataTypes ?? ['balance', 'metadata', 'price'];
327
- if (accounts.length === 0 || chainIds?.length === 0) {
328
- return this.#getAssetsFromState(accounts, chainIds, assetTypes);
329
- }
330
- if (options?.forceUpdate && chainIds) {
331
- await this.#forceUpdateAssets({
332
- accounts,
333
- chainIds,
334
- requestOptions: {
335
- assetTypes,
336
- dataTypes,
337
- forceUpdate: true,
338
- bypassServerCache: options.bypassServerCache,
339
- },
340
- });
341
- }
342
- const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
343
- return result;
344
- }, "#getAssetsTracked") }, _private_getAssetsTracked_decorators, { kind: "method", name: "#getAssetsTracked", static: false, private: true, access: { has: obj => #getAssetsTracked in obj, get: obj => obj.#getAssetsTracked }, metadata: _metadata }, null, _instanceExtraInitializers);
342
+ _getAssets_decorators = [trackAssetsLoading];
343
+ __esDecorate(this, null, _getAssets_decorators, { kind: "method", name: "getAssets", static: false, private: false, access: { has: obj => "getAssets" in obj, get: obj => obj.getAssets }, metadata: _metadata }, null, _instanceExtraInitializers);
345
344
  if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
346
345
  }
347
346
  /** Whether the controller is enabled */
@@ -416,10 +415,10 @@ let AssetsController = (() => {
416
415
  */
417
416
  #activeSubscriptions = new Map();
418
417
  /**
419
- * Guards against `#startTracking()` re-entrancy. `#activeSubscriptions` only
418
+ * Guards against `#start()` re-entrancy. `#activeSubscriptions` only
420
419
  * becomes non-empty once `#runStartupRefresh()`'s forced `getAssets()`
421
420
  * call resolves, which can take many seconds for accounts with many
422
- * chains/snaps. `#startTracking()` is invoked by `#updateActive()`, which is
421
+ * chains/snaps. `#start()` is invoked by `#updateActive()`, which is
423
422
  * wired to several independent events (e.g. keyring unlock, account tree
424
423
  * init, client state change). If a second such event fires before the
425
424
  * first `getAssets()` call resolves, the `#activeSubscriptions.size > 0`
@@ -427,6 +426,8 @@ let AssetsController = (() => {
427
426
  * its forced `getAssets()` call) runs a second time for the same accounts.
428
427
  */
429
428
  #startInFlight = false;
429
+ /** Currently enabled chains from NetworkEnablementController */
430
+ #enabledChains = new Set();
430
431
  /**
431
432
  * Get the currently selected accounts from AccountTreeController.
432
433
  * This includes all accounts in the same group as the selected account
@@ -469,14 +470,6 @@ let AssetsController = (() => {
469
470
  #isKeyringUnlocked() {
470
471
  return this.messenger.call('KeyringController:isUnlocked');
471
472
  }
472
- /**
473
- * Data sources and middlewares. Assigned in `#createSources` the first time
474
- * the UI opens, not by the constructor: their constructors read other
475
- * controllers (network, snaps, feature flags), which may not be registered
476
- * yet. Not `readonly` because that assignment happens outside the
477
- * constructor. Definite assignment (`!`) keeps call sites unchanged;
478
- * `#hasSources` is the guard for paths that can run before the UI opens.
479
- */
480
473
  #accountActivityDataSource;
481
474
  #accountsApiDataSource;
482
475
  #snapDataSource;
@@ -501,19 +494,6 @@ let AssetsController = (() => {
501
494
  #customAssetGraduationMiddleware;
502
495
  #rpcFallbackMiddleware;
503
496
  #tokenDataSource;
504
- /**
505
- * Whether `#createSources` has assigned the data sources. Entry points that
506
- * can run before the UI first opens check this and return.
507
- */
508
- #hasSources = false;
509
- /** Options forwarded to the data sources when they are created. */
510
- #sourceOptions;
511
- /** The pending or settled bootstrap, so it runs at most once. */
512
- #bootstrapPromise;
513
- /** Whether the bootstrap has finished. */
514
- #isBootstrapped = false;
515
- /** Whether `destroy()` has been called. */
516
- #isDestroyed = false;
517
497
  #unsubscribeBasicFunctionality = null;
518
498
  #queryApiClient;
519
499
  #onActiveChainsUpdated;
@@ -555,123 +535,12 @@ let AssetsController = (() => {
555
535
  });
556
536
  }
557
537
  };
558
- this.#sourceOptions = {
559
- queryApiClient,
560
- rpcDataSourceConfig: rpcConfig,
561
- accountsApiDataSourceConfig,
562
- priceDataSourceConfig,
563
- stakedBalanceDataSourceConfig,
564
- isOnboarded,
565
- subscribeToBasicFunctionalityChange,
566
- };
567
- log('Initializing AssetsController', {
568
- defaultUpdateInterval: this.#defaultUpdateInterval,
569
- });
570
- // The constructor only registers action handlers and subscribes to
571
- // events; it never calls another controller, so it does not depend on the
572
- // order in which controllers are constructed. Reading other controllers
573
- // and creating the data sources happen the first time the UI opens.
574
- this.#registerActionHandlers();
575
- this.#subscribeToEvents();
576
- }
577
- // ============================================================================
578
- // INITIALIZATION
579
- // ============================================================================
580
- /**
581
- * Bootstrap the controller the first time the UI is seen open, then start
582
- * or stop asset tracking. Runs at most once; later calls share the same
583
- * promise.
584
- *
585
- * @returns A promise that resolves once the controller is bootstrapped.
586
- */
587
- async #ensureBootstrapped() {
588
- this.#bootstrapPromise ??= this.#bootstrap().catch((error) => {
589
- // Allow a later lifecycle event to retry when a data source constructor
590
- // throws before the data sources are assigned.
591
- if (!this.#hasSources) {
592
- this.#bootstrapPromise = undefined;
593
- }
594
- throw error;
595
- });
596
- return this.#bootstrapPromise;
597
- }
598
- /**
599
- * Create the data sources, subscribe to basic-functionality changes, wait
600
- * for the Accounts API supported networks and run the unlock cleanups when
601
- * the keyring is already unlocked. Then start asset tracking if the keyring
602
- * is unlocked and the account tree is initialized.
603
- *
604
- * Enabled chains are read from NetworkEnablementController when a fetch or
605
- * subscription needs them. By the time the UI opens, the client has
606
- * registered every controller this one depends on, so reading them here is
607
- * safe.
608
- */
609
- async #bootstrap() {
610
- if (this.#isDestroyed) {
611
- return;
612
- }
613
- log('Bootstrapping AssetsController');
614
- this.#createSources();
615
- this.#subscribeToBasicFunctionality();
616
- await Promise.all([
617
- // AccountsApiDataSource fetches its supported networks asynchronously
618
- // from its constructor. Wait for them so the first forced fetch can use
619
- // the Accounts API instead of routing every chain to the slow lane.
620
- // `fetchQuery` shares the in-flight request, so this does not issue a
621
- // second one. Failures are logged by the data source and do not reject.
622
- this.#accountsApiDataSource.refreshActiveChains(),
623
- this.#runUnlockCleanupsIfUnlocked(),
624
- ]);
625
- if (this.#isDestroyed) {
626
- return;
627
- }
628
- // Chain updates reported while bootstrapping are ignored; `#updateActive`
629
- // subscribes with every source's current chains.
630
- this.#isBootstrapped = true;
631
- this.#updateActive();
632
- }
633
- /**
634
- * Run the unlock cleanups when the keyring is already unlocked. The
635
- * `KeyringController:unlock` handler skips them before the bootstrap, so an
636
- * unlock that happened earlier is handled here.
637
- */
638
- async #runUnlockCleanupsIfUnlocked() {
639
- if (!this.#isKeyringUnlocked()) {
640
- return;
641
- }
642
- await this.#runUnlockCleanups();
643
- }
644
- /**
645
- * Run the cleanups that happen on unlock: drop balances outside the
646
- * selected accounts' scopes, then remove spam tokens.
647
- */
648
- async #runUnlockCleanups() {
649
- try {
650
- this.#runOutOfScopeBalanceCleanup();
651
- }
652
- catch {
653
- /* Do nothing */
654
- }
655
- await this.#runSpamCleanup().catch(() => {
656
- /* Do nothing */
657
- });
658
- }
659
- /**
660
- * Create every data source and middleware.
661
- *
662
- * Data source constructors read other controllers and may report active
663
- * chains synchronously. `#handleActiveChainsUpdate` ignores those reports
664
- * until the bootstrap finishes, and `#updateActive` subscribes afterwards
665
- * with every source's chains.
666
- */
667
- #createSources() {
668
- const { queryApiClient, rpcDataSourceConfig, accountsApiDataSourceConfig, priceDataSourceConfig, stakedBalanceDataSourceConfig, isOnboarded, } = this.#sourceOptions;
669
- const accountActivityDataSource = new AccountActivityDataSource({
538
+ this.#accountActivityDataSource = new AccountActivityDataSource({
670
539
  messenger: this.messenger,
671
540
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
672
- onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, accountActivityDataSource.getName(), request),
541
+ onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, this.#accountActivityDataSource.getName(), request),
673
542
  });
674
- const accountsApiDataSource = new AccountsApiDataSource({
543
+ this.#accountsApiDataSource = new AccountsApiDataSource({
675
544
  messenger: this.messenger,
676
545
  queryApiClient,
677
546
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
@@ -680,7 +549,7 @@ let AssetsController = (() => {
680
549
  getAssetsState: () => this.state,
681
550
  getAssetVisibility: this.#getAssetVisibility.bind(this),
682
551
  });
683
- const snapDataSource = new SnapDataSource({
552
+ this.#snapDataSource = new SnapDataSource({
684
553
  messenger: this.messenger,
685
554
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
686
555
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
@@ -688,7 +557,7 @@ let AssetsController = (() => {
688
557
  getAssetVisibility: this.#getAssetVisibility.bind(this),
689
558
  getAssetsState: () => this.state,
690
559
  });
691
- const rpcDataSource = new RpcDataSource({
560
+ this.#rpcDataSource = new RpcDataSource({
692
561
  messenger: this.messenger,
693
562
  getAssetsState: () => this.state,
694
563
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
@@ -696,16 +565,16 @@ let AssetsController = (() => {
696
565
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
697
566
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
698
567
  queryApiClient,
699
- ...rpcDataSourceConfig,
700
- isOnboarded: rpcDataSourceConfig.isOnboarded ?? isOnboarded,
568
+ ...rpcConfig,
569
+ isOnboarded: rpcConfig.isOnboarded ?? isOnboarded,
701
570
  getAssetType: (assetId) => this.#getAssetType(assetId),
702
571
  });
703
- const stakedBalanceDataSource = new StakedBalanceDataSource({
572
+ this.#stakedBalanceDataSource = new StakedBalanceDataSource({
704
573
  messenger: this.messenger,
705
574
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
706
575
  ...stakedBalanceDataSourceConfig,
707
576
  });
708
- const tokenDataSource = new TokenDataSource(this.messenger, {
577
+ this.#tokenDataSource = new TokenDataSource(this.messenger, {
709
578
  queryApiClient,
710
579
  getNativeAssetIds: () => {
711
580
  return this.#getNativeAssetIdsForEnabledChains();
@@ -713,13 +582,13 @@ let AssetsController = (() => {
713
582
  getAssetType: (assetId) => this.#getAssetType(assetId),
714
583
  getAssetsState: () => this.state,
715
584
  });
716
- const priceDataSource = new PriceDataSource({
585
+ this.#priceDataSource = new PriceDataSource({
717
586
  queryApiClient,
718
587
  getSelectedCurrency: () => this.state.selectedCurrency,
719
588
  getAssetsState: () => this.state,
720
589
  ...priceDataSourceConfig,
721
590
  });
722
- const customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
591
+ this.#customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
723
592
  getSelectedAccountId: () => {
724
593
  try {
725
594
  return this.#getSelectedAccounts()[0]?.id;
@@ -731,40 +600,30 @@ let AssetsController = (() => {
731
600
  removeCustomAsset: (accountId, assetId) => this.removeCustomAsset(accountId, assetId),
732
601
  getAssetsState: () => this.state,
733
602
  });
734
- const rpcFallbackMiddleware = new RpcFallbackMiddleware({
735
- rpcDataSource,
603
+ this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
604
+ rpcDataSource: this.#rpcDataSource,
736
605
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
737
606
  getAssetsState: () => this.state,
738
607
  });
739
- // Assign only after every constructor has succeeded, so a throw leaves
740
- // `#hasSources` false and a later lifecycle event can retry.
741
- this.#accountActivityDataSource = accountActivityDataSource;
742
- this.#accountsApiDataSource = accountsApiDataSource;
743
- this.#snapDataSource = snapDataSource;
744
- this.#rpcDataSource = rpcDataSource;
745
- this.#stakedBalanceDataSource = stakedBalanceDataSource;
746
- this.#tokenDataSource = tokenDataSource;
747
- this.#priceDataSource = priceDataSource;
748
- this.#customAssetGraduationMiddleware = customAssetGraduationMiddleware;
749
- this.#rpcFallbackMiddleware = rpcFallbackMiddleware;
750
- this.#hasSources = true;
751
- }
752
- /**
753
- * Subscribe to the host's basic-functionality setting, if the host provided
754
- * a way to. Runs during the bootstrap, after the data sources exist and
755
- * before `#isBootstrapped` is set. A synchronous `onChange` is ignored
756
- * until the bootstrap finishes; `#updateActive` subscribes afterwards.
757
- */
758
- #subscribeToBasicFunctionality() {
759
- const { subscribeToBasicFunctionalityChange } = this.#sourceOptions;
760
- if (!subscribeToBasicFunctionalityChange) {
761
- return;
762
- }
763
- const unsubscribe = subscribeToBasicFunctionalityChange((isBasic) => this.handleBasicFunctionalityChange(isBasic));
764
- if (typeof unsubscribe === 'function') {
765
- this.#unsubscribeBasicFunctionality = unsubscribe;
608
+ log('Initializing AssetsController', {
609
+ defaultUpdateInterval: this.#defaultUpdateInterval,
610
+ });
611
+ this.#initializeState();
612
+ this.#subscribeToEvents();
613
+ this.#registerActionHandlers();
614
+ // Subscriptions start only when both UI is open and keyring unlocked -> #updateActive().
615
+ // Subscribe to basic-functionality changes after construction so a synchronous
616
+ // onChange during subscribe cannot run before data sources are initialized.
617
+ if (subscribeToBasicFunctionalityChange) {
618
+ const unsubscribe = subscribeToBasicFunctionalityChange((isBasic) => this.handleBasicFunctionalityChange(isBasic));
619
+ if (typeof unsubscribe === 'function') {
620
+ this.#unsubscribeBasicFunctionality = unsubscribe;
621
+ }
766
622
  }
767
623
  }
624
+ // ============================================================================
625
+ // INITIALIZATION
626
+ // ============================================================================
768
627
  #initializeNativeAssetsMap(queryApiClient) {
769
628
  queryApiClient.queryClient
770
629
  .fetchQuery({
@@ -785,44 +644,13 @@ let AssetsController = (() => {
785
644
  const initialNativeAssetMap = buildNativeAssetsFromConstant();
786
645
  queryApiClient.setCachedData(NATIVE_ASSETS_QUERY_KEY, initialNativeAssetMap);
787
646
  }
788
- /**
789
- * Read the currently enabled chains from NetworkEnablementController.
790
- *
791
- * Returns `undefined` when that action is not registered yet. Callers that
792
- * filter assets must not treat "not readable" as "every network is disabled".
793
- *
794
- * @returns The enabled chain set, or `undefined` when enablement state cannot be read.
795
- */
796
- #readEnabledChains() {
797
- try {
798
- const { enabledNetworkMap } = this.messenger.call('NetworkEnablementController:getState');
799
- return this.#extractEnabledChains(enabledNetworkMap);
800
- }
801
- catch (error) {
802
- if (this.#isMissingMessengerHandler(error)) {
803
- return undefined;
804
- }
805
- throw error;
806
- }
807
- }
808
- /**
809
- * Enabled chains, or an empty set when enablement state cannot be read yet.
810
- *
811
- * @returns The enabled chain set.
812
- */
813
- #getEnabledChains() {
814
- return this.#readEnabledChains() ?? new Set();
815
- }
816
- /**
817
- * Whether a messenger call failed because the action has no handler.
818
- *
819
- * @param error - The error thrown by `messenger.call`.
820
- * @returns True when the action is not registered or not delegated.
821
- */
822
- #isMissingMessengerHandler(error) {
823
- return (error instanceof Error &&
824
- (error.message.includes('has not been registered') ||
825
- error.message.includes('has not been delegated')));
647
+ #initializeState() {
648
+ const { enabledNetworkMap } = this.messenger.call('NetworkEnablementController:getState');
649
+ this.#enabledChains = this.#extractEnabledChains(enabledNetworkMap);
650
+ log('Initialized state', {
651
+ enabledNetworkMap,
652
+ enabledChains: this.#enabledChains,
653
+ });
826
654
  }
827
655
  /**
828
656
  * Extract enabled chains from enabledNetworkMap.
@@ -839,150 +667,21 @@ let AssetsController = (() => {
839
667
  for (const [namespace, networks] of Object.entries(enabledNetworkMap)) {
840
668
  for (const [reference, isEnabled] of Object.entries(networks)) {
841
669
  if (isEnabled) {
842
- chains.add(this.#toEnabledChainId(namespace, reference));
670
+ // Check if reference is already a full CAIP-2 chain ID (contains colon)
671
+ if (reference.includes(':')) {
672
+ // Already a full chain ID, use as-is
673
+ chains.add(reference);
674
+ }
675
+ else {
676
+ // Normalize EIP155 chain references from hex to decimal (CAIP-2 standard)
677
+ const normalizedReference = this.#normalizeChainReference(namespace, reference);
678
+ chains.add(`${namespace}:${normalizedReference}`);
679
+ }
843
680
  }
844
681
  }
845
682
  }
846
683
  return chains;
847
684
  }
848
- /**
849
- * Build the CAIP-2 chain id stored for one enabled-network entry.
850
- *
851
- * A reference that already contains `:` is a full chain id. EIP-155 hex
852
- * references are normalized to decimal.
853
- *
854
- * @param namespace - The CAIP namespace.
855
- * @param reference - The network reference from `enabledNetworkMap`.
856
- * @returns The CAIP-2 chain id.
857
- */
858
- #toEnabledChainId(namespace, reference) {
859
- if (reference.includes(':')) {
860
- return reference;
861
- }
862
- return `${namespace}:${this.#normalizeChainReference(namespace, reference)}`;
863
- }
864
- /**
865
- * Chains whose enablement changed in a NetworkEnablementController update.
866
- *
867
- * The published state is already the new map. Patches describe the edit, so
868
- * a cached previous set is not required. Boolean replaces and adds are
869
- * exact: immer only emits them when the value changed. A removed key does
870
- * not include its previous value, so it is reported as removed.
871
- *
872
- * @param patches - Patches from `NetworkEnablementController:stateChange`.
873
- * @returns Chains that became enabled and chains that stopped being enabled.
874
- */
875
- #diffEnabledChains(patches) {
876
- const addedChains = [];
877
- const removedChains = [];
878
- for (const patch of patches) {
879
- if (String(patch.path[0]) !== 'enabledNetworkMap') {
880
- continue;
881
- }
882
- const namespace = patch.path[1];
883
- const reference = patch.path[2];
884
- if (namespace === undefined) {
885
- this.#collectEnabledChainsFromMapPatch(patch, addedChains);
886
- continue;
887
- }
888
- if (reference === undefined) {
889
- this.#collectEnabledChainsFromNamespacePatch(String(namespace), patch, addedChains);
890
- continue;
891
- }
892
- this.#collectEnabledChainFromEntryPatch(String(namespace), String(reference), patch, addedChains, removedChains);
893
- }
894
- return {
895
- addedChains: [...new Set(addedChains)],
896
- removedChains: [...new Set(removedChains)],
897
- };
898
- }
899
- /**
900
- * Treat every currently enabled chain in a whole-map add or replace as added.
901
- * NetworkEnablementController edits keys in place, so this shape is unused
902
- * by that controller; it covers a replacement of `enabledNetworkMap`.
903
- *
904
- * @param patch - A patch whose path is `['enabledNetworkMap']`.
905
- * @param addedChains - Chains to append newly enabled ids to.
906
- */
907
- #collectEnabledChainsFromMapPatch(patch, addedChains) {
908
- if (patch.op === 'remove' || !this.#isNetworkRecord(patch.value)) {
909
- return;
910
- }
911
- for (const [namespace, networks] of Object.entries(patch.value)) {
912
- this.#pushEnabledChainIds(addedChains, namespace, networks);
913
- }
914
- }
915
- /**
916
- * Treat every enabled chain in an added or replaced namespace object as added.
917
- * Creating a namespace and enabling a chain in one update is one `add` of
918
- * that object.
919
- *
920
- * @param namespace - The CAIP namespace the patch targets.
921
- * @param patch - A patch whose path is `['enabledNetworkMap', namespace]`.
922
- * @param addedChains - Chains to append newly enabled ids to.
923
- */
924
- #collectEnabledChainsFromNamespacePatch(namespace, patch, addedChains) {
925
- if (patch.op === 'remove') {
926
- return;
927
- }
928
- this.#pushEnabledChainIds(addedChains, namespace, patch.value);
929
- }
930
- /**
931
- * Record one network entry that was enabled, disabled, or removed.
932
- *
933
- * @param namespace - The CAIP namespace.
934
- * @param reference - The network reference.
935
- * @param patch - A patch whose path is `['enabledNetworkMap', namespace, reference]`.
936
- * @param addedChains - Chains to append newly enabled ids to.
937
- * @param removedChains - Chains to append ids that are no longer enabled to.
938
- */
939
- #collectEnabledChainFromEntryPatch(namespace, reference, patch, addedChains, removedChains) {
940
- const chainId = this.#toEnabledChainId(namespace, reference);
941
- switch (patch.op) {
942
- case 'add':
943
- case 'replace':
944
- if (patch.value === true) {
945
- addedChains.push(chainId);
946
- }
947
- else if (patch.value === false) {
948
- removedChains.push(chainId);
949
- }
950
- return;
951
- case 'remove':
952
- removedChains.push(chainId);
953
- return;
954
- default: {
955
- const unexpected = patch.op;
956
- log('Ignoring unknown enabled-network patch', { op: unexpected });
957
- }
958
- }
959
- }
960
- /**
961
- * Append enabled chain ids from one namespace's network map.
962
- *
963
- * @param target - Chain ids to append to.
964
- * @param namespace - The CAIP namespace.
965
- * @param networks - The namespace's reference-to-enabled map, if it is one.
966
- */
967
- #pushEnabledChainIds(target, namespace, networks) {
968
- if (!this.#isNetworkRecord(networks)) {
969
- return;
970
- }
971
- for (const [reference, isEnabled] of Object.entries(networks)) {
972
- if (isEnabled === true) {
973
- target.push(this.#toEnabledChainId(namespace, reference));
974
- }
975
- }
976
- }
977
- /**
978
- * Whether a patch value is a string-keyed record.
979
- *
980
- * @param value - The patch value.
981
- * @returns True when `value` is a non-null object.
982
- */
983
- #isNetworkRecord(value) {
984
- return typeof value === 'object' && value !== null && !Array.isArray(value);
985
- }
986
685
  /**
987
686
  * Normalize chain reference to CAIP-2 standard format.
988
687
  * For EIP155, converts hex chain IDs to decimal.
@@ -998,21 +697,8 @@ let AssetsController = (() => {
998
697
  }
999
698
  return reference;
1000
699
  }
1001
- /**
1002
- * Subscribe to every external event. Runs from the constructor: subscribing
1003
- * does not need the publishing controller to exist yet, so this does not
1004
- * depend on construction order.
1005
- *
1006
- * Lifecycle events (client, keyring, account tree) drive `#updateActive`,
1007
- * which bootstraps the controller the first time the UI is seen open.
1008
- * Every other event needs the data sources, so it is ignored until they
1009
- * exist.
1010
- */
1011
700
  #subscribeToEvents() {
1012
701
  this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId, previousGroupId) => {
1013
- if (!this.#hasSources) {
1014
- return;
1015
- }
1016
702
  this.#handleAccountGroupChanged(groupId, previousGroupId).catch(console.error);
1017
703
  });
1018
704
  this.messenger.subscribe('AccountTreeController:initialized', () => {
@@ -1022,11 +708,8 @@ let AssetsController = (() => {
1022
708
  this.#updateActive();
1023
709
  });
1024
710
  // Subscribe to network enablement changes (only enabledNetworkMap)
1025
- this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }, patches) => {
1026
- if (!this.#hasSources) {
1027
- return;
1028
- }
1029
- this.#handleEnabledNetworksChanged(enabledNetworkMap, patches).catch(console.error);
711
+ this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }) => {
712
+ this.#handleEnabledNetworksChanged(enabledNetworkMap).catch(console.error);
1030
713
  });
1031
714
  // When a network is added or removed from NetworkController, refresh
1032
715
  // assets across every data source so balances, prices, and metadata
@@ -1035,46 +718,34 @@ let AssetsController = (() => {
1035
718
  // entries appear immediately without waiting for it to also be
1036
719
  // enabled in NetworkEnablementController.
1037
720
  this.messenger.subscribe('NetworkController:networkAdded', (networkConfiguration) => {
1038
- if (!this.#hasSources) {
1039
- return;
1040
- }
1041
721
  this.#handleNetworkAdded(networkConfiguration.chainId);
1042
722
  this.#refreshAssetsAfterNetworkAdded(networkConfiguration.chainId).catch((error) => {
1043
723
  log('Failed to refresh assets after network added', { error });
1044
724
  });
1045
725
  });
1046
726
  this.messenger.subscribe('NetworkController:networkRemoved', () => {
1047
- if (!this.#hasSources) {
1048
- return;
1049
- }
1050
727
  this.#refreshAssetsAfterNetworkChange();
1051
728
  });
1052
729
  // Selected EVM network switch (network picker). Enablement changes are
1053
730
  // handled separately via NetworkEnablementController:stateChange.
1054
731
  this.messenger.subscribe('NetworkController:networkDidChange', (networkState) => {
1055
- if (!this.#hasSources) {
1056
- return;
1057
- }
1058
732
  this.#handleNetworkDidChange(networkState).catch(console.error);
1059
733
  });
1060
- // Client + Keyring lifecycle: only run when UI is open AND keyring is
1061
- // unlocked. The first time the UI opens, this bootstraps the controller.
734
+ // Client + Keyring lifecycle: only run when UI is open AND keyring is unlocked
1062
735
  this.messenger.subscribe('ClientController:stateChange', () => {
1063
736
  this.#updateActive();
1064
737
  }, clientControllerSelectors.selectIsUiOpen);
1065
738
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
1066
739
  this.messenger.subscribe('KeyringController:unlock', async () => {
1067
- // Wait for an in-flight bootstrap: it may have checked the keyring
1068
- // before this unlock and skipped the cleanups. Once bootstrapped, the
1069
- // cleanups start synchronously, as before.
1070
- if (!this.#isBootstrapped && this.#bootstrapPromise) {
1071
- await this.#bootstrapPromise.catch(() => undefined);
740
+ try {
741
+ this.#runOutOfScopeBalanceCleanup();
1072
742
  }
1073
- if (this.#isBootstrapped) {
1074
- await this.#runUnlockCleanups();
743
+ catch {
744
+ /* Do nothing */
1075
745
  }
1076
- // Before the bootstrap, this bootstraps the controller if the UI is
1077
- // open, and the bootstrap runs the cleanups.
746
+ await this.#runSpamCleanup().catch(() => {
747
+ /* Do nothing */
748
+ });
1078
749
  this.#updateActive();
1079
750
  });
1080
751
  this.messenger.subscribe('KeyringController:lock', () => {
@@ -1084,9 +755,6 @@ let AssetsController = (() => {
1084
755
  // Ensures balances for the account making the transaction are updated
1085
756
  // (e.g. for gas estimations), except on AccountActivity-active chains.
1086
757
  this.messenger.subscribe('TransactionController:unapprovedTransactionAdded', (transactionMeta) => {
1087
- if (!this.#hasSources) {
1088
- return;
1089
- }
1090
758
  this.#refreshAssetsForEVMTransaction(transactionMeta);
1091
759
  });
1092
760
  // Post-tx refresh via the full fetch pipeline (Accounts API + RPC fallback).
@@ -1094,9 +762,6 @@ let AssetsController = (() => {
1094
762
  // RpcDataSource also listens for transactionConfirmed, but only refreshes
1095
763
  // chains it owns via an active subscription.
1096
764
  this.messenger.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
1097
- if (!this.#hasSources) {
1098
- return;
1099
- }
1100
765
  this.#refreshAssetsForEVMTransaction(transactionMeta);
1101
766
  });
1102
767
  // Non-EVM equivalent of the above: Snap keyrings report transaction
@@ -1104,9 +769,6 @@ let AssetsController = (() => {
1104
769
  // not covered by AccountActivity (WebSocket down / unsupported), refresh
1105
770
  // via the Accounts API with the server cache bypassed.
1106
771
  this.messenger.subscribe('MultichainTransactionsController:transactionConfirmed', (transaction) => {
1107
- if (!this.#hasSources) {
1108
- return;
1109
- }
1110
772
  this.#refreshAssetsForNonEvmTransaction(transaction);
1111
773
  });
1112
774
  }
@@ -1232,33 +894,16 @@ let AssetsController = (() => {
1232
894
  * Start or stop asset tracking based on client (UI) open state, keyring
1233
895
  * unlock state, and account-tree readiness. Only runs when the UI is open,
1234
896
  * the keyring is unlocked, and the account tree has finished `init()`.
1235
- *
1236
- * Before the bootstrap, this only bootstraps the controller when the UI is
1237
- * open. It reads other controllers only when one of their events fires, by
1238
- * which point they are registered.
1239
897
  */
1240
898
  #updateActive() {
1241
- if (this.#isDestroyed) {
1242
- return;
1243
- }
1244
- if (!this.#isBootstrapped) {
1245
- // Bootstrap the first time the UI is seen open. The bootstrap calls
1246
- // back into `#updateActive` once it finishes.
1247
- if (this.#isUiOpen()) {
1248
- this.#ensureBootstrapped().catch((error) => {
1249
- log('Failed to bootstrap AssetsController', { error });
1250
- });
1251
- }
1252
- return;
1253
- }
1254
899
  const shouldRun = this.#isUiOpen() &&
1255
900
  this.#isKeyringUnlocked() &&
1256
901
  this.#isAccountTreeInitialized();
1257
902
  if (shouldRun) {
1258
- this.#startTracking();
903
+ this.#start();
1259
904
  }
1260
905
  else {
1261
- this.#stopTracking();
906
+ this.#stop();
1262
907
  }
1263
908
  }
1264
909
  /**
@@ -1270,7 +915,7 @@ let AssetsController = (() => {
1270
915
  const releaseLock = await this.#accountRefreshMutex.acquire();
1271
916
  try {
1272
917
  await this.getAssets(accounts, {
1273
- chainIds: [...this.#getEnabledChains()],
918
+ chainIds: [...this.#enabledChains],
1274
919
  forceUpdate: true,
1275
920
  });
1276
921
  // Seed before subscribe so the price poll / update fetch sees natives
@@ -1310,13 +955,6 @@ let AssetsController = (() => {
1310
955
  * @param previousChains - Previous chains; used to compute added/removed.
1311
956
  */
1312
957
  #handleActiveChainsUpdate(dataSourceId, activeChains, previousChains) {
1313
- // Data sources report their chains while the bootstrap is still running.
1314
- // The bootstrap subscribes afterwards with every source's chains.
1315
- // Subscribing here first would make `#startTracking` skip the startup
1316
- // refresh.
1317
- if (!this.#isBootstrapped) {
1318
- return;
1319
- }
1320
958
  if (!this.#isUiOpen() || !this.#isKeyringUnlocked() || !this.#isEnabled()) {
1321
959
  return;
1322
960
  }
@@ -1370,36 +1008,28 @@ let AssetsController = (() => {
1370
1008
  // ============================================================================
1371
1009
  // PUBLIC API: QUERY METHODS
1372
1010
  // ============================================================================
1373
- /**
1374
- * Get assets for the given accounts, optionally force-fetching them first.
1375
- *
1376
- * Before the UI first opens there are no data sources, so a forced fetch is
1377
- * skipped and the assets already in state are returned. An omitted
1378
- * `chainIds` uses the networks enabled in NetworkEnablementController when
1379
- * that state can be read, and does not filter by chain when it cannot. The
1380
- * loading status of the accounts is left untouched, so the first fetch
1381
- * afterwards still reports them as loading.
1382
- *
1383
- * @param accounts - Accounts to get assets for.
1384
- * @param options - Fetch options.
1385
- * @param options.chainIds - Chains to include. Defaults to the enabled chains.
1386
- * @param options.assetTypes - Asset types to include. Defaults to fungible.
1387
- * @param options.forceUpdate - Fetch from the data sources before reading state.
1388
- * @param options.bypassServerCache - Also bypass server-side HTTP caches.
1389
- * @param options.dataTypes - Data types to fetch.
1390
- * @returns Assets keyed by account ID and asset ID.
1391
- */
1392
1011
  async getAssets(accounts, options) {
1393
- if (options?.forceUpdate && !this.#hasSources) {
1394
- log('Skipping forced asset fetch: data sources have not been created');
1395
- return this.#getAssetsTracked(accounts, {
1396
- ...options,
1397
- forceUpdate: false,
1012
+ const chainIds = options?.chainIds ?? [...this.#enabledChains];
1013
+ const assetTypes = options?.assetTypes ?? ['fungible'];
1014
+ const dataTypes = options?.dataTypes ?? ['balance', 'metadata', 'price'];
1015
+ if (accounts.length === 0 || chainIds.length === 0) {
1016
+ return this.#getAssetsFromState(accounts, chainIds, assetTypes);
1017
+ }
1018
+ if (options?.forceUpdate) {
1019
+ await this.#forceUpdateAssets({
1020
+ accounts,
1021
+ chainIds,
1022
+ requestOptions: {
1023
+ assetTypes,
1024
+ dataTypes,
1025
+ forceUpdate: true,
1026
+ bypassServerCache: options.bypassServerCache,
1027
+ },
1398
1028
  });
1399
1029
  }
1400
- return this.#getAssetsTracked(accounts, options);
1030
+ const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
1031
+ return result;
1401
1032
  }
1402
- get #getAssetsTracked() { return _private_getAssetsTracked_descriptor.value; }
1403
1033
  /**
1404
1034
  * Force-fetch spot prices for an explicit asset list.
1405
1035
  *
@@ -1414,9 +1044,7 @@ let AssetsController = (() => {
1414
1044
  * @param assetIds - CAIP-19 asset IDs to sync.
1415
1045
  */
1416
1046
  async syncAssetsPrices(assetIds) {
1417
- if (!this.#hasSources ||
1418
- !this.#isBasicFunctionality() ||
1419
- assetIds.length === 0) {
1047
+ if (!this.#isBasicFunctionality() || assetIds.length === 0) {
1420
1048
  return;
1421
1049
  }
1422
1050
  const assetsPrice = await this.#priceDataSource.fetchAssetPrices(assetIds);
@@ -2071,7 +1699,7 @@ let AssetsController = (() => {
2071
1699
  previousCurrency,
2072
1700
  selectedCurrency,
2073
1701
  });
2074
- if (!this.#hasSources || !this.#isBasicFunctionality()) {
1702
+ if (!this.#isBasicFunctionality()) {
2075
1703
  return;
2076
1704
  }
2077
1705
  // Currency changed — old cached prices are in the wrong currency.
@@ -2091,7 +1719,7 @@ let AssetsController = (() => {
2091
1719
  * @param chainIds - Chain IDs to filter prices for.
2092
1720
  */
2093
1721
  subscribeAssetsPrice(accounts, chainIds) {
2094
- if (!this.#hasSources || !this.#isBasicFunctionality()) {
1722
+ if (!this.#isBasicFunctionality()) {
2095
1723
  return;
2096
1724
  }
2097
1725
  const subscriptionKey = 'ds:PriceDataSource';
@@ -2266,7 +1894,7 @@ let AssetsController = (() => {
2266
1894
  * @returns Array of native asset IDs, one per enabled chain that has a registered identifier.
2267
1895
  */
2268
1896
  #getNativeAssetIdsForEnabledChains() {
2269
- return this.#resolveNativeAssetIds(this.#getEnabledChains());
1897
+ return this.#resolveNativeAssetIds(this.#enabledChains);
2270
1898
  }
2271
1899
  /**
2272
1900
  * Returns native asset IDs for the chains that this account supports
@@ -2362,7 +1990,7 @@ let AssetsController = (() => {
2362
1990
  // why mUSD appears on mainnet/Linea immediately (those are normally
2363
1991
  // enabled at startup) but only appears on Monad once the user
2364
1992
  // turns the Monad network on.
2365
- const candidateChains = chainsToSeed ?? [...this.#getEnabledChains()];
1993
+ const candidateChains = chainsToSeed ?? [...this.#enabledChains];
2366
1994
  const targetChains = candidateChains.filter((chainId) => CHAINS_WITH_DEFAULT_TRACKED_ASSETS.has(chainId));
2367
1995
  if (targetChains.length === 0) {
2368
1996
  return;
@@ -2597,19 +2225,10 @@ let AssetsController = (() => {
2597
2225
  releaseLock();
2598
2226
  }
2599
2227
  }
2600
- /**
2601
- * Read combined assets from state.
2602
- *
2603
- * @param accounts - Accounts to read.
2604
- * @param chainIds - Chains to include. `undefined` includes every chain.
2605
- * @param assetTypes - Asset types to include.
2606
- * @returns Assets keyed by account ID and asset ID.
2607
- */
2608
2228
  #getAssetsFromState(accounts, chainIds, assetTypes) {
2609
2229
  const result = Object.create(null);
2610
- // Convert to Sets for O(1) lookups. An undefined list is not a filter:
2611
- // `new Set(undefined)` is empty and would hide every asset.
2612
- const chainIdSet = chainIds === undefined ? undefined : new Set(chainIds);
2230
+ // Convert to Sets for O(1) lookups
2231
+ const chainIdSet = new Set(chainIds);
2613
2232
  const assetTypeSet = new Set(assetTypes);
2614
2233
  for (const account of accounts) {
2615
2234
  result[account.id] = Object.create(null);
@@ -2734,9 +2353,9 @@ let AssetsController = (() => {
2734
2353
  * Idempotent — returns early if accounts/chains are not yet available or
2735
2354
  * subscriptions are already active.
2736
2355
  */
2737
- #startTracking() {
2356
+ #start() {
2738
2357
  const accounts = this.#getSelectedAccounts();
2739
- const chainIds = [...this.#getEnabledChains()];
2358
+ const chainIds = [...this.#enabledChains];
2740
2359
  if (accounts.length === 0 || chainIds.length === 0) {
2741
2360
  return;
2742
2361
  }
@@ -2760,16 +2379,13 @@ let AssetsController = (() => {
2760
2379
  * Stop asset tracking: unsubscribe from all updates.
2761
2380
  * Called when app closes or keyring locks.
2762
2381
  */
2763
- #stopTracking() {
2382
+ #stop() {
2764
2383
  log('Stopping asset tracking', {
2765
2384
  activeSubscriptionCount: this.#activeSubscriptions.size,
2766
2385
  hasPriceSubscription: this.#activeSubscriptions.has('ds:PriceDataSource'),
2767
2386
  });
2768
2387
  this.#firstInitFetchReported = false;
2769
2388
  this.#stateSizeReported = false;
2770
- if (!this.#hasSources) {
2771
- return;
2772
- }
2773
2389
  // Stop price subscription first (uses direct messenger call)
2774
2390
  this.unsubscribeAssetsPrice();
2775
2391
  // Stop balance subscriptions by properly notifying data sources via messenger
@@ -2803,15 +2419,7 @@ let AssetsController = (() => {
2803
2419
  * @param _isBasic - The new value (for call-site clarity; the getter is the source of truth).
2804
2420
  */
2805
2421
  handleBasicFunctionalityChange(_isBasic) {
2806
- // Data sources exist before `#isBootstrapped` is set. A synchronous
2807
- // `onChange` from the host subscribe callback lands in that window.
2808
- // Subscribing here would fill `#activeSubscriptions` and make
2809
- // `#startTracking` skip the startup refresh. `#updateActive` subscribes
2810
- // afterwards with the current basic-functionality setting.
2811
- if (!this.#hasSources || !this.#isBootstrapped) {
2812
- return;
2813
- }
2814
- this.#stopTracking();
2422
+ this.#stop();
2815
2423
  this.#subscribeAssets();
2816
2424
  }
2817
2425
  /**
@@ -2820,13 +2428,10 @@ let AssetsController = (() => {
2820
2428
  * @param options - Subscription options.
2821
2429
  * @param options.skipInitialFetch - When true, AccountsApi skips its
2822
2430
  * one-shot subscribe poll (use after a force `getAssets` for the same scope).
2823
- * @param options.chainIds - Chains to subscribe. Defaults to the enabled
2824
- * chains from NetworkEnablementController. The enablement-change handler
2825
- * passes the chains from that event.
2826
2431
  */
2827
2432
  #subscribeAssets(options) {
2828
2433
  const accounts = this.#getSelectedAccounts();
2829
- const enabledChains = options?.chainIds ?? [...this.#getEnabledChains()];
2434
+ const enabledChains = [...this.#enabledChains];
2830
2435
  if (accounts.length === 0 || enabledChains.length === 0) {
2831
2436
  return;
2832
2437
  }
@@ -3123,7 +2728,7 @@ let AssetsController = (() => {
3123
2728
  // Wildcard scope (e.g., "eip155:0" means all enabled chains in that namespace)
3124
2729
  if (reference === '0') {
3125
2730
  // Add enabled chains
3126
- for (const chain of this.#getEnabledChains()) {
2731
+ for (const chain of this.#enabledChains) {
3127
2732
  if (isCaipChainId(chain)) {
3128
2733
  const chainParsed = parseCaipChainId(chain);
3129
2734
  if (chainParsed.namespace === namespace) {
@@ -3158,7 +2763,7 @@ let AssetsController = (() => {
3158
2763
  if (!groupId) {
3159
2764
  return;
3160
2765
  }
3161
- // First start is owned by `AccountTreeController:initialized` / `#startTracking`.
2766
+ // First start is owned by `AccountTreeController:initialized` / `#start`.
3162
2767
  // ATC also re-publishes `selectedAccountGroupChange` on every `init()`
3163
2768
  // (including when the group did not change) so late subscribers can catch
3164
2769
  // up — ignore those until we are already tracking.
@@ -3181,7 +2786,7 @@ let AssetsController = (() => {
3181
2786
  this.#ensureDefaultTrackedAssetsSeeded();
3182
2787
  if (accounts.length > 0) {
3183
2788
  await this.getAssets(accounts, {
3184
- chainIds: [...this.#getEnabledChains()],
2789
+ chainIds: [...this.#enabledChains],
3185
2790
  forceUpdate: true,
3186
2791
  });
3187
2792
  }
@@ -3191,11 +2796,26 @@ let AssetsController = (() => {
3191
2796
  releaseLock();
3192
2797
  }
3193
2798
  }
3194
- async #handleEnabledNetworksChanged(enabledNetworkMap, patches) {
3195
- const enabledChains = this.#extractEnabledChains(enabledNetworkMap);
3196
- const { addedChains, removedChains } = this.#diffEnabledChains(patches);
2799
+ async #handleEnabledNetworksChanged(enabledNetworkMap) {
2800
+ const previousChains = this.#enabledChains;
2801
+ this.#enabledChains = this.#extractEnabledChains(enabledNetworkMap);
2802
+ // Find newly enabled chains (in new set but not in previous)
2803
+ const addedChains = [];
2804
+ for (const chain of this.#enabledChains) {
2805
+ if (!previousChains.has(chain)) {
2806
+ addedChains.push(chain);
2807
+ }
2808
+ }
2809
+ // Find disabled chains to clean up (in previous but not in new)
2810
+ const removedChains = [];
2811
+ for (const chain of previousChains) {
2812
+ if (!this.#enabledChains.has(chain)) {
2813
+ removedChains.push(chain);
2814
+ }
2815
+ }
3197
2816
  log('Enabled networks changed', {
3198
- newCount: enabledChains.size,
2817
+ previousCount: previousChains.size,
2818
+ newCount: this.#enabledChains.size,
3199
2819
  addedChains,
3200
2820
  removedChains,
3201
2821
  });
@@ -3207,9 +2827,8 @@ let AssetsController = (() => {
3207
2827
  if (addedChains.length > 0) {
3208
2828
  this.#ensureDefaultTrackedAssetsSeeded(addedChains);
3209
2829
  }
3210
- // Refresh subscriptions for the chain set from this event. Later reads use
3211
- // NetworkEnablementController state, which is already this map in production.
3212
- this.#subscribeAssets({ chainIds: [...enabledChains] });
2830
+ // Refresh subscriptions for new chain set
2831
+ this.#subscribeAssets();
3213
2832
  // One-time fetch for newly enabled chains. v6 `full` replace is scoped to
3214
2833
  // those chains; existing balances on other chains are left untouched.
3215
2834
  if (addedChains.length > 0 && accounts.length > 0) {
@@ -3366,12 +2985,6 @@ let AssetsController = (() => {
3366
2985
  assetsBalance: response.assetsBalance,
3367
2986
  assetsPrice: response.assetsPrice,
3368
2987
  });
3369
- if (!this.#hasSources) {
3370
- log('Ignoring assets update: data sources have not been created', {
3371
- sourceId,
3372
- });
3373
- return;
3374
- }
3375
2988
  if (this.#isBalanceV6Enabled()) {
3376
2989
  await this.#handleAssetsUpdateV6(response, sourceId, request);
3377
2990
  return;
@@ -3524,20 +3137,17 @@ let AssetsController = (() => {
3524
3137
  // ============================================================================
3525
3138
  destroy() {
3526
3139
  log('Destroying AssetsController', {
3527
- isBootstrapped: this.#isBootstrapped,
3140
+ dataSourceCount: this.#allBalanceDataSources.length,
3528
3141
  subscriptionCount: this.#activeSubscriptions.size,
3529
3142
  });
3530
- this.#isDestroyed = true;
3531
- // Destroy instantiated data sources (none exist before the UI first opens)
3532
- if (this.#hasSources) {
3533
- this.#accountActivityDataSource.destroy();
3534
- this.#accountsApiDataSource.destroy();
3535
- this.#snapDataSource.destroy();
3536
- this.#rpcDataSource.destroy();
3537
- this.#stakedBalanceDataSource.destroy();
3538
- }
3143
+ // Destroy instantiated data sources
3144
+ this.#accountActivityDataSource?.destroy?.();
3145
+ this.#accountsApiDataSource?.destroy?.();
3146
+ this.#snapDataSource?.destroy?.();
3147
+ this.#rpcDataSource?.destroy?.();
3148
+ this.#stakedBalanceDataSource?.destroy?.();
3539
3149
  // Stop all active subscriptions
3540
- this.#stopTracking();
3150
+ this.#stop();
3541
3151
  if (this.#unsubscribeBasicFunctionality) {
3542
3152
  this.#unsubscribeBasicFunctionality();
3543
3153
  this.#unsubscribeBasicFunctionality = null;