Skip to content

perf(keyring-controller): add withReadonlyKeyring action #5727

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions packages/keyring-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add `withReadonlyKeyring` action ([#5727](https://github.com/MetaMask/core/pull/5727))

### Changed

- Bump `@metamask/base-controller` from ^8.0.0 to ^8.0.1 ([#5722](https://github.com/MetaMask/core/pull/5722))
Expand Down
168 changes: 131 additions & 37 deletions packages/keyring-controller/src/KeyringController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ export type KeyringControllerWithKeyringAction = {
handler: KeyringController['withKeyring'];
};

export type KeyringControllerWithReadonlyKeyringAction = {
type: `${typeof name}:withReadonlyKeyring`;
handler: KeyringController['withReadonlyKeyring'];
};

export type KeyringControllerStateChangeEvent = {
type: `${typeof name}:stateChange`;
payload: [KeyringControllerState, Patch[]];
Expand Down Expand Up @@ -233,7 +238,8 @@ export type KeyringControllerActions =
| KeyringControllerPatchUserOperationAction
| KeyringControllerSignUserOperationAction
| KeyringControllerAddNewAccountAction
| KeyringControllerWithKeyringAction;
| KeyringControllerWithKeyringAction
| KeyringControllerWithReadonlyKeyringAction;

export type KeyringControllerEvents =
| KeyringControllerStateChangeEvent
Expand Down Expand Up @@ -1465,6 +1471,74 @@ export class KeyringController extends BaseController<
);
}

/**
* Execute an operation on the selected keyring.
*
* @param selector - Keyring selector object.
* @param operation - Function to execute with the selected keyring.
* @param options - Additional options.
* @returns Promise resolving to the result of the function execution.
* @template SelectedKeyring - The type of the selected keyring.
* @template CallbackResult - The type of the value resolved by the callback function.
*/
async #executeWithKeyring<
SelectedKeyring extends EthKeyring = EthKeyring,
CallbackResult = void,
>(
selector: KeyringSelector,
operation: ({
keyring,
metadata,
}: {
keyring: SelectedKeyring;
metadata: KeyringMetadata;
}) => Promise<CallbackResult>,

options:
| { createIfMissing?: false }
| { createIfMissing: true; createWithData?: unknown },
): Promise<CallbackResult> {
let keyring: SelectedKeyring | undefined;

if ('address' in selector) {
keyring = (await this.getKeyringForAccount(selector.address)) as
| SelectedKeyring
| undefined;
} else if ('type' in selector) {
keyring = this.getKeyringsByType(selector.type)[selector.index || 0] as
| SelectedKeyring
| undefined;

if (!keyring && options.createIfMissing) {
keyring = (await this.#newKeyring(
selector.type,
options.createWithData,
)) as SelectedKeyring;
}
} else if ('id' in selector) {
keyring = this.#getKeyringById(selector.id) as SelectedKeyring;
}

if (!keyring) {
throw new Error(KeyringControllerError.KeyringNotFound);
}

const result = await operation({
keyring,
metadata: this.#getKeyringMetadata(keyring),
});

if (Object.is(result, keyring)) {
// Access to a keyring instance outside of controller safeguards
// should be discouraged, as it can lead to unexpected behavior.
// This error is thrown to prevent consumers using `withKeyring`
// as a way to get a reference to a keyring instance.
throw new Error(KeyringControllerError.UnsafeDirectKeyringAccess);
}

return result;
}

/**
* Select a keyring and execute the given operation with
* the selected keyring, as a mutually exclusive atomic
Expand Down Expand Up @@ -1552,45 +1626,60 @@ export class KeyringController extends BaseController<
this.#assertIsUnlocked();

return this.#persistOrRollback(async () => {
let keyring: SelectedKeyring | undefined;

if ('address' in selector) {
keyring = (await this.getKeyringForAccount(selector.address)) as
| SelectedKeyring
| undefined;
} else if ('type' in selector) {
keyring = this.getKeyringsByType(selector.type)[selector.index || 0] as
| SelectedKeyring
| undefined;

if (!keyring && options.createIfMissing) {
keyring = (await this.#newKeyring(
selector.type,
options.createWithData,
)) as SelectedKeyring;
}
} else if ('id' in selector) {
keyring = this.#getKeyringById(selector.id) as SelectedKeyring;
}

if (!keyring) {
throw new Error(KeyringControllerError.KeyringNotFound);
}
return await this.#executeWithKeyring(selector, operation, options);
});
}

const result = await operation({
keyring,
metadata: this.#getKeyringMetadata(keyring),
});
/**
* Select a keyring and execute the given operation with
* the selected keyring, as a mutually exclusive atomic
* operation.
*
* The method won't persists changes at the end of the
* function execution.
*
* @param selector - Keyring selector object.
* @param operation - Function to execute with the selected keyring.
* @returns Promise resolving to the result of the function execution.
* @template SelectedKeyring - The type of the selected keyring.
* @template CallbackResult - The type of the value resolved by the callback function.
*/
async withReadonlyKeyring<
SelectedKeyring extends EthKeyring = EthKeyring,
CallbackResult = void,
>(
selector: KeyringSelector,
operation: ({
keyring,
metadata,
}: {
keyring: Readonly<SelectedKeyring>;
metadata: KeyringMetadata;
}) => Promise<CallbackResult>,
): Promise<CallbackResult>;

if (Object.is(result, keyring)) {
// Access to a keyring instance outside of controller safeguards
// should be discouraged, as it can lead to unexpected behavior.
// This error is thrown to prevent consumers using `withKeyring`
// as a way to get a reference to a keyring instance.
throw new Error(KeyringControllerError.UnsafeDirectKeyringAccess);
}
async withReadonlyKeyring<
SelectedKeyring extends EthKeyring = EthKeyring,
CallbackResult = void,
>(
selector: KeyringSelector,
operation: ({
keyring,
metadata,
}: {
keyring: Readonly<SelectedKeyring>;
metadata: KeyringMetadata;
}) => Promise<CallbackResult>,
options:
| { createIfMissing?: false }
| { createIfMissing: true; createWithData?: unknown } = {
createIfMissing: false,
},
): Promise<CallbackResult> {
this.#assertIsUnlocked();

return result;
return this.#withControllerLock(async () => {
return await this.#executeWithKeyring(selector, operation, options);
});
}

Expand Down Expand Up @@ -1913,6 +2002,11 @@ export class KeyringController extends BaseController<
`${name}:withKeyring`,
this.withKeyring.bind(this),
);

this.messagingSystem.registerActionHandler(
`${name}:withReadonlyKeyring`,
this.withReadonlyKeyring.bind(this),
);
}

/**
Expand Down
Loading