Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,7 @@
/packages/wallet/src/initialization/instances/accounts-controller/ @MetaMask/accounts-engineers
/packages/wallet/src/initialization/instances/address-book-controller/ @MetaMask/confirmations
/packages/wallet/src/initialization/instances/approval-controller/ @MetaMask/confirmations
/packages/wallet/src/initialization/instances/assets-controllers/ @MetaMask/metamask-assets
/packages/wallet/src/initialization/instances/claims-controller/ @MetaMask/web3auth
/packages/wallet/src/initialization/instances/claims-service/ @MetaMask/web3auth
/packages/wallet/src/initialization/instances/client-controller/ @MetaMask/core-platform @MetaMask/extension-platform @MetaMask/mobile-platform
Expand Down
1 change: 1 addition & 0 deletions codeowners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const config = {
},
'assets-controllers': {
teams: ['@MetaMask/metamask-assets'],
initializationPath: 'assets-controllers',
},
'authenticated-user-storage': {
teams: ['@MetaMask/auth-engineers'],
Expand Down
24 changes: 21 additions & 3 deletions packages/assets-controllers/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Add `serviceProfile` string option to `searchTokens`, sent as the `x-mm-service-profile` header on the `/tokens/search` request ([#11274](https://github.com/MetaMask/core/pull/11274))
- Defaults to `assets--trending-search`, so the header is sent on every search request

### Changed

- Add `init` method to `TokensController`, `TokenBalancesController`, `TokenDetectionController`, `TokenRatesController`, `AccountTrackerController`, `NftController`, `MultichainBalancesController`, `MultichainAssetsRatesController`, `MultichainAssetsController` and `TokenListController` ([#11314](https://github.com/MetaMask/core/pull/11314))
- `init` reads the other controllers that the constructor used to read. Calling it more than once has no effect.
- `TokenListController.init` calls `initialize` once.
- Expose `addNfts` through the `NftController` messenger ([#11314](https://github.com/MetaMask/core/pull/11314))

### Changed

- **BREAKING:** The constructors of `TokensController`, `TokenBalancesController`, `TokenDetectionController`, `TokenRatesController`, `AccountTrackerController`, `NftController`, `MultichainBalancesController`, `MultichainAssetsRatesController` and `MultichainAssetsController` no longer call other controllers or start background work, so they can be constructed in any order ([#11314](https://github.com/MetaMask/core/pull/11314))
- Call `init` on each of them once the controllers they read from are registered. Until then:
- `TokensController` does not enrich persisted tokens from the token list, and reads the selected account on demand.
- `TokenBalancesController`, `TokenDetectionController` and `AccountTrackerController` treat the keyring as locked, and `TokenBalancesController` knows of no tokens.
- `TokenRatesController` knows of no tokens and does not pass native asset identifiers to the token prices service.
- `AccountTrackerController` starts with an empty `accountsByChainId`; `init` adds an empty entry for the selected network's chain when no `accountsByChainId` state was provided.
- `NftController` reads the selected account on demand.
- `MultichainBalancesController` does not fetch the initial non-EVM balances.
- `MultichainAssetsRatesController` uses `usd` as the current currency.
- `MultichainAssetsController` does not start the periodic Blockaid re-scan.
- `TokenDetectionController.init` reports a failure to read `PreferencesController:getState` through `messenger.captureException` instead of throwing, and takes the preference from the next `PreferencesController:stateChange` event.
- **BREAKING:** `TokensControllerMessenger` must allow the `NetworkController:getSelectedNetworkClient` action ([#11314](https://github.com/MetaMask/core/pull/11314))
- `TokensController` no longer requires the `chainId` and `provider` options ([#11314](https://github.com/MetaMask/core/pull/11314))
- When `provider` is omitted, the provider of the selected network client (`NetworkController:getSelectedNetworkClient`) is used.
- Bump `uuid` from `^14.0.1` to `^14.0.2` ([#11305](https://github.com/MetaMask/core/pull/11305))

## [113.1.1]
Expand Down
109 changes: 109 additions & 0 deletions packages/assets-controllers/src/AccountTrackerController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import type {
NetworkClientId,
NetworkClientConfiguration,
NetworkConfiguration,
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerGetStateAction,
} from '@metamask/network-controller';
import { getDefaultPreferencesState } from '@metamask/preferences-controller';
import { TransactionStatus } from '@metamask/transaction-controller';
Expand Down Expand Up @@ -139,6 +141,112 @@ describe('AccountTrackerController', () => {
);
});

describe('construction and init', () => {
it('does not call other controllers when constructed', () => {
const messenger: AccountTrackerControllerMessenger = new Messenger({
namespace: 'AccountTrackerController',
});
const call = vi.spyOn(messenger, 'call');

const controller = new AccountTrackerController({
messenger,
getStakedBalanceForChain: vi.fn(),
});

expect(controller.state).toStrictEqual({ accountsByChainId: {} });
expect(controller.isActive).toBe(false);
expect(call).not.toHaveBeenCalled();
});

it('does not add the selected chain in init when accountsByChainId state is provided', async () => {
await withController(
{
options: {
state: { accountsByChainId: { '0x89': {} } },
},
},
({ controller }) => {
expect(controller.state).toStrictEqual({
accountsByChainId: { '0x89': {} },
});
},
);
});

it('keeps an entry for the selected chain that was added before init', () => {
const rootMessenger: RootMessenger = new Messenger({
namespace: MOCK_ANY_NAMESPACE,
});
const messenger: AccountTrackerControllerMessenger = new Messenger({
namespace: 'AccountTrackerController',
parent: rootMessenger,
});
rootMessenger.delegate({
messenger,
actions: [
'KeyringController:getState',
'NetworkController:getState',
'NetworkController:getNetworkClientById',
],
});
rootMessenger.registerActionHandler('KeyringController:getState', () => ({
isUnlocked: true,
keyrings: [],
}));
rootMessenger.registerActionHandler(
'NetworkController:getState',
() =>
({ selectedNetworkClientId: 'mainnet' }) as ReturnType<
NetworkControllerGetStateAction['handler']
>,
);
rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() =>
({
configuration: { chainId: initialChainId },
}) as unknown as ReturnType<
NetworkControllerGetNetworkClientByIdAction['handler']
>,
);
const controller = new AccountTrackerController({
messenger,
getStakedBalanceForChain: vi.fn(),
});
controller.updateNativeBalances([
{ address: ADDRESS_1, chainId: initialChainId, balance: '0x1' },
]);

controller.init();

expect(controller.isActive).toBe(true);
expect(controller.state.accountsByChainId).toStrictEqual({
[initialChainId]: {
[CHECKSUM_ADDRESS_1]: { balance: '0x1' },
},
});
});

it('does not add the selected chain in init when isDeprecated() returns true', async () => {
await withController(
{ options: { isDeprecated: () => true } },
({ controller }) => {
expect(controller.state).toStrictEqual({ accountsByChainId: {} });
},
);
});

it('reads other controllers only once when init is called repeatedly', async () => {
await withController(({ controller, messenger }) => {
const call = vi.spyOn(messenger, 'call');

controller.init();

expect(call).not.toHaveBeenCalled();
});
});
});

it('should refresh when selectedAccount changes', async () => {
await withController(
{
Expand Down Expand Up @@ -2467,6 +2575,7 @@ async function withController<ReturnValue>(
getStakedBalanceForChain: vi.fn(),
...options,
});
controller.init();

const refresh = async (
networkClientIds: NetworkClientId[],
Expand Down
60 changes: 45 additions & 15 deletions packages/assets-controllers/src/AccountTrackerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac
/** Track if the keyring is locked */
#isLocked = true;

readonly #seedSelectedChain: boolean;

#initialized = false;

/**
* Creates an AccountTracker instance.
*
Expand Down Expand Up @@ -313,26 +317,16 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac
isOnboarded?: () => boolean;
isDeprecated?: () => boolean;
}) {
const { selectedNetworkClientId } = messenger.call(
'NetworkController:getState',
);
const {
configuration: { chainId },
} = messenger.call(
'NetworkController:getNetworkClientById',
selectedNetworkClientId,
);
super({
name: controllerName,
messenger,
state: {
accountsByChainId: {
[chainId]: {},
},
accountsByChainId: {},
...state,
},
metadata: accountTrackerMetadata,
});
this.#seedSelectedChain = state?.accountsByChainId === undefined;
this.#getStakedBalanceForChain = getStakedBalanceForChain;

this.#includeStakedAssets = includeStakedAssets;
Expand All @@ -359,9 +353,6 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac
this.#enforceDisabledState();
}

const { isUnlocked } = this.messenger.call('KeyringController:getState');
this.#isLocked = !isUnlocked;

this.setIntervalLength(interval);

this.messenger.subscribe(
Expand Down Expand Up @@ -436,6 +427,45 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac
messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
}

/**
* Complete initialization once the controllers this controller reads from
* have been constructed: read the lock state from `KeyringController` and,
* when no `accountsByChainId` state was provided, add an empty entry for the
* chain of the selected network.
*
* The constructor does not call other controllers, so it can run before they
* are constructed. Until this is called, the controller treats the keyring as
* locked. Calling it more than once has no effect.
*/
init(): void {
if (this.#initialized) {
return;
}
this.#initialized = true;

const { isUnlocked } = this.messenger.call('KeyringController:getState');
this.#isLocked = !isUnlocked;

if (!this.#seedSelectedChain || this.#isDeprecated()) {
return;
}

const { selectedNetworkClientId } = this.messenger.call(
'NetworkController:getState',
);
const {
configuration: { chainId },
} = this.messenger.call(
'NetworkController:getNetworkClientById',
selectedNetworkClientId,
);
if (this.state.accountsByChainId[chainId] === undefined) {
this.update((state) => {
state.accountsByChainId[chainId] = {};
});
}
}

/**
* Whether the controller is active (keyring is unlocked and user is onboarded).
* When locked or not onboarded, balance updates should be skipped.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ const setupController = ({
blockaidTokenRescanInterval,
...(isDeprecated && { isDeprecated }),
});
controller.init();

return {
controller,
Expand Down Expand Up @@ -1822,6 +1823,51 @@ describe('MultichainAssetsController', () => {
expect(storedAssets).toHaveLength(119);
});

it('does not start the periodic rescan or call other controllers when constructed', async () => {
const messenger: MultichainAssetsControllerMessenger = new Messenger({
namespace: 'MultichainAssetsController',
});
const call = vi.spyOn(messenger, 'call');

const controller = new MultichainAssetsController({
messenger,
blockaidTokenRescanInterval: 60_000,
state: {
accountsAssets: {
account1: [
'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1/token:SomeAddr',
],
},
assetsMetadata: {},
allIgnoredAssets: {},
},
});
await vi.advanceTimersByTimeAsync(60_001);

expect(call).not.toHaveBeenCalled();
controller.stopAllPolling();
});

it('starts the periodic rescan only once when init is called repeatedly', async () => {
const mockAccountId = 'account1';
const token = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1/token:SomeAddr';
const { controller, mockBulkScanTokens } = setupController({
blockaidTokenRescanInterval: 60_000,
state: {
accountsAssets: { [mockAccountId]: [token] },
assetsMetadata: {},
allIgnoredAssets: {},
},
});
mockBulkScanTokens.mockResolvedValue({});

controller.init();
await vi.advanceTimersByTimeAsync(1);

expect(mockBulkScanTokens).toHaveBeenCalledTimes(1);
controller.stopAllPolling();
});

it('periodic rescan ignores SPL tokens that Blockaid later marks malicious', async () => {
const mockAccountId = 'account1';
const token =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ export class MultichainAssetsController extends StaticIntervalPollingController<

readonly #isDeprecated: () => boolean;

readonly #blockaidTokenRescanInterval: number;

#initialized = false;

constructor({
messenger,
state = {},
Expand All @@ -238,12 +242,10 @@ export class MultichainAssetsController extends StaticIntervalPollingController<

this.#snaps = {};
this.#isDeprecated = isDeprecated;
this.#blockaidTokenRescanInterval = blockaidTokenRescanInterval;

if (this.#isDeprecated()) {
this.#enforceDisabledState();
} else if (blockaidTokenRescanInterval > 0) {
this.setIntervalLength(blockaidTokenRescanInterval);
this.startPolling(null);
}

this.messenger.subscribe(
Expand All @@ -265,6 +267,32 @@ export class MultichainAssetsController extends StaticIntervalPollingController<
messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
}

/**
* Complete initialization once the controllers this controller reads from
* have been constructed: start the periodic Blockaid re-scan of stored
* tokens, unless it is disabled.
*
* The constructor does not call other controllers or start polling, so it
* can run before they are constructed. Calling it more than once has no
* effect.
*/
init(): void {
if (this.#initialized) {
return;
}
this.#initialized = true;

if (this.#isDeprecated()) {
this.#enforceDisabledState();
return;
}

if (this.#blockaidTokenRescanInterval > 0) {
this.setIntervalLength(this.#blockaidTokenRescanInterval);
this.startPolling(null);
}
}

/**
* Clears all persisted `accountsAssets`, `assetsMetadata`, and
* `allIgnoredAssets` so that no stale asset data remains in state.
Expand Down
Loading
Loading