Skip to content

Commit

Permalink
fix: fix account controller legacy polling (#5321)
Browse files Browse the repository at this point in the history
## Explanation
Changes were made to accountTrackerController inside the
@metamask/assets-controllers package.

The account tracker polling was executed on the constructor with the
initialisation. This caused additional requests to be sent by the app,
leading to performance issues.

Additionally, the accountTracker was still using legacy polling via the
poll function. This function has now been removed, and a test has been
added to prevent the creation of multiple polling instances.

These changes improve efficiency by reducing unnecessary network
requests and ensuring the polling mechanism is properly controlled.

<!--
Thanks for your contribution! Take a moment to answer these questions so
that reviewers have the information they need to properly understand
your changes:

* What is the current state of things and why does it need to change?
* What is the solution your changes offer and how does it work?
* Are there any changes whose purpose might not obvious to those
unfamiliar with the domain?
* If your primary goal was to update one package but you found you had
to update another one along the way, why did you do so?
* If you had to upgrade a dependency, why did you do so?
-->

## References

<!--
Are there any issues that this pull request is tied to?
Are there other links that reviewers should consult to understand these
changes better?
Are there client or consumer pull requests to adopt any breaking
changes?

For example:

* Fixes #12345
* Related to #67890
-->

## Changelog

<!--
If you're making any consumer-facing changes, list those changes here as
if you were updating a changelog, using the template below as a guide.

(CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or
FIXED. For security-related issues, follow the Security Advisory
process.)

Please take care to name the exact pieces of the API you've added or
changed (e.g. types, interfaces, functions, or methods).

If there are any breaking changes, make sure to offer a solution for
consumers to follow once they upgrade to the changes.

Finally, if you're only making changes to development scripts or tests,
you may replace the template below with "None".
-->

### `@metamask/assets-controllers`

- **CHANGED**: Removed legacy poll function to prevent redundant
polling.
- **FIXED**: ensure that the polling is not triggered on the constructor
with the initialisation


## Checklist

- [ ] I've updated the test suite for new or updated code as appropriate
- [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [ ] I've highlighted breaking changes using the "BREAKING" category
above as appropriate
- [ ] I've prepared draft pull requests for clients and consumer
packages to resolve any breaking changes

Co-authored-by: sahar-fehri <[email protected]>
  • Loading branch information
salimtb and sahar-fehri authored Feb 13, 2025
1 parent 13ca538 commit 422ab57
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 46 deletions.
3 changes: 1 addition & 2 deletions eslint-warning-thresholds.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@
"no-shadow": 2
},
"packages/assets-controllers/src/AccountTrackerController.test.ts": {
"import-x/namespace": 2,
"import-x/order": 2
"import-x/namespace": 2
},
"packages/assets-controllers/src/AccountTrackerController.ts": {
"jsdoc/check-tag-names": 5,
Expand Down
52 changes: 37 additions & 15 deletions packages/assets-controllers/src/AccountTrackerController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import {
import { getDefaultPreferencesState } from '@metamask/preferences-controller';
import * as sinon from 'sinon';

import type {
AccountTrackerControllerMessenger,
AllowedActions,
AllowedEvents,
} from './AccountTrackerController';
import { AccountTrackerController } from './AccountTrackerController';
import { advanceTime } from '../../../tests/helpers';
import { createMockInternalAccount } from '../../accounts-controller/src/tests/mocks';
import type {
Expand All @@ -19,12 +25,6 @@ import {
buildCustomNetworkClientConfiguration,
buildMockGetNetworkClientById,
} from '../../network-controller/tests/helpers';
import type {
AccountTrackerControllerMessenger,
AllowedActions,
AllowedEvents,
} from './AccountTrackerController';
import { AccountTrackerController } from './AccountTrackerController';

jest.mock('@metamask/controller-utils', () => {
return {
Expand Down Expand Up @@ -95,12 +95,6 @@ describe('AccountTrackerController', () => {
});

describe('refresh', () => {
beforeEach(() => {
jest
.spyOn(AccountTrackerController.prototype, 'poll')
.mockImplementationOnce(async () => Promise.resolve());
});

describe('without networkClientId', () => {
it('should sync addresses', async () => {
const mockAddress1 = '0xbabe9bbeab5f83a755ac92c7a09b9ab3ff527f8c';
Expand Down Expand Up @@ -787,8 +781,11 @@ describe('AccountTrackerController', () => {
});
});

it('should call refresh every interval on legacy polling', async () => {
const pollSpy = jest.spyOn(AccountTrackerController.prototype, 'poll');
it('should call refresh every interval on polling', async () => {
const pollSpy = jest.spyOn(
AccountTrackerController.prototype,
'_executePoll',
);
await withController(
{
options: { interval: 100 },
Expand All @@ -799,6 +796,11 @@ describe('AccountTrackerController', () => {
async ({ controller }) => {
jest.spyOn(controller, 'refresh').mockResolvedValue();

await controller.startPolling({
networkClientId: 'networkClientId1',
});
await advanceTime({ clock, duration: 1 });

expect(pollSpy).toHaveBeenCalledTimes(1);

await advanceTime({ clock, duration: 50 });
Expand All @@ -813,7 +815,6 @@ describe('AccountTrackerController', () => {
});

it('should call refresh every interval for each networkClientId being polled', async () => {
jest.spyOn(AccountTrackerController.prototype, 'poll').mockResolvedValue();
const networkClientId1 = 'networkClientId1';
const networkClientId2 = 'networkClientId2';
await withController(
Expand Down Expand Up @@ -867,6 +868,27 @@ describe('AccountTrackerController', () => {
},
);
});

it('should not call polling twice', async () => {
await withController(
{
options: { interval: 100 },
},
async ({ controller }) => {
const refreshSpy = jest
.spyOn(controller, 'refresh')
.mockResolvedValue();

expect(refreshSpy).not.toHaveBeenCalled();
controller.startPolling({
networkClientId: 'networkClientId1',
});

await advanceTime({ clock, duration: 1 });
expect(refreshSpy).toHaveBeenCalledTimes(1);
},
);
});
});

type WithControllerCallback<ReturnValue> = ({
Expand Down
29 changes: 0 additions & 29 deletions packages/assets-controllers/src/AccountTrackerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,6 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac

readonly #getStakedBalanceForChain: AssetsContractController['getStakedBalanceForChain'];

#handle?: ReturnType<typeof setTimeout>;

/**
* Creates an AccountTracker instance.
*
Expand Down Expand Up @@ -198,10 +196,6 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac

this.setIntervalLength(interval);

// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.poll();

this.messagingSystem.subscribe(
'AccountsController:selectedEvmAccountChange',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
Expand Down Expand Up @@ -309,29 +303,6 @@ export class AccountTrackerController extends StaticIntervalPollingController<Ac
};
}

/**
* Starts a new polling interval.
*
* @param interval - Polling interval trigger a 'refresh'.
*/
async poll(interval?: number): Promise<void> {
if (interval) {
this.setIntervalLength(interval);
}

if (this.#handle) {
clearTimeout(this.#handle);
}

await this.refresh();

this.#handle = setTimeout(() => {
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.poll(this.getIntervalLength());
}, this.getIntervalLength());
}

/**
* Refreshes the balances of the accounts using the networkClientId
*
Expand Down

0 comments on commit 422ab57

Please sign in to comment.