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