-
-
Notifications
You must be signed in to change notification settings - Fork 279
feat: Implement wallet initialization library #8838
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
FrederikBolding
wants to merge
26
commits into
main
Choose a base branch
from
fb/wallet-lib-v1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 c60a904
Add KeyringController initialization
FrederikBolding cba84fb
Update README
FrederikBolding 6e45a2f
Add more tests
FrederikBolding b4bf73c
Fix Yarn constraints
FrederikBolding 9a2bb50
Add instance specific options
FrederikBolding 90b4ca7
Return instances directly
FrederikBolding 77a0013
Add CHANGELOG
FrederikBolding 465ed33
Fix tests and lint
FrederikBolding 04e70f2
Fix Node 18 tests
FrederikBolding 0f91628
Expose instances for now
FrederikBolding 48fb182
Allow passing messenger
FrederikBolding 0fd9d7f
Address a couple comments
FrederikBolding d706aa2
Address more PR comments
FrederikBolding 7eb54d2
Fix import
FrederikBolding 8b2d364
Tweak state types
FrederikBolding 23ef6e2
Export DefaultInstances
FrederikBolding 0b89138
Add overloads for getInstance
FrederikBolding 285edb4
Use camel case for instanceOptions
FrederikBolding 2bdac54
Tweak encryptor types
FrederikBolding 33fc20d
Fix cast
FrederikBolding 49b8e9e
Add MobileEncryptionResult type
FrederikBolding 559f322
Adjust messenger name, add JSDocs, cleanup
FrederikBolding a2c4a8c
Address more PR comments
FrederikBolding 5a37811
Remove unused import
FrederikBolding 681bd35
Export DefaultState
FrederikBolding File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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), | ||
| }); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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>> { | ||
|
mcmire marked this conversation as resolved.
|
||
| return this.#messenger; | ||
| } | ||
|
|
||
| set messenger(_) { | ||
| throw new Error('The messenger cannot be directly mutated.'); | ||
|
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) { | ||
|
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; | ||
| }), | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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%?