Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@metamask/eth-keyring-controller

MetaMask2.7kISC17.0.1TypeScript support: included

A module for managing various keyrings of Ethereum accounts, encrypting them, and using them

ethereum, metamask, accounts, keys

readme

Eth Keyring Controller

A module for managing groups of Ethereum accounts called "Keyrings", defined originally for MetaMask's multiple-account-type feature.

To add new account types to a KeyringController, just make sure it follows The Keyring Class Protocol.

The KeyringController has three main responsibilities:

  • Initializing & using (signing with) groups of Ethereum accounts ("keyrings").
  • Keeping track of local nicknames for those individual accounts.
  • Providing password-encryption persisting & restoring of secret information.

Installation

yarn add @metamask/eth-keyring-controller

This library uses the Node.js events API. If you are using this library outside of a Node.js context, ensure that you have a polyfill for the events API (this is built-in to browserify).

Usage

const { KeyringController } = require('@metamask/eth-keyring-controller');
const SimpleKeyring = require('@metamask/eth-simple-keyring');

const keyringController = new KeyringController({
  keyringTypes: [SimpleKeyring], // optional array of types to support.
  initState: initState.KeyringController, // Last emitted persisted state.
  encryptor: {
    // An optional object for defining encryption schemes:
    // Defaults to Browser-native SubtleCrypto.
    encrypt(password, object) {
      return new Promise('encrypted!');
    },
    decrypt(password, encryptedString) {
      return new Promise({ foo: 'bar' });
    },
  },
});

// The KeyringController is also an event emitter:
this.keyringController.on('newAccount', (address) => {
  console.log(`New account created: ${address}`);
});
this.keyringController.on('removedAccount', handleThat);

Methods

Currently the methods are heavily commented in the source code, so it's the best place to look until we aggregate it here as well.

Contributing

Setup

  • Install Node.js version 14
    • If you are using nvm (recommended) running nvm use will automatically choose the right node version for you.
  • Install Yarn v3
  • Run yarn install to install dependencies and run any required post-install scripts

Testing and Linting

Run yarn test to run the tests once.

Run yarn lint to run the linter, or run yarn lint:fix to run the linter and fix any automatically fixable issues.

Release & Publishing

The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions action-create-release-pr and action-publish-release are used to automate the release process; see those repositories for more information about how they work.

  1. Choose a release version.

    • The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See the SemVer specification for more information.
  2. If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. 1.x for a v1 backport release).

    • The major version branch should be set to the most recent release with that major version. For example, when backporting a v1.0.2 release, you'd want to ensure there was a 1.x branch that was set to the v1.0.1 tag.
  3. Trigger the workflow_dispatch event manually for the Create Release Pull Request action to create the release PR.

    • For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).
    • This should trigger the action-create-release-pr workflow to create the release PR.
  4. Update the changelog to move each change entry into the appropriate change category (See here for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.

    • Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).
    • Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
    • Consolidate related changes into one change entry if it makes it easier to explain.
    • Run yarn auto-changelog validate --rc to check that the changelog is correctly formatted.
  5. Review and QA the release.

    • If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.
  6. Squash & Merge the release.

    • This should trigger the action-publish-release workflow to tag the final release commit and publish the release on GitHub.
  7. Publish the release on npm.

    • Wait for the publish-release GitHub Action workflow to finish. This should trigger a second job (publish-npm), which will wait for a run approval by the npm publishers team.
    • Approve the publish-npm job (or ask somebody on the npm publishers team to approve it for you).
    • Once the publish-npm job has finished, check npm to verify that it has been published.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

Unreleased

17.0.1

