@metamask-previews/assets-controller 20.2.1-preview-686445658 → 20.2.1-preview-d44afa95d

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';
@@ -306,43 +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 once they have been read.
320
- // Before that, `#enabledChains` is empty because it has not been
321
- // initialized. `undefined` means "do not filter by chain".
322
- const chainIds = options?.chainIds ??
323
- (this.#hasInitializedEnabledChains
324
- ? [...this.#enabledChains]
325
- : undefined);
326
- const assetTypes = options?.assetTypes ?? ['fungible'];
327
- const dataTypes = options?.dataTypes ?? ['balance', 'metadata', 'price'];
328
- if (accounts.length === 0 || chainIds?.length === 0) {
329
- return this.#getAssetsFromState(accounts, chainIds, assetTypes);
330
- }
331
- if (options?.forceUpdate && chainIds) {
332
- await this.#forceUpdateAssets({
333
- accounts,
334
- chainIds,
335
- requestOptions: {
336
- assetTypes,
337
- dataTypes,
338
- forceUpdate: true,
339
- bypassServerCache: options.bypassServerCache,
340
- },
341
- });
342
- }
343
- const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
344
- return result;
345
- }, "#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);
346
344
  if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
347
345
  }
348
346
  /** Whether the controller is enabled */
@@ -417,10 +415,10 @@ let AssetsController = (() => {
417
415
  */
418
416
  #activeSubscriptions = new Map();
419
417
  /**
420
- * Guards against `#startTracking()` re-entrancy. `#activeSubscriptions` only
418
+ * Guards against `#start()` re-entrancy. `#activeSubscriptions` only
421
419
  * becomes non-empty once `#runStartupRefresh()`'s forced `getAssets()`
422
420
  * call resolves, which can take many seconds for accounts with many
423
- * chains/snaps. `#startTracking()` is invoked by `#updateActive()`, which is
421
+ * chains/snaps. `#start()` is invoked by `#updateActive()`, which is
424
422
  * wired to several independent events (e.g. keyring unlock, account tree
425
423
  * init, client state change). If a second such event fires before the
426
424
  * first `getAssets()` call resolves, the `#activeSubscriptions.size > 0`
@@ -430,12 +428,6 @@ let AssetsController = (() => {
430
428
  #startInFlight = false;
431
429
  /** Currently enabled chains from NetworkEnablementController */
432
430
  #enabledChains = new Set();
433
- /**
434
- * Whether `#enabledChains` has been read from NetworkEnablementController.
435
- * Until then the set is empty because it has not been initialized, not
436
- * because every network is disabled.
437
- */
438
- #hasInitializedEnabledChains = false;
439
431
  /**
440
432
  * Get the currently selected accounts from AccountTreeController.
441
433
  * This includes all accounts in the same group as the selected account
@@ -478,49 +470,11 @@ let AssetsController = (() => {
478
470
  #isKeyringUnlocked() {
479
471
  return this.messenger.call('KeyringController:isUnlocked');
480
472
  }
481
- /**
482
- * Data sources and middlewares. Created the first time the UI opens, not by
483
- * the constructor: their constructors read other controllers (network,
484
- * snaps, feature flags), which may not be registered yet when this
485
- * controller is constructed.
486
- */
487
- #sources;
488
- /** Options forwarded to the data sources when they are created. */
489
- #sourceOptions;
490
- /** The pending or settled bootstrap, so it runs at most once. */
491
- #bootstrapPromise;
492
- /** Whether the bootstrap has finished. */
493
- #isBootstrapped = false;
494
- /** Whether `destroy()` has been called. */
495
- #isDestroyed = false;
496
- /**
497
- * Get the data sources, throwing if they have not been created yet.
498
- * Entry points that can run before the UI first opens check `#sources`
499
- * first.
500
- *
501
- * @returns The data sources and middlewares.
502
- */
503
- #getSources() {
504
- if (!this.#sources) {
505
- throw new Error('AssetsController data sources have not been created yet. They are created when the UI first opens.');
506
- }
507
- return this.#sources;
508
- }
509
- get #accountActivityDataSource() {
510
- return this.#getSources().accountActivityDataSource;
511
- }
512
- get #accountsApiDataSource() {
513
- return this.#getSources().accountsApiDataSource;
514
- }
515
- get #snapDataSource() {
516
- return this.#getSources().snapDataSource;
517
- }
518
- get #rpcDataSource() {
519
- return this.#getSources().rpcDataSource;
520
- }
521
- get #stakedBalanceDataSource() {
522
- return this.#getSources().stakedBalanceDataSource;
523
- }
473
+ #accountActivityDataSource;
474
+ #accountsApiDataSource;
475
+ #snapDataSource;
476
+ #rpcDataSource;
477
+ #stakedBalanceDataSource;
524
478
  /**
525
479
  * All balance data sources in priority order for chain-claiming and cleanup.
526
480
  * Note: StakedBalanceDataSource is excluded because it provides supplementary
@@ -536,18 +490,10 @@ let AssetsController = (() => {
536
490
  this.#rpcDataSource,
537
491
  ];
538
492
  }
539
- get #priceDataSource() {
540
- return this.#getSources().priceDataSource;
541
- }
542
- get #customAssetGraduationMiddleware() {
543
- return this.#getSources().customAssetGraduationMiddleware;
544
- }
545
- get #rpcFallbackMiddleware() {
546
- return this.#getSources().rpcFallbackMiddleware;
547
- }
548
- get #tokenDataSource() {
549
- return this.#getSources().tokenDataSource;
550
- }
493
+ #priceDataSource;
494
+ #customAssetGraduationMiddleware;
495
+ #rpcFallbackMiddleware;
496
+ #tokenDataSource;
551
497
  #unsubscribeBasicFunctionality = null;
552
498
  #queryApiClient;
553
499
  #onActiveChainsUpdated;
@@ -589,126 +535,12 @@ let AssetsController = (() => {
589
535
  });
590
536
  }
591
537
  };
592
- this.#sourceOptions = {
593
- queryApiClient,
594
- rpcDataSourceConfig: rpcConfig,
595
- accountsApiDataSourceConfig,
596
- priceDataSourceConfig,
597
- stakedBalanceDataSourceConfig,
598
- isOnboarded,
599
- subscribeToBasicFunctionalityChange,
600
- };
601
- log('Initializing AssetsController', {
602
- defaultUpdateInterval: this.#defaultUpdateInterval,
603
- });
604
- // The constructor only registers action handlers and subscribes to
605
- // events; it never calls another controller, so it does not depend on the
606
- // order in which controllers are constructed. Reading other controllers
607
- // and creating the data sources happen the first time the UI opens.
608
- this.#registerActionHandlers();
609
- this.#subscribeToEvents();
610
- }
611
- // ============================================================================
612
- // INITIALIZATION
613
- // ============================================================================
614
- /**
615
- * Bootstrap the controller the first time the UI is seen open, then start
616
- * or stop asset tracking. Runs at most once; later calls share the same
617
- * promise.
618
- *
619
- * @returns A promise that resolves once the controller is bootstrapped.
620
- */
621
- async #ensureBootstrapped() {
622
- this.#bootstrapPromise ??= this.#bootstrap().catch((error) => {
623
- // Allow a later lifecycle event to retry when the bootstrap failed
624
- // before the data sources were created (e.g. a controller it reads was
625
- // not registered yet).
626
- if (!this.#sources) {
627
- this.#bootstrapPromise = undefined;
628
- }
629
- throw error;
630
- });
631
- return this.#bootstrapPromise;
632
- }
633
- /**
634
- * Read enabled networks, create the data sources, subscribe to
635
- * basic-functionality changes, wait for the Accounts API supported networks
636
- * and run the unlock cleanups when the keyring is already unlocked. Then
637
- * start asset tracking if the keyring is unlocked and the account tree is
638
- * initialized.
639
- *
640
- * By the time the UI opens, the client has registered every controller this
641
- * one depends on, so reading them here is safe.
642
- */
643
- async #bootstrap() {
644
- if (this.#isDestroyed) {
645
- return;
646
- }
647
- log('Bootstrapping AssetsController');
648
- this.#initializeState();
649
- this.#sources = this.#createSources();
650
- this.#subscribeToBasicFunctionality();
651
- await Promise.all([
652
- // AccountsApiDataSource fetches its supported networks asynchronously
653
- // from its constructor. Wait for them so the first forced fetch can use
654
- // the Accounts API instead of routing every chain to the slow lane.
655
- // `fetchQuery` shares the in-flight request, so this does not issue a
656
- // second one. Failures are logged by the data source and do not reject.
657
- this.#sources.accountsApiDataSource.refreshActiveChains(),
658
- this.#runUnlockCleanupsIfUnlocked(),
659
- ]);
660
- if (this.#isDestroyed) {
661
- return;
662
- }
663
- // Chain updates reported while bootstrapping are ignored; `#updateActive`
664
- // subscribes with every source's current chains.
665
- this.#isBootstrapped = true;
666
- this.#updateActive();
667
- }
668
- /**
669
- * Run the unlock cleanups when the keyring is already unlocked. The
670
- * `KeyringController:unlock` handler skips them before the bootstrap, so an
671
- * unlock that happened earlier is handled here.
672
- */
673
- async #runUnlockCleanupsIfUnlocked() {
674
- if (!this.#isKeyringUnlocked()) {
675
- return;
676
- }
677
- await this.#runUnlockCleanups();
678
- }
679
- /**
680
- * Run the cleanups that happen on unlock: drop balances outside the
681
- * selected accounts' scopes, then remove spam tokens.
682
- */
683
- async #runUnlockCleanups() {
684
- try {
685
- this.#runOutOfScopeBalanceCleanup();
686
- }
687
- catch {
688
- /* Do nothing */
689
- }
690
- await this.#runSpamCleanup().catch(() => {
691
- /* Do nothing */
692
- });
693
- }
694
- /**
695
- * Create every data source and middleware.
696
- *
697
- * Data source constructors read other controllers and may report active
698
- * chains synchronously. `#handleActiveChainsUpdate` ignores those reports
699
- * until the bootstrap finishes, and `#updateActive` subscribes afterwards
700
- * with every source's chains.
701
- *
702
- * @returns The data sources and middlewares.
703
- */
704
- #createSources() {
705
- const { queryApiClient, rpcDataSourceConfig, accountsApiDataSourceConfig, priceDataSourceConfig, stakedBalanceDataSourceConfig, isOnboarded, } = this.#sourceOptions;
706
- const accountActivityDataSource = new AccountActivityDataSource({
538
+ this.#accountActivityDataSource = new AccountActivityDataSource({
707
539
  messenger: this.messenger,
708
540
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
709
- onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, accountActivityDataSource.getName(), request),
541
+ onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, this.#accountActivityDataSource.getName(), request),
710
542
  });
