@metamask-previews/assets-controller 20.2.1-preview-c3d36da85 → 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,37 +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
- const chainIds = options?.chainIds ?? [...this.#enabledChains];
320
- const assetTypes = options?.assetTypes ?? ['fungible'];
321
- const dataTypes = options?.dataTypes ?? ['balance', 'metadata', 'price'];
322
- if (accounts.length === 0 || chainIds.length === 0) {
323
- return this.#getAssetsFromState(accounts, chainIds, assetTypes);
324
- }
325
- if (options?.forceUpdate) {
326
- await this.#forceUpdateAssets({
327
- accounts,
328
- chainIds,
329
- requestOptions: {
330
- assetTypes,
331
- dataTypes,
332
- forceUpdate: true,
333
- bypassServerCache: options.bypassServerCache,
334
- },
335
- });
336
- }
337
- const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
338
- return result;
339
- }, "#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);
340
344
  if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
341
345
  }
342
346
  /** Whether the controller is enabled */
@@ -411,10 +415,10 @@ let AssetsController = (() => {
411
415
  */
412
416
  #activeSubscriptions = new Map();
413
417
  /**
414
- * Guards against `#startTracking()` re-entrancy. `#activeSubscriptions` only
418
+ * Guards against `#start()` re-entrancy. `#activeSubscriptions` only
415
419
  * becomes non-empty once `#runStartupRefresh()`'s forced `getAssets()`
416
420
  * call resolves, which can take many seconds for accounts with many
417
- * chains/snaps. `#startTracking()` is invoked by `#updateActive()`, which is
421
+ * chains/snaps. `#start()` is invoked by `#updateActive()`, which is
418
422
  * wired to several independent events (e.g. keyring unlock, account tree
419
423
  * init, client state change). If a second such event fires before the
420
424
  * first `getAssets()` call resolves, the `#activeSubscriptions.size > 0`
@@ -466,49 +470,11 @@ let AssetsController = (() => {
466
470
  #isKeyringUnlocked() {
467
471
  return this.messenger.call('KeyringController:isUnlocked');
468
472
  }
469
- /**
470
- * Data sources and middlewares. Created the first time the UI opens, not by
471
- * the constructor: their constructors read other controllers (network,
472
- * snaps, feature flags), which may not be registered yet when this
473
- * controller is constructed.
474
- */
475
- #sources;
476
- /** Options forwarded to the data sources when they are created. */
477
- #sourceOptions;
478
- /** The pending or settled bootstrap, so it runs at most once. */
479
- #bootstrapPromise;
480
- /** Whether the bootstrap has finished. */
481
- #isBootstrapped = false;
482
- /** Whether `destroy()` has been called. */
483
- #isDestroyed = false;
484
- /**
485
- * Get the data sources, throwing if they have not been created yet.
486
- * Entry points that can run before the UI first opens check `#sources`
487
- * first.
488
- *
489
- * @returns The data sources and middlewares.
490
- */
491
- #getSources() {
492
- if (!this.#sources) {
493
- throw new Error('AssetsController data sources have not been created yet. They are created when the UI first opens.');
494
- }
495
- return this.#sources;
496
- }
497
- get #accountActivityDataSource() {
498
- return this.#getSources().accountActivityDataSource;
499
- }
500
- get #accountsApiDataSource() {
501
- return this.#getSources().accountsApiDataSource;
502
- }
503
- get #snapDataSource() {
504
- return this.#getSources().snapDataSource;
505
- }
506
- get #rpcDataSource() {
507
- return this.#getSources().rpcDataSource;
508
- }
509
- get #stakedBalanceDataSource() {
510
- return this.#getSources().stakedBalanceDataSource;
511
- }
473
+ #accountActivityDataSource;
474
+ #accountsApiDataSource;
475
+ #snapDataSource;
476
+ #rpcDataSource;
477
+ #stakedBalanceDataSource;
512
478
  /**
513
479
  * All balance data sources in priority order for chain-claiming and cleanup.
514
480
  * Note: StakedBalanceDataSource is excluded because it provides supplementary
@@ -524,18 +490,10 @@ let AssetsController = (() => {
524
490
  this.#rpcDataSource,
525
491
  ];
526
492
  }
527
- get #priceDataSource() {
528
- return this.#getSources().priceDataSource;
529
- }
530
- get #customAssetGraduationMiddleware() {
531
- return this.#getSources().customAssetGraduationMiddleware;
532
- }
533
- get #rpcFallbackMiddleware() {
534
- return this.#getSources().rpcFallbackMiddleware;
535
- }
536
- get #tokenDataSource() {
537
- return this.#getSources().tokenDataSource;
538
- }
493
+ #priceDataSource;
494
+ #customAssetGraduationMiddleware;
495
+ #rpcFallbackMiddleware;
496
+ #tokenDataSource;
539
497
  #unsubscribeBasicFunctionality = null;
540
498
  #queryApiClient;
541
499
  #onActiveChainsUpdated;
@@ -577,126 +535,12 @@ let AssetsController = (() => {
577
535
  });
578
536
  }
579
537
  };
580
- this.#sourceOptions = {
581
- queryApiClient,
582
- rpcDataSourceConfig: rpcConfig,
583
- accountsApiDataSourceConfig,
584
- priceDataSourceConfig,
585
- stakedBalanceDataSourceConfig,
586
- isOnboarded,
587
- subscribeToBasicFunctionalityChange,
588
- };
589
- log('Initializing AssetsController', {
590
- defaultUpdateInterval: this.#defaultUpdateInterval,
591
- });
592
- // The constructor only registers action handlers and subscribes to
593
- // events; it never calls another controller, so it does not depend on the
594
- // order in which controllers are constructed. Reading other controllers
595
- // and creating the data sources happen the first time the UI opens.
596
- this.#registerActionHandlers();
597
- this.#subscribeToEvents();
598
- }
599
- // ============================================================================
600
- // INITIALIZATION
601
- // ============================================================================
602
- /**
603
- * Bootstrap the controller the first time the UI is seen open, then start
604
- * or stop asset tracking. Runs at most once; later calls share the same
605
- * promise.
606
- *
607
- * @returns A promise that resolves once the controller is bootstrapped.
608
- */
609
- async #ensureBootstrapped() {
610
- this.#bootstrapPromise ??= this.#bootstrap().catch((error) => {
611
- // Allow a later lifecycle event to retry when the bootstrap failed
612
- // before the data sources were created (e.g. a controller it reads was
613
- // not registered yet).
614
- if (!this.#sources) {
615
- this.#bootstrapPromise = undefined;
616
- }
617
- throw error;
618
- });
619
- return this.#bootstrapPromise;
620
- }
621
- /**
622
- * Read enabled networks, create the data sources, subscribe to
623
- * basic-functionality changes, wait for the Accounts API supported networks
624
- * and run the unlock cleanups when the keyring is already unlocked. Then
625
- * start asset tracking if the keyring is unlocked and the account tree is
626
- * initialized.
627
- *
628
- * By the time the UI opens, the client has registered every controller this
629
- * one depends on, so reading them here is safe.
630
- */
631
- async #bootstrap() {
632
- if (this.#isDestroyed) {
633
- return;
634
- }
635
- log('Bootstrapping AssetsController');
636
- this.#initializeState();
637
- this.#sources = this.#createSources();
638
- this.#subscribeToBasicFunctionality();
639
- await Promise.all([
640
- // AccountsApiDataSource fetches its supported networks asynchronously
641
- // from its constructor. Wait for them so the first forced fetch can use
642
- // the Accounts API instead of routing every chain to the slow lane.
643
- // `fetchQuery` shares the in-flight request, so this does not issue a
644
- // second one. Failures are logged by the data source and do not reject.
645
- this.#sources.accountsApiDataSource.refreshActiveChains(),
646
- this.#runUnlockCleanupsIfUnlocked(),
647
- ]);
648
- if (this.#isDestroyed) {
649
- return;
650
- }
651
- // Chain updates reported while bootstrapping are ignored; `#updateActive`
652
- // subscribes with every source's current chains.
653
- this.#isBootstrapped = true;
654
- this.#updateActive();
655
- }
656
- /**
657
- * Run the unlock cleanups when the keyring is already unlocked. The
658
- * `KeyringController:unlock` handler skips them before the bootstrap, so an
659
- * unlock that happened earlier is handled here.
660
- */
661
- async #runUnlockCleanupsIfUnlocked() {
662
- if (!this.#isKeyringUnlocked()) {
663
- return;
664
- }
665
- await this.#runUnlockCleanups();
666
- }
667
- /**
668
- * Run the cleanups that happen on unlock: drop balances outside the
669
- * selected accounts' scopes, then remove spam tokens.
670
- */
671
- async #runUnlockCleanups() {
672
- try {
673
- this.#runOutOfScopeBalanceCleanup();
674
- }
675
- catch {
676
- /* Do nothing */
677
- }
678
- await this.#runSpamCleanup().catch(() => {
679
- /* Do nothing */
680
- });
681
- }
682
- /**
683
- * Create every data source and middleware.
684
- *
685
- * Data source constructors read other controllers and may report active
686
- * chains synchronously. `#handleActiveChainsUpdate` ignores those reports
687
- * until the bootstrap finishes, and `#updateActive` subscribes afterwards
688
- * with every source's chains.
689
- *
690
- * @returns The data sources and middlewares.
691
- */
692
- #createSources() {
693
- const { queryApiClient, rpcDataSourceConfig, accountsApiDataSourceConfig, priceDataSourceConfig, stakedBalanceDataSourceConfig, isOnboarded, } = this.#sourceOptions;
694
- const accountActivityDataSource = new AccountActivityDataSource({
538
+ this.#accountActivityDataSource = new AccountActivityDataSource({
695
539
  messenger: this.messenger,
696
540
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
697
- onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, accountActivityDataSource.getName(), request),
541
+ onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, this.#accountActivityDataSource.getName(), request),
698
542
  });
