Skip to content

perf(keyring-controller): do not fire unnecessary :stageChange in withKeyring #5732

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ccharly
Copy link
Contributor

@ccharly ccharly commented Apr 30, 2025

Explanation

We were always calling #updateVault when using withKeyring even when the keyring was not mutated.

This PR now compare the states after the operation execution and see if the keyring got updated or not and decide to call #updateVault only if needed.

Testing PR:

References

N/A

Changelog

N/A

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 communicated my changes to consumers by updating changelogs for packages I've changed, highlighting breaking changes as necessary
  • I've prepared draft pull requests for clients and consumer packages to resolve any breaking changes

@ccharly ccharly force-pushed the perf/with-keyring branch from ba27fd6 to f603e07 Compare April 30, 2025 11:53
@ccharly
Copy link
Contributor Author

ccharly commented Apr 30, 2025

@metamaskbot publish-preview

Copy link
Contributor

Preview builds have been published. See these instructions for more information about preview builds.

Expand for full list of packages and versions.
{
  "@metamask-previews/accounts-controller": "27.0.0-preview-f603e07",
  "@metamask-previews/address-book-controller": "6.0.3-preview-f603e07",
  "@metamask-previews/announcement-controller": "7.0.3-preview-f603e07",
  "@metamask-previews/app-metadata-controller": "1.0.0-preview-f603e07",
  "@metamask-previews/approval-controller": "7.1.3-preview-f603e07",
  "@metamask-previews/assets-controllers": "60.0.0-preview-f603e07",
  "@metamask-previews/base-controller": "8.0.1-preview-f603e07",
  "@metamask-previews/bridge-controller": "19.0.0-preview-f603e07",
  "@metamask-previews/bridge-status-controller": "16.0.0-preview-f603e07",
  "@metamask-previews/build-utils": "3.0.3-preview-f603e07",
  "@metamask-previews/chain-agnostic-permission": "0.5.0-preview-f603e07",
  "@metamask-previews/composable-controller": "11.0.0-preview-f603e07",
  "@metamask-previews/controller-utils": "11.7.0-preview-f603e07",
  "@metamask-previews/delegation-controller": "0.1.0-preview-f603e07",
  "@metamask-previews/earn-controller": "0.12.0-preview-f603e07",
  "@metamask-previews/eip1193-permission-middleware": "0.1.0-preview-f603e07",
  "@metamask-previews/ens-controller": "16.0.0-preview-f603e07",
  "@metamask-previews/eth-json-rpc-provider": "4.1.8-preview-f603e07",
  "@metamask-previews/gas-fee-controller": "23.0.0-preview-f603e07",
  "@metamask-previews/json-rpc-engine": "10.0.3-preview-f603e07",
  "@metamask-previews/json-rpc-middleware-stream": "8.0.7-preview-f603e07",
  "@metamask-previews/keyring-controller": "21.0.4-preview-f603e07",
  "@metamask-previews/logging-controller": "6.0.4-preview-f603e07",
  "@metamask-previews/message-manager": "12.0.1-preview-f603e07",
  "@metamask-previews/multichain": "4.0.0-preview-f603e07",
  "@metamask-previews/multichain-api-middleware": "0.2.0-preview-f603e07",
  "@metamask-previews/multichain-network-controller": "0.5.1-preview-f603e07",
  "@metamask-previews/multichain-transactions-controller": "0.9.0-preview-f603e07",
  "@metamask-previews/name-controller": "8.0.3-preview-f603e07",
  "@metamask-previews/network-controller": "23.3.0-preview-f603e07",
  "@metamask-previews/notification-services-controller": "6.0.0-preview-f603e07",
  "@metamask-previews/permission-controller": "11.0.6-preview-f603e07",
  "@metamask-previews/permission-log-controller": "3.0.3-preview-f603e07",
  "@metamask-previews/phishing-controller": "12.5.0-preview-f603e07",
  "@metamask-previews/polling-controller": "13.0.0-preview-f603e07",
  "@metamask-previews/preferences-controller": "17.0.0-preview-f603e07",
  "@metamask-previews/profile-sync-controller": "12.0.0-preview-f603e07",
  "@metamask-previews/queued-request-controller": "10.0.0-preview-f603e07",
  "@metamask-previews/rate-limit-controller": "6.0.3-preview-f603e07",
  "@metamask-previews/remote-feature-flag-controller": "1.6.0-preview-f603e07",
  "@metamask-previews/sample-controllers": "0.1.0-preview-f603e07",
  "@metamask-previews/selected-network-controller": "22.0.0-preview-f603e07",
  "@metamask-previews/signature-controller": "27.1.0-preview-f603e07",
  "@metamask-previews/token-search-discovery-controller": "3.1.0-preview-f603e07",
  "@metamask-previews/transaction-controller": "54.3.0-preview-f603e07",
  "@metamask-previews/user-operation-controller": "33.0.0-preview-f603e07"
}