711
- const accountsApiDataSource = new AccountsApiDataSource({
543
+ this.#accountsApiDataSource = new AccountsApiDataSource({
712
544
  messenger: this.messenger,
713
545
  queryApiClient,
714
546
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
@@ -717,7 +549,7 @@ let AssetsController = (() => {
717
549
  getAssetsState: () => this.state,
718
550
  getAssetVisibility: this.#getAssetVisibility.bind(this),
719
551
  });
720
- const snapDataSource = new SnapDataSource({
552
+ this.#snapDataSource = new SnapDataSource({
721
553
  messenger: this.messenger,
722
554
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
723
555
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
@@ -725,7 +557,7 @@ let AssetsController = (() => {
725
557
  getAssetVisibility: this.#getAssetVisibility.bind(this),
726
558
  getAssetsState: () => this.state,
727
559
  });
728
- const rpcDataSource = new RpcDataSource({
560
+ this.#rpcDataSource = new RpcDataSource({
729
561
  messenger: this.messenger,
730
562
  getAssetsState: () => this.state,
731
563
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
@@ -733,16 +565,16 @@ let AssetsController = (() => {
733
565
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
734
566
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
735
567
  queryApiClient,
736
- ...rpcDataSourceConfig,
737
- isOnboarded: rpcDataSourceConfig.isOnboarded ?? isOnboarded,
568
+ ...rpcConfig,
569
+ isOnboarded: rpcConfig.isOnboarded ?? isOnboarded,
738
570
  getAssetType: (assetId) => this.#getAssetType(assetId),
739
571
  });
740
- const stakedBalanceDataSource = new StakedBalanceDataSource({
572
+ this.#stakedBalanceDataSource = new StakedBalanceDataSource({
741
573
  messenger: this.messenger,
742
574
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
743
575
  ...stakedBalanceDataSourceConfig,
744
576
  });
745
- const tokenDataSource = new TokenDataSource(this.messenger, {
577
+ this.#tokenDataSource = new TokenDataSource(this.messenger, {
746
578
  queryApiClient,
747
579
  getNativeAssetIds: () => {
748
580
  return this.#getNativeAssetIdsForEnabledChains();
@@ -750,13 +582,13 @@ let AssetsController = (() => {
750
582
  getAssetType: (assetId) => this.#getAssetType(assetId),
751
583
  getAssetsState: () => this.state,
752
584
  });
753
- const priceDataSource = new PriceDataSource({
585
+ this.#priceDataSource = new PriceDataSource({
754
586
  queryApiClient,
755
587
  getSelectedCurrency: () => this.state.selectedCurrency,
756
588
  getAssetsState: () => this.state,
757
589
  ...priceDataSourceConfig,
758
590
  });
759
- const customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
591
+ this.#customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
760
592
  getSelectedAccountId: () => {
761
593
  try {
762
594
  return this.#getSelectedAccounts()[0]?.id;
@@ -768,39 +600,30 @@ let AssetsController = (() => {
768
600
  removeCustomAsset: (accountId, assetId) => this.removeCustomAsset(accountId, assetId),
769
601
  getAssetsState: () => this.state,
770
602
  });
771
- const rpcFallbackMiddleware = new RpcFallbackMiddleware({
772
- rpcDataSource,
603
+ this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
604
+ rpcDataSource: this.#rpcDataSource,
773
605
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
774
606
  getAssetsState: () => this.state,
775
607
  });
776
- return {
777
- accountActivityDataSource,
778
- accountsApiDataSource,
779
- snapDataSource,
780
- rpcDataSource,
781
- stakedBalanceDataSource,
782
- tokenDataSource,
783
- priceDataSource,
784
- customAssetGraduationMiddleware,
785
- rpcFallbackMiddleware,
786
- };
787
- }
788
- /**
789
- * Subscribe to the host's basic-functionality setting, if the host provided
790
- * a way to. Runs during the bootstrap, after the data sources exist and
791
- * before `#isBootstrapped` is set. A synchronous `onChange` is ignored
792
- * until the bootstrap finishes; `#updateActive` subscribes afterwards.
793
- */
794
- #subscribeToBasicFunctionality() {
795
- const { subscribeToBasicFunctionalityChange } = this.#sourceOptions;
796
- if (!subscribeToBasicFunctionalityChange) {
797
- return;
798
- }
799
- const unsubscribe = subscribeToBasicFunctionalityChange((isBasic) => this.handleBasicFunctionalityChange(isBasic));
800
- if (typeof unsubscribe === 'function') {
801
- 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
+ }
802
622
  }
803
623
  }
624
+ // ============================================================================
625
+ // INITIALIZATION
626
+ // ============================================================================
804
627
  #initializeNativeAssetsMap(queryApiClient) {
805
628
  queryApiClient.queryClient
806
629
  .fetchQuery({
@@ -824,7 +647,6 @@ let AssetsController = (() => {
824
647
  #initializeState() {
825
648
  const { enabledNetworkMap } = this.messenger.call('NetworkEnablementController:getState');
826
649
  this.#enabledChains = this.#extractEnabledChains(enabledNetworkMap);
827
- this.#hasInitializedEnabledChains = true;
828
650
  log('Initialized state', {
829
651
  enabledNetworkMap,
830
652
  enabledChains: this.#enabledChains,
@@ -875,21 +697,8 @@ let AssetsController = (() => {
875
697
  }
876
698
  return reference;
877
699
  }
878
- /**
879
- * Subscribe to every external event. Runs from the constructor: subscribing
880
- * does not need the publishing controller to exist yet, so this does not
881
- * depend on construction order.
882
- *
883
- * Lifecycle events (client, keyring, account tree) drive `#updateActive`,
884
- * which bootstraps the controller the first time the UI is seen open.
885
- * Every other event needs the data sources, so it is ignored until they
886
- * exist.
887
- */
888
700
  #subscribeToEvents() {
889
701
  this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId, previousGroupId) => {
890
- if (!this.#sources) {
891
- return;
892
- }
893
702
  this.#handleAccountGroupChanged(groupId, previousGroupId).catch(console.error);
894
703
  });
895
704
  this.messenger.subscribe('AccountTreeController:initialized', () => {
@@ -900,9 +709,6 @@ let AssetsController = (() => {
900
709
  });
901
710
  // Subscribe to network enablement changes (only enabledNetworkMap)
902
711
  this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }) => {
903
- if (!this.#sources) {
904
- return;
905
- }
906
712
  this.#handleEnabledNetworksChanged(enabledNetworkMap).catch(console.error);
907
713
  });
908
714
  // When a network is added or removed from NetworkController, refresh
@@ -912,46 +718,34 @@ let AssetsController = (() => {
912
718
  // entries appear immediately without waiting for it to also be
913
719
  // enabled in NetworkEnablementController.
914
720
  this.messenger.subscribe('NetworkController:networkAdded', (networkConfiguration) => {
915
- if (!this.#sources) {
916
- return;
917
- }
918
721
  this.#handleNetworkAdded(networkConfiguration.chainId);
919
722
  this.#refreshAssetsAfterNetworkAdded(networkConfiguration.chainId).catch((error) => {
920
723
  log('Failed to refresh assets after network added', { error });
921
724
  });
922
725
  });
923
726
  this.messenger.subscribe('NetworkController:networkRemoved', () => {
924
- if (!this.#sources) {
925
- return;
926
- }
927
727
  this.#refreshAssetsAfterNetworkChange();
928
728
  });
929
729
  // Selected EVM network switch (network picker). Enablement changes are
930
730
  // handled separately via NetworkEnablementController:stateChange.
931
731
  this.messenger.subscribe('NetworkController:networkDidChange', (networkState) => {
932
- if (!this.#sources) {
933
- return;
934
- }
935
732
  this.#handleNetworkDidChange(networkState).catch(console.error);
936
733
  });
937
- // Client + Keyring lifecycle: only run when UI is open AND keyring is
938
- // 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
939
735
  this.messenger.subscribe('ClientController:stateChange', () => {
940
736
  this.#updateActive();
941
737
  }, clientControllerSelectors.selectIsUiOpen);
942
738
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
943
739
  this.messenger.subscribe('KeyringController:unlock', async () => {
944
- // Wait for an in-flight bootstrap: it may have checked the keyring
945
- // before this unlock and skipped the cleanups. Once bootstrapped, the
946
- // cleanups start synchronously, as before.
947
- if (!this.#isBootstrapped && this.#bootstrapPromise) {
948
- await this.#bootstrapPromise.catch(() => undefined);
740
+ try {
741
+ this.#runOutOfScopeBalanceCleanup();
949
742
  }
950
- if (this.#isBootstrapped) {
951
- await this.#runUnlockCleanups();
743
+ catch {
744
+ /* Do nothing */
952
745
  }
953
- // Before the bootstrap, this bootstraps the controller if the UI is
954
- // open, and the bootstrap runs the cleanups.
746
+ await this.#runSpamCleanup().catch(() => {
747
+ /* Do nothing */
748
+ });
955
749
  this.#updateActive();
956
750
  });
957
751
  this.messenger.subscribe('KeyringController:lock', () => {
@@ -961,9 +755,6 @@ let AssetsController = (() => {
961
755
  // Ensures balances for the account making the transaction are updated
962
756
  // (e.g. for gas estimations), except on AccountActivity-active chains.
963
757
  this.messenger.subscribe('TransactionController:unapprovedTransactionAdded', (transactionMeta) => {
964
- if (!this.#sources) {
965
- return;
966
- }
967
758
  this.#refreshAssetsForEVMTransaction(transactionMeta);
968
759
  });
969
760
  // Post-tx refresh via the full fetch pipeline (Accounts API + RPC fallback).
@@ -971,9 +762,6 @@ let AssetsController = (() => {
971
762
  // RpcDataSource also listens for transactionConfirmed, but only refreshes
972
763
  // chains it owns via an active subscription.
973
764
  this.messenger.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
974
- if (!this.#sources) {
975
- return;
976
- }
977
765
  this.#refreshAssetsForEVMTransaction(transactionMeta);
978
766
  });
979
767
  // Non-EVM equivalent of the above: Snap keyrings report transaction
@@ -981,9 +769,6 @@ let AssetsController = (() => {
981
769
  // not covered by AccountActivity (WebSocket down / unsupported), refresh
982
770
  // via the Accounts API with the server cache bypassed.
983
771
  this.messenger.subscribe('MultichainTransactionsController:transactionConfirmed', (transaction) => {
984
- if (!this.#sources) {
985
- return;
986
- }
987
772
  this.#refreshAssetsForNonEvmTransaction(transaction);
988
773
  });
989
774
  }
@@ -1109,33 +894,16 @@ let AssetsController = (() => {
1109
894
  * Start or stop asset tracking based on client (UI) open state, keyring
1110
895
  * unlock state, and account-tree readiness. Only runs when the UI is open,
1111
896
  * the keyring is unlocked, and the account tree has finished `init()`.
1112
- *
1113
- * Before the bootstrap, this only bootstraps the controller when the UI is
1114
- * open. It reads other controllers only when one of their events fires, by
1115
- * which point they are registered.
1116
897
  */
1117
898
  #updateActive() {
1118
- if (this.#isDestroyed) {
1119
- return;
1120
- }
1121
- if (!this.#isBootstrapped) {
1122
- // Bootstrap the first time the UI is seen open. The bootstrap calls
1123
- // back into `#updateActive` once it finishes.
1124
- if (this.#isUiOpen()) {
1125
- this.#ensureBootstrapped().catch((error) => {
1126
- log('Failed to bootstrap AssetsController', { error });
1127
- });
1128
- }
1129
- return;
1130
- }
1131
899
  const shouldRun = this.#isUiOpen() &&
1132
900
  this.#isKeyringUnlocked() &&
1133
901
  this.#isAccountTreeInitialized();
1134
902
  if (shouldRun) {
1135
- this.#startTracking();
903
+ this.#start();
1136
904
  }
1137
905
  else {
1138
- this.#stopTracking();
906
+ this.#stop();
1139
907
  }
1140
908
  }
1141
909
  /**
@@ -1187,13 +955,6 @@ let AssetsController = (() => {
1187
955
  * @param previousChains - Previous chains; used to compute added/removed.
1188
956
  */
1189
957
  #handleActiveChainsUpdate(dataSourceId, activeChains, previousChains) {
1190
- // Data sources report their chains while the bootstrap is still running.
1191
- // The bootstrap subscribes afterwards with every source's chains.
1192
- // Subscribing here first would make `#startTracking` skip the startup
1193
- // refresh.
1194
- if (!this.#isBootstrapped) {
1195
- return;
1196
- }
1197
958
  if (!this.#isUiOpen() || !this.#isKeyringUnlocked() || !this.#isEnabled()) {
1198
959
  return;
1199
960
  }
@@ -1247,36 +1008,28 @@ let AssetsController = (() => {
1247
1008
  // ============================================================================
1248
1009
  // PUBLIC API: QUERY METHODS
1249
1010
  // ============================================================================
1250
- /**
1251
- * Get assets for the given accounts, optionally force-fetching them first.
1252
- *
1253
- * Before the UI first opens there are no data sources, so a forced fetch is
1254
- * skipped and the assets already in state are returned. Enabled networks
1255
- * have not been read yet, so an omitted `chainIds` includes every asset in
1256
- * state rather than treating the empty enabled-chain set as a filter. The
1257
- * loading status of the accounts is left untouched, so the first fetch
1258
- * afterwards still reports them as loading.
1259
- *
1260
- * @param accounts - Accounts to get assets for.
1261
- * @param options - Fetch options.
1262
- * @param options.chainIds - Chains to include. Defaults to the enabled chains once they have been read.
1263
- * @param options.assetTypes - Asset types to include. Defaults to fungible.
1264
- * @param options.forceUpdate - Fetch from the data sources before reading state.
1265
- * @param options.bypassServerCache - Also bypass server-side HTTP caches.
1266
- * @param options.dataTypes - Data types to fetch.
1267
- * @returns Assets keyed by account ID and asset ID.
1268
- */
1269
1011
  async getAssets(accounts, options) {
1270
- if (options?.forceUpdate && !this.#sources) {
1271
- log('Skipping forced asset fetch: data sources have not been created');
1272
- return this.#getAssetsTracked(accounts, {
1273
- ...options,
1274
- 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
+ },
1275
1028
  });
1276
1029
  }
1277
- return this.#getAssetsTracked(accounts, options);
1030
+ const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
1031
+ return result;
1278
1032
  }
1279
- get #getAssetsTracked() { return _private_getAssetsTracked_descriptor.value; }
1280
1033
  /**
1281
1034
  * Force-fetch spot prices for an explicit asset list.
1282
1035
  *
@@ -1291,9 +1044,7 @@ let AssetsController = (() => {
1291
1044
  * @param assetIds - CAIP-19 asset IDs to sync.
1292
1045
  */
1293
1046
  async syncAssetsPrices(assetIds) {
1294
- if (!this.#sources ||
1295
- !this.#isBasicFunctionality() ||
1296
- assetIds.length === 0) {
1047
+ if (!this.#isBasicFunctionality() || assetIds.length === 0) {
1297
1048
  return;
1298
1049
  }
1299
1050
  const assetsPrice = await this.#priceDataSource.fetchAssetPrices(assetIds);
@@ -1948,7 +1699,7 @@ let AssetsController = (() => {
1948
1699
  previousCurrency,
1949
1700
  selectedCurrency,
1950
1701
  });
1951
- if (!this.#sources || !this.#isBasicFunctionality()) {
1702
+ if (!this.#isBasicFunctionality()) {
1952
1703
  return;
1953
1704
  }
1954
1705
  // Currency changed — old cached prices are in the wrong currency.
@@ -1968,7 +1719,7 @@ let AssetsController = (() => {
1968
1719
  * @param chainIds - Chain IDs to filter prices for.
1969
1720
  */
1970
1721
  subscribeAssetsPrice(accounts, chainIds) {
1971
- if (!this.#sources || !this.#isBasicFunctionality()) {
1722
+ if (!this.#isBasicFunctionality()) {
1972
1723
  return;
1973
1724
  }
1974
1725
  const subscriptionKey = 'ds:PriceDataSource';
@@ -2474,19 +2225,10 @@ let AssetsController = (() => {
2474
2225
  releaseLock();
2475
2226
  }
2476
2227
  }
2477
- /**
2478
- * Read combined assets from state.
2479
- *
2480
- * @param accounts - Accounts to read.
2481
- * @param chainIds - Chains to include. `undefined` includes every chain.
2482
- * @param assetTypes - Asset types to include.
2483
- * @returns Assets keyed by account ID and asset ID.
2484
- */
2485
2228
  #getAssetsFromState(accounts, chainIds, assetTypes) {
2486
2229
  const result = Object.create(null);
2487
- // Convert to Sets for O(1) lookups. An undefined list is not a filter:
2488
- // `new Set(undefined)` is empty and would hide every asset.
2489
- const chainIdSet = chainIds === undefined ? undefined : new Set(chainIds);
2230
+ // Convert to Sets for O(1) lookups
2231
+ const chainIdSet = new Set(chainIds);
2490
2232
  const assetTypeSet = new Set(assetTypes);
2491
2233
  for (const account of accounts) {
2492
2234
  result[account.id] = Object.create(null);
@@ -2611,7 +2353,7 @@ let AssetsController = (() => {
2611
2353
  * Idempotent — returns early if accounts/chains are not yet available or
2612
2354
  * subscriptions are already active.
2613
2355
  */
2614
- #startTracking() {
2356
+ #start() {
2615
2357
  const accounts = this.#getSelectedAccounts();
2616
2358
  const chainIds = [...this.#enabledChains];
2617
2359
  if (accounts.length === 0 || chainIds.length === 0) {
@@ -2637,16 +2379,13 @@ let AssetsController = (() => {
2637
2379
  * Stop asset tracking: unsubscribe from all updates.
2638
2380
  * Called when app closes or keyring locks.
2639
2381
  */
2640
- #stopTracking() {
2382
+ #stop() {
2641
2383
  log('Stopping asset tracking', {
2642
2384
  activeSubscriptionCount: this.#activeSubscriptions.size,
2643
2385
  hasPriceSubscription: this.#activeSubscriptions.has('ds:PriceDataSource'),
2644
2386
  });
2645
2387
  this.#firstInitFetchReported = false;
2646
2388
  this.#stateSizeReported = false;
2647
- if (!this.#sources) {
2648
- return;
2649
- }
2650
2389
  // Stop price subscription first (uses direct messenger call)
2651
2390
  this.unsubscribeAssetsPrice();
2652
2391
  // Stop balance subscriptions by properly notifying data sources via messenger
@@ -2680,15 +2419,7 @@ let AssetsController = (() => {
2680
2419
  * @param _isBasic - The new value (for call-site clarity; the getter is the source of truth).
2681
2420
  */
2682
2421
  handleBasicFunctionalityChange(_isBasic) {
2683
- // Data sources exist before `#isBootstrapped` is set. A synchronous
2684
- // `onChange` from the host subscribe callback lands in that window.
2685
- // Subscribing here would fill `#activeSubscriptions` and make
2686
- // `#startTracking` skip the startup refresh. `#updateActive` subscribes
2687
- // afterwards with the current basic-functionality setting.
2688
- if (!this.#sources || !this.#isBootstrapped) {
2689
- return;
2690
- }
2691
- this.#stopTracking();
2422
+ this.#stop();
2692
2423
  this.#subscribeAssets();
2693
2424
  }
2694
2425
  /**
@@ -3032,7 +2763,7 @@ let AssetsController = (() => {
3032
2763
  if (!groupId) {
3033
2764
  return;
3034
2765
  }
3035
- // First start is owned by `AccountTreeController:initialized` / `#startTracking`.
2766
+ // First start is owned by `AccountTreeController:initialized` / `#start`.
3036
2767
  // ATC also re-publishes `selectedAccountGroupChange` on every `init()`
3037
2768
  // (including when the group did not change) so late subscribers can catch
3038
2769
  // up — ignore those until we are already tracking.
@@ -3254,12 +2985,6 @@ let AssetsController = (() => {
3254
2985
  assetsBalance: response.assetsBalance,
3255
2986
  assetsPrice: response.assetsPrice,
3256
2987
  });
3257
- if (!this.#sources) {
3258
- log('Ignoring assets update: data sources have not been created', {
3259
- sourceId,
3260
- });
3261
- return;
3262
- }
3263
2988
  if (this.#isBalanceV6Enabled()) {
3264
2989
  await this.#handleAssetsUpdateV6(response, sourceId, request);
3265
2990
  return;
@@ -3412,20 +3137,17 @@ let AssetsController = (() => {
3412
3137
  // ============================================================================
3413
3138
  destroy() {
3414
3139
  log('Destroying AssetsController', {
3415
- isBootstrapped: this.#isBootstrapped,
3140
+ dataSourceCount: this.#allBalanceDataSources.length,
3416
3141
  subscriptionCount: this.#activeSubscriptions.size,
3417
3142
  });
3418
- this.#isDestroyed = true;
3419
- // Destroy instantiated data sources (none exist before the UI first opens)
3420
- if (this.#sources) {
3421
- this.#sources.accountActivityDataSource.destroy();
3422
- this.#sources.accountsApiDataSource.destroy();
3423
- this.#sources.snapDataSource.destroy();
3424
- this.#sources.rpcDataSource.destroy();
3425
- this.#sources.stakedBalanceDataSource.destroy();
3426
- }
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?.();
3427
3149
  // Stop all active subscriptions
3428
- this.#stopTracking();
3150
+ this.#stop();
3429
3151
  if (this.#unsubscribeBasicFunctionality) {
3430
3152
  this.#unsubscribeBasicFunctionality();
3431
3153
  this.#unsubscribeBasicFunctionality = null;