@metamask-previews/assets-controller 20.2.0-preview-8b7a55483 → 20.2.1-preview-c3d36da85

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,6 +32,10 @@ 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
+ };
35
39
  import { BaseController } from '@metamask/base-controller';
36
40
  import { clientControllerSelectors } from '@metamask/client-controller';
37
41
  import { isCaipChainId, isStrictHexString, KnownCaipNamespace, parseCaipAssetType, parseCaipChainId, } from '@metamask/utils';
@@ -302,45 +306,37 @@ function effectiveAccountBalancesV6(previousBalances, updatedBalances, undeletab
302
306
  }
303
307
  return { ...keptBalances, ...updatedBalances };
304
308
  }
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
- */
335
309
  let AssetsController = (() => {
336
310
  let _classSuper = BaseController;
337
311
  let _instanceExtraInitializers = [];
338
- let _getAssets_decorators;
312
+ let _private_getAssetsTracked_decorators;
313
+ let _private_getAssetsTracked_descriptor;
339
314
  return class AssetsController extends _classSuper {
340
315
  static {
341
316
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
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);
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);
344
340
  if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
345
341
  }
346
342
  /** Whether the controller is enabled */
@@ -415,10 +411,10 @@ let AssetsController = (() => {
415
411
  */
416
412
  #activeSubscriptions = new Map();
417
413
  /**
418
- * Guards against `#start()` re-entrancy. `#activeSubscriptions` only
414
+ * Guards against `#startTracking()` re-entrancy. `#activeSubscriptions` only
419
415
  * becomes non-empty once `#runStartupRefresh()`'s forced `getAssets()`
420
416
  * call resolves, which can take many seconds for accounts with many
421
- * chains/snaps. `#start()` is invoked by `#updateActive()`, which is
417
+ * chains/snaps. `#startTracking()` is invoked by `#updateActive()`, which is
422
418
  * wired to several independent events (e.g. keyring unlock, account tree
423
419
  * init, client state change). If a second such event fires before the
424
420
  * first `getAssets()` call resolves, the `#activeSubscriptions.size > 0`
@@ -470,11 +466,49 @@ let AssetsController = (() => {
470
466
  #isKeyringUnlocked() {
471
467
  return this.messenger.call('KeyringController:isUnlocked');
472
468
  }
473
- #accountActivityDataSource;
474
- #accountsApiDataSource;
475
- #snapDataSource;
476
- #rpcDataSource;
477
- #stakedBalanceDataSource;
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
+ }
478
512
  /**
479
513
  * All balance data sources in priority order for chain-claiming and cleanup.
480
514
  * Note: StakedBalanceDataSource is excluded because it provides supplementary
@@ -490,10 +524,18 @@ let AssetsController = (() => {
490
524
  this.#rpcDataSource,
491
525
  ];
492
526
  }
493
- #priceDataSource;
494
- #customAssetGraduationMiddleware;
495
- #rpcFallbackMiddleware;
496
- #tokenDataSource;
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
+ }
497
539
  #unsubscribeBasicFunctionality = null;
498
540
  #queryApiClient;
499
541
  #onActiveChainsUpdated;
@@ -535,12 +577,126 @@ let AssetsController = (() => {
535
577
  });
536
578
  }
537
579
  };
538
- this.#accountActivityDataSource = new AccountActivityDataSource({
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({
539
695
  messenger: this.messenger,
540
696
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
541
- onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, this.#accountActivityDataSource.getName(), request),
697
+ onAssetsUpdate: (response, request) => this.handleAssetsUpdate(response, accountActivityDataSource.getName(), request),
542
698
  });
543
- this.#accountsApiDataSource = new AccountsApiDataSource({
699
+ const accountsApiDataSource = new AccountsApiDataSource({
544
700
  messenger: this.messenger,
545
701
  queryApiClient,
546
702
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
@@ -549,7 +705,7 @@ let AssetsController = (() => {
549
705
  getAssetsState: () => this.state,
550
706
  getAssetVisibility: this.#getAssetVisibility.bind(this),
551
707
  });
552
- this.#snapDataSource = new SnapDataSource({
708
+ const snapDataSource = new SnapDataSource({
553
709
  messenger: this.messenger,
554
710
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
555
711
  onAssetsUpdate: (response) => this.handleAssetsUpdate(response, 'SnapDataSource'),
@@ -557,7 +713,7 @@ let AssetsController = (() => {
557
713
  getAssetVisibility: this.#getAssetVisibility.bind(this),
558
714
  getAssetsState: () => this.state,
559
715
  });
560
- this.#rpcDataSource = new RpcDataSource({
716
+ const rpcDataSource = new RpcDataSource({
561
717
  messenger: this.messenger,
562
718
  getAssetsState: () => this.state,
563
719
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
@@ -565,16 +721,16 @@ let AssetsController = (() => {
565
721
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
566
722
  getNativeAssetForChain: (chainId) => this.#getNativeAssetForChain(chainId),
567
723
  queryApiClient,
568
- ...rpcConfig,
569
- isOnboarded: rpcConfig.isOnboarded ?? isOnboarded,
724
+ ...rpcDataSourceConfig,
725
+ isOnboarded: rpcDataSourceConfig.isOnboarded ?? isOnboarded,
570
726
  getAssetType: (assetId) => this.#getAssetType(assetId),
571
727
  });
572
- this.#stakedBalanceDataSource = new StakedBalanceDataSource({
728
+ const stakedBalanceDataSource = new StakedBalanceDataSource({
573
729
  messenger: this.messenger,
574
730
  onActiveChainsUpdated: this.#onActiveChainsUpdated,
575
731
  ...stakedBalanceDataSourceConfig,
576
732
  });
577
- this.#tokenDataSource = new TokenDataSource(this.messenger, {
733
+ const tokenDataSource = new TokenDataSource(this.messenger, {
578
734
  queryApiClient,
579
735
  getNativeAssetIds: () => {
580
736
  return this.#getNativeAssetIdsForEnabledChains();
@@ -582,13 +738,13 @@ let AssetsController = (() => {
582
738
  getAssetType: (assetId) => this.#getAssetType(assetId),
583
739
  getAssetsState: () => this.state,
584
740
  });
585
- this.#priceDataSource = new PriceDataSource({
741
+ const priceDataSource = new PriceDataSource({
586
742
  queryApiClient,
587
743
  getSelectedCurrency: () => this.state.selectedCurrency,
588
744
  getAssetsState: () => this.state,
589
745
  ...priceDataSourceConfig,
590
746
  });
591
- this.#customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
747
+ const customAssetGraduationMiddleware = new CustomAssetGraduationMiddleware({
592
748
  getSelectedAccountId: () => {
593
749
  try {
594
750
  return this.#getSelectedAccounts()[0]?.id;
@@ -600,30 +756,38 @@ let AssetsController = (() => {
600
756
  removeCustomAsset: (accountId, assetId) => this.removeCustomAsset(accountId, assetId),
601
757
  getAssetsState: () => this.state,
602
758
  });
603
- this.#rpcFallbackMiddleware = new RpcFallbackMiddleware({
604
- rpcDataSource: this.#rpcDataSource,
759
+ const rpcFallbackMiddleware = new RpcFallbackMiddleware({
760
+ rpcDataSource,
605
761
  isBalanceV6Enabled: () => this.#isBalanceV6Enabled(),
606
762
  getAssetsState: () => this.state,
607
763
  });
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
- }
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;
622
789
  }
623
790
  }
624
- // ============================================================================
625
- // INITIALIZATION
626
- // ============================================================================
627
791
  #initializeNativeAssetsMap(queryApiClient) {
628
792
  queryApiClient.queryClient
629
793
  .fetchQuery({
@@ -697,8 +861,21 @@ let AssetsController = (() => {
697
861
  }
698
862
  return reference;
699
863
  }
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
+ */
700
874
  #subscribeToEvents() {
701
875
  this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId, previousGroupId) => {
876
+ if (!this.#sources) {
877
+ return;
878
+ }
702
879
  this.#handleAccountGroupChanged(groupId, previousGroupId).catch(console.error);
703
880
  });
704
881
  this.messenger.subscribe('AccountTreeController:initialized', () => {
@@ -709,6 +886,9 @@ let AssetsController = (() => {
709
886
  });
710
887
  // Subscribe to network enablement changes (only enabledNetworkMap)
711
888
  this.messenger.subscribe('NetworkEnablementController:stateChange', ({ enabledNetworkMap }) => {
889
+ if (!this.#sources) {
890
+ return;
891
+ }
712
892
  this.#handleEnabledNetworksChanged(enabledNetworkMap).catch(console.error);
713
893
  });
714
894
  // When a network is added or removed from NetworkController, refresh
@@ -718,34 +898,46 @@ let AssetsController = (() => {
718
898
  // entries appear immediately without waiting for it to also be
719
899
  // enabled in NetworkEnablementController.
720
900
  this.messenger.subscribe('NetworkController:networkAdded', (networkConfiguration) => {
901
+ if (!this.#sources) {
902
+ return;
903
+ }
721
904
  this.#handleNetworkAdded(networkConfiguration.chainId);
722
905
  this.#refreshAssetsAfterNetworkAdded(networkConfiguration.chainId).catch((error) => {
723
906
  log('Failed to refresh assets after network added', { error });
724
907
  });
725
908
  });
726
909
  this.messenger.subscribe('NetworkController:networkRemoved', () => {
910
+ if (!this.#sources) {
911
+ return;
912
+ }
727
913
  this.#refreshAssetsAfterNetworkChange();
728
914
  });
729
915
  // Selected EVM network switch (network picker). Enablement changes are
730
916
  // handled separately via NetworkEnablementController:stateChange.
731
917
  this.messenger.subscribe('NetworkController:networkDidChange', (networkState) => {
918
+ if (!this.#sources) {
919
+ return;
920
+ }
732
921
  this.#handleNetworkDidChange(networkState).catch(console.error);
733
922
  });
734
- // Client + Keyring lifecycle: only run when UI is open AND keyring is unlocked
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.
735
925
  this.messenger.subscribe('ClientController:stateChange', () => {
736
926
  this.#updateActive();
737
927
  }, clientControllerSelectors.selectIsUiOpen);
738
928
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
739
929
  this.messenger.subscribe('KeyringController:unlock', async () => {
740
- try {
741
- this.#runOutOfScopeBalanceCleanup();
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);
742
935
  }
743
- catch {
744
- /* Do nothing */
936
+ if (this.#isBootstrapped) {
937
+ await this.#runUnlockCleanups();
745
938
  }
746
- await this.#runSpamCleanup().catch(() => {
747
- /* Do nothing */
748
- });
939
+ // Before the bootstrap, this bootstraps the controller if the UI is
940
+ // open, and the bootstrap runs the cleanups.
749
941
  this.#updateActive();
750
942
  });
751
943
  this.messenger.subscribe('KeyringController:lock', () => {
@@ -755,6 +947,9 @@ let AssetsController = (() => {
755
947
  // Ensures balances for the account making the transaction are updated
756
948
  // (e.g. for gas estimations), except on AccountActivity-active chains.
757
949
  this.messenger.subscribe('TransactionController:unapprovedTransactionAdded', (transactionMeta) => {
950
+ if (!this.#sources) {
951
+ return;
952
+ }
758
953
  this.#refreshAssetsForEVMTransaction(transactionMeta);
759
954
  });
760
955
  // Post-tx refresh via the full fetch pipeline (Accounts API + RPC fallback).
@@ -762,6 +957,9 @@ let AssetsController = (() => {
762
957
  // RpcDataSource also listens for transactionConfirmed, but only refreshes
763
958
  // chains it owns via an active subscription.
764
959
  this.messenger.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
960
+ if (!this.#sources) {
961
+ return;
962
+ }
765
963
  this.#refreshAssetsForEVMTransaction(transactionMeta);
766
964
  });
767
965
  // Non-EVM equivalent of the above: Snap keyrings report transaction
@@ -769,6 +967,9 @@ let AssetsController = (() => {
769
967
  // not covered by AccountActivity (WebSocket down / unsupported), refresh
770
968
  // via the Accounts API with the server cache bypassed.
771
969
  this.messenger.subscribe('MultichainTransactionsController:transactionConfirmed', (transaction) => {
970
+ if (!this.#sources) {
971
+ return;
972
+ }
772
973
  this.#refreshAssetsForNonEvmTransaction(transaction);
773
974
  });
774
975
  }
@@ -894,16 +1095,33 @@ let AssetsController = (() => {
894
1095
  * Start or stop asset tracking based on client (UI) open state, keyring
895
1096
  * unlock state, and account-tree readiness. Only runs when the UI is open,
896
1097
  * 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.
897
1102
  */
898
1103
  #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
+ }
899
1117
  const shouldRun = this.#isUiOpen() &&
900
1118
  this.#isKeyringUnlocked() &&
901
1119
  this.#isAccountTreeInitialized();
902
1120
  if (shouldRun) {
903
- this.#start();
1121
+ this.#startTracking();
904
1122
  }
905
1123
  else {
906
- this.#stop();
1124
+ this.#stopTracking();
907
1125
  }
908
1126
  }
909
1127
  /**
@@ -955,6 +1173,13 @@ let AssetsController = (() => {
955
1173
  * @param previousChains - Previous chains; used to compute added/removed.
956
1174
  */
957
1175
  #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
+ }
958
1183
  if (!this.#isUiOpen() || !this.#isKeyringUnlocked() || !this.#isEnabled()) {
959
1184
  return;
960
1185
  }
@@ -1008,28 +1233,34 @@ let AssetsController = (() => {
1008
1233
  // ============================================================================
1009
1234
  // PUBLIC API: QUERY METHODS
1010
1235
  // ============================================================================
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
+ */
1011
1253
  async getAssets(accounts, options) {
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
- },
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,
1028
1259
  });
1029
1260
  }
1030
- const result = this.#getAssetsFromState(accounts, chainIds, assetTypes);
1031
- return result;
1261
+ return this.#getAssetsTracked(accounts, options);
1032
1262
  }
1263
+ get #getAssetsTracked() { return _private_getAssetsTracked_descriptor.value; }
1033
1264
  /**
1034
1265
  * Force-fetch spot prices for an explicit asset list.
1035
1266
  *
@@ -1044,7 +1275,9 @@ let AssetsController = (() => {
1044
1275
  * @param assetIds - CAIP-19 asset IDs to sync.
1045
1276
  */
1046
1277
  async syncAssetsPrices(assetIds) {
1047
- if (!this.#isBasicFunctionality() || assetIds.length === 0) {
1278
+ if (!this.#sources ||
1279
+ !this.#isBasicFunctionality() ||
1280
+ assetIds.length === 0) {
1048
1281
  return;
1049
1282
  }
1050
1283
  const assetsPrice = await this.#priceDataSource.fetchAssetPrices(assetIds);
@@ -1699,7 +1932,7 @@ let AssetsController = (() => {
1699
1932
  previousCurrency,
1700
1933
  selectedCurrency,
1701
1934
  });
1702
- if (!this.#isBasicFunctionality()) {
1935
+ if (!this.#sources || !this.#isBasicFunctionality()) {
1703
1936
  return;
1704
1937
  }
1705
1938
  // Currency changed — old cached prices are in the wrong currency.
@@ -1719,7 +1952,7 @@ let AssetsController = (() => {
1719
1952
  * @param chainIds - Chain IDs to filter prices for.
1720
1953
  */
1721
1954
  subscribeAssetsPrice(accounts, chainIds) {
1722
- if (!this.#isBasicFunctionality()) {
1955
+ if (!this.#sources || !this.#isBasicFunctionality()) {
1723
1956
  return;
1724
1957
  }
1725
1958
  const subscriptionKey = 'ds:PriceDataSource';
@@ -2353,7 +2586,7 @@ let AssetsController = (() => {
2353
2586
  * Idempotent — returns early if accounts/chains are not yet available or
2354
2587
  * subscriptions are already active.
2355
2588
  */
2356
- #start() {
2589
+ #startTracking() {
2357
2590
  const accounts = this.#getSelectedAccounts();
2358
2591
  const chainIds = [...this.#enabledChains];
2359
2592
  if (accounts.length === 0 || chainIds.length === 0) {
@@ -2379,13 +2612,16 @@ let AssetsController = (() => {
2379
2612
  * Stop asset tracking: unsubscribe from all updates.
2380
2613
  * Called when app closes or keyring locks.
2381
2614
  */
2382
- #stop() {
2615
+ #stopTracking() {
2383
2616
  log('Stopping asset tracking', {
2384
2617
  activeSubscriptionCount: this.#activeSubscriptions.size,
2385
2618
  hasPriceSubscription: this.#activeSubscriptions.has('ds:PriceDataSource'),
2386
2619
  });
2387
2620
  this.#firstInitFetchReported = false;
2388
2621
  this.#stateSizeReported = false;
2622
+ if (!this.#sources) {
2623
+ return;
2624
+ }
2389
2625
  // Stop price subscription first (uses direct messenger call)
2390
2626
  this.unsubscribeAssetsPrice();
2391
2627
  // Stop balance subscriptions by properly notifying data sources via messenger
@@ -2419,7 +2655,10 @@ let AssetsController = (() => {
2419
2655
  * @param _isBasic - The new value (for call-site clarity; the getter is the source of truth).
2420
2656
  */
2421
2657
  handleBasicFunctionalityChange(_isBasic) {
2422
- this.#stop();
2658
+ if (!this.#sources) {
2659
+ return;
2660
+ }
2661
+ this.#stopTracking();
2423
2662
  this.#subscribeAssets();
2424
2663
  }
2425
2664
  /**
@@ -2763,7 +3002,7 @@ let AssetsController = (() => {
2763
3002
  if (!groupId) {
2764
3003
  return;
2765
3004
  }
2766
- // First start is owned by `AccountTreeController:initialized` / `#start`.
3005
+ // First start is owned by `AccountTreeController:initialized` / `#startTracking`.
2767
3006
  // ATC also re-publishes `selectedAccountGroupChange` on every `init()`
2768
3007
  // (including when the group did not change) so late subscribers can catch
2769
3008
  // up — ignore those until we are already tracking.
@@ -2985,6 +3224,12 @@ let AssetsController = (() => {
2985
3224
  assetsBalance: response.assetsBalance,
2986
3225
  assetsPrice: response.assetsPrice,
2987
3226
  });
3227
+ if (!this.#sources) {
3228
+ log('Ignoring assets update: data sources have not been created', {
3229
+ sourceId,
3230
+ });
3231
+ return;
3232
+ }
2988
3233
  if (this.#isBalanceV6Enabled()) {
2989
3234
  await this.#handleAssetsUpdateV6(response, sourceId, request);
2990
3235
  return;
@@ -3137,17 +3382,20 @@ let AssetsController = (() => {
3137
3382
  // ============================================================================
3138
3383
  destroy() {
3139
3384
  log('Destroying AssetsController', {
3140
- dataSourceCount: this.#allBalanceDataSources.length,
3385
+ isBootstrapped: this.#isBootstrapped,
3141
3386
  subscriptionCount: this.#activeSubscriptions.size,
3142
3387
  });
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?.();
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
+ }
3149
3397
  // Stop all active subscriptions
3150
- this.#stop();
3398
+ this.#stopTracking();
3151
3399
  if (this.#unsubscribeBasicFunctionality) {
3152
3400
  this.#unsubscribeBasicFunctionality();
3153
3401
  this.#unsubscribeBasicFunctionality = null;