Skip to content
Merged
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
8 changes: 0 additions & 8 deletions app/scripts/controllers/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ export default class PreferencesController {

this.store = new ObservableStore(initState);
this.store.setMaxListeners(13);
this.tokenListController = opts.tokenListController;

opts.onKeyringStateChange((state) => {
const accounts = new Set();
Expand Down Expand Up @@ -217,13 +216,6 @@ export default class PreferencesController {
*/
setUseTokenDetection(val) {
this.store.updateState({ useTokenDetection: val });
this.tokenListController.updatePreventPollingOnNetworkRestart(!val);
if (val) {
this.tokenListController.start();
} else {
this.tokenListController.clearingTokenListData();
this.tokenListController.stop();
}
}

/**
Expand Down
98 changes: 74 additions & 24 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,6 @@ export default class MetamaskController extends EventEmitter {
initState: initState.PreferencesController,
initLangCode: opts.initLangCode,
messenger: preferencesMessenger,
tokenListController: this.tokenListController,
provider: this.provider,
networkConfigurations: this.networkController.state.networkConfigurations,
onKeyringStateChange: (listener) =>
Expand Down Expand Up @@ -2210,12 +2209,19 @@ export default class MetamaskController extends EventEmitter {
this.accountTracker.start();
this.txController.startIncomingTransactionPolling();
this.tokenDetectionController.enable();
if (this.preferencesController.store.getState().useCurrencyRateCheck) {

const preferencesControllerState =
this.preferencesController.store.getState();

const { useCurrencyRateCheck } = preferencesControllerState;

if (useCurrencyRateCheck) {
this.currencyRateController.startPollingByNetworkClientId(
this.networkController.state.selectedNetworkClientId,
);
}
if (this.preferencesController.store.getState().useTokenDetection) {

if (this.#isTokenListPollingRequired(preferencesControllerState)) {
this.tokenListController.start();
}
}
Expand All @@ -2224,10 +2230,17 @@ export default class MetamaskController extends EventEmitter {
this.accountTracker.stop();
this.txController.stopIncomingTransactionPolling();
this.tokenDetectionController.disable();
if (this.preferencesController.store.getState().useCurrencyRateCheck) {

const preferencesControllerState =
this.preferencesController.store.getState();

const { useCurrencyRateCheck } = preferencesControllerState;

if (useCurrencyRateCheck) {
this.currencyRateController.stopAllPolling();
}
if (this.preferencesController.store.getState().useTokenDetection) {

if (this.#isTokenListPollingRequired(preferencesControllerState)) {
this.tokenListController.stop();
this.tokenRatesController.stop();
}
Expand Down Expand Up @@ -2488,25 +2501,11 @@ export default class MetamaskController extends EventEmitter {
setupControllerEventSubscriptions() {
let lastSelectedAddress;

this.preferencesController.store.subscribe(async (state) => {
const { currentLocale } = state;

const { chainId } = this.networkController.state.providerConfig;
await updateCurrentLocale(currentLocale);

if (state.incomingTransactionsPreferences?.[chainId]) {
this.txController.startIncomingTransactionPolling();
} else {
this.txController.stopIncomingTransactionPolling();
}

// TODO: Remove once the preferences controller has been replaced with the core monorepo implementation
this.controllerMessenger.publish(
'PreferencesController:stateChange',
state,
[],
);
});
this.preferencesController.store.subscribe(
previousValueComparator((prevState, currState) => {
this.#onPreferencesControllerStateChange(currState, prevState);
}, this.preferencesController.store.getState()),
);

this.controllerMessenger.subscribe(
`${this.accountsController.name}:selectedAccountChange`,
Expand Down Expand Up @@ -6020,4 +6019,55 @@ export default class MetamaskController extends EventEmitter {
{ updatedTransactionMeta },
);
}

async #onPreferencesControllerStateChange(currentState, previousState) {
const { currentLocale } = currentState;
const { chainId } = this.networkController.state.providerConfig;

await updateCurrentLocale(currentLocale);

if (currentState.incomingTransactionsPreferences?.[chainId]) {
this.txController.startIncomingTransactionPolling();
} else {
this.txController.stopIncomingTransactionPolling();
}

this.#checkTokenListPolling(currentState, previousState);

// TODO: Remove once the preferences controller has been replaced with the core monorepo implementation
this.controllerMessenger.publish(
'PreferencesController:stateChange',
currentState,
[],
);
}

#checkTokenListPolling(currentState, previousState) {
const previousEnabled = this.#isTokenListPollingRequired(previousState);
const newEnabled = this.#isTokenListPollingRequired(currentState);

if (previousEnabled === newEnabled) {
return;
}

this.tokenListController.updatePreventPollingOnNetworkRestart(!newEnabled);

if (newEnabled) {
log.debug('Started token list controller polling');
this.tokenListController.start();
} else {
log.debug('Stopped token list controller polling');
this.tokenListController.clearingTokenListData();
this.tokenListController.stop();
}
}

#isTokenListPollingRequired(preferencesControllerState) {
const { useTokenDetection, useTransactionSimulations, preferences } =
preferencesControllerState ?? {};

const { petnamesEnabled } = preferences ?? {};

return useTokenDetection || petnamesEnabled || useTransactionSimulations;
}
}
142 changes: 130 additions & 12 deletions app/scripts/metamask-controller.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ import { NetworkType } from '@metamask/controller-utils';
import { ControllerMessenger } from '@metamask/base-controller';
import { LoggingController, LogType } from '@metamask/logging-controller';
import { TransactionController } from '@metamask/transaction-controller';
import { TokenListController } from '@metamask/assets-controllers';
import { NETWORK_TYPES } from '../../shared/constants/network';
import { createTestProviderTools } from '../../test/stub/provider';
import { HardwareDeviceNames } from '../../shared/constants/hardware-wallets';
import { KeyringType } from '../../shared/constants/keyring';
import { LOG_EVENT } from '../../shared/constants/logs';
import mockEncryptor from '../../test/lib/mock-encryptor';
import * as tokenUtils from '../../shared/lib/token-util';
import { flushPromises } from '../../test/lib/timer-helpers';
import { deferredPromise } from './lib/util';
import MetaMaskController from './metamask-controller';

Expand Down Expand Up @@ -294,6 +296,14 @@ describe('MetaMaskController', () => {
describe('MetaMaskController Behaviour', () => {
let metamaskController;

async function simulatePreferencesChange(preferences) {
metamaskController.preferencesController.store.subscribe.mock.lastCall[0](
preferences,
);

await flushPromises();
}

beforeEach(() => {
jest.spyOn(MetaMaskController.prototype, 'resetStates');

Expand All @@ -316,6 +326,9 @@ describe('MetaMaskController', () => {
.mockReturnValue();

jest.spyOn(ControllerMessenger.prototype, 'subscribe');
jest.spyOn(TokenListController.prototype, 'start');
jest.spyOn(TokenListController.prototype, 'stop');
jest.spyOn(TokenListController.prototype, 'clearingTokenListData');

metamaskController = new MetaMaskController({
showUserConfirmation: noop,
Expand Down Expand Up @@ -1779,13 +1792,11 @@ describe('MetaMaskController', () => {
TransactionController.prototype.startIncomingTransactionPolling,
).not.toHaveBeenCalled();

await metamaskController.preferencesController.store.subscribe.mock.lastCall[0](
{
incomingTransactionsPreferences: {
[MAINNET_CHAIN_ID]: true,
},
await simulatePreferencesChange({
incomingTransactionsPreferences: {
[MAINNET_CHAIN_ID]: true,
},
);
});

expect(
TransactionController.prototype.startIncomingTransactionPolling,
Expand All @@ -1797,13 +1808,11 @@ describe('MetaMaskController', () => {
TransactionController.prototype.stopIncomingTransactionPolling,
).not.toHaveBeenCalled();

await metamaskController.preferencesController.store.subscribe.mock.lastCall[0](
{
incomingTransactionsPreferences: {
[MAINNET_CHAIN_ID]: false,
},
await simulatePreferencesChange({
incomingTransactionsPreferences: {
[MAINNET_CHAIN_ID]: false,
},
);
});

expect(
TransactionController.prototype.stopIncomingTransactionPolling,
Expand Down Expand Up @@ -1839,6 +1848,115 @@ describe('MetaMaskController', () => {
).toHaveBeenCalledTimes(1);
});
});

describe('token list controller', () => {
it('stops polling if petnames, simulations, and token detection disabled', async () => {
expect(TokenListController.prototype.stop).not.toHaveBeenCalled();

expect(
TokenListController.prototype.clearingTokenListData,
).not.toHaveBeenCalled();

await simulatePreferencesChange({
useTransactionSimulations: false,
useTokenDetection: false,
preferences: {
petnamesEnabled: false,
},
});

expect(TokenListController.prototype.stop).toHaveBeenCalledTimes(1);

expect(
TokenListController.prototype.clearingTokenListData,
).toHaveBeenCalledTimes(1);
});

it.each([
[
'petnames',
{
preferences: { petnamesEnabled: false },
useTokenDetection: true,
useTransactionSimulations: true,
},
],
[
'simulations',
{
preferences: { petnamesEnabled: true },
useTokenDetection: true,
useTransactionSimulations: false,
},
],
[
'token detection',
{
preferences: { petnamesEnabled: true },
useTokenDetection: false,
useTransactionSimulations: true,
},
],
])(
'does not stop polling if only %s disabled',
async (_, preferences) => {
expect(TokenListController.prototype.stop).not.toHaveBeenCalled();

expect(
TokenListController.prototype.clearingTokenListData,
).not.toHaveBeenCalled();

await simulatePreferencesChange(preferences);

expect(TokenListController.prototype.stop).not.toHaveBeenCalled();

expect(
TokenListController.prototype.clearingTokenListData,
).not.toHaveBeenCalled();
},
);

it.each([
[
'petnames',
{
preferences: { petnamesEnabled: true },
useTokenDetection: false,
useTransactionSimulations: false,
},
],
[
'simulations',
{
preferences: { petnamesEnabled: false },
useTokenDetection: false,
useTransactionSimulations: true,
},
],
[
'token detection',
{
preferences: { petnamesEnabled: false },
useTokenDetection: true,
useTransactionSimulations: false,
},
],
])('starts polling if only %s enabled', async (_, preferences) => {
expect(TokenListController.prototype.start).not.toHaveBeenCalled();

await simulatePreferencesChange({
useTransactionSimulations: false,
useTokenDetection: false,
preferences: {
petnamesEnabled: false,
},
});

await simulatePreferencesChange(preferences);

expect(TokenListController.prototype.start).toHaveBeenCalledTimes(1);
});
});
});

describe('MV3 Specific behaviour', () => {
Expand Down
32 changes: 32 additions & 0 deletions test/e2e/mock-e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,38 @@ async function setupMocking(server, testSpecificMock, { chainId }) {
],
occurrences: 9,
},
{
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
symbol: 'DAI',
decimals: 18,
name: 'Dai Stablecoin',
iconUrl:
'https://raw.githubusercontent.com/MetaMask/contract-metadata/master/images/dai.svg',
type: 'erc20',
aggregators: [
'metamask',
'aave',
'bancor',
'cmc',
'cryptocom',
'coinGecko',
'oneInch',
'pmm',
'sushiswap',
'zerion',
'lifi',
'socket',
'squid',
'openswap',
'sonarwatch',
'uniswapLabs',
'coinmarketcap',
],
occurrences: 17,
erc20Permit: true,
fees: { '0xb0da5965d43369968574d399dbe6374683773a65': 0 },
storage: { balance: 2 },
},
],
};
});
Expand Down
Loading