Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 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
8e35748
Add CODEOWNERS entry
FrederikBolding May 26, 2026
2bbd49c
Add a couple more tests
FrederikBolding May 26, 2026
19bfd38
Fix tests on Node 18
FrederikBolding May 26, 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 .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@
/packages/client-controller @MetaMask/core-platform @MetaMask/extension-platform @MetaMask/mobile-platform
/packages/profile-metrics-controller @MetaMask/mobile-platform @MetaMask/extension-platform

## Initialization
/packages/wallet/src/initialization/instances/keyring-controller.ts @MetaMask/accounts-engineers @MetaMask/core-platform

## Package Release related
/packages/account-tree-controller/package.json @MetaMask/accounts-engineers @MetaMask/core-platform
/packages/account-tree-controller/CHANGELOG.md @MetaMask/accounts-engineers @MetaMask/core-platform
Expand Down
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/
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",

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.

I guess we're using this package in a way that works across platforms? Curious if it might be worth it at some point to extract the more platform-agnostic functions to some other library. Otherwise it might be a bit confusing. We can think about that later perhaps.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@metamask/browser-passworder works on most platforms except mobile, so it seemed fine to include. It's a good default option IMO.

"@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
228 changes: 228 additions & 0 deletions packages/wallet/src/Wallet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
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 unlock a persisted vault', async () => {
const vault =
'{"data":"iOD5pIcPeRZYQ4WdEMsNYoZ3xBxWBafIU8Cr4nD0X4zBvrOA06tGen3sKQ/ValasXSweLnzH9Fk2frkPYmqeJWBtTNYFwdHPe7P970ThZwreSXN1Sqrx9Ad+YzmIN0y89Yg3KrUodPWaRgIZmgWbfDon6ADPgeEDkX0/GAEYET39O7Rx/gL+rcaTpxnpHPTgHiLbhRHWGsS3z+JVomSqoLAO5XVvrJWenO6R3Nzm62BaJaSPrf/pwstZqhSvxTq8hnQf7aR81hWfwYTxNBVG7TC/dniSQ8K5So6PvUN5nzAqvtzzHT2TagOuxQkX88Zi17P8os21jNmNdA90IGYroD+b/mppyRIgRYWtAUQZH9ji36atEuFupszbg8Qw1iaL3EQyUogC30Cpj9ko5bbqhYgqmFHF0J/kflhPHKuO6d4tgSmhYpTumydQRjxaPnlghIS5YI4W+7p9HVBpb+c6IPUz9y/x3Ngbp+ukJwOnXt2U/eZhXrJzi2z1x/nzPg4fzDJoM7k=","iv":"yrZsyC7dso/q7pQ48YX3vw==","keyMetadata":{"algorithm":"PBKDF2","params":{"iterations":600000}},"salt":"s7nIrMWK1lcZVjfdmES1DBML8Uz4ja2fpm8zUz1lWI0="}';

const wallet = new Wallet({
state: {
KeyringController: {
vault,
},
},
});

await wallet.messenger.call(
'KeyringController:submitPassword',
TEST_PASSWORD,
);

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

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),
});
});
});
});
Loading
Loading