Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0b94d68
feat: Implement wallet initialization library
FrederikBolding May 18, 2026
c60a904
Add KeyringController initialization
FrederikBolding May 18, 2026
cba84fb
Update README
FrederikBolding May 18, 2026
6e45a2f
Add more tests
FrederikBolding May 18, 2026
b4bf73c
Fix Yarn constraints
FrederikBolding May 18, 2026
9a2bb50
Add instance specific options
FrederikBolding May 18, 2026
90b4ca7
Return instances directly
FrederikBolding May 18, 2026
77a0013
Add CHANGELOG
FrederikBolding May 18, 2026
465ed33
Fix tests and lint
FrederikBolding May 18, 2026
04e70f2
Fix Node 18 tests
FrederikBolding May 18, 2026
0f91628
Expose instances for now
FrederikBolding May 18, 2026
48fb182
Allow passing messenger
FrederikBolding May 19, 2026
0fd9d7f
Address a couple comments
FrederikBolding May 19, 2026
d706aa2
Address more PR comments
FrederikBolding May 20, 2026
7eb54d2
Fix import
FrederikBolding May 20, 2026
8b2d364
Tweak state types
FrederikBolding May 20, 2026
23ef6e2
Export DefaultInstances
FrederikBolding May 20, 2026
0b89138
Add overloads for getInstance
FrederikBolding May 20, 2026
285edb4
Use camel case for instanceOptions
FrederikBolding May 21, 2026
2bdac54
Tweak encryptor types
FrederikBolding May 21, 2026
33fc20d
Fix cast
FrederikBolding May 21, 2026
49b8e9e
Add MobileEncryptionResult type
FrederikBolding May 21, 2026
559f322
Adjust messenger name, add JSDocs, cleanup
FrederikBolding May 21, 2026
a2c4a8c
Address more PR comments
FrederikBolding May 21, 2026
5a37811
Remove unused import
FrederikBolding May 21, 2026
681bd35
Export DefaultState
FrederikBolding May 21, 2026
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,9 @@ linkStyle default opacity:0.5
user_operation_controller --> polling_controller;
user_operation_controller --> transaction_controller;
user_operation_controller --> eth_block_tracker;
wallet --> base_controller;
wallet --> keyring_controller;
wallet --> messenger;
```

<!-- end dependency graph -->
Expand Down
4 changes: 4 additions & 0 deletions packages/wallet/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Initial release ([#8838](https://github.com/MetaMask/core/pull/8838))

[Unreleased]: https://github.com/MetaMask/core/
6 changes: 3 additions & 3 deletions packages/wallet/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ module.exports = merge(baseConfig, {
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
functions: 89.65,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is it possible to reach 100%?

lines: 95.77,
statements: 95.89,
},
},
});
8 changes: 8 additions & 0 deletions packages/wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
},
"dependencies": {
"@metamask/base-controller": "^9.1.0",
"@metamask/browser-passworder": "^6.0.0",
"@metamask/keyring-controller": "^25.5.0",
"@metamask/messenger": "^1.2.0",
"@metamask/scure-bip39": "^2.1.1",
"@metamask/utils": "^11.9.0"
},
"devDependencies": {
"@metamask/auto-changelog": "^6.1.0",
"@ts-bridge/cli": "^0.6.4",
Expand Down
202 changes: 202 additions & 0 deletions packages/wallet/src/Wallet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { Messenger } from '@metamask/messenger';
import { Json } from '@metamask/utils';
import { webcrypto } from 'crypto';

import MockEncryptor from '../../keyring-controller/tests/mocks/mockEncryptor';
import * as initializationModule from './initialization/initialization';
import { importSecretRecoveryPhrase } from './utilities';
import { Wallet } from './Wallet';

const TEST_SRP = 'test test test test test test test test test test test ball';
const TEST_PASSWORD = 'testpass';

async function setupWallet(): Promise<Wallet> {
const wallet = new Wallet({});

await importSecretRecoveryPhrase(wallet, TEST_PASSWORD, TEST_SRP);

return wallet;
}

describe('Wallet', () => {
beforeAll(() => {
// We can remove this once we drop Node 18
// eslint-disable-next-line n/no-unsupported-features/node-builtins
globalThis.crypto ??= webcrypto as typeof globalThis.crypto;

// eslint-disable-next-line no-restricted-syntax
if (!('CryptoKey' in globalThis)) {
Object.defineProperty(globalThis, 'CryptoKey', {
value: webcrypto.CryptoKey,
});
}
});

it('exposes state', async () => {
const wallet = await setupWallet();
const { state } = wallet;

expect(state.KeyringController).toStrictEqual({
isUnlocked: true,
keyrings: expect.any(Array),
encryptionKey: expect.any(String),
encryptionSalt: expect.any(String),
vault: expect.any(String),
});
});

it('exposes instances', async () => {
const wallet = await setupWallet();

expect(wallet.getInstance('KeyringController').state).toStrictEqual({
isUnlocked: true,
keyrings: expect.any(Array),
encryptionKey: expect.any(String),
encryptionSalt: expect.any(String),
vault: expect.any(String),
});
});

it('supports passing instance options', async () => {
const wallet = new Wallet({
instanceOptions: {
keyringController: {
encryptor: new MockEncryptor(),
},
},
});

await importSecretRecoveryPhrase(wallet, TEST_PASSWORD, TEST_SRP);

const { state } = wallet;

const vault = JSON.parse(state.KeyringController.vault as string);

expect(vault).toStrictEqual({
data: expect.any(String),
iv: 'iv',
salt: 'salt',
});
});

it('supports passing additional initialization configurations', async () => {
class DummyController {
state = { foo: 'bar' };
}

class DummyService {}

const wallet = new Wallet({
initializationConfigurations: [
{
name: 'KeyringController',
getMessenger: (): Messenger<string> =>
new Messenger({ namespace: 'KeyringController' }),
init: (): DummyController => new DummyController(),
},
{
name: 'TestService',
getMessenger: (): Messenger<string> =>
new Messenger({ namespace: 'TestService' }),
init: (): DummyService => new DummyService(),
},
],
});
const { state } = wallet;

expect(state.KeyringController).toStrictEqual({
foo: 'bar',
});

expect((state as Record<string, Json>).TestService).toBeUndefined();
});

it('exposes controllerMetadata for each initialized controller', async () => {
const wallet = await setupWallet();

const names = Object.keys(wallet.controllerMetadata);
expect(names).toStrictEqual(Object.keys(wallet.state));
for (const name of names) {
expect(wallet.controllerMetadata[name]).toBeDefined();
}
});

it('omits instances without a metadata property from controllerMetadata', async () => {
const fakeMetadata = {
foo: { persist: true, includeInDebugSnapshot: false },
};
jest.spyOn(initializationModule, 'initialize').mockReturnValueOnce({
// @ts-expect-error Mock data.
WithMeta: { state: {}, metadata: fakeMetadata },
NoMeta: { state: {} },
});

const wallet = new Wallet({});

expect(wallet.controllerMetadata).toStrictEqual({
WithMeta: fakeMetadata,
});
expect(Object.keys(wallet.state)).toStrictEqual(['WithMeta', 'NoMeta']);
});

it('disallows modifying the messenger', async () => {
const wallet = await setupWallet();

expect(() => {
wallet.messenger = new Messenger({ namespace: 'Root' });
}).toThrow('The messenger cannot be directly mutated.');
});

it('disallows modifying the state', async () => {
const wallet = await setupWallet();

expect(() => {
wallet.state = { KeyringController: { isUnlocked: false, keyrings: [] } };
}).toThrow('Wallet state cannot be directly mutated.');
});

it('disallows modifying the controller metadata', async () => {
const wallet = await setupWallet();

expect(() => {
wallet.controllerMetadata = {};
}).toThrow('The controller metadata cannot be directly mutated.');
});

it('calls destroy on instances exactly once', async () => {
const wallet = await setupWallet();

const keyringController = wallet.getInstance('KeyringController');

const spy = jest.spyOn(keyringController, 'destroy');

await wallet.destroy();
await wallet.destroy();

expect(spy).toHaveBeenCalledTimes(1);
});

describe('KeyringController', () => {
it('can unlock and populate accounts', async () => {
const wallet = await setupWallet();
const { messenger } = wallet;

expect(
await messenger.call('KeyringController:getAccounts'),
).toStrictEqual(['0xc6d5a3c98ec9073b54fa0969957bd582e8d874bf']);
});

it('can lock', async () => {
const wallet = await setupWallet();
const { messenger } = wallet;

await messenger.call('KeyringController:setLocked');

expect(wallet.state.KeyringController).toStrictEqual({
isUnlocked: false,
keyrings: [],
vault: expect.any(String),
});
});
});
});
144 changes: 144 additions & 0 deletions packages/wallet/src/Wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type { StateMetadataConstraint } from '@metamask/base-controller';
import { Messenger } from '@metamask/messenger';
import { hasProperty } from '@metamask/utils';

import type {
DefaultActions,
DefaultEvents,
DefaultInstances,
DefaultState,
RootMessenger,
} from './initialization/defaults';
import { initialize } from './initialization/initialization';
import { WalletOptions } from './types';

export class Wallet {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: Would be good to add JSDoc that briefly describes the purpose of this class and provides an example. Same for the README. This can be done in a future PR, however.

// TODO: Expand default types when passing additionalConfigurations.
readonly #messenger: RootMessenger<DefaultActions, DefaultEvents>;

readonly #instances: DefaultInstances;

readonly #controllerMetadata: Readonly<
Record<string, Readonly<StateMetadataConstraint>>
>;

#isDestroyed = false;

/**
* Creates a `Wallet` instance, initializing all instances as specified by the passed options.
*
* @param options - Options bag.
* @param options.messenger - An optional messenger to override the default one.
* @param options.state - An optional state blob.
* @param options.initializationConfigurations - An optional list of additional initialization configurations
* required beyond the ones included by default.
* @param options.instanceOptions - An optional object containing options that should be passed
* to specific instances for additional customization.
*/
constructor(options: WalletOptions) {
this.#messenger =
options.messenger ??
new Messenger({
namespace: 'Root',
});

this.#instances = initialize({
...options,
messenger: this.#messenger,
});

this.#controllerMetadata = Object.fromEntries(
Object.entries(this.#instances)
.filter(([_, instance]) => hasProperty(instance, 'metadata'))
.map(([name, instance]) => [name, instance.metadata]),
);
}

/**
* @returns The root messenger of the wallet.
*/
get messenger(): Readonly<RootMessenger<DefaultActions, DefaultEvents>> {
Comment thread
mcmire marked this conversation as resolved.
return this.#messenger;
}

set messenger(_) {
throw new Error('The messenger cannot be directly mutated.');
Comment thread
Mrtenz marked this conversation as resolved.
}

/**
* @returns The combined state of the wallet.
*/
get state(): DefaultState {
return Object.entries(this.#instances).reduce<Record<string, unknown>>(
(totalState, [name, instance]) => {
if (instance.state) {
Comment thread
FrederikBolding marked this conversation as resolved.
totalState[name] = instance.state;
}
return totalState;
},
{},
) as DefaultState;
}

set state(_) {
throw new Error('Wallet state cannot be directly mutated.');
}

/**
* @returns The controller metadata; containing per-controller information about what properties to persist etc.
*/
get controllerMetadata(): Readonly<
Record<string, Readonly<StateMetadataConstraint>>
> {
return this.#controllerMetadata;
}

set controllerMetadata(_) {
throw new Error('The controller metadata cannot be directly mutated.');
}

getInstance<Name extends keyof DefaultInstances>(
name: Name,
): DefaultInstances[Name];

getInstance(
name: string,
): DefaultInstances[keyof DefaultInstances] | undefined;

/**
* Get an instantiated controller or service.
*
* @param name - The name.
* @returns The instance, if it exists.
* @deprecated - Please use the messenger instead of direct access.
*/
getInstance(
name: string,
): DefaultInstances[keyof DefaultInstances] | undefined {
return this.#instances[name as keyof DefaultInstances];
}

/**
* Destroy the wallet instance.
*/
async destroy(): Promise<void> {
if (this.#isDestroyed) {
return;
}

this.#isDestroyed = true;

await Promise.allSettled(
Object.values(this.#instances).map(async (instance) => {
// @ts-expect-error Accessing protected property.
if (typeof instance.destroy === 'function') {
// @ts-expect-error Accessing protected property.
// eslint-disable-next-line @typescript-eslint/await-thenable
return await instance.destroy();
}
/* istanbul ignore next */
return undefined;
}),
);
}
}
Loading
Loading