@ccharly ccharly marked this pull request as ready for review April 30, 2025 14:13
@ccharly ccharly requested review from a team as code owners April 30, 2025 14:13
@@ -1551,8 +1552,9 @@ export class KeyringController extends BaseController<
): Promise<CallbackResult> {
this.#assertIsUnlocked();

return this.#persistOrRollback(async () => {
return this.#withRollback(async () => {
Copy link
Member

Choose a reason for hiding this comment

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

Thoughts on moving the check in #persistOrRollback instead of using #withRollback here? it would avoid giving to withKeyring the responsibility to update the vault directly

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, that was my initial idea but the thing is I need to have a reference of the keyring to be able to serialize it.

So this would probably require to move the "keyring selector" to that method?

I also thought of adding a new persistKeyringOrRollback to not pollute the existing persistOrRollback.

Any preferences?

Copy link
Member

Choose a reason for hiding this comment

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

We wouldn't check a single keyring in #persistOrRollback (as some operations need to interact with multiple keyrings) - we would have to use this.#getSerializedKeyrings() before and after executing the callback passed to #persistOrRollback

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That makes sense yes, I just went with the "fastest option" (being, just serializing + comparing what we need in that case)

But having this in #persistOrRollback is an option too, just potentially a bit slower, but maybe we wouldn't notice the difference.

Comment on lines 1574 to 1575
// This is a new keyring, so we force the vault update in that case.
forceUpdate = true;
Copy link
Member

@mikesposito mikesposito Apr 30, 2025

Choose a reason for hiding this comment

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

As the withKeyring overload that creates a new keyring is deprecated (createIfMissing), thoughts on removing it completely so that we don't need to manage this case?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I can definitely get rid of this yes. I thought we were still relying on this behavior in some of the clients, and given that the keyring is not yet on the vault at that point, I needed a way to force call the #updateVault method.

Copy link
Member

@mikesposito mikesposito Apr 30, 2025

Choose a reason for hiding this comment

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

I think that it is probably used in a couple of places, but I don't see blockers from using addNewKeyring explicitly

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As discussed internally, if we don't support this anymore, we probably wants to remove the deprecated method altogether, given that, without the forceUpdate logic, the createIfMissing option won't work anymore, so I'd just remove it entirely (but we could do that in another PR and keep the force update logic for now)

Comment on lines 3085 to 3111
it('should update the vault if the keyring is being updated', async () => {
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockMutableKeyring)] },
async ({ controller, messenger }) => {
const selector = { type: MockMutableKeyring.type };

const mockStateChange = jest.fn();
messenger.subscribe(
'KeyringController:stateChange',
mockStateChange,
);

await controller.withKeyring(
selector,
async ({ keyring }) => {
(keyring as MockMutableKeyring).update(); // Update the keyring state.
},
{
createIfMissing: true,
},
);

expect(mockStateChange).toHaveBeenCalled();
expect(controller.state.keyrings).toHaveLength(2);
},
);
});
Copy link
Member

@mikesposito mikesposito Apr 30, 2025

Choose a reason for hiding this comment

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

nit: We can probably accomplish the same result without adding a MockMutableKeyring and by looking at what happens to the vault specifically through the encryptor (also without using the deprecated variant of withKeyring):

Suggested change
it('should update the vault if the keyring is being updated', async () => {
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockMutableKeyring)] },
async ({ controller, messenger }) => {
const selector = { type: MockMutableKeyring.type };
const mockStateChange = jest.fn();
messenger.subscribe(
'KeyringController:stateChange',
mockStateChange,
);
await controller.withKeyring(
selector,
async ({ keyring }) => {
(keyring as MockMutableKeyring).update(); // Update the keyring state.
},
{
createIfMissing: true,
},
);
expect(mockStateChange).toHaveBeenCalled();
expect(controller.state.keyrings).toHaveLength(2);
},
);
});
it('should update the vault if the keyring is being updated', async () => {
stubKeyringClassWithAccount(MockKeyring, '0x1234');
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockKeyring)] },
async ({ controller, encryptor }) => {
await controller.addNewKeyring(MockKeyring.type);
const encryptSpy = jest.spyOn(encryptor, 'encrypt');
jest.spyOn(MockKeyring.prototype, 'serialize').mockResolvedValue({
foo: 'bar',
});
await controller.withKeyring(
{ type: MockKeyring.type },
async () => {
// No-op
},
);
expect(encryptSpy).not.toHaveBeenCalled();
},
);
});

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I did something similar to your suggestion but kept my use of the messenger since I think it's more "explicit" for my use-case: 676415f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: performance degradation during account creation
2 participants