699
- const accountsApiDataSource = new AccountsApiDataSource({
543
+ this.#accountsApiDataSource = new AccountsApiDataSource({
700
544
  messenger: this.messenger,
701
545
  queryApiClient,
702
546
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
@@ -705,7 +549,7 @@ let AssetsController = (() => {
705
549
  getAssetsState: () => this.state,
706
550
  getAssetVisibility: this.#getAssetVisibility.bind(this),
707
551
  });
708
- const snapDataSource = new SnapDataSource({
552
+ this.#snapDataSource = new SnapDataSource({
709
553
  messenger: this.messenger,
710
554
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
711
555
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
@@ -713,7 +557,7 @@ let AssetsController = (() => {
713
557
  getAssetVisibility: this.#getAssetVisibility.bind(this),
714
558
  getAssetsState: () => this.state,
715
559
  });
716
- const rpcDataSource = new RpcDataSource({
560
+ this.#rpcDataSource = new RpcDataSource({
717
561
  messenger: this.messenger,
718
562
  getAssetsState: () => this.state,
719
563
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
@@ -721,16 +565,16 @@ let AssetsController = (() => {
721
565
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
722
566
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
723
567
  queryApiClient,
724
- ...rpcDataSourceConfig,
725
- isOnboarded: rpcDataSourceConfig.isOnboarded ?? isOnboarded,
568
+ ...rpcConfig,
569
+ isOnboarded: rpcConfig.isOnboarded ?? isOnboarded,
726
570
  getAssetType: (assetId) => this.#getAssetType(assetId),
727
571
  });
728
- const stakedBalanceDataSource = new StakedBalanceDataSource({
572
+ this.#stakedBalanceDataSource = new StakedBalanceDataSource({
729
573
  messenger: this.messenger,
730
574
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
731
575
  ...stakedBalanceDataSourceConfig,
732
576
  });
733
- const tokenDataSource = new TokenDataSource(this.messenger, {
577
+ this.#tokenDataSource = new TokenDataSource(this.messenger, {
734
578
  queryApiClient,
735
579
  getNativeAssetIds: () => {
736
580
  return this.#getNativeAssetIdsForEnabledChains();
@@ -738,13 +582,13 @@ let AssetsController = (() => {
738
582
  getAssetType: (assetId) => this.#getAssetType(assetId),
739
583
  getAssetsState: () => this.state,
740
584
  });
741
- const priceDataSource = new PriceDataSource({
585
+ this.#priceDataSource = new PriceDataSource({
742
586
  queryApiClient,
743
587
  getSelectedCurrency: () => this.state.selectedCurrency,
744
588
  getAssetsState: () => this.state,
745
589
  ...priceDataSourceConfig,
746
590
  });
747
- const customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
591
+ this.#customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
748
592
  getSelectedAccountId: () => {
749
593
  try {
750
594
  return this.#getSelectedAccounts()[0]?.id;
@@ -756,38 +600,30 @@ let AssetsController = (() => {
756
600
  removeCustomAsset: (accountId, assetId) => this.removeCustomAsset(accountId, assetId),
757
601
  getAssetsState: () => this.state,
758
602
  });
759
- const rpcFallbackMiddleware = new RpcFallbackMiddleware({
760
- rpcDataSource,
603
+ this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
604
+ rpcDataSource: this.#rpcDataSource,
761
605
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
762
606
  getAssetsState: () => this.state,
763
607
  });
764
- return {
765
- accountActivityDataSource,
766
- accountsApiDataSource,
767
- snapDataSource,
768
- rpcDataSource,
769
- stakedBalanceDataSource,
770
- tokenDataSource,
771
- priceDataSource,
772
- customAssetGraduationMiddleware,
773
- rpcFallbackMiddleware,
774
- };
775
- }
776
- /**
777
- * Subscribe to the host's basic-functionality setting, if the host provided
778
- * a way to. Runs during the bootstrap, after the data sources exist, so a
779
- * synchronous `onChange` cannot run before they are created.
780
- */
781
- #subscribeToBasicFunctionality() {
782
- const { subscribeToBasicFunctionalityChange } = this.#sourceOptions;
783
- if (!subscribeToBasicFunctionalityChange) {
784
- return;
785
- }
786
- const unsubscribe = subscribeToBasicFunctionalityChange((isBasic) => this.handleBasicFunctionalityChange(isBasic));
787
- if (typeof unsubscribe === 'function') {
788
- 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
+ }
789
622
  }
790
623
  }
624
+ // ============================================================================
625
+ // INITIALIZATION
626
+ // ============================================================================
791
627
  #initializeNativeAssetsMap(queryApiClient) {
792
628
  queryApiClient.queryClient
793
629
  .fetchQuery({
@@ -861,21 +697,8 @@ let AssetsController = (() => {
861
697
  }
862
698
  return reference;
863
699
  }
864
- /**
865
- * Subscribe to every external event. Runs from the constructor: subscribing
866
- * does not need the publishing controller to exist yet, so this does not
867
- * depend on construction order.
868
- *
869
- * Lifecycle events (client, keyring, account tree) drive `#updateActive`,
870
- * which bootstraps the controller the first time the UI is seen open.
871
- * Every other event needs the data sources, so it is ignored until they
872
- * exist.
873
- */
874
700
  #subscribeToEvents() {
875
701
  this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId, previousGroupId) => {
876
- if (!this.#sources) {
877
- return;
878
- }
879
702
  this.#handleAccountGroupChanged(groupId, previousGroupId).catch(console.error);
880
703
  });
881
704
  this.messenger.subscribe('AccountTreeController:initialized', () => {
@@ -886,9 +709,6 @@ let AssetsController = (() => {
886
709
  });
887
710
  // Subscribe to network enablement changes (only enabledNetworkMap)
888
711
  this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }) => {
889
- if (!this.#sources) {
890
- return;
891
- }
892
712
  this.#handleEnabledNetworksChanged(enabledNetworkMap).catch(console.error);
893
713
  });
894
714
  // When a network is added or removed from NetworkController, refresh
@@ -898,46 +718,34 @@ let AssetsController = (() => {
898
718
  // entries appear immediately without waiting for it to also be
899
719
  // enabled in NetworkEnablementController.
900
720
  this.messenger.subscribe('NetworkController:networkAdded', (networkConfiguration) => {
901
- if (!this.#sources) {
902
- return;
903
- }
904
721
  this.#handleNetworkAdded(networkConfiguration.chainId);
905
722
  this.#refreshAssetsAfterNetworkAdded(networkConfiguration.chainId).catch((error) => {
906
723
  log('Failed to refresh assets after network added', { error });
907
724
  });
908
725
  });
909
726
  this.messenger.subscribe('NetworkController:networkRemoved', () => {
910
- if (!this.#sources) {
911
- return;
912
- }
913
727
  this.#refreshAssetsAfterNetworkChange();
914
728
  });
915
729
  // Selected EVM network switch (network picker). Enablement changes are
916
730
  // handled separately via NetworkEnablementController:stateChange.
917
731
  this.messenger.subscribe('NetworkController:networkDidChange', (networkState) => {
918
- if (!this.#sources) {
919
- return;
920
- }
921
732
  this.#handleNetworkDidChange(networkState).catch(console.error);
922
733
  });
923
- // Client + Keyring lifecycle: only run when UI is open AND keyring is
924
- // 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
925
735
  this.messenger.subscribe('ClientController:stateChange', () => {
926
736
  this.#updateActive();
927
737
  }, clientControllerSelectors.selectIsUiOpen);
928
738
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
929
739
  this.messenger.subscribe('KeyringController:unlock', async () => {
930
- // Wait for an in-flight bootstrap: it may have checked the keyring
931
- // before this unlock and skipped the cleanups. Once bootstrapped, the
932
- // cleanups start synchronously, as before.
933
- if (!this.#isBootstrapped && this.#bootstrapPromise) {
934
- await this.#bootstrapPromise.catch(() => undefined);
740
+ try {
741
+ this.#runOutOfScopeBalanceCleanup();
935
742
  }
936
- if (this.#isBootstrapped) {
937
- await this.#runUnlockCleanups();
743
+ catch {
744
+ /* Do nothing */
938
745
  }
939
- // Before the bootstrap, this bootstraps the controller if the UI is
940
- // open, and the bootstrap runs the cleanups.
746
+ await this.#runSpamCleanup().catch(() => {
747
+ /* Do nothing */
748
+ });
941
749
  this.#updateActive();
942
750
  });
943
751
  this.messenger.subscribe('KeyringController:lock', () => {
@@ -947,9 +755,6 @@ let AssetsController = (() => {
947
755
  // Ensures balances for the account making the transaction are updated
948
756
  // (e.g. for gas estimations), except on AccountActivity-active chains.
949
757
  this.messenger.subscribe('TransactionController:unapprovedTransactionAdded', (transactionMeta) => {
950
- if (!this.#sources) {
951
- return;
952
- }
953
758
  this.#refreshAssetsForEVMTransaction(transactionMeta);
954
759
  });
955
760
  // Post-tx refresh via the full fetch pipeline (Accounts API + RPC fallback).
@@ -957,9 +762,6 @@ let AssetsController = (() => {
957
762
  // RpcDataSource also listens for transactionConfirmed, but only refreshes
958
763
  // chains it owns via an active subscription.
959
764
  this.messenger.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
960
- if (!this.#sources) {
961
- return;
962
- }
963
765
  this.#refreshAssetsForEVMTransaction(transactionMeta);
964
766
  });
965
767
  // Non-EVM equivalent of the above: Snap keyrings report transaction
@@ -967,9 +769,6 @@ let AssetsController = (() => {
967
769
  // not covered by AccountActivity (WebSocket down / unsupported), refresh
968
770
  // via the Accounts API with the server cache bypassed.
969
771
  this.messenger.subscribe('MultichainTransactionsController:transactionConfirmed', (transaction) => {
970
- if (!this.#sources) {
971
- return;
972
- }
973
772
  this.#refreshAssetsForNonEvmTransaction(transaction);
974
773
  });
975
774
  }
@@ -1095,33 +894,16 @@ let AssetsController = (() => {
1095
894
  * Start or stop asset tracking based on client (UI) open state, keyring
1096
895
  * unlock state, and account-tree readiness. Only runs when the UI is open,
1097
896
  * the keyring is unlocked, and the account tree has finished `init()`.
1098
- *
1099
- * Before the bootstrap, this only bootstraps the controller when the UI is
1100
- * open. It reads other controllers only when one of their events fires, by
1101
- * which point they are registered.
1102
897
  */
1103
898
  #updateActive() {
1104
- if (this.#isDestroyed) {
1105
- return;
1106
- }
1107
- if (!this.#isBootstrapped) {
1108
- // Bootstrap the first time the UI is seen open. The bootstrap calls
1109
- // back into `#updateActive` once it finishes.
1110
- if (this.#isUiOpen()) {
1111
- this.#ensureBootstrapped().catch((error) => {
1112
- log('Failed to bootstrap AssetsController', { error });
1113
- });
1114
- }
1115
- return;
1116
- }
1117
899
  const shouldRun = this.#isUiOpen() &&
1118
900
  this.#isKeyringUnlocked() &&
1119
901
  this.#isAccountTreeInitialized();
1120
902
  if (shouldRun) {
1121
- this.#startTracking();
903
+ this.#start();
1122
904
  }
1123
905
  else {
1124
- this.#stopTracking();
906
+ this.#stop();
1125
907
  }
1126
908
  }
1127
909
  /**
@@ -1173,13 +955,6 @@ let AssetsController = (() => {
1173
955
  * @param previousChains - Previous chains; used to compute added/removed.
1174
956
  */
1175
957
  #handleActiveChainsUpdate(dataSourceId, activeChains, previousChains) {
1176
- // Data sources report their chains while the bootstrap is still running.
1177
- // The bootstrap subscribes afterwards with every source's chains.
1178
- // Subscribing here first would make `#startTracking` skip the startup
1179
- // refresh.
1180
- if (!this.#isBootstrapped) {
1181
- return;
1182
- }
1183
958
  if (!this.#isUiOpen() || !this.#isKeyringUnlocked() || !this.#isEnabled()) {
1184
959
  return;
1185
960
  }
@@ -1233,34 +1008,28 @@ let AssetsController = (() => {
1233
1008
  // ============================================================================
1234
1009
  // PUBLIC API: QUERY METHODS
1235
1010
  // ============================================================================
1236
- /**
1237
- * Get assets for the given accounts, optionally force-fetching them first.
1238
- *
1239
- * Before the UI first opens there are no data sources, so a forced fetch is
1240
- * skipped and the assets already in state are returned. The loading status
1241
- * of the accounts is left untouched, so the first fetch afterwards still
1242
- * reports them as loading.
1243
- *
1244
- * @param accounts - Accounts to get assets for.
1245
- * @param options - Fetch options.
1246
- * @param options.chainIds - Chains to include. Defaults to the enabled chains.
1247
- * @param options.assetTypes - Asset types to include. Defaults to fungible.
1248
- * @param options.forceUpdate - Fetch from the data sources before reading state.
1249
- * @param options.bypassServerCache - Also bypass server-side HTTP caches.
1250
- * @param options.dataTypes - Data types to fetch.
1251
- * @returns Assets keyed by account ID and asset ID.
1252
- */
1253
1011
  async getAssets(accounts, options) {
1254
- if (options?.forceUpdate && !this.#sources) {
1255
- log('Skipping forced asset fetch: data sources have not been created');
1256
- return this.#getAssetsTracked(accounts, {
1257
- ...options,
1258
- 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
+ },
1259
1028
  });
1260
1029
  }
1261
- return this.#getAssetsTracked(accounts, options);
1030
+ const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
1031
+ return result;
1262
1032
  }
1263
- get #getAssetsTracked() { return _private_getAssetsTracked_descriptor.value; }
1264
1033
  /**
1265
1034
  * Force-fetch spot prices for an explicit asset list.
1266
1035
  *
@@ -1275,9 +1044,7 @@ let AssetsController = (() => {
1275
1044
  * @param assetIds - CAIP-19 asset IDs to sync.
1276
1045
  */
1277
1046
  async syncAssetsPrices(assetIds) {
1278
- if (!this.#sources ||
1279
- !this.#isBasicFunctionality() ||
1280
- assetIds.length === 0) {
1047
+ if (!this.#isBasicFunctionality() || assetIds.length === 0) {
1281
1048
  return;
1282
1049
  }
1283
1050
  const assetsPrice = await this.#priceDataSource.fetchAssetPrices(assetIds);
@@ -1932,7 +1699,7 @@ let AssetsController = (() => {
1932
1699
  previousCurrency,
1933
1700
  selectedCurrency,
1934
1701
  });
1935
- if (!this.#sources || !this.#isBasicFunctionality()) {
1702
+ if (!this.#isBasicFunctionality()) {
1936
1703
  return;
1937
1704
  }
1938
1705
  // Currency changed — old cached prices are in the wrong currency.
@@ -1952,7 +1719,7 @@ let AssetsController = (() => {
1952
1719
  * @param chainIds - Chain IDs to filter prices for.
1953
1720
  */
1954
1721
  subscribeAssetsPrice(accounts, chainIds) {
1955
- if (!this.#sources || !this.#isBasicFunctionality()) {
1722
+ if (!this.#isBasicFunctionality()) {
1956
1723
  return;
1957
1724
  }
1958
1725
  const subscriptionKey = 'ds:PriceDataSource';
@@ -2586,7 +2353,7 @@ let AssetsController = (() => {
2586
2353
  * Idempotent — returns early if accounts/chains are not yet available or
2587
2354
  * subscriptions are already active.
2588
2355
  */
2589
- #startTracking() {
2356
+ #start() {
2590
2357
  const accounts = this.#getSelectedAccounts();
2591
2358
  const chainIds = [...this.#enabledChains];
2592
2359
  if (accounts.length === 0 || chainIds.length === 0) {
@@ -2612,16 +2379,13 @@ let AssetsController = (() => {
2612
2379
  * Stop asset tracking: unsubscribe from all updates.
2613
2380
  * Called when app closes or keyring locks.
2614
2381
  */
2615
- #stopTracking() {
2382
+ #stop() {
2616
2383
  log('Stopping asset tracking', {
2617
2384
  activeSubscriptionCount: this.#activeSubscriptions.size,
2618
2385
  hasPriceSubscription: this.#activeSubscriptions.has('ds:PriceDataSource'),
2619
2386
  });
2620
2387
  this.#firstInitFetchReported = false;
2621
2388
  this.#stateSizeReported = false;
2622
- if (!this.#sources) {
2623
- return;
2624
- }
2625
2389
  // Stop price subscription first (uses direct messenger call)
2626
2390
  this.unsubscribeAssetsPrice();
2627
2391
  // Stop balance subscriptions by properly notifying data sources via messenger
@@ -2655,10 +2419,7 @@ let AssetsController = (() => {
2655
2419
  * @param _isBasic - The new value (for call-site clarity; the getter is the source of truth).
2656
2420
  */
2657
2421
  handleBasicFunctionalityChange(_isBasic) {
2658
- if (!this.#sources) {
2659
- return;
2660
- }
2661
- this.#stopTracking();
2422
+ this.#stop();
2662
2423
  this.#subscribeAssets();
2663
2424
  }
2664
2425
  /**
@@ -3002,7 +2763,7 @@ let AssetsController = (() => {
3002
2763
  if (!groupId) {
3003
2764
  return;
3004
2765
  }
3005
- // First start is owned by `AccountTreeController:initialized` / `#startTracking`.
2766
+ // First start is owned by `AccountTreeController:initialized` / `#start`.
3006
2767
  // ATC also re-publishes `selectedAccountGroupChange` on every `init()`
3007
2768
  // (including when the group did not change) so late subscribers can catch
3008
2769
  // up — ignore those until we are already tracking.
@@ -3224,12 +2985,6 @@ let AssetsController = (() => {
3224
2985
  assetsBalance: response.assetsBalance,
3225
2986
  assetsPrice: response.assetsPrice,
3226
2987
  });
3227
- if (!this.#sources) {
3228
- log('Ignoring assets update: data sources have not been created', {
3229
- sourceId,
3230
- });
3231
- return;
3232
- }
3233
2988
  if (this.#isBalanceV6Enabled()) {
3234
2989
  await this.#handleAssetsUpdateV6(response, sourceId, request);
3235
2990
  return;
@@ -3382,20 +3137,17 @@ let AssetsController = (() => {
3382
3137
  // ============================================================================
3383
3138
  destroy() {
3384
3139
  log('Destroying AssetsController', {
3385
- isBootstrapped: this.#isBootstrapped,
3140
+ dataSourceCount: this.#allBalanceDataSources.length,
3386
3141
  subscriptionCount: this.#activeSubscriptions.size,
3387
3142
  });
3388
- this.#isDestroyed = true;
3389
- // Destroy instantiated data sources (none exist before the UI first opens)
3390
- if (this.#sources) {
3391
- this.#sources.accountActivityDataSource.destroy();
3392
- this.#sources.accountsApiDataSource.destroy();
3393
- this.#sources.snapDataSource.destroy();
3394
- this.#sources.rpcDataSource.destroy();
3395
- this.#sources.stakedBalanceDataSource.destroy();
3396
- }
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?.();
3397
3149
  // Stop all active subscriptions
3398
- this.#stopTracking();
3150
+ this.#stop();
3399
3151
  if (this.#unsubscribeBasicFunctionality) {
3400
3152
  this.#unsubscribeBasicFunctionality();
3401
3153
  this.#unsubscribeBasicFunctionality = null;