Changed

  • Bump @metamask/keyring-api to ^3.0.0 (#344)

17.0.0

Changed

  • BREAKING: Unify createNewVaultAndKeychain and createNewVaultAndRestore into new method createNewVaultWithKeyring. createNewVaultWithKeyring accepts a password and a keyring object provided by the client and returns the KeyringControllerState (#329)
  • Bump @metamask/utils from 8.2.1 to 8.3.0 (#335)

16.0.0

Changed

  • BREAKING: Bump @metamask/obs-store from ^8.1.0 to ^9.0.0 (#306)
    • The store and memStore properties now expose streams confirming to readable-stream@^3.6.2
  • BREAKING: Replace GenericEncryptor.updateVault with GenericEncryptor.isVaultUpdated (#310))
  • Bump @metamask/browser-passworder from ^4.2.0 to ^4.3.0 (#310 #311)

Fixed

  • Prefer cached encryptionKey over password when possible (#307)

15.1.0

Added

  • Added optional isVaultUpdated property to GenericEncryptor type (#312)

Changed

  • Bump @metamask/browser-passworder to ^4.3.0 (#312)

Removed

  • Removed updateVault optional property from GenericEncryptor type (#312)

Fixed

  • Improved encryption performance when the controller is constructed with cacheEncryptionKey: true (#312)

15.0.0

Changed

  • BREAKING Removed encryptor class variable (#293)
  • BREAKING Removed cacheEncryptionKey class variable (#293)
  • BREAKING Changed encryptor constructor option property type to GenericEncryptor | ExportableKeyEncryptor | undefined (#293)
    • When the controller is instantiated with cacheEncryptionKey = true, the encryptor type is restricted to ExportableKeyEncryptor | undefined

14.0.1

Fixed

  • Fix removeAccount to await the account removal in order to account for Snaps keyrings (#280)
  • Bump @metamask/eth-simple-keyring from ^6.0.0 to ^6.0.1 (#287)

14.0.0

Changed

  • BREAKING: Bump @metamask/eth-sig-util from ^6.0.0 to ^7.0.0 (#269)
  • BREAKING: Bump @metamask/eth-hd-keyring from ^6.0.0 to ^7.0.1 (#275)
  • BREAKING: Bump @metamask/eth-simple-keyring from ^5.0.0 to ^6.0.0 (#273)

13.0.1

Changed

  • Bump @metamask/utils from ^6.2.0 to ^8.1.0 (#261)

13.0.0

Added

  • Added KeyringControllerPersistentState type which includes only persistent state, an optional string property with key vault (#247)
  • Added KeyringObject type for how keyrings are represented in memStore (#247)

Changed

  • BREAKING: Add types for store and fix type discrepancies (#247)
  • BREAKING: Constructor parameter KeyringControllerArgs fields changed (#247):
  • BREAKING: type of store and memStore public properties changed (#247):
    • KeyringController.store is now an ObservableStore<KeyringControllerPersistentState>
    • KeyringController.memStore is now an ObservableStore<KeyringControllerState>
  • BREAKING: updateMemStoreKeyrings method return type changed to Promise<void> (#247)
  • BREAKING: KeyringControllerState type changed to include only non-persistent state (#247):
    • Now undefined is used instead of null when encryptionKey and encryptionSalt are unset
    • keyrings is now of type KeyringObject[] instead of Keyring<Json>
    • password, store, memStore have been removed - note that in practice this change only affects types
    • This changes cause the following methods also to change the return type:
      • createNewVaultAndKeychain
      • createNewVaultAndRestore
      • setLocked
      • submitPassword
      • submitEncryptionKey
      • addNewAccount
      • removeAccount
      • fullUpdate
  • BREAKING: When constructing a simple keyring with addNewKeyring, the second parameter (opts) is now expected to be an array of private keys rather than an object with a privateKeys property (#253)
  • Restored support for keyrings with non-object serialized state (#253)
  • Narrow return type of signTypedMessage and encryption methods (#249)
    • The methods signTypedMessage, getEncryptionPublicKey, and decryptMessage now return string rather than Bytes

Fixed

  • Fix signTypedMessage parameter types (#250)
  • Restore compatibility with QR Keyring (#252)
    • An empty object is no longer used as a default when deserialized state was not provided to the addNewKeyring method. This default empty object was breaking the QR keyring.

12.0.1

Fixed

  • Improved error handling when calling getKeyringForAccount with empty or invalid address (#238)

12.0.0

Changed

  • BREAKING: Update @metamask/eth-sig-util to version ^6 (#235)
    • signPersonalMessage now normalizes msgParams.data in a different way for 0 and empty strings inputs. 0 will be normalized to 0x00 and empty strings to 0x
  • BREAKING: Update Node.js min version to 16.0.0 (#236)
  • Update @metamask/utils package (#234)
  • Destroy keyrings on reference drop (#233)

11.0.0

Changed

  • BREAKING: The addNewKeyring method now expects an object containing the property privateKeys of type string[] in case the supplied keyring is a "Simple Keyring". (#202), (#228)
  • Migrate the project to TypeScript (#202)
    • Methods that started with an underscore are now # private methods
    • Additional validation has been added to most methods
  • deps: Unpin and bump @metamask/eth-sig-utils@5.0.2->^5.1.0 (#224)

10.0.1

Fixed

  • Save encryption salt when persistAllKeyrings yields a new encryption key (#203)

10.0.0

Changed

  • BREAKING: Update module name to use @metamask scope (#187)
    • Consumers will now need to import this package as @metamask/eth-keyring-controller
  • BREAKING: @metamask/eth-hd-keyring to v6.0.0 (#193)
    • Reverts the serialization format of mnemonics on HDKeyrings from Uint8Arrays back to an untyped array of UTF8 encoded bytes, which was the format prior to v9.0.0 of this package.

9.0.0 [DEPRECATED]

Added

  • Add support for keyring init method (#163).
    • If a keyring has an init method, it will be called automatically upon construction. It is called with await, so it can be asynchronous.

Changed

  • BREAKING: Replace constructor option and public property keyringTypes with keyringBuilders (#163).
    • The constructor now takes keyring builder functions rather than classes. Each builder function should return a keyring instance when called, and it must have a type string property set to the keyring type name. See the newly exported keyringBuilderFactory function for an example. The builder functions must be synchronous; use an init method for asynchronous initialization steps.
  • BREAKING: KeyringController is now a named export instead of a default export (#163).
  • BREAKING: Update @metamask/eth-simple-keyring from v4 to v5 (#171).
  • BREAKING: Replace getKeyringClassForType method with getKeyringBuilderForType (#163).
  • BREAKING: Update @metamask/eth-hd-keyring to v5 (#177)
  • BREAKING: Require support for ES2020 (#177, #180)
    • As a result of some dependency updates made in this release, this package now requires ES2020 support. If using this package in an environment that does not support ES2020 completely, consider investigating these two dependency changes and transpiling any packages using ES2020 syntax.
  • Update @metamask/eth-sig-util to v5 (#180)
  • Update minimum supported version of @metamask/browser-passworder from v4.0.1 to v4.0.2 (#182)
  • Remove bip39 dependency (#179)

Fixed

  • Fix support for asynchronous addAccounts HD Keyring method (#176)
    • This method was asynchronous, but was called synchronously. Currently the method does not do anything asynchronous so this should have no functional impact, but this ensures any future errors or asynchronous steps added to that method work correctly in the future.

8.1.0

Changed

  • Allow deserializing vaults with unrecognized keyrings (#169)
    • When deserializing a vault with an unrecognized keyring, the controller will no longer crash. The unrecognized keyring vault data will be preserved in the vault for future use, but will otherwise be ignored.

8.0.1

Fixed

  • Restore full state return value (#161)
    • Some methods were accidentally changed in v8.0.0 to return nothing, where previously they returned the full KeyringController state.
    • The affected methods were:
      • createNewVaultAndKeychain
      • submitPassword
      • submitEncryptionKey
      • addNewAccount
      • removeAccount
    • They now all return the full state, just as they did in earlier versions.

8.0.0 [DEPRECATED]

Added

  • Allow login with encryption key rather than password (#152)
    • This is required to support MetaMask extension builds using manifest v3.
    • This is enabled via the option cacheEncryptionKey.
    • The encryption key and salt have been added to the memStore as encryptionKey and encryptionSalt. The salt is used to verify that the key matches the vault being decrypted.
    • If the cacheEncryptionKey option is enabled, the encryption key and salt get cached in the memStore whenever the password is submitted.
    • The encryption key can be submitted with the new method submitEncryptionKey.
    • The unlockKeyrings method now accepts additional parameters for the encryption key and salt, though we don't recommend using this method directly.

Changed

  • BREAKING: Update minimum Node.js version to v14 (#146)
  • BREAKING:: Remove password parameter from persistAllKeyrings and createFirstKeyTree (#154)
    • The password or encryption key must now be set already before these method are called. It is set by createNewVaultAndKeychain, createNewVaultAndRestore, and submitPassword/submitEncryptionKey.
    • This change was made to reduce redundant state changes.

Fixed

  • Fix a typo in the duplicate account import error (#153)

7.0.2

Fixed

  • createNewVaultAndRestore now accepts a seedphrase formatted as an array of numbers (#138)

7.0.1

Fixed

  • Fix breaking change in addNewKeyring function that was accidentally introduced in v7.0.0 (#136)
    • We updated the method such that keyrings were always constructed with constructor arguments, defaulting to an empty object if none were provided. But some keyrings (such as the QR Keyring) relied upon the options being undefined in some cases.

7.0.0

Added

  • Add forget Keyring method for some hardware devices (#124)
  • Add @lavamoat/allow-scripts (#109)

Changed

  • BREAKING: Bump eth-hd-keyring to latest version (#132)
    • When calling the addNewKeyring method, an options object can no longer be passed containing a numberOfAccounts property without also including a mnemonic. Not adding any option argument will result in the generation of a new mnemonic and the addition of 1 account derived from that mnemonic to the keyring.
  • When calling createNewVaultAndKeychain all keyrings are cleared first thing (#129)
  • Validate user imported seedphrase across all bip39 wordlists (#77)