Skip to content

perf(accounts-controller): prevent unnecessary update with SnapController:stateChange #5735

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 30, 2025
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
1 change: 1 addition & 0 deletions packages/accounts-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **BREAKING:** Bump `@metamask/providers` peer dependency from ^18.1.0 to ^21.0.0 ([#5639](https://github.com/MetaMask/core/pull/5639))
- Bump `@metamask/snaps-sdk` from ^6.17.1 to ^6.22.0 ([#5639](https://github.com/MetaMask/core/pull/5639))
- Bump `@metamask/snaps-utils` from ^8.10.0 to ^9.2.0 ([#5639](https://github.com/MetaMask/core/pull/5639))
- Prevent unnecasary state updates when updating `InternalAccount.metadata.snap` ([#5735](https://github.com/MetaMask/core/pull/5735))

## [27.0.0]

Expand Down
61 changes: 58 additions & 3 deletions packages/accounts-controller/src/AccountsController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import type { SnapControllerState } from '@metamask/snaps-controllers';
import { SnapStatus } from '@metamask/snaps-utils';
import type { CaipChainId } from '@metamask/utils';
import * as uuid from 'uuid';

Check warning on line 20 in packages/accounts-controller/src/AccountsController.test.ts

View workflow job for this annotation

GitHub Actions / Lint, build, and test / Lint (22.x)

No exported names found in module 'uuid'
import type { V4Options } from 'uuid';

import type {
Expand Down Expand Up @@ -280,7 +280,7 @@
});

describe('onSnapStateChange', () => {
it('be used enable an account if the Snap is enabled and not blocked', async () => {
it('enables an account if the Snap is enabled and not blocked', async () => {
const messenger = buildMessenger();
const mockSnapAccount = createMockInternalAccount({
id: 'mock-id',
Expand Down Expand Up @@ -326,7 +326,7 @@
expect(updatedAccount.metadata.snap?.enabled).toBe(true);
});

it('be used disable an account if the Snap is disabled', async () => {
it('disables an account if the Snap is disabled', async () => {
const messenger = buildMessenger();
const mockSnapAccount = createMockInternalAccount({
id: 'mock-id',
Expand Down Expand Up @@ -372,7 +372,7 @@
expect(updatedAccount.metadata.snap?.enabled).toBe(false);
});

it('be used disable an account if the Snap is blocked', async () => {
it('disables an account if the Snap is blocked', async () => {
const messenger = buildMessenger();
const mockSnapAccount = createMockInternalAccount({
id: 'mock-id',
Expand Down Expand Up @@ -417,6 +417,61 @@

expect(updatedAccount.metadata.snap?.enabled).toBe(false);
});

it('does not trigger any unnecessary updates', async () => {
const messenger = buildMessenger();
const mockSnapAccount = createMockInternalAccount({
id: 'mock-id',
name: 'Snap Account 1',
address: '0x0',
keyringType: KeyringTypes.snap,
snap: {
id: 'mock-snap',
name: 'mock-snap-name',
enabled: false, // Will be enabled later by a `SnapController:stateChange`.
},
});
const mockSnapChangeState = {
snaps: {
'mock-snap': {
enabled: true,
id: 'mock-snap',
blocked: false,
status: SnapStatus.Running,
},
},
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any as SnapControllerState;
const mockStateChange = jest.fn();
const { accountsController } = setupAccountsController({
initialState: {
internalAccounts: {
accounts: {
[mockSnapAccount.id]: mockSnapAccount,
},
selectedAccount: mockSnapAccount.id,
},
},
messenger,
});

messenger.subscribe('AccountsController:stateChange', mockStateChange);

// First update will update the account's metadata, thus triggering a `AccountsController:stateChange`.
messenger.publish('SnapController:stateChange', mockSnapChangeState, []);
const updatedAccount = accountsController.getAccountExpect(
mockSnapAccount.id,
);
expect(updatedAccount.metadata.snap?.enabled).toBe(true);
expect(mockStateChange).toHaveBeenCalled();

// Second update is the same, thus the account does not need any update, and SHOULD NOT trigger a `AccountsController:stateChange`.
mockStateChange.mockReset();
messenger.publish('SnapController:stateChange', mockSnapChangeState, []);
expect(updatedAccount.metadata.snap?.enabled).toBe(true);
expect(mockStateChange).not.toHaveBeenCalled();
});
});

describe('onKeyringStateChange', () => {
Expand Down
35 changes: 21 additions & 14 deletions packages/accounts-controller/src/AccountsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -988,24 +988,31 @@ export class AccountsController extends BaseController<
#handleOnSnapStateChange(snapState: SnapControllerState) {
// only check if snaps changed in status
const { snaps } = snapState;
const accounts = this.listMultichainAccounts().filter(
(account) => account.metadata.snap,
);

this.update((currentState) => {
accounts.forEach((account) => {
const currentAccount =
currentState.internalAccounts.accounts[account.id];
if (currentAccount.metadata.snap) {
const snapId = currentAccount.metadata.snap.id;
const storedSnap: Snap = snaps[snapId as SnapId];
if (storedSnap) {
currentAccount.metadata.snap.enabled =
storedSnap.enabled && !storedSnap.blocked;
const accounts: { id: string; enabled: boolean }[] = [];
for (const account of this.listMultichainAccounts()) {
if (account.metadata.snap) {
const snap: Snap = snaps[account.metadata.snap.id as SnapId];
const enabled = snap.enabled && !snap.blocked;
const metadata = account.metadata.snap;

if (metadata.enabled !== enabled) {
accounts.push({ id: account.id, enabled });
}
}
}

if (accounts.length > 0) {
this.update((state) => {
for (const { id, enabled } of accounts) {
const account = state.internalAccounts.accounts[id];

if (account.metadata.snap) {
account.metadata.snap.enabled = enabled;
Comment on lines +992 to +1011
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we add some test cases to cover the new scenario

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, just added one, thanks :)

}
}
});
});
}
}

/**
Expand Down
Loading