@metamask-previews/keyring-controller 24.0.0-preview-c0feb25 → 24.0.0-preview-607c80f8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"KeyringController.mjs","sourceRoot":"","sources":["../src/KeyringController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,yBAAyB;AACjE,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,cAAc,qCAAqC;AAC/D,OAAO,EAAE,SAAS,EAAE,iCAAiC;AACrD,OAAO,EAAE,SAAS,IAAI,YAAY,EAAE,+BAA+B;AACnE,OAAO,aAAa,qCAAqC;AAYzD,OAAO,EACL,KAAK,EACL,uBAAuB,EACvB,UAAU,EACV,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oBAAoB;;;;;;AAKpC,sHAAsH;AACtH,OAAO,EAAE,IAAI,EAAE,aAAa;AAE5B,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AAOrD,MAAM,IAAI,GAAG,mBAAmB,CAAC;AAEjC;;GAEG;AACH,MAAM,CAAN,IAAY,YASX;AATD,WAAY,YAAY;IACtB,0CAA0B,CAAA;IAC1B,kCAAkB,CAAA;IAClB,gDAAgC,CAAA;IAChC,0CAA0B,CAAA;IAC1B,0CAA0B,CAAA;IAC1B,0CAA0B,CAAA;IAC1B,4CAA4B,CAAA;IAC5B,qCAAqB,CAAA;AACvB,CAAC,EATW,YAAY,KAAZ,YAAY,QASvB;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,WAAmB,EAAW,EAAE;IAC/D,OAAO,WAAW,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;AAC3C,CAAC,CA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QAAQ,EAAE,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,sBAAsB,CAAC,CAAC;KAChE;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,gDACH,QAA2C;IAE3C,OAAO,QAAQ,CAAC,uBAAA,IAAI,mDAA0B,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC;AAED;;;;;;;;;;GAUG;AACH,KAAK,2CACH,QAA2C;IAE3C,uBAAA,IAAI,sFAA+B,MAAnC,IAAI,CAAiC,CAAC;IAEtC,OAAO,QAAQ,CAAC,uBAAA,IAAI,8CAAqB,EAAE,QAAQ,CAAC,CAAC;AACvD,CAAC;AAGH;;;;;;;;GAQG;AACH,KAAK,UAAU,QAAQ,CACrB,KAAY,EACZ,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI;QACF,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;KACxC;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,yBAAyB;IAChC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;AAClC,CAAC;AAED,eAAe,iBAAiB,CAAC","sourcesContent":["import type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { isValidPrivate, getBinarySize } from '@ethereumjs/util';\nimport { BaseController } from '@metamask/base-controller';\nimport * as encryptorUtils from '@metamask/browser-passworder';\nimport { HdKeyring } from '@metamask/eth-hd-keyring';\nimport { normalize as ethNormalize } from '@metamask/eth-sig-util';\nimport SimpleKeyring from '@metamask/eth-simple-keyring';\nimport type {\n KeyringExecutionContext,\n EthBaseTransaction,\n EthBaseUserOperation,\n EthUserOperation,\n EthUserOperationPatch,\n} from '@metamask/keyring-api';\nimport type { EthKeyring } from '@metamask/keyring-internal-api';\nimport type { KeyringClass } from '@metamask/keyring-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Eip1024EncryptedData, Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n assertIsStrictHexString,\n bytesToHex,\n hasProperty,\n hexToBytes,\n isObject,\n isStrictHexString,\n isValidHexAddress,\n isValidJson,\n remove0x,\n} from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport type { MutexInterface } from 'async-mutex';\nimport Wallet, { thirdparty as importers } from 'ethereumjs-wallet';\nimport type { Patch } from 'immer';\nimport { isEqual } from 'lodash';\n// When generating a ULID within the same millisecond, monotonicFactory provides some guarantees regarding sort order.\nimport { ulid } from 'ulid';\n\nimport { KeyringControllerError } from './constants';\nimport type {\n Eip7702AuthorizationParams,\n PersonalMessageParams,\n TypedMessageParams,\n} from './types';\n\nconst name = 'KeyringController';\n\n/**\n * Available keyring types\n */\nexport enum KeyringTypes {\n simple = 'Simple Key Pair',\n hd = 'HD Key Tree',\n qr = 'QR Hardware Wallet Device',\n trezor = 'Trezor Hardware',\n oneKey = 'OneKey Hardware',\n ledger = 'Ledger Hardware',\n lattice = 'Lattice Hardware',\n snap = 'Snap Keyring',\n}\n\n/**\n * Custody keyring types are a special case, as they are not a single type\n * but they all start with the prefix \"Custody\".\n *\n * @param keyringType - The type of the keyring.\n * @returns Whether the keyring type is a custody keyring.\n */\nexport const isCustodyKeyring = (keyringType: string): boolean => {\n return keyringType.startsWith('Custody');\n};\n\n/**\n * The KeyringController state\n */\nexport type KeyringControllerState = {\n /**\n * Encrypted array of serialized keyrings data.\n */\n vault?: string;\n /**\n * Whether the vault has been decrypted successfully and\n * keyrings contained within are deserialized and available.\n */\n isUnlocked: boolean;\n /**\n * Representations of managed keyrings.\n */\n keyrings: KeyringObject[];\n /**\n * The encryption key derived from the password and used to encrypt\n * the vault. This is only stored if the `cacheEncryptionKey` option\n * is enabled.\n */\n encryptionKey?: string;\n /**\n * The salt used to derive the encryption key from the password.\n */\n encryptionSalt?: string;\n};\n\nexport type KeyringControllerMemState = Omit<\n KeyringControllerState,\n 'vault' | 'encryptionKey' | 'encryptionSalt'\n>;\n\nexport type KeyringControllerGetStateAction = {\n type: `${typeof name}:getState`;\n handler: () => KeyringControllerState;\n};\n\nexport type KeyringControllerSignMessageAction = {\n type: `${typeof name}:signMessage`;\n handler: KeyringController['signMessage'];\n};\n\nexport type KeyringControllerSignEip7702AuthorizationAction = {\n type: `${typeof name}:signEip7702Authorization`;\n handler: KeyringController['signEip7702Authorization'];\n};\n\nexport type KeyringControllerSignPersonalMessageAction = {\n type: `${typeof name}:signPersonalMessage`;\n handler: KeyringController['signPersonalMessage'];\n};\n\nexport type KeyringControllerSignTypedMessageAction = {\n type: `${typeof name}:signTypedMessage`;\n handler: KeyringController['signTypedMessage'];\n};\n\nexport type KeyringControllerDecryptMessageAction = {\n type: `${typeof name}:decryptMessage`;\n handler: KeyringController['decryptMessage'];\n};\n\nexport type KeyringControllerGetEncryptionPublicKeyAction = {\n type: `${typeof name}:getEncryptionPublicKey`;\n handler: KeyringController['getEncryptionPublicKey'];\n};\n\nexport type KeyringControllerGetKeyringsByTypeAction = {\n type: `${typeof name}:getKeyringsByType`;\n handler: KeyringController['getKeyringsByType'];\n};\n\nexport type KeyringControllerGetKeyringForAccountAction = {\n type: `${typeof name}:getKeyringForAccount`;\n handler: KeyringController['getKeyringForAccount'];\n};\n\nexport type KeyringControllerGetAccountsAction = {\n type: `${typeof name}:getAccounts`;\n handler: KeyringController['getAccounts'];\n};\n\nexport type KeyringControllerPersistAllKeyringsAction = {\n type: `${typeof name}:persistAllKeyrings`;\n handler: KeyringController['persistAllKeyrings'];\n};\n\nexport type KeyringControllerPrepareUserOperationAction = {\n type: `${typeof name}:prepareUserOperation`;\n handler: KeyringController['prepareUserOperation'];\n};\n\nexport type KeyringControllerPatchUserOperationAction = {\n type: `${typeof name}:patchUserOperation`;\n handler: KeyringController['patchUserOperation'];\n};\n\nexport type KeyringControllerSignUserOperationAction = {\n type: `${typeof name}:signUserOperation`;\n handler: KeyringController['signUserOperation'];\n};\n\nexport type KeyringControllerAddNewAccountAction = {\n type: `${typeof name}:addNewAccount`;\n handler: KeyringController['addNewAccount'];\n};\n\nexport type KeyringControllerWithKeyringAction = {\n type: `${typeof name}:withKeyring`;\n handler: KeyringController['withKeyring'];\n};\n\nexport type KeyringControllerCreateNewVaultAndKeychainAction = {\n type: `${typeof name}:createNewVaultAndKeychain`;\n handler: KeyringController['createNewVaultAndKeychain'];\n};\n\nexport type KeyringControllerCreateNewVaultAndRestoreAction = {\n type: `${typeof name}:createNewVaultAndRestore`;\n handler: KeyringController['createNewVaultAndRestore'];\n};\n\nexport type KeyringControllerAddNewKeyringAction = {\n type: `${typeof name}:addNewKeyring`;\n handler: KeyringController['addNewKeyring'];\n};\n\nexport type KeyringControllerStateChangeEvent = {\n type: `${typeof name}:stateChange`;\n payload: [KeyringControllerState, Patch[]];\n};\n\nexport type KeyringControllerAccountRemovedEvent = {\n type: `${typeof name}:accountRemoved`;\n payload: [string];\n};\n\nexport type KeyringControllerLockEvent = {\n type: `${typeof name}:lock`;\n payload: [];\n};\n\nexport type KeyringControllerUnlockEvent = {\n type: `${typeof name}:unlock`;\n payload: [];\n};\n\nexport type KeyringControllerActions =\n | KeyringControllerGetStateAction\n | KeyringControllerSignMessageAction\n | KeyringControllerSignEip7702AuthorizationAction\n | KeyringControllerSignPersonalMessageAction\n | KeyringControllerSignTypedMessageAction\n | KeyringControllerDecryptMessageAction\n | KeyringControllerGetEncryptionPublicKeyAction\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetKeyringsByTypeAction\n | KeyringControllerGetKeyringForAccountAction\n | KeyringControllerPersistAllKeyringsAction\n | KeyringControllerPrepareUserOperationAction\n | KeyringControllerPatchUserOperationAction\n | KeyringControllerSignUserOperationAction\n | KeyringControllerAddNewAccountAction\n | KeyringControllerWithKeyringAction\n | KeyringControllerAddNewKeyringAction\n | KeyringControllerCreateNewVaultAndKeychainAction\n | KeyringControllerCreateNewVaultAndRestoreAction;\n\nexport type KeyringControllerEvents =\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | KeyringControllerAccountRemovedEvent;\n\nexport type KeyringControllerMessenger = Messenger<\n typeof name,\n KeyringControllerActions,\n KeyringControllerEvents\n>;\n\nexport type KeyringControllerOptions = {\n keyringBuilders?: { (): EthKeyring; type: string }[];\n messenger: KeyringControllerMessenger;\n state?: { vault?: string; keyringsMetadata?: KeyringMetadata[] };\n} & (\n | {\n cacheEncryptionKey: true;\n encryptor?: ExportableKeyEncryptor;\n }\n | {\n cacheEncryptionKey?: false;\n encryptor?: GenericEncryptor | ExportableKeyEncryptor;\n }\n);\n\n/**\n * A keyring object representation.\n */\nexport type KeyringObject = {\n /**\n * Accounts associated with the keyring.\n */\n accounts: string[];\n /**\n * Keyring type.\n */\n type: string;\n /**\n * Additional data associated with the keyring.\n */\n metadata: KeyringMetadata;\n};\n\n/**\n * Additional information related to a keyring.\n */\nexport type KeyringMetadata = {\n /**\n * Keyring ID\n */\n id: string;\n /**\n * Keyring name\n */\n name: string;\n};\n\n/**\n * A strategy for importing an account\n */\nexport enum AccountImportStrategy {\n privateKey = 'privateKey',\n json = 'json',\n}\n\n/**\n * The `signTypedMessage` version\n *\n * @see https://docs.metamask.io/guide/signing-data.html\n */\nexport enum SignTypedDataVersion {\n V1 = 'V1',\n V3 = 'V3',\n V4 = 'V4',\n}\n\n/**\n * A serialized keyring object.\n */\nexport type SerializedKeyring = {\n type: string;\n data: Json;\n metadata?: KeyringMetadata;\n};\n\n/**\n * State/data that can be updated during a `withKeyring` operation.\n */\ntype SessionState = {\n keyrings: SerializedKeyring[];\n password?: string;\n};\n\n/**\n * A generic encryptor interface that supports encrypting and decrypting\n * serializable data with a password.\n */\nexport type GenericEncryptor = {\n /**\n * Encrypts the given object with the given password.\n *\n * @param password - The password to encrypt with.\n * @param object - The object to encrypt.\n * @returns The encrypted string.\n */\n encrypt: (password: string, object: Json) => Promise<string>;\n /**\n * Decrypts the given encrypted string with the given password.\n *\n * @param password - The password to decrypt with.\n * @param encryptedString - The encrypted string to decrypt.\n * @returns The decrypted object.\n */\n decrypt: (password: string, encryptedString: string) => Promise<unknown>;\n /**\n * Optional vault migration helper. Checks if the provided vault is up to date\n * with the desired encryption algorithm.\n *\n * @param vault - The encrypted string to check.\n * @param targetDerivationParams - The desired target derivation params.\n * @returns The updated encrypted string.\n */\n isVaultUpdated?: (\n vault: string,\n targetDerivationParams?: encryptorUtils.KeyDerivationOptions,\n ) => boolean;\n};\n\n/**\n * An encryptor interface that supports encrypting and decrypting\n * serializable data with a password, and exporting and importing keys.\n */\nexport type ExportableKeyEncryptor<EncryptionKey = unknown> =\n GenericEncryptor & {\n /**\n * Encrypts the given object with the given encryption key.\n *\n * @param key - The encryption key to encrypt with.\n * @param object - The object to encrypt.\n * @returns The encryption result.\n */\n encryptWithKey: (\n key: EncryptionKey,\n object: Json,\n ) => Promise<encryptorUtils.EncryptionResult>;\n /**\n * Encrypts the given object with the given password, and returns the\n * encryption result and the exported key string.\n *\n * @param password - The password to encrypt with.\n * @param object - The object to encrypt.\n * @param salt - The optional salt to use for encryption.\n * @returns The encrypted string and the exported key string.\n */\n encryptWithDetail: (\n password: string,\n object: Json,\n salt?: string,\n ) => Promise<encryptorUtils.DetailedEncryptionResult>;\n /**\n * Decrypts the given encrypted string with the given encryption key.\n *\n * @param key - The encryption key to decrypt with.\n * @param encryptedString - The encrypted string to decrypt.\n * @returns The decrypted object.\n */\n decryptWithKey: (\n key: EncryptionKey,\n encryptedString: string,\n ) => Promise<unknown>;\n /**\n * Decrypts the given encrypted string with the given password, and returns\n * the decrypted object and the salt and exported key string used for\n * encryption.\n *\n * @param password - The password to decrypt with.\n * @param encryptedString - The encrypted string to decrypt.\n * @returns The decrypted object and the salt and exported key string used for\n * encryption.\n */\n decryptWithDetail: (\n password: string,\n encryptedString: string,\n ) => Promise<encryptorUtils.DetailedDecryptResult>;\n /**\n * Generates an encryption key from exported key string.\n *\n * @param key - The exported key string.\n * @returns The encryption key.\n */\n importKey: (key: string) => Promise<EncryptionKey>;\n };\n\nexport type KeyringSelector =\n | {\n type: string;\n index?: number;\n }\n | {\n address: Hex;\n }\n | {\n id: string;\n };\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Get builder function for `Keyring`\n *\n * Returns a builder function for `Keyring` with a `type` property.\n *\n * @param KeyringConstructor - The Keyring class for the builder.\n * @returns A builder function for the given Keyring.\n */\nexport function keyringBuilderFactory(KeyringConstructor: KeyringClass) {\n const builder = () => new KeyringConstructor();\n\n builder.type = KeyringConstructor.type;\n\n return builder;\n}\n\nconst defaultKeyringBuilders = [\n // todo: keyring types are mismatched, this should be fixed in they keyrings themselves\n // @ts-expect-error keyring types are mismatched\n keyringBuilderFactory(SimpleKeyring),\n keyringBuilderFactory(HdKeyring),\n];\n\nexport const getDefaultKeyringState = (): KeyringControllerState => {\n return {\n isUnlocked: false,\n keyrings: [],\n };\n};\n\n/**\n * Assert that the given keyring has an exportable\n * mnemonic.\n *\n * @param keyring - The keyring to check\n * @throws When the keyring does not have a mnemonic\n */\nfunction assertHasUint8ArrayMnemonic(\n keyring: EthKeyring,\n): asserts keyring is EthKeyring & { mnemonic: Uint8Array } {\n if (\n !(\n hasProperty(keyring, 'mnemonic') && keyring.mnemonic instanceof Uint8Array\n )\n ) {\n throw new Error(\"Can't get mnemonic bytes from keyring\");\n }\n}\n\n/**\n * Assert that the provided encryptor supports\n * encryption and encryption key export.\n *\n * @param encryptor - The encryptor to check.\n * @throws If the encryptor does not support key encryption.\n */\nfunction assertIsExportableKeyEncryptor(\n encryptor: GenericEncryptor | ExportableKeyEncryptor,\n): asserts encryptor is ExportableKeyEncryptor {\n if (\n !(\n 'importKey' in encryptor &&\n typeof encryptor.importKey === 'function' &&\n 'decryptWithKey' in encryptor &&\n typeof encryptor.decryptWithKey === 'function' &&\n 'encryptWithKey' in encryptor &&\n typeof encryptor.encryptWithKey === 'function'\n )\n ) {\n throw new Error(KeyringControllerError.UnsupportedEncryptionKeyExport);\n }\n}\n\n/**\n * Assert that the provided password is a valid non-empty string.\n *\n * @param password - The password to check.\n * @throws If the password is not a valid string.\n */\nfunction assertIsValidPassword(password: unknown): asserts password is string {\n if (typeof password !== 'string') {\n throw new Error(KeyringControllerError.WrongPasswordType);\n }\n\n if (!password || !password.length) {\n throw new Error(KeyringControllerError.InvalidEmptyPassword);\n }\n}\n\n/**\n * Assert that the provided encryption key is a valid non-empty string.\n *\n * @param encryptionKey - The encryption key to check.\n * @throws If the encryption key is not a valid string.\n */\nfunction assertIsEncryptionKeySet(\n encryptionKey: string | undefined,\n): asserts encryptionKey is string {\n if (!encryptionKey) {\n throw new Error(KeyringControllerError.EncryptionKeyNotSet);\n }\n}\n\n/**\n * Checks if the provided value is a serialized keyrings array.\n *\n * @param array - The value to check.\n * @returns True if the value is a serialized keyrings array.\n */\nfunction isSerializedKeyringsArray(\n array: unknown,\n): array is SerializedKeyring[] {\n return (\n typeof array === 'object' &&\n Array.isArray(array) &&\n array.every((value) => value.type && isValidJson(value.data))\n );\n}\n\n/**\n * Display For Keyring\n *\n * Is used for adding the current keyrings to the state object.\n *\n * @param keyringWithMetadata - The keyring and its metadata.\n * @param keyringWithMetadata.keyring - The keyring to display.\n * @param keyringWithMetadata.metadata - The metadata of the keyring.\n * @returns A keyring display object, with type and accounts properties.\n */\nasync function displayForKeyring({\n keyring,\n metadata,\n}: {\n keyring: EthKeyring;\n metadata: KeyringMetadata;\n}): Promise<KeyringObject> {\n const accounts = await keyring.getAccounts();\n\n return {\n type: keyring.type,\n // Cast to `string[]` here is safe here because `accounts` has no nullish\n // values, and `normalize` returns `string` unless given a nullish value\n accounts: accounts.map(normalize) as string[],\n metadata,\n };\n}\n\n/**\n * Check if address is an ethereum address\n *\n * @param address - An address.\n * @returns Returns true if the address is an ethereum one, false otherwise.\n */\nfunction isEthAddress(address: string): boolean {\n // We first check if it's a matching `Hex` string, so that is narrows down\n // `address` as an `Hex` type, allowing us to use `isValidHexAddress`\n return (\n // NOTE: This function only checks for lowercased strings\n isStrictHexString(address.toLowerCase()) &&\n // This checks for lowercased addresses and checksum addresses too\n isValidHexAddress(address as Hex)\n );\n}\n\n/**\n * Normalize ethereum or non-EVM address.\n *\n * @param address - Ethereum or non-EVM address.\n * @returns The normalized address.\n */\nfunction normalize(address: string): string | undefined {\n // Since the `KeyringController` is only dealing with address, we have\n // no other way to get the associated account type with this address. So we\n // are down to check the actual address format for now\n // TODO: Find a better way to not have those runtime checks based on the\n // address value!\n return isEthAddress(address) ? ethNormalize(address) : address;\n}\n\n/**\n * Controller responsible for establishing and managing user identity.\n *\n * This class is a wrapper around the `eth-keyring-controller` package. The\n * `eth-keyring-controller` manages the \"vault\", which is an encrypted store of private keys, and\n * it manages the wallet \"lock\" state. This wrapper class has convenience methods for interacting\n * with the internal keyring controller and handling certain complex operations that involve the\n * keyrings.\n */\nexport class KeyringController extends BaseController<\n typeof name,\n KeyringControllerState,\n KeyringControllerMessenger\n> {\n readonly #controllerOperationMutex = new Mutex();\n\n readonly #vaultOperationMutex = new Mutex();\n\n readonly #keyringBuilders: { (): EthKeyring; type: string }[];\n\n readonly #encryptor: GenericEncryptor | ExportableKeyEncryptor;\n\n readonly #cacheEncryptionKey: boolean;\n\n #keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n\n #unsupportedKeyrings: SerializedKeyring[];\n\n #password?: string;\n\n /**\n * Creates a KeyringController instance.\n *\n * @param options - Initial options used to configure this controller\n * @param options.encryptor - An optional object for defining encryption schemes.\n * @param options.keyringBuilders - Set a new name for account.\n * @param options.cacheEncryptionKey - Whether to cache or not encryption key.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor(options: KeyringControllerOptions) {\n const {\n encryptor = encryptorUtils,\n keyringBuilders,\n messenger,\n state,\n } = options;\n\n super({\n name,\n metadata: {\n vault: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n isUnlocked: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n keyrings: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n encryptionKey: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n encryptionSalt: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n },\n messenger,\n state: {\n ...getDefaultKeyringState(),\n ...state,\n },\n });\n\n this.#keyringBuilders = keyringBuilders\n ? keyringBuilders.concat(defaultKeyringBuilders)\n : defaultKeyringBuilders;\n\n this.#encryptor = encryptor;\n this.#keyrings = [];\n this.#unsupportedKeyrings = [];\n\n // This option allows the controller to cache an exported key\n // for use in decrypting and encrypting data without password\n this.#cacheEncryptionKey = Boolean(options.cacheEncryptionKey);\n if (this.#cacheEncryptionKey) {\n assertIsExportableKeyEncryptor(encryptor);\n }\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Adds a new account to the default (first) HD seed phrase keyring.\n *\n * @param accountCount - Number of accounts before adding a new one, used to\n * make the method idempotent.\n * @returns Promise resolving to the added account address.\n */\n async addNewAccount(accountCount?: number): Promise<string> {\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n const oldAccounts = await primaryKeyring.getAccounts();\n\n if (accountCount && oldAccounts.length !== accountCount) {\n if (accountCount > oldAccounts.length) {\n throw new Error('Account out of sequence');\n }\n // we return the account already existing at index `accountCount`\n const existingAccount = oldAccounts[accountCount];\n\n if (!existingAccount) {\n throw new Error(`Can't find account at index ${accountCount}`);\n }\n\n return existingAccount;\n }\n\n const [addedAccountAddress] = await primaryKeyring.addAccounts(1);\n await this.#verifySeedPhrase();\n\n return addedAccountAddress;\n });\n }\n\n /**\n * Adds a new account to the specified keyring.\n *\n * @param keyring - Keyring to add the account to.\n * @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.\n * @returns Promise resolving to the added account address\n */\n async addNewAccountForKeyring(\n keyring: EthKeyring,\n accountCount?: number,\n ): Promise<Hex> {\n // READ THIS CAREFULLY:\n // We still uses `Hex` here, since we are not using this method when creating\n // and account using a \"Snap Keyring\". This function assume the `keyring` is\n // ethereum compatible, but \"Snap Keyring\" might not be.\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n const oldAccounts = await this.#getAccountsFromKeyrings();\n\n if (accountCount && oldAccounts.length !== accountCount) {\n if (accountCount > oldAccounts.length) {\n throw new Error('Account out of sequence');\n }\n\n const existingAccount = oldAccounts[accountCount];\n assertIsStrictHexString(existingAccount);\n\n return existingAccount;\n }\n\n await keyring.addAccounts(1);\n\n const addedAccountAddress = (await this.#getAccountsFromKeyrings()).find(\n (selectedAddress) => !oldAccounts.includes(selectedAddress),\n );\n assertIsStrictHexString(addedAccountAddress);\n\n return addedAccountAddress;\n });\n }\n\n /**\n * Effectively the same as creating a new keychain then populating it\n * using the given seed phrase.\n *\n * @param password - Password to unlock keychain.\n * @param seed - A BIP39-compliant seed phrase as Uint8Array,\n * either as a string or an array of UTF-8 bytes that represent the string.\n * @returns Promise resolving when the operation ends successfully.\n */\n async createNewVaultAndRestore(\n password: string,\n seed: Uint8Array,\n ): Promise<void> {\n return this.#persistOrRollback(async () => {\n assertIsValidPassword(password);\n\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n opts: {\n mnemonic: seed,\n numberOfAccounts: 1,\n },\n });\n });\n }\n\n /**\n * Create a new vault and primary keyring.\n *\n * This only works if keyrings are empty. If there is a pre-existing unlocked vault, calling this will have no effect.\n * If there is a pre-existing locked vault, it will be replaced.\n *\n * @param password - Password to unlock the new vault.\n * @returns Promise resolving when the operation ends successfully.\n */\n async createNewVaultAndKeychain(password: string) {\n return this.#persistOrRollback(async () => {\n const accounts = await this.#getAccountsFromKeyrings();\n if (!accounts.length) {\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n });\n }\n });\n }\n\n /**\n * Adds a new keyring of the given `type`.\n *\n * @param type - Keyring type name.\n * @param opts - Keyring options.\n * @throws If a builder for the given `type` does not exist.\n * @returns Promise resolving to the new keyring metadata.\n */\n async addNewKeyring(\n type: KeyringTypes | string,\n opts?: unknown,\n ): Promise<KeyringMetadata> {\n this.#assertIsUnlocked();\n\n return this.#getKeyringMetadata(\n await this.#persistOrRollback(async () => this.#newKeyring(type, opts)),\n );\n }\n\n /**\n * Method to verify a given password validity. Throws an\n * error if the password is invalid.\n *\n * @param password - Password of the keyring.\n */\n async verifyPassword(password: string) {\n if (!this.state.vault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n await this.#encryptor.decrypt(password, this.state.vault);\n }\n\n /**\n * Returns the status of the vault.\n *\n * @returns Boolean returning true if the vault is unlocked.\n */\n isUnlocked(): boolean {\n return this.state.isUnlocked;\n }\n\n /**\n * Gets the seed phrase of the HD keyring.\n *\n * @param password - Password of the keyring.\n * @param keyringId - The id of the keyring.\n * @returns Promise resolving to the seed phrase.\n */\n async exportSeedPhrase(\n password: string,\n keyringId?: string,\n ): Promise<Uint8Array> {\n this.#assertIsUnlocked();\n await this.verifyPassword(password);\n const selectedKeyring = this.#getKeyringByIdOrDefault(keyringId);\n if (!selectedKeyring) {\n throw new Error('Keyring not found');\n }\n assertHasUint8ArrayMnemonic(selectedKeyring);\n\n return selectedKeyring.mnemonic;\n }\n\n /**\n * Gets the private key from the keyring controlling an address.\n *\n * @param password - Password of the keyring.\n * @param address - Address to export.\n * @returns Promise resolving to the private key for an address.\n */\n async exportAccount(password: string, address: string): Promise<string> {\n await this.verifyPassword(password);\n\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.exportAccount) {\n throw new Error(KeyringControllerError.UnsupportedExportAccount);\n }\n\n return await keyring.exportAccount(normalize(address) as Hex);\n }\n\n /**\n * Returns the public addresses of all accounts from every keyring.\n *\n * @returns A promise resolving to an array of addresses.\n */\n async getAccounts(): Promise<string[]> {\n this.#assertIsUnlocked();\n return this.state.keyrings.reduce<string[]>(\n (accounts, keyring) => accounts.concat(keyring.accounts),\n [],\n );\n }\n\n /**\n * Get encryption public key.\n *\n * @param account - An account address.\n * @param opts - Additional encryption options.\n * @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method\n * @returns Promise resolving to encyption public key of the `account` if one exists.\n */\n async getEncryptionPublicKey(\n account: string,\n opts?: Record<string, unknown>,\n ): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(account) as Hex;\n const keyring = (await this.getKeyringForAccount(account)) as EthKeyring;\n if (!keyring.getEncryptionPublicKey) {\n throw new Error(KeyringControllerError.UnsupportedGetEncryptionPublicKey);\n }\n\n return await keyring.getEncryptionPublicKey(address, opts);\n }\n\n /**\n * Attempts to decrypt the provided message parameters.\n *\n * @param messageParams - The decryption message parameters.\n * @param messageParams.from - The address of the account you want to use to decrypt the message.\n * @param messageParams.data - The encrypted data that you want to decrypt.\n * @returns The raw decryption result.\n */\n async decryptMessage(messageParams: {\n from: string;\n data: Eip1024EncryptedData;\n }): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.decryptMessage) {\n throw new Error(KeyringControllerError.UnsupportedDecryptMessage);\n }\n\n return keyring.decryptMessage(address, messageParams.data);\n }\n\n /**\n * Returns the currently initialized keyring that manages\n * the specified `address` if one exists.\n *\n * @deprecated Use of this method is discouraged as actions executed directly on\n * keyrings are not being reflected in the KeyringController state and not\n * persisted in the vault. Use `withKeyring` instead.\n * @param account - An account address.\n * @returns Promise resolving to keyring of the `account` if one exists.\n */\n async getKeyringForAccount(account: string): Promise<unknown> {\n this.#assertIsUnlocked();\n const address = normalize(account);\n\n const candidates = await Promise.all(\n this.#keyrings.map(async ({ keyring }) => {\n return Promise.all([keyring, keyring.getAccounts()]);\n }),\n );\n\n const winners = candidates.filter((candidate) => {\n const accounts = candidate[1].map(normalize);\n return accounts.includes(address);\n });\n\n if (winners.length && winners[0]?.length) {\n return winners[0][0];\n }\n\n // Adding more info to the error\n let errorInfo = '';\n if (!candidates.length) {\n errorInfo = 'There are no keyrings';\n } else if (!winners.length) {\n errorInfo = 'There are keyrings, but none match the address';\n }\n throw new Error(\n `${KeyringControllerError.NoKeyring}. Error info: ${errorInfo}`,\n );\n }\n\n /**\n * Returns all keyrings of the given type.\n *\n * @deprecated Use of this method is discouraged as actions executed directly on\n * keyrings are not being reflected in the KeyringController state and not\n * persisted in the vault. Use `withKeyring` instead.\n * @param type - Keyring type name.\n * @returns An array of keyrings of the given type.\n */\n getKeyringsByType(type: KeyringTypes | string): unknown[] {\n this.#assertIsUnlocked();\n return this.#keyrings\n .filter(({ keyring }) => keyring.type === type)\n .map(({ keyring }) => keyring);\n }\n\n /**\n * Persist all serialized keyrings in the vault.\n *\n * @deprecated This method is being phased out in favor of `withKeyring`.\n * @returns Promise resolving with `true` value when the\n * operation completes.\n */\n async persistAllKeyrings(): Promise<boolean> {\n return this.#withRollback(async () => {\n this.#assertIsUnlocked();\n\n await this.#updateVault();\n return true;\n });\n }\n\n /**\n * Imports an account with the specified import strategy.\n *\n * @param strategy - Import strategy name.\n * @param args - Array of arguments to pass to the underlying stategy.\n * @throws Will throw when passed an unrecognized strategy.\n * @returns Promise resolving to the imported account address.\n */\n async importAccountWithStrategy(\n strategy: AccountImportStrategy,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[],\n ): Promise<string> {\n this.#assertIsUnlocked();\n return this.#persistOrRollback(async () => {\n let privateKey;\n switch (strategy) {\n case AccountImportStrategy.privateKey:\n const [importedKey] = args;\n if (!importedKey) {\n throw new Error('Cannot import an empty key.');\n }\n const prefixed = add0x(importedKey);\n\n let bufferedPrivateKey;\n try {\n bufferedPrivateKey = hexToBytes(prefixed);\n } catch {\n throw new Error('Cannot import invalid private key.');\n }\n\n if (\n !isValidPrivate(bufferedPrivateKey) ||\n // ensures that the key is 64 bytes long\n getBinarySize(prefixed) !== 64 + '0x'.length\n ) {\n throw new Error('Cannot import invalid private key.');\n }\n\n privateKey = remove0x(prefixed);\n break;\n case AccountImportStrategy.json:\n let wallet;\n const [input, password] = args;\n try {\n wallet = importers.fromEtherWallet(input, password);\n } catch (e) {\n wallet = wallet || (await Wallet.fromV3(input, password, true));\n }\n privateKey = bytesToHex(wallet.getPrivateKey());\n break;\n default:\n throw new Error(`Unexpected import strategy: '${String(strategy)}'`);\n }\n const newKeyring = (await this.#newKeyring(KeyringTypes.simple, [\n privateKey,\n ])) as EthKeyring;\n const accounts = await newKeyring.getAccounts();\n return accounts[0];\n });\n }\n\n /**\n * Removes an account from keyring state.\n *\n * @param address - Address of the account to remove.\n * @fires KeyringController:accountRemoved\n * @returns Promise resolving when the account is removed.\n */\n async removeAccount(address: string): Promise<void> {\n this.#assertIsUnlocked();\n\n await this.#persistOrRollback(async () => {\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n const keyringIndex = this.state.keyrings.findIndex((kr) =>\n kr.accounts.includes(address),\n );\n\n const isPrimaryKeyring = keyringIndex === 0;\n const shouldRemoveKeyring = (await keyring.getAccounts()).length === 1;\n\n // Primary keyring should never be removed, so we need to keep at least one account in it\n if (isPrimaryKeyring && shouldRemoveKeyring) {\n throw new Error(KeyringControllerError.LastAccountInPrimaryKeyring);\n }\n\n // Not all the keyrings support this, so we have to check\n if (!keyring.removeAccount) {\n throw new Error(KeyringControllerError.UnsupportedRemoveAccount);\n }\n\n // The `removeAccount` method of snaps keyring is async. We have to update\n // the interface of the other keyrings to be async as well.\n // FIXME: We do cast to `Hex` to makes the type checker happy here, and\n // because `Keyring<State>.removeAccount` requires address to be `Hex`. Those\n // type would need to be updated for a full non-EVM support.\n keyring.removeAccount(address as Hex);\n\n if (shouldRemoveKeyring) {\n await this.#removeEmptyKeyrings();\n }\n });\n\n this.messenger.publish(`${name}:accountRemoved`, address);\n }\n\n /**\n * Deallocates all secrets and locks the wallet.\n *\n * @returns Promise resolving when the operation completes.\n */\n async setLocked(): Promise<void> {\n this.#assertIsUnlocked();\n\n return this.#withRollback(async () => {\n this.#password = undefined;\n await this.#clearKeyrings();\n\n this.update((state) => {\n state.isUnlocked = false;\n state.keyrings = [];\n delete state.encryptionKey;\n delete state.encryptionSalt;\n });\n\n this.messenger.publish(`${name}:lock`);\n });\n }\n\n /**\n * Signs message by calling down into a specific keyring.\n *\n * @param messageParams - PersonalMessageParams object to sign.\n * @returns Promise resolving to a signed message string.\n */\n async signMessage(messageParams: PersonalMessageParams): Promise<string> {\n this.#assertIsUnlocked();\n\n if (!messageParams.data) {\n throw new Error(\"Can't sign an empty message\");\n }\n\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signMessage) {\n throw new Error(KeyringControllerError.UnsupportedSignMessage);\n }\n\n return await keyring.signMessage(address, messageParams.data);\n }\n\n /**\n * Signs EIP-7702 Authorization message by calling down into a specific keyring.\n *\n * @param params - EIP7702AuthorizationParams object to sign.\n * @returns Promise resolving to an EIP-7702 Authorization signature.\n * @throws Will throw UnsupportedSignEIP7702Authorization if the keyring does not support signing EIP-7702 Authorization messages.\n */\n async signEip7702Authorization(\n params: Eip7702AuthorizationParams,\n ): Promise<string> {\n const from = ethNormalize(params.from) as Hex;\n\n const keyring = (await this.getKeyringForAccount(from)) as EthKeyring;\n\n if (!keyring.signEip7702Authorization) {\n throw new Error(\n KeyringControllerError.UnsupportedSignEip7702Authorization,\n );\n }\n\n const { chainId, nonce } = params;\n const contractAddress = ethNormalize(params.contractAddress) as\n | Hex\n | undefined;\n\n if (contractAddress === undefined) {\n throw new Error(\n KeyringControllerError.MissingEip7702AuthorizationContractAddress,\n );\n }\n\n return await keyring.signEip7702Authorization(from, [\n chainId,\n contractAddress,\n nonce,\n ]);\n }\n\n /**\n * Signs personal message by calling down into a specific keyring.\n *\n * @param messageParams - PersonalMessageParams object to sign.\n * @returns Promise resolving to a signed message string.\n */\n async signPersonalMessage(messageParams: PersonalMessageParams) {\n this.#assertIsUnlocked();\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signPersonalMessage) {\n throw new Error(KeyringControllerError.UnsupportedSignPersonalMessage);\n }\n\n const normalizedData = normalize(messageParams.data) as Hex;\n\n return await keyring.signPersonalMessage(address, normalizedData);\n }\n\n /**\n * Signs typed message by calling down into a specific keyring.\n *\n * @param messageParams - TypedMessageParams object to sign.\n * @param version - Compatibility version EIP712.\n * @throws Will throw when passed an unrecognized version.\n * @returns Promise resolving to a signed message string or an error if any.\n */\n async signTypedMessage(\n messageParams: TypedMessageParams,\n version: SignTypedDataVersion,\n ): Promise<string> {\n this.#assertIsUnlocked();\n\n try {\n if (\n ![\n SignTypedDataVersion.V1,\n SignTypedDataVersion.V3,\n SignTypedDataVersion.V4,\n ].includes(version)\n ) {\n throw new Error(`Unexpected signTypedMessage version: '${version}'`);\n }\n\n // Cast to `Hex` here is safe here because `messageParams.from` is not nullish.\n // `normalize` returns `Hex` unless given a nullish value.\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signTypedData) {\n throw new Error(KeyringControllerError.UnsupportedSignTypedMessage);\n }\n\n return await keyring.signTypedData(\n address,\n version !== SignTypedDataVersion.V1 &&\n typeof messageParams.data === 'string'\n ? JSON.parse(messageParams.data)\n : messageParams.data,\n { version },\n );\n } catch (error) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n throw new Error(`Keyring Controller signTypedMessage: ${error}`);\n }\n }\n\n /**\n * Signs a transaction by calling down into a specific keyring.\n *\n * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance.\n * @param from - Address to sign from, should be in keychain.\n * @param opts - An optional options object.\n * @returns Promise resolving to a signed transaction string.\n */\n async signTransaction(\n transaction: TypedTransaction,\n from: string,\n opts?: Record<string, unknown>,\n ): Promise<TypedTxData> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signTransaction) {\n throw new Error(KeyringControllerError.UnsupportedSignTransaction);\n }\n\n return await keyring.signTransaction(address, transaction, opts);\n }\n\n /**\n * Convert a base transaction to a base UserOperation.\n *\n * @param from - Address of the sender.\n * @param transactions - Base transactions to include in the UserOperation.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns A pseudo-UserOperation that can be used to construct a real.\n */\n async prepareUserOperation(\n from: string,\n transactions: EthBaseTransaction[],\n executionContext: KeyringExecutionContext,\n ): Promise<EthBaseUserOperation> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.prepareUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPrepareUserOperation);\n }\n\n return await keyring.prepareUserOperation(\n address,\n transactions,\n executionContext,\n );\n }\n\n /**\n * Patches properties of a UserOperation. Currently, only the\n * `paymasterAndData` can be patched.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to patch.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns A patch to apply to the UserOperation.\n */\n async patchUserOperation(\n from: string,\n userOp: EthUserOperation,\n executionContext: KeyringExecutionContext,\n ): Promise<EthUserOperationPatch> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.patchUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPatchUserOperation);\n }\n\n return await keyring.patchUserOperation(address, userOp, executionContext);\n }\n\n /**\n * Signs an UserOperation.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n from: string,\n userOp: EthUserOperation,\n executionContext: KeyringExecutionContext,\n ): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.signUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedSignUserOperation);\n }\n\n return await keyring.signUserOperation(address, userOp, executionContext);\n }\n\n /**\n * Changes the password used to encrypt the vault.\n *\n * @param password - The new password.\n * @returns Promise resolving when the operation completes.\n */\n changePassword(password: string): Promise<void> {\n this.#assertIsUnlocked();\n\n // If the password is the same, do nothing.\n if (this.#password === password) {\n return Promise.resolve();\n }\n\n return this.#persistOrRollback(async () => {\n assertIsValidPassword(password);\n\n this.#password = password;\n // We need to clear encryption key and salt from state\n // to force the controller to re-encrypt the vault using\n // the new password.\n if (this.#cacheEncryptionKey) {\n this.update((state) => {\n delete state.encryptionKey;\n delete state.encryptionSalt;\n });\n }\n });\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings, using the\n * given encryption key and salt. The optional salt can be used to check for\n * consistency with the vault salt.\n *\n * @param encryptionKey - Key to unlock the keychain.\n * @param encryptionSalt - Optional salt to unlock the keychain.\n * @returns Promise resolving when the operation completes.\n */\n async submitEncryptionKey(\n encryptionKey: string,\n encryptionSalt?: string,\n ): Promise<void> {\n const { newMetadata } = await this.#withRollback(async () => {\n const result = await this.#unlockKeyrings(\n undefined,\n encryptionKey,\n encryptionSalt,\n );\n this.#setUnlocked();\n return result;\n });\n\n try {\n // if new metadata has been generated during login, we\n // can attempt to upgrade the vault.\n await this.#withRollback(async () => {\n if (newMetadata) {\n await this.#updateVault();\n }\n });\n } catch (error) {\n // We don't want to throw an error if the upgrade fails\n // since the controller is already unlocked.\n console.error('Failed to update vault during login:', error);\n }\n }\n\n /**\n * Exports the vault encryption key.\n *\n * @returns The vault encryption key.\n */\n async exportEncryptionKey(): Promise<string> {\n this.#assertIsUnlocked();\n\n return await this.#withControllerLock(async () => {\n const { encryptionKey } = this.state;\n assertIsEncryptionKeySet(encryptionKey);\n\n return encryptionKey;\n });\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings,\n * using the given password.\n *\n * @param password - Password to unlock the keychain.\n * @returns Promise resolving when the operation completes.\n */\n async submitPassword(password: string): Promise<void> {\n const { newMetadata } = await this.#withRollback(async () => {\n const result = await this.#unlockKeyrings(password);\n this.#setUnlocked();\n return result;\n });\n\n try {\n // If there are stronger encryption params available, or\n // if new metadata has been generated during login, we\n // can attempt to upgrade the vault.\n await this.#withRollback(async () => {\n if (newMetadata || this.#isNewEncryptionAvailable()) {\n await this.#updateVault();\n }\n });\n } catch (error) {\n // We don't want to throw an error if the upgrade fails\n // since the controller is already unlocked.\n console.error('Failed to update vault during login:', error);\n }\n }\n\n /**\n * Verifies the that the seed phrase restores the current keychain's accounts.\n *\n * @param keyringId - The id of the keyring to verify.\n * @returns Promise resolving to the seed phrase as Uint8Array.\n */\n async verifySeedPhrase(keyringId?: string): Promise<Uint8Array> {\n this.#assertIsUnlocked();\n\n return this.#withControllerLock(async () =>\n this.#verifySeedPhrase(keyringId),\n );\n }\n\n /**\n * Select a keyring and execute the given operation with\n * the selected keyring, as a mutually exclusive atomic\n * operation.\n *\n * The method automatically persists changes at the end of the\n * function execution, or rolls back the changes if an error\n * is thrown.\n *\n * @param selector - Keyring selector object.\n * @param operation - Function to execute with the selected keyring.\n * @param options - Additional options.\n * @param options.createIfMissing - Whether to create a new keyring if the selected one is missing.\n * @param options.createWithData - Optional data to use when creating a new keyring.\n * @returns Promise resolving to the result of the function execution.\n * @template SelectedKeyring - The type of the selected keyring.\n * @template CallbackResult - The type of the value resolved by the callback function.\n * @deprecated This method overload is deprecated. Use `withKeyring` without options instead.\n */\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n options:\n | { createIfMissing?: false }\n | { createIfMissing: true; createWithData?: unknown },\n ): Promise<CallbackResult>;\n\n /**\n * Select a keyring and execute the given operation with\n * the selected keyring, as a mutually exclusive atomic\n * operation.\n *\n * The method automatically persists changes at the end of the\n * function execution, or rolls back the changes if an error\n * is thrown.\n *\n * @param selector - Keyring selector object.\n * @param operation - Function to execute with the selected keyring.\n * @returns Promise resolving to the result of the function execution.\n * @template SelectedKeyring - The type of the selected keyring.\n * @template CallbackResult - The type of the value resolved by the callback function.\n */\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult>;\n\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n options:\n | { createIfMissing?: false }\n | { createIfMissing: true; createWithData?: unknown } = {\n createIfMissing: false,\n },\n ): Promise<CallbackResult> {\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n let keyring: SelectedKeyring | undefined;\n\n if ('address' in selector) {\n keyring = (await this.getKeyringForAccount(selector.address)) as\n | SelectedKeyring\n | undefined;\n } else if ('type' in selector) {\n keyring = this.getKeyringsByType(selector.type)[selector.index || 0] as\n | SelectedKeyring\n | undefined;\n\n if (!keyring && options.createIfMissing) {\n keyring = (await this.#newKeyring(\n selector.type,\n options.createWithData,\n )) as SelectedKeyring;\n }\n } else if ('id' in selector) {\n keyring = this.#getKeyringById(selector.id) as SelectedKeyring;\n }\n\n if (!keyring) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n\n const result = await operation({\n keyring,\n metadata: this.#getKeyringMetadata(keyring),\n });\n\n if (Object.is(result, keyring)) {\n // Access to a keyring instance outside of controller safeguards\n // should be discouraged, as it can lead to unexpected behavior.\n // This error is thrown to prevent consumers using `withKeyring`\n // as a way to get a reference to a keyring instance.\n throw new Error(KeyringControllerError.UnsafeDirectKeyringAccess);\n }\n\n return result;\n });\n }\n\n async getAccountKeyringType(account: string): Promise<string> {\n this.#assertIsUnlocked();\n\n const keyring = (await this.getKeyringForAccount(account)) as EthKeyring;\n return keyring.type;\n }\n\n /**\n * Constructor helper for registering this controller's messeger\n * actions.\n */\n #registerMessageHandlers() {\n this.messenger.registerActionHandler(\n `${name}:signMessage`,\n this.signMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signEip7702Authorization`,\n this.signEip7702Authorization.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signPersonalMessage`,\n this.signPersonalMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signTypedMessage`,\n this.signTypedMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:decryptMessage`,\n this.decryptMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getEncryptionPublicKey`,\n this.getEncryptionPublicKey.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getAccounts`,\n this.getAccounts.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getKeyringsByType`,\n this.getKeyringsByType.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getKeyringForAccount`,\n this.getKeyringForAccount.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:persistAllKeyrings`,\n this.persistAllKeyrings.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:prepareUserOperation`,\n this.prepareUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:patchUserOperation`,\n this.patchUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signUserOperation`,\n this.signUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:addNewAccount`,\n this.addNewAccount.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:withKeyring`,\n this.withKeyring.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:addNewKeyring`,\n this.addNewKeyring.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:createNewVaultAndKeychain`,\n this.createNewVaultAndKeychain.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:createNewVaultAndRestore`,\n this.createNewVaultAndRestore.bind(this),\n );\n }\n\n /**\n * Get the keyring by id.\n *\n * @param keyringId - The id of the keyring.\n * @returns The keyring.\n */\n #getKeyringById(keyringId: string): EthKeyring | undefined {\n return this.#keyrings.find(({ metadata }) => metadata.id === keyringId)\n ?.keyring;\n }\n\n /**\n * Get the keyring by id or return the first keyring if the id is not found.\n *\n * @param keyringId - The id of the keyring.\n * @returns The keyring.\n */\n #getKeyringByIdOrDefault(keyringId?: string): EthKeyring | undefined {\n if (!keyringId) {\n return this.#keyrings[0]?.keyring;\n }\n\n return this.#getKeyringById(keyringId);\n }\n\n /**\n * Get the metadata for the specified keyring.\n *\n * @param keyring - The keyring instance to get the metadata for.\n * @returns The keyring metadata.\n */\n #getKeyringMetadata(keyring: unknown): KeyringMetadata {\n const keyringWithMetadata = this.#keyrings.find(\n (candidate) => candidate.keyring === keyring,\n );\n if (!keyringWithMetadata) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n return keyringWithMetadata.metadata;\n }\n\n /**\n * Get the keyring builder for the given `type`.\n *\n * @param type - The type of keyring to get the builder for.\n * @returns The keyring builder, or undefined if none exists.\n */\n #getKeyringBuilderForType(\n type: string,\n ): { (): EthKeyring; type: string } | undefined {\n return this.#keyringBuilders.find(\n (keyringBuilder) => keyringBuilder.type === type,\n );\n }\n\n /**\n * Create new vault with an initial keyring\n *\n * Destroys any old encrypted storage,\n * creates a new encrypted store with the given password,\n * creates a new wallet with 1 account.\n *\n * @fires KeyringController:unlock\n * @param password - The password to encrypt the vault with.\n * @param keyring - A object containing the params to instantiate a new keyring.\n * @param keyring.type - The keyring type.\n * @param keyring.opts - Optional parameters required to instantiate the keyring.\n * @returns A promise that resolves to the state.\n */\n async #createNewVaultWithKeyring(\n password: string,\n keyring: {\n type: string;\n opts?: unknown;\n },\n ): Promise<void> {\n this.#assertControllerMutexIsLocked();\n\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n\n this.update((state) => {\n delete state.encryptionKey;\n delete state.encryptionSalt;\n });\n\n this.#password = password;\n\n await this.#clearKeyrings();\n await this.#createKeyringWithFirstAccount(keyring.type, keyring.opts);\n this.#setUnlocked();\n }\n\n /**\n * Internal non-exclusive method to verify the seed phrase.\n *\n * @param keyringId - The id of the keyring to verify the seed phrase for.\n * @returns A promise resolving to the seed phrase as Uint8Array.\n */\n async #verifySeedPhrase(keyringId?: string): Promise<Uint8Array> {\n this.#assertControllerMutexIsLocked();\n\n const keyring = this.#getKeyringByIdOrDefault(keyringId);\n\n if (!keyring) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (keyring.type !== KeyringTypes.hd) {\n throw new Error(KeyringControllerError.UnsupportedVerifySeedPhrase);\n }\n\n assertHasUint8ArrayMnemonic(keyring);\n\n const seedWords = keyring.mnemonic;\n const accounts = await keyring.getAccounts();\n /* istanbul ignore if */\n if (accounts.length === 0) {\n throw new Error('Cannot verify an empty keyring.');\n }\n\n // The HD Keyring Builder is a default keyring builder\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const hdKeyringBuilder = this.#getKeyringBuilderForType(KeyringTypes.hd)!;\n\n const hdKeyring = hdKeyringBuilder();\n // @ts-expect-error @metamask/eth-hd-keyring correctly handles\n // Uint8Array seed phrases in the `deserialize` method.\n await hdKeyring.deserialize({\n mnemonic: seedWords,\n numberOfAccounts: accounts.length,\n });\n const testAccounts = await hdKeyring.getAccounts();\n /* istanbul ignore if */\n if (testAccounts.length !== accounts.length) {\n throw new Error('Seed phrase imported incorrect number of accounts.');\n }\n\n testAccounts.forEach((account: string, i: number) => {\n /* istanbul ignore if */\n if (account.toLowerCase() !== accounts[i].toLowerCase()) {\n throw new Error('Seed phrase imported different accounts.');\n }\n });\n\n return seedWords;\n }\n\n /**\n * Get the updated array of each keyring's type and\n * accounts list.\n *\n * @returns A promise resolving to the updated keyrings array.\n */\n async #getUpdatedKeyrings(): Promise<KeyringObject[]> {\n return Promise.all(this.#keyrings.map(displayForKeyring));\n }\n\n /**\n * Serialize the current array of keyring instances,\n * including unsupported keyrings by default.\n *\n * @param options - Method options.\n * @param options.includeUnsupported - Whether to include unsupported keyrings.\n * @returns The serialized keyrings.\n */\n async #getSerializedKeyrings(\n { includeUnsupported }: { includeUnsupported: boolean } = {\n includeUnsupported: true,\n },\n ): Promise<SerializedKeyring[]> {\n const serializedKeyrings: SerializedKeyring[] = await Promise.all(\n this.#keyrings.map(async ({ keyring, metadata }) => {\n return {\n type: keyring.type,\n data: await keyring.serialize(),\n metadata,\n };\n }),\n );\n\n if (includeUnsupported) {\n serializedKeyrings.push(...this.#unsupportedKeyrings);\n }\n\n return serializedKeyrings;\n }\n\n /**\n * Get a snapshot of session data held by class variables.\n *\n * @returns An object with serialized keyrings, keyrings metadata,\n * and the user password.\n */\n async #getSessionState(): Promise<SessionState> {\n return {\n keyrings: await this.#getSerializedKeyrings(),\n password: this.#password,\n };\n }\n\n /**\n * Restore a serialized keyrings array.\n *\n * @param serializedKeyrings - The serialized keyrings array.\n * @returns The restored keyrings.\n */\n async #restoreSerializedKeyrings(\n serializedKeyrings: SerializedKeyring[],\n ): Promise<{\n keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n newMetadata: boolean;\n }> {\n await this.#clearKeyrings();\n const keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[] = [];\n let newMetadata = false;\n\n for (const serializedKeyring of serializedKeyrings) {\n const result = await this.#restoreKeyring(serializedKeyring);\n if (result) {\n const { keyring, metadata } = result;\n keyrings.push({ keyring, metadata });\n if (result.newMetadata) {\n newMetadata = true;\n }\n }\n }\n\n return { keyrings, newMetadata };\n }\n\n /**\n * Unlock Keyrings, decrypting the vault and deserializing all\n * keyrings contained in it, using a password or an encryption key with salt.\n *\n * @param password - The keyring controller password.\n * @param encryptionKey - An exported key string to unlock keyrings with.\n * @param encryptionSalt - The salt used to encrypt the vault.\n * @returns A promise resolving to the deserialized keyrings array.\n */\n async #unlockKeyrings(\n password: string | undefined,\n encryptionKey?: string,\n encryptionSalt?: string,\n ): Promise<{\n keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n newMetadata: boolean;\n }> {\n return this.#withVaultLock(async () => {\n const encryptedVault = this.state.vault;\n if (!encryptedVault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n\n let vault;\n const updatedState: Partial<KeyringControllerState> = {};\n\n if (this.#cacheEncryptionKey) {\n assertIsExportableKeyEncryptor(this.#encryptor);\n\n if (password) {\n const result = await this.#encryptor.decryptWithDetail(\n password,\n encryptedVault,\n );\n vault = result.vault;\n this.#password = password;\n\n updatedState.encryptionKey = result.exportedKeyString;\n updatedState.encryptionSalt = result.salt;\n } else {\n const parsedEncryptedVault = JSON.parse(encryptedVault);\n\n if (encryptionSalt && encryptionSalt !== parsedEncryptedVault.salt) {\n throw new Error(KeyringControllerError.ExpiredCredentials);\n } else {\n encryptionSalt = parsedEncryptedVault.salt as string;\n }\n\n if (typeof encryptionKey !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n\n const key = await this.#encryptor.importKey(encryptionKey);\n vault = await this.#encryptor.decryptWithKey(\n key,\n parsedEncryptedVault,\n );\n\n // This call is required on the first call because encryptionKey\n // is not yet inside the memStore\n updatedState.encryptionKey = encryptionKey;\n updatedState.encryptionSalt = encryptionSalt;\n }\n } else {\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n\n vault = await this.#encryptor.decrypt(password, encryptedVault);\n this.#password = password;\n }\n\n if (!isSerializedKeyringsArray(vault)) {\n throw new Error(KeyringControllerError.VaultDataError);\n }\n\n const { keyrings, newMetadata } =\n await this.#restoreSerializedKeyrings(vault);\n\n const updatedKeyrings = await this.#getUpdatedKeyrings();\n\n this.update((state) => {\n state.keyrings = updatedKeyrings;\n if (updatedState.encryptionKey || updatedState.encryptionSalt) {\n state.encryptionKey = updatedState.encryptionKey;\n state.encryptionSalt = updatedState.encryptionSalt;\n }\n });\n\n return { keyrings, newMetadata };\n });\n }\n\n /**\n * Update the vault with the current keyrings.\n *\n * @returns A promise resolving to `true` if the operation is successful.\n */\n #updateVault(): Promise<boolean> {\n return this.#withVaultLock(async () => {\n // Ensure no duplicate accounts are persisted.\n await this.#assertNoDuplicateAccounts();\n\n const { encryptionKey, encryptionSalt, vault } = this.state;\n // READ THIS CAREFULLY:\n // We do check if the vault is still considered up-to-date, if not, we would not re-use the\n // cached key and we will re-generate a new one (based on the password).\n //\n // This helps doing seamless updates of the vault. Useful in case we change some cryptographic\n // parameters to the KDF.\n const useCachedKey =\n encryptionKey && vault && this.#encryptor.isVaultUpdated?.(vault);\n\n if (!this.#password && !encryptionKey) {\n throw new Error(KeyringControllerError.MissingCredentials);\n }\n\n const serializedKeyrings = await this.#getSerializedKeyrings();\n\n if (\n !serializedKeyrings.some((keyring) => keyring.type === KeyringTypes.hd)\n ) {\n throw new Error(KeyringControllerError.NoHdKeyring);\n }\n\n const updatedState: Partial<KeyringControllerState> = {};\n\n if (this.#cacheEncryptionKey) {\n assertIsExportableKeyEncryptor(this.#encryptor);\n\n if (useCachedKey) {\n const key = await this.#encryptor.importKey(encryptionKey);\n const vaultJSON = await this.#encryptor.encryptWithKey(\n key,\n serializedKeyrings,\n );\n vaultJSON.salt = encryptionSalt;\n updatedState.vault = JSON.stringify(vaultJSON);\n } else if (this.#password) {\n const { vault: newVault, exportedKeyString } =\n await this.#encryptor.encryptWithDetail(\n this.#password,\n serializedKeyrings,\n );\n\n updatedState.vault = newVault;\n updatedState.encryptionKey = exportedKeyString;\n }\n } else {\n assertIsValidPassword(this.#password);\n updatedState.vault = await this.#encryptor.encrypt(\n this.#password,\n serializedKeyrings,\n );\n }\n\n if (!updatedState.vault) {\n throw new Error(KeyringControllerError.MissingVaultData);\n }\n\n const updatedKeyrings = await this.#getUpdatedKeyrings();\n\n this.update((state) => {\n state.vault = updatedState.vault;\n state.keyrings = updatedKeyrings;\n if (updatedState.encryptionKey) {\n state.encryptionKey = updatedState.encryptionKey;\n state.encryptionSalt = JSON.parse(updatedState.vault as string).salt;\n }\n });\n\n return true;\n });\n }\n\n /**\n * Check if there are new encryption parameters available.\n *\n * @returns A promise resolving to `void`.\n */\n #isNewEncryptionAvailable(): boolean {\n const { vault } = this.state;\n\n if (!vault || !this.#password || !this.#encryptor.isVaultUpdated) {\n return false;\n }\n\n return !this.#encryptor.isVaultUpdated(vault);\n }\n\n /**\n * Retrieves all the accounts from keyrings instances\n * that are currently in memory.\n *\n * @param additionalKeyrings - Additional keyrings to include in the search.\n * @returns A promise resolving to an array of accounts.\n */\n async #getAccountsFromKeyrings(\n additionalKeyrings: EthKeyring[] = [],\n ): Promise<string[]> {\n const keyrings = this.#keyrings.map(({ keyring }) => keyring);\n\n const keyringArrays = await Promise.all(\n [...keyrings, ...additionalKeyrings].map(async (keyring) =>\n keyring.getAccounts(),\n ),\n );\n const addresses = keyringArrays.reduce((res, arr) => {\n return res.concat(arr);\n }, []);\n\n // Cast to `string[]` here is safe here because `addresses` has no nullish\n // values, and `normalize` returns `string` unless given a nullish value\n return addresses.map(normalize) as string[];\n }\n\n /**\n * Create a new keyring, ensuring that the first account is\n * also created.\n *\n * @param type - Keyring type to instantiate.\n * @param opts - Optional parameters required to instantiate the keyring.\n * @returns A promise that resolves if the operation is successful.\n */\n async #createKeyringWithFirstAccount(type: string, opts?: unknown) {\n this.#assertControllerMutexIsLocked();\n\n const keyring = (await this.#newKeyring(type, opts)) as EthKeyring;\n\n const [firstAccount] = await keyring.getAccounts();\n if (!firstAccount) {\n throw new Error(KeyringControllerError.NoFirstAccount);\n }\n return firstAccount;\n }\n\n /**\n * Instantiate, initialize and return a new keyring of the given `type`,\n * using the given `opts`. The keyring is built using the keyring builder\n * registered for the given `type`.\n *\n * The internal keyring and keyring metadata arrays are updated with the new\n * keyring as well.\n *\n * @param type - The type of keyring to add.\n * @param data - Keyring initialization options.\n * @returns The new keyring.\n * @throws If the keyring includes duplicated accounts.\n */\n async #newKeyring(type: string, data?: unknown): Promise<EthKeyring> {\n const keyring = await this.#createKeyring(type, data);\n\n this.#keyrings.push({ keyring, metadata: getDefaultKeyringMetadata() });\n\n return keyring;\n }\n\n /**\n * Instantiate, initialize and return a keyring of the given `type` using the\n * given `opts`. The keyring is built using the keyring builder registered\n * for the given `type`.\n *\n * The keyring might be new, or it might be restored from the vault. This\n * function should only be called from `#newKeyring` or `#restoreKeyring`,\n * for the \"new\" and \"restore\" cases respectively.\n *\n * The internal keyring and keyring metadata arrays are *not* updated, the\n * caller is expected to update them.\n *\n * @param type - The type of keyring to add.\n * @param data - Keyring initialization options.\n * @returns The new keyring.\n * @throws If the keyring includes duplicated accounts.\n */\n async #createKeyring(type: string, data?: unknown): Promise<EthKeyring> {\n this.#assertControllerMutexIsLocked();\n\n const keyringBuilder = this.#getKeyringBuilderForType(type);\n\n if (!keyringBuilder) {\n throw new Error(\n `${KeyringControllerError.NoKeyringBuilder}. Keyring type: ${type}`,\n );\n }\n\n const keyring = keyringBuilder();\n if (data) {\n // @ts-expect-error Enforce data type after updating clients\n await keyring.deserialize(data);\n }\n\n if (keyring.init) {\n await keyring.init();\n }\n\n if (type === KeyringTypes.hd && (!isObject(data) || !data.mnemonic)) {\n if (!keyring.generateRandomMnemonic) {\n throw new Error(\n KeyringControllerError.UnsupportedGenerateRandomMnemonic,\n );\n }\n\n // NOTE: Not all keyrings implement this method in a asynchronous-way. Using `await` for\n // non-thenable will still be valid (despite not being really useful). It allows us to cover both\n // cases and allow retro-compatibility too.\n await keyring.generateRandomMnemonic();\n await keyring.addAccounts(1);\n }\n\n return keyring;\n }\n\n /**\n * Remove all managed keyrings, destroying all their\n * instances in memory.\n */\n async #clearKeyrings() {\n this.#assertControllerMutexIsLocked();\n for (const { keyring } of this.#keyrings) {\n await this.#destroyKeyring(keyring);\n }\n this.#keyrings = [];\n this.#unsupportedKeyrings = [];\n }\n\n /**\n * Restore a Keyring from a provided serialized payload.\n * On success, returns the resulting keyring instance.\n *\n * @param serialized - The serialized keyring.\n * @returns The deserialized keyring or undefined if the keyring type is unsupported.\n */\n async #restoreKeyring(\n serialized: SerializedKeyring,\n ): Promise<\n | { keyring: EthKeyring; metadata: KeyringMetadata; newMetadata: boolean }\n | undefined\n > {\n this.#assertControllerMutexIsLocked();\n\n try {\n const { type, data, metadata: serializedMetadata } = serialized;\n let newMetadata = false;\n let metadata = serializedMetadata;\n const keyring = await this.#createKeyring(type, data);\n await this.#assertNoDuplicateAccounts([keyring]);\n // If metadata is missing, assume the data is from an installation before\n // we had keyring metadata.\n if (!metadata) {\n newMetadata = true;\n metadata = getDefaultKeyringMetadata();\n }\n // The keyring is added to the keyrings array only if it's successfully restored\n // and the metadata is successfully added to the controller\n this.#keyrings.push({\n keyring,\n metadata,\n });\n return { keyring, metadata, newMetadata };\n } catch (error) {\n console.error(error);\n this.#unsupportedKeyrings.push(serialized);\n return undefined;\n }\n }\n\n /**\n * Destroy Keyring\n *\n * Some keyrings support a method called `destroy`, that destroys the\n * keyring along with removing all its event listeners and, in some cases,\n * clears the keyring bridge iframe from the DOM.\n *\n * @param keyring - The keyring to destroy.\n */\n async #destroyKeyring(keyring: EthKeyring) {\n await keyring.destroy?.();\n }\n\n /**\n * Remove empty keyrings.\n *\n * Loops through the keyrings and removes the ones with empty accounts\n * (usually after removing the last / only account) from a keyring.\n */\n async #removeEmptyKeyrings(): Promise<void> {\n this.#assertControllerMutexIsLocked();\n const validKeyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[] =\n [];\n\n // Since getAccounts returns a Promise\n // We need to wait to hear back form each keyring\n // in order to decide which ones are now valid (accounts.length > 0)\n\n await Promise.all(\n this.#keyrings.map(async ({ keyring, metadata }) => {\n const accounts = await keyring.getAccounts();\n if (accounts.length > 0) {\n validKeyrings.push({ keyring, metadata });\n } else {\n await this.#destroyKeyring(keyring);\n }\n }),\n );\n this.#keyrings = validKeyrings;\n }\n\n /**\n * Assert that there are no duplicate accounts in the keyrings.\n *\n * @param additionalKeyrings - Additional keyrings to include in the check.\n * @throws If there are duplicate accounts.\n */\n async #assertNoDuplicateAccounts(\n additionalKeyrings: EthKeyring[] = [],\n ): Promise<void> {\n const accounts = await this.#getAccountsFromKeyrings(additionalKeyrings);\n\n if (new Set(accounts).size !== accounts.length) {\n throw new Error(KeyringControllerError.DuplicatedAccount);\n }\n }\n\n /**\n * Set the `isUnlocked` to true and notify listeners\n * through the messenger.\n *\n * @fires KeyringController:unlock\n */\n #setUnlocked(): void {\n this.#assertControllerMutexIsLocked();\n\n this.update((state) => {\n state.isUnlocked = true;\n });\n this.messenger.publish(`${name}:unlock`);\n }\n\n /**\n * Assert that the controller is unlocked.\n *\n * @throws If the controller is locked.\n */\n #assertIsUnlocked(): void {\n if (!this.state.isUnlocked) {\n throw new Error(KeyringControllerError.ControllerLocked);\n }\n }\n\n /**\n * Execute the given function after acquiring the controller lock\n * and save the vault to state after it (only if needed), or rollback to their\n * previous state in case of error.\n *\n * @param callback - The function to execute.\n * @returns The result of the function.\n */\n async #persistOrRollback<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return this.#withRollback(async ({ releaseLock }) => {\n const oldState = JSON.stringify(await this.#getSessionState());\n const callbackResult = await callback({ releaseLock });\n const newState = JSON.stringify(await this.#getSessionState());\n\n // State is committed only if the operation is successful and need to trigger a vault update.\n if (!isEqual(oldState, newState)) {\n await this.#updateVault();\n }\n\n return callbackResult;\n });\n }\n\n /**\n * Execute the given function after acquiring the controller lock\n * and rollback keyrings and password states in case of error.\n *\n * @param callback - The function to execute atomically.\n * @returns The result of the function.\n */\n async #withRollback<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return this.#withControllerLock(async ({ releaseLock }) => {\n const currentSerializedKeyrings = await this.#getSerializedKeyrings();\n const currentPassword = this.#password;\n\n try {\n return await callback({ releaseLock });\n } catch (e) {\n // Keyrings and password are restored to their previous state\n this.#password = currentPassword;\n await this.#restoreSerializedKeyrings(currentSerializedKeyrings);\n\n throw e;\n }\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(KeyringControllerError.ControllerLockRequired);\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n\n /**\n * Lock the vault mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This ensures that each operation that interacts with the vault\n * is executed in a mutually exclusive way.\n *\n * @param callback - The function to execute while the vault mutex is locked.\n * @returns The result of the function.\n */\n async #withVaultLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n this.#assertControllerMutexIsLocked();\n\n return withLock(this.#vaultOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n\n/**\n * Generate a new keyring metadata object.\n *\n * @returns Keyring metadata.\n */\nfunction getDefaultKeyringMetadata(): KeyringMetadata {\n return { id: ulid(), name: '' };\n}\n\nexport default KeyringController;\n"]}
1
+ {"version":3,"file":"KeyringController.mjs","sourceRoot":"","sources":["../src/KeyringController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,yBAAyB;AACjE,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,EAAE,SAAS,EAAE,iCAAiC;AACrD,OAAO,EAAE,SAAS,IAAI,YAAY,EAAE,+BAA+B;AACnE,OAAO,aAAa,qCAAqC;AAYzD,OAAO,EACL,KAAK,EACL,uBAAuB,EACvB,UAAU,EACV,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oBAAoB;;;;;;AAKpC,sHAAsH;AACtH,OAAO,EAAE,IAAI,EAAE,aAAa;AAE5B,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AAOrD,MAAM,IAAI,GAAG,mBAAmB,CAAC;AAEjC;;GAEG;AACH,MAAM,CAAN,IAAY,YASX;AATD,WAAY,YAAY;IACtB,0CAA0B,CAAA;IAC1B,kCAAkB,CAAA;IAClB,gDAAgC,CAAA;IAChC,0CAA0B,CAAA;IAC1B,0CAA0B,CAAA;IAC1B,0CAA0B,CAAA;IA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ypedTxData } from '@ethereumjs/tx';\nimport { isValidPrivate, getBinarySize } from '@ethereumjs/util';\nimport { BaseController } from '@metamask/base-controller';\nimport type * as encryptorUtils from '@metamask/browser-passworder';\nimport { HdKeyring } from '@metamask/eth-hd-keyring';\nimport { normalize as ethNormalize } from '@metamask/eth-sig-util';\nimport SimpleKeyring from '@metamask/eth-simple-keyring';\nimport type {\n KeyringExecutionContext,\n EthBaseTransaction,\n EthBaseUserOperation,\n EthUserOperation,\n EthUserOperationPatch,\n} from '@metamask/keyring-api';\nimport type { EthKeyring } from '@metamask/keyring-internal-api';\nimport type { KeyringClass } from '@metamask/keyring-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Eip1024EncryptedData, Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n assertIsStrictHexString,\n bytesToHex,\n hasProperty,\n hexToBytes,\n isObject,\n isStrictHexString,\n isValidHexAddress,\n isValidJson,\n remove0x,\n} from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport type { MutexInterface } from 'async-mutex';\nimport Wallet, { thirdparty as importers } from 'ethereumjs-wallet';\nimport type { Patch } from 'immer';\nimport { cloneDeep, isEqual } from 'lodash';\n// When generating a ULID within the same millisecond, monotonicFactory provides some guarantees regarding sort order.\nimport { ulid } from 'ulid';\n\nimport { KeyringControllerError } from './constants';\nimport type {\n Eip7702AuthorizationParams,\n PersonalMessageParams,\n TypedMessageParams,\n} from './types';\n\nconst name = 'KeyringController';\n\n/**\n * Available keyring types\n */\nexport enum KeyringTypes {\n simple = 'Simple Key Pair',\n hd = 'HD Key Tree',\n qr = 'QR Hardware Wallet Device',\n trezor = 'Trezor Hardware',\n oneKey = 'OneKey Hardware',\n ledger = 'Ledger Hardware',\n lattice = 'Lattice Hardware',\n snap = 'Snap Keyring',\n}\n\n/**\n * Custody keyring types are a special case, as they are not a single type\n * but they all start with the prefix \"Custody\".\n *\n * @param keyringType - The type of the keyring.\n * @returns Whether the keyring type is a custody keyring.\n */\nexport const isCustodyKeyring = (keyringType: string): boolean => {\n return keyringType.startsWith('Custody');\n};\n\n/**\n * The KeyringController state\n */\nexport type KeyringControllerState = {\n /**\n * Encrypted array of serialized keyrings data.\n */\n vault?: string;\n /**\n * Whether the vault has been decrypted successfully and\n * keyrings contained within are deserialized and available.\n */\n isUnlocked: boolean;\n /**\n * Representations of managed keyrings.\n */\n keyrings: KeyringObject[];\n /**\n * The encryption key derived from the password and used to encrypt\n * the vault.\n */\n encryptionKey?: string;\n /**\n * The salt used to derive the encryption key from the password.\n */\n encryptionSalt?: string;\n};\n\nexport type KeyringControllerMemState = Omit<\n KeyringControllerState,\n 'vault' | 'encryptionKey' | 'encryptionSalt'\n>;\n\nexport type KeyringControllerGetStateAction = {\n type: `${typeof name}:getState`;\n handler: () => KeyringControllerState;\n};\n\nexport type KeyringControllerSignMessageAction = {\n type: `${typeof name}:signMessage`;\n handler: KeyringController['signMessage'];\n};\n\nexport type KeyringControllerSignEip7702AuthorizationAction = {\n type: `${typeof name}:signEip7702Authorization`;\n handler: KeyringController['signEip7702Authorization'];\n};\n\nexport type KeyringControllerSignPersonalMessageAction = {\n type: `${typeof name}:signPersonalMessage`;\n handler: KeyringController['signPersonalMessage'];\n};\n\nexport type KeyringControllerSignTypedMessageAction = {\n type: `${typeof name}:signTypedMessage`;\n handler: KeyringController['signTypedMessage'];\n};\n\nexport type KeyringControllerDecryptMessageAction = {\n type: `${typeof name}:decryptMessage`;\n handler: KeyringController['decryptMessage'];\n};\n\nexport type KeyringControllerGetEncryptionPublicKeyAction = {\n type: `${typeof name}:getEncryptionPublicKey`;\n handler: KeyringController['getEncryptionPublicKey'];\n};\n\nexport type KeyringControllerGetKeyringsByTypeAction = {\n type: `${typeof name}:getKeyringsByType`;\n handler: KeyringController['getKeyringsByType'];\n};\n\nexport type KeyringControllerGetKeyringForAccountAction = {\n type: `${typeof name}:getKeyringForAccount`;\n handler: KeyringController['getKeyringForAccount'];\n};\n\nexport type KeyringControllerGetAccountsAction = {\n type: `${typeof name}:getAccounts`;\n handler: KeyringController['getAccounts'];\n};\n\nexport type KeyringControllerPersistAllKeyringsAction = {\n type: `${typeof name}:persistAllKeyrings`;\n handler: KeyringController['persistAllKeyrings'];\n};\n\nexport type KeyringControllerPrepareUserOperationAction = {\n type: `${typeof name}:prepareUserOperation`;\n handler: KeyringController['prepareUserOperation'];\n};\n\nexport type KeyringControllerPatchUserOperationAction = {\n type: `${typeof name}:patchUserOperation`;\n handler: KeyringController['patchUserOperation'];\n};\n\nexport type KeyringControllerSignUserOperationAction = {\n type: `${typeof name}:signUserOperation`;\n handler: KeyringController['signUserOperation'];\n};\n\nexport type KeyringControllerAddNewAccountAction = {\n type: `${typeof name}:addNewAccount`;\n handler: KeyringController['addNewAccount'];\n};\n\nexport type KeyringControllerWithKeyringAction = {\n type: `${typeof name}:withKeyring`;\n handler: KeyringController['withKeyring'];\n};\n\nexport type KeyringControllerCreateNewVaultAndKeychainAction = {\n type: `${typeof name}:createNewVaultAndKeychain`;\n handler: KeyringController['createNewVaultAndKeychain'];\n};\n\nexport type KeyringControllerCreateNewVaultAndRestoreAction = {\n type: `${typeof name}:createNewVaultAndRestore`;\n handler: KeyringController['createNewVaultAndRestore'];\n};\n\nexport type KeyringControllerAddNewKeyringAction = {\n type: `${typeof name}:addNewKeyring`;\n handler: KeyringController['addNewKeyring'];\n};\n\nexport type KeyringControllerStateChangeEvent = {\n type: `${typeof name}:stateChange`;\n payload: [KeyringControllerState, Patch[]];\n};\n\nexport type KeyringControllerAccountRemovedEvent = {\n type: `${typeof name}:accountRemoved`;\n payload: [string];\n};\n\nexport type KeyringControllerLockEvent = {\n type: `${typeof name}:lock`;\n payload: [];\n};\n\nexport type KeyringControllerUnlockEvent = {\n type: `${typeof name}:unlock`;\n payload: [];\n};\n\nexport type KeyringControllerActions =\n | KeyringControllerGetStateAction\n | KeyringControllerSignMessageAction\n | KeyringControllerSignEip7702AuthorizationAction\n | KeyringControllerSignPersonalMessageAction\n | KeyringControllerSignTypedMessageAction\n | KeyringControllerDecryptMessageAction\n | KeyringControllerGetEncryptionPublicKeyAction\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetKeyringsByTypeAction\n | KeyringControllerGetKeyringForAccountAction\n | KeyringControllerPersistAllKeyringsAction\n | KeyringControllerPrepareUserOperationAction\n | KeyringControllerPatchUserOperationAction\n | KeyringControllerSignUserOperationAction\n | KeyringControllerAddNewAccountAction\n | KeyringControllerWithKeyringAction\n | KeyringControllerAddNewKeyringAction\n | KeyringControllerCreateNewVaultAndKeychainAction\n | KeyringControllerCreateNewVaultAndRestoreAction;\n\nexport type KeyringControllerEvents =\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | KeyringControllerAccountRemovedEvent;\n\nexport type KeyringControllerMessenger = Messenger<\n typeof name,\n KeyringControllerActions,\n KeyringControllerEvents\n>;\n\nexport type KeyringControllerOptions<\n EncryptionKey = encryptorUtils.EncryptionKey | CryptoKey,\n SupportedKeyDerivationOptions = encryptorUtils.KeyDerivationOptions,\n> = {\n keyringBuilders?: { (): EthKeyring; type: string }[];\n messenger: KeyringControllerMessenger;\n state?: { vault?: string; keyringsMetadata?: KeyringMetadata[] };\n encryptor: Encryptor<EncryptionKey, SupportedKeyDerivationOptions>;\n};\n\n/**\n * A keyring object representation.\n */\nexport type KeyringObject = {\n /**\n * Accounts associated with the keyring.\n */\n accounts: string[];\n /**\n * Keyring type.\n */\n type: string;\n /**\n * Additional data associated with the keyring.\n */\n metadata: KeyringMetadata;\n};\n\n/**\n * Additional information related to a keyring.\n */\nexport type KeyringMetadata = {\n /**\n * Keyring ID\n */\n id: string;\n /**\n * Keyring name\n */\n name: string;\n};\n\n/**\n * A strategy for importing an account\n */\nexport enum AccountImportStrategy {\n privateKey = 'privateKey',\n json = 'json',\n}\n\n/**\n * The `signTypedMessage` version\n *\n * @see https://docs.metamask.io/guide/signing-data.html\n */\nexport enum SignTypedDataVersion {\n V1 = 'V1',\n V3 = 'V3',\n V4 = 'V4',\n}\n\n/**\n * A serialized keyring object.\n */\nexport type SerializedKeyring = {\n type: string;\n data: Json;\n metadata?: KeyringMetadata;\n};\n\n/**\n * Cached encryption key used to encrypt/decrypt the vault.\n */\ntype CachedEncryptionKey = {\n /**\n * The serialized encryption key.\n */\n serialized: string;\n /**\n * The salt used to derive the encryption key.\n */\n salt: string;\n};\n\n/**\n * State/data that can be updated during a `withKeyring` operation.\n */\ntype SessionState = {\n keyrings: SerializedKeyring[];\n encryptionKey?: CachedEncryptionKey;\n};\n\n/**\n * An encryptor interface that supports encrypting and decrypting\n * serializable data with a password, and exporting and importing keys.\n */\nexport type Encryptor<\n EncryptionKey = encryptorUtils.EncryptionKey | CryptoKey,\n SupportedKeyDerivationParams = encryptorUtils.KeyDerivationOptions,\n> = {\n /**\n * Encrypts the given object with the given password.\n *\n * @param password - The password to encrypt with.\n * @param object - The object to encrypt.\n * @returns The encrypted string.\n */\n encrypt: (password: string, object: Json) => Promise<string>;\n /**\n * Decrypts the given encrypted string with the given password.\n *\n * @param password - The password to decrypt with.\n * @param encryptedString - The encrypted string to decrypt.\n * @returns The decrypted object.\n */\n decrypt: (password: string, encryptedString: string) => Promise<unknown>;\n /**\n * Optional vault migration helper. Checks if the provided vault is up to date\n * with the desired encryption algorithm.\n *\n * @param vault - The encrypted string to check.\n * @param targetDerivationParams - The desired target derivation params.\n * @returns The updated encrypted string.\n */\n isVaultUpdated?: (\n vault: string,\n targetDerivationParams?: encryptorUtils.KeyDerivationOptions,\n ) => boolean;\n /**\n * Encrypts the given object with the given encryption key.\n *\n * @param key - The encryption key to encrypt with.\n * @param object - The object to encrypt.\n * @returns The encryption result.\n */\n encryptWithKey: (\n key: EncryptionKey,\n object: Json,\n ) => Promise<encryptorUtils.EncryptionResult>;\n /**\n * Encrypts the given object with the given password, and returns the\n * encryption result and the serialized key string.\n *\n * @param password - The password to encrypt with.\n * @param object - The object to encrypt.\n * @param salt - The optional salt to use for encryption.\n * @returns The encrypted string and the serialized key string.\n */\n encryptWithDetail: (\n password: string,\n object: Json,\n salt?: string,\n ) => Promise<encryptorUtils.DetailedEncryptionResult>;\n /**\n * Decrypts the given encrypted string with the given encryption key.\n *\n * @param key - The encryption key to decrypt with.\n * @param encryptedObject - The encrypted string to decrypt.\n * @returns The decrypted object.\n */\n decryptWithKey: (\n key: EncryptionKey,\n encryptedObject: encryptorUtils.EncryptionResult,\n ) => Promise<unknown>;\n /**\n * Decrypts the given encrypted string with the given password, and returns\n * the decrypted object and the salt and serialized key string used for\n * encryption.\n *\n * @param password - The password to decrypt with.\n * @param encryptedString - The encrypted string to decrypt.\n * @returns The decrypted object and the salt and serialized key string used for\n * encryption.\n */\n decryptWithDetail: (\n password: string,\n encryptedString: string,\n ) => Promise<encryptorUtils.DetailedDecryptResult>;\n /**\n * Generates an encryption key from a serialized key.\n *\n * @param key - The serialized key string.\n * @returns The encryption key.\n */\n importKey: (key: string) => Promise<EncryptionKey>;\n /**\n * Exports the encryption key as a string.\n *\n * @param key - The encryption key to export.\n * @returns The serialized key string.\n */\n exportKey: (key: EncryptionKey) => Promise<string>;\n /**\n * Derives an encryption key from a password.\n *\n * @param password - The password to derive the key from.\n * @param salt - The salt to use for key derivation.\n * @param exportable - Whether the key should be exportable or not.\n * @param options - Optional key derivation options.\n * @returns The derived encryption key.\n */\n keyFromPassword: (\n password: string,\n salt: string,\n exportable?: boolean,\n keyDerivationOptions?: SupportedKeyDerivationParams,\n ) => Promise<EncryptionKey>;\n /**\n * Generates a random salt for key derivation.\n */\n generateSalt: typeof encryptorUtils.generateSalt;\n};\n\nexport type KeyringSelector =\n | {\n type: string;\n index?: number;\n }\n | {\n address: Hex;\n }\n | {\n id: string;\n };\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Get builder function for `Keyring`\n *\n * Returns a builder function for `Keyring` with a `type` property.\n *\n * @param KeyringConstructor - The Keyring class for the builder.\n * @returns A builder function for the given Keyring.\n */\nexport function keyringBuilderFactory(KeyringConstructor: KeyringClass) {\n const builder = () => new KeyringConstructor();\n\n builder.type = KeyringConstructor.type;\n\n return builder;\n}\n\nconst defaultKeyringBuilders = [\n // todo: keyring types are mismatched, this should be fixed in they keyrings themselves\n // @ts-expect-error keyring types are mismatched\n keyringBuilderFactory(SimpleKeyring),\n keyringBuilderFactory(HdKeyring),\n];\n\nexport const getDefaultKeyringState = (): KeyringControllerState => {\n return {\n isUnlocked: false,\n keyrings: [],\n };\n};\n\n/**\n * Assert that the given keyring has an exportable\n * mnemonic.\n *\n * @param keyring - The keyring to check\n * @throws When the keyring does not have a mnemonic\n */\nfunction assertHasUint8ArrayMnemonic(\n keyring: EthKeyring,\n): asserts keyring is EthKeyring & { mnemonic: Uint8Array } {\n if (\n !(\n hasProperty(keyring, 'mnemonic') && keyring.mnemonic instanceof Uint8Array\n )\n ) {\n throw new Error(\"Can't get mnemonic bytes from keyring\");\n }\n}\n\n/**\n * Assert that the provided password is a valid non-empty string.\n *\n * @param password - The password to check.\n * @throws If the password is not a valid string.\n */\nfunction assertIsValidPassword(password: unknown): asserts password is string {\n if (typeof password !== 'string') {\n throw new Error(KeyringControllerError.WrongPasswordType);\n }\n\n if (!password || !password.length) {\n throw new Error(KeyringControllerError.InvalidEmptyPassword);\n }\n}\n\n/**\n * Assert that the provided encryption key is a valid non-empty string.\n *\n * @param encryptionKey - The encryption key to check.\n * @throws If the encryption key is not a valid string.\n */\nfunction assertIsEncryptionKeySet(\n encryptionKey: string | undefined,\n): asserts encryptionKey is string {\n if (!encryptionKey) {\n throw new Error(KeyringControllerError.EncryptionKeyNotSet);\n }\n}\n\n/**\n * Checks if the provided value is a serialized keyrings array.\n *\n * @param array - The value to check.\n * @returns True if the value is a serialized keyrings array.\n */\nfunction isSerializedKeyringsArray(\n array: unknown,\n): array is SerializedKeyring[] {\n return (\n typeof array === 'object' &&\n Array.isArray(array) &&\n array.every((value) => value.type && isValidJson(value.data))\n );\n}\n\n/**\n * Display For Keyring\n *\n * Is used for adding the current keyrings to the state object.\n *\n * @param keyringWithMetadata - The keyring and its metadata.\n * @param keyringWithMetadata.keyring - The keyring to display.\n * @param keyringWithMetadata.metadata - The metadata of the keyring.\n * @returns A keyring display object, with type and accounts properties.\n */\nasync function displayForKeyring({\n keyring,\n metadata,\n}: {\n keyring: EthKeyring;\n metadata: KeyringMetadata;\n}): Promise<KeyringObject> {\n const accounts = await keyring.getAccounts();\n\n return {\n type: keyring.type,\n // Cast to `string[]` here is safe here because `accounts` has no nullish\n // values, and `normalize` returns `string` unless given a nullish value\n accounts: accounts.map(normalize) as string[],\n metadata,\n };\n}\n\n/**\n * Check if address is an ethereum address\n *\n * @param address - An address.\n * @returns Returns true if the address is an ethereum one, false otherwise.\n */\nfunction isEthAddress(address: string): boolean {\n // We first check if it's a matching `Hex` string, so that is narrows down\n // `address` as an `Hex` type, allowing us to use `isValidHexAddress`\n return (\n // NOTE: This function only checks for lowercased strings\n isStrictHexString(address.toLowerCase()) &&\n // This checks for lowercased addresses and checksum addresses too\n isValidHexAddress(address as Hex)\n );\n}\n\n/**\n * Normalize ethereum or non-EVM address.\n *\n * @param address - Ethereum or non-EVM address.\n * @returns The normalized address.\n */\nfunction normalize(address: string): string | undefined {\n // Since the `KeyringController` is only dealing with address, we have\n // no other way to get the associated account type with this address. So we\n // are down to check the actual address format for now\n // TODO: Find a better way to not have those runtime checks based on the\n // address value!\n return isEthAddress(address) ? ethNormalize(address) : address;\n}\n\n/**\n * Controller responsible for establishing and managing user identity.\n *\n * This class is a wrapper around the `eth-keyring-controller` package. The\n * `eth-keyring-controller` manages the \"vault\", which is an encrypted store of private keys, and\n * it manages the wallet \"lock\" state. This wrapper class has convenience methods for interacting\n * with the internal keyring controller and handling certain complex operations that involve the\n * keyrings.\n */\nexport class KeyringController<\n EncryptionKey = encryptorUtils.EncryptionKey | CryptoKey,\n SupportedKeyDerivationOptions = encryptorUtils.KeyDerivationOptions,\n> extends BaseController<\n typeof name,\n KeyringControllerState,\n KeyringControllerMessenger\n> {\n readonly #controllerOperationMutex = new Mutex();\n\n readonly #vaultOperationMutex = new Mutex();\n\n readonly #keyringBuilders: { (): EthKeyring; type: string }[];\n\n readonly #encryptor: Encryptor<EncryptionKey, SupportedKeyDerivationOptions>;\n\n #keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n\n #unsupportedKeyrings: SerializedKeyring[];\n\n #encryptionKey?: CachedEncryptionKey;\n\n /**\n * Creates a KeyringController instance.\n *\n * @param options - Initial options used to configure this controller\n * @param options.encryptor - An optional object for defining encryption schemes.\n * @param options.keyringBuilders - Set a new name for account.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor(\n options: KeyringControllerOptions<\n EncryptionKey,\n SupportedKeyDerivationOptions\n >,\n ) {\n const { encryptor, keyringBuilders, messenger, state } = options;\n\n super({\n name,\n metadata: {\n vault: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n isUnlocked: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n keyrings: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n encryptionKey: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n encryptionSalt: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n },\n messenger,\n state: {\n ...getDefaultKeyringState(),\n ...state,\n },\n });\n\n this.#keyringBuilders = keyringBuilders\n ? keyringBuilders.concat(defaultKeyringBuilders)\n : defaultKeyringBuilders;\n\n this.#encryptor = encryptor;\n this.#keyrings = [];\n this.#unsupportedKeyrings = [];\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Adds a new account to the default (first) HD seed phrase keyring.\n *\n * @param accountCount - Number of accounts before adding a new one, used to\n * make the method idempotent.\n * @returns Promise resolving to the added account address.\n */\n async addNewAccount(accountCount?: number): Promise<string> {\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n const oldAccounts = await primaryKeyring.getAccounts();\n\n if (accountCount && oldAccounts.length !== accountCount) {\n if (accountCount > oldAccounts.length) {\n throw new Error('Account out of sequence');\n }\n // we return the account already existing at index `accountCount`\n const existingAccount = oldAccounts[accountCount];\n\n if (!existingAccount) {\n throw new Error(`Can't find account at index ${accountCount}`);\n }\n\n return existingAccount;\n }\n\n const [addedAccountAddress] = await primaryKeyring.addAccounts(1);\n await this.#verifySeedPhrase();\n\n return addedAccountAddress;\n });\n }\n\n /**\n * Adds a new account to the specified keyring.\n *\n * @param keyring - Keyring to add the account to.\n * @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.\n * @returns Promise resolving to the added account address\n */\n async addNewAccountForKeyring(\n keyring: EthKeyring,\n accountCount?: number,\n ): Promise<Hex> {\n // READ THIS CAREFULLY:\n // We still uses `Hex` here, since we are not using this method when creating\n // and account using a \"Snap Keyring\". This function assume the `keyring` is\n // ethereum compatible, but \"Snap Keyring\" might not be.\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n const oldAccounts = await this.#getAccountsFromKeyrings();\n\n if (accountCount && oldAccounts.length !== accountCount) {\n if (accountCount > oldAccounts.length) {\n throw new Error('Account out of sequence');\n }\n\n const existingAccount = oldAccounts[accountCount];\n assertIsStrictHexString(existingAccount);\n\n return existingAccount;\n }\n\n await keyring.addAccounts(1);\n\n const addedAccountAddress = (await this.#getAccountsFromKeyrings()).find(\n (selectedAddress) => !oldAccounts.includes(selectedAddress),\n );\n assertIsStrictHexString(addedAccountAddress);\n\n return addedAccountAddress;\n });\n }\n\n /**\n * Effectively the same as creating a new keychain then populating it\n * using the given seed phrase.\n *\n * @param password - Password to unlock keychain.\n * @param seed - A BIP39-compliant seed phrase as Uint8Array,\n * either as a string or an array of UTF-8 bytes that represent the string.\n * @returns Promise resolving when the operation ends successfully.\n */\n async createNewVaultAndRestore(\n password: string,\n seed: Uint8Array,\n ): Promise<void> {\n return this.#persistOrRollback(async () => {\n assertIsValidPassword(password);\n\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n opts: {\n mnemonic: seed,\n numberOfAccounts: 1,\n },\n });\n });\n }\n\n /**\n * Create a new vault and primary keyring.\n *\n * This only works if keyrings are empty. If there is a pre-existing unlocked vault, calling this will have no effect.\n * If there is a pre-existing locked vault, it will be replaced.\n *\n * @param password - Password to unlock the new vault.\n * @returns Promise resolving when the operation ends successfully.\n */\n async createNewVaultAndKeychain(password: string) {\n return this.#persistOrRollback(async () => {\n const accounts = await this.#getAccountsFromKeyrings();\n if (!accounts.length) {\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n });\n }\n });\n }\n\n /**\n * Adds a new keyring of the given `type`.\n *\n * @param type - Keyring type name.\n * @param opts - Keyring options.\n * @throws If a builder for the given `type` does not exist.\n * @returns Promise resolving to the new keyring metadata.\n */\n async addNewKeyring(\n type: KeyringTypes | string,\n opts?: unknown,\n ): Promise<KeyringMetadata> {\n this.#assertIsUnlocked();\n\n return this.#getKeyringMetadata(\n await this.#persistOrRollback(async () => this.#newKeyring(type, opts)),\n );\n }\n\n /**\n * Method to verify a given password validity. Throws an\n * error if the password is invalid.\n *\n * @param password - Password of the keyring.\n */\n async verifyPassword(password: string) {\n if (!this.state.vault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n await this.#encryptor.decrypt(password, this.state.vault);\n }\n\n /**\n * Returns the status of the vault.\n *\n * @returns Boolean returning true if the vault is unlocked.\n */\n isUnlocked(): boolean {\n return this.state.isUnlocked;\n }\n\n /**\n * Gets the seed phrase of the HD keyring.\n *\n * @param password - Password of the keyring.\n * @param keyringId - The id of the keyring.\n * @returns Promise resolving to the seed phrase.\n */\n async exportSeedPhrase(\n password: string,\n keyringId?: string,\n ): Promise<Uint8Array> {\n this.#assertIsUnlocked();\n await this.verifyPassword(password);\n const selectedKeyring = this.#getKeyringByIdOrDefault(keyringId);\n if (!selectedKeyring) {\n throw new Error('Keyring not found');\n }\n assertHasUint8ArrayMnemonic(selectedKeyring);\n\n return selectedKeyring.mnemonic;\n }\n\n /**\n * Gets the private key from the keyring controlling an address.\n *\n * @param password - Password of the keyring.\n * @param address - Address to export.\n * @returns Promise resolving to the private key for an address.\n */\n async exportAccount(password: string, address: string): Promise<string> {\n await this.verifyPassword(password);\n\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.exportAccount) {\n throw new Error(KeyringControllerError.UnsupportedExportAccount);\n }\n\n return await keyring.exportAccount(normalize(address) as Hex);\n }\n\n /**\n * Returns the public addresses of all accounts from every keyring.\n *\n * @returns A promise resolving to an array of addresses.\n */\n async getAccounts(): Promise<string[]> {\n this.#assertIsUnlocked();\n return this.state.keyrings.reduce<string[]>(\n (accounts, keyring) => accounts.concat(keyring.accounts),\n [],\n );\n }\n\n /**\n * Get encryption public key.\n *\n * @param account - An account address.\n * @param opts - Additional encryption options.\n * @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method\n * @returns Promise resolving to encyption public key of the `account` if one exists.\n */\n async getEncryptionPublicKey(\n account: string,\n opts?: Record<string, unknown>,\n ): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(account) as Hex;\n const keyring = (await this.getKeyringForAccount(account)) as EthKeyring;\n if (!keyring.getEncryptionPublicKey) {\n throw new Error(KeyringControllerError.UnsupportedGetEncryptionPublicKey);\n }\n\n return await keyring.getEncryptionPublicKey(address, opts);\n }\n\n /**\n * Attempts to decrypt the provided message parameters.\n *\n * @param messageParams - The decryption message parameters.\n * @param messageParams.from - The address of the account you want to use to decrypt the message.\n * @param messageParams.data - The encrypted data that you want to decrypt.\n * @returns The raw decryption result.\n */\n async decryptMessage(messageParams: {\n from: string;\n data: Eip1024EncryptedData;\n }): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.decryptMessage) {\n throw new Error(KeyringControllerError.UnsupportedDecryptMessage);\n }\n\n return keyring.decryptMessage(address, messageParams.data);\n }\n\n /**\n * Returns the currently initialized keyring that manages\n * the specified `address` if one exists.\n *\n * @deprecated Use of this method is discouraged as actions executed directly on\n * keyrings are not being reflected in the KeyringController state and not\n * persisted in the vault. Use `withKeyring` instead.\n * @param account - An account address.\n * @returns Promise resolving to keyring of the `account` if one exists.\n */\n async getKeyringForAccount(account: string): Promise<unknown> {\n this.#assertIsUnlocked();\n const address = normalize(account);\n\n const candidates = await Promise.all(\n this.#keyrings.map(async ({ keyring }) => {\n return Promise.all([keyring, keyring.getAccounts()]);\n }),\n );\n\n const winners = candidates.filter((candidate) => {\n const accounts = candidate[1].map(normalize);\n return accounts.includes(address);\n });\n\n if (winners.length && winners[0]?.length) {\n return winners[0][0];\n }\n\n // Adding more info to the error\n let errorInfo = '';\n if (!candidates.length) {\n errorInfo = 'There are no keyrings';\n } else if (!winners.length) {\n errorInfo = 'There are keyrings, but none match the address';\n }\n throw new Error(\n `${KeyringControllerError.NoKeyring}. Error info: ${errorInfo}`,\n );\n }\n\n /**\n * Returns all keyrings of the given type.\n *\n * @deprecated Use of this method is discouraged as actions executed directly on\n * keyrings are not being reflected in the KeyringController state and not\n * persisted in the vault. Use `withKeyring` instead.\n * @param type - Keyring type name.\n * @returns An array of keyrings of the given type.\n */\n getKeyringsByType(type: KeyringTypes | string): unknown[] {\n this.#assertIsUnlocked();\n return this.#keyrings\n .filter(({ keyring }) => keyring.type === type)\n .map(({ keyring }) => keyring);\n }\n\n /**\n * Persist all serialized keyrings in the vault.\n *\n * @deprecated This method is being phased out in favor of `withKeyring`.\n * @returns Promise resolving with `true` value when the\n * operation completes.\n */\n async persistAllKeyrings(): Promise<boolean> {\n return this.#withRollback(async () => {\n this.#assertIsUnlocked();\n\n await this.#updateVault();\n return true;\n });\n }\n\n /**\n * Imports an account with the specified import strategy.\n *\n * @param strategy - Import strategy name.\n * @param args - Array of arguments to pass to the underlying stategy.\n * @throws Will throw when passed an unrecognized strategy.\n * @returns Promise resolving to the imported account address.\n */\n async importAccountWithStrategy(\n strategy: AccountImportStrategy,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[],\n ): Promise<string> {\n this.#assertIsUnlocked();\n return this.#persistOrRollback(async () => {\n let privateKey;\n switch (strategy) {\n case AccountImportStrategy.privateKey:\n const [importedKey] = args;\n if (!importedKey) {\n throw new Error('Cannot import an empty key.');\n }\n const prefixed = add0x(importedKey);\n\n let bufferedPrivateKey;\n try {\n bufferedPrivateKey = hexToBytes(prefixed);\n } catch {\n throw new Error('Cannot import invalid private key.');\n }\n\n if (\n !isValidPrivate(bufferedPrivateKey) ||\n // ensures that the key is 64 bytes long\n getBinarySize(prefixed) !== 64 + '0x'.length\n ) {\n throw new Error('Cannot import invalid private key.');\n }\n\n privateKey = remove0x(prefixed);\n break;\n case AccountImportStrategy.json:\n let wallet;\n const [input, password] = args;\n try {\n wallet = importers.fromEtherWallet(input, password);\n } catch (e) {\n wallet = wallet || (await Wallet.fromV3(input, password, true));\n }\n privateKey = bytesToHex(wallet.getPrivateKey());\n break;\n default:\n throw new Error(`Unexpected import strategy: '${String(strategy)}'`);\n }\n const newKeyring = (await this.#newKeyring(KeyringTypes.simple, [\n privateKey,\n ])) as EthKeyring;\n const accounts = await newKeyring.getAccounts();\n return accounts[0];\n });\n }\n\n /**\n * Removes an account from keyring state.\n *\n * @param address - Address of the account to remove.\n * @fires KeyringController:accountRemoved\n * @returns Promise resolving when the account is removed.\n */\n async removeAccount(address: string): Promise<void> {\n this.#assertIsUnlocked();\n\n await this.#persistOrRollback(async () => {\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n const keyringIndex = this.state.keyrings.findIndex((kr) =>\n kr.accounts.includes(address),\n );\n\n const isPrimaryKeyring = keyringIndex === 0;\n const shouldRemoveKeyring = (await keyring.getAccounts()).length === 1;\n\n // Primary keyring should never be removed, so we need to keep at least one account in it\n if (isPrimaryKeyring && shouldRemoveKeyring) {\n throw new Error(KeyringControllerError.LastAccountInPrimaryKeyring);\n }\n\n // Not all the keyrings support this, so we have to check\n if (!keyring.removeAccount) {\n throw new Error(KeyringControllerError.UnsupportedRemoveAccount);\n }\n\n // The `removeAccount` method of snaps keyring is async. We have to update\n // the interface of the other keyrings to be async as well.\n // FIXME: We do cast to `Hex` to makes the type checker happy here, and\n // because `Keyring<State>.removeAccount` requires address to be `Hex`. Those\n // type would need to be updated for a full non-EVM support.\n keyring.removeAccount(address as Hex);\n\n if (shouldRemoveKeyring) {\n await this.#removeEmptyKeyrings();\n }\n });\n\n this.messenger.publish(`${name}:accountRemoved`, address);\n }\n\n /**\n * Deallocates all secrets and locks the wallet.\n *\n * @returns Promise resolving when the operation completes.\n */\n async setLocked(): Promise<void> {\n this.#assertIsUnlocked();\n\n return this.#withRollback(async () => {\n this.#encryptionKey = undefined;\n await this.#clearKeyrings();\n\n this.update((state) => {\n state.isUnlocked = false;\n state.keyrings = [];\n delete state.encryptionKey;\n delete state.encryptionSalt;\n });\n\n this.messenger.publish(`${name}:lock`);\n });\n }\n\n /**\n * Signs message by calling down into a specific keyring.\n *\n * @param messageParams - PersonalMessageParams object to sign.\n * @returns Promise resolving to a signed message string.\n */\n async signMessage(messageParams: PersonalMessageParams): Promise<string> {\n this.#assertIsUnlocked();\n\n if (!messageParams.data) {\n throw new Error(\"Can't sign an empty message\");\n }\n\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signMessage) {\n throw new Error(KeyringControllerError.UnsupportedSignMessage);\n }\n\n return await keyring.signMessage(address, messageParams.data);\n }\n\n /**\n * Signs EIP-7702 Authorization message by calling down into a specific keyring.\n *\n * @param params - EIP7702AuthorizationParams object to sign.\n * @returns Promise resolving to an EIP-7702 Authorization signature.\n * @throws Will throw UnsupportedSignEIP7702Authorization if the keyring does not support signing EIP-7702 Authorization messages.\n */\n async signEip7702Authorization(\n params: Eip7702AuthorizationParams,\n ): Promise<string> {\n const from = ethNormalize(params.from) as Hex;\n\n const keyring = (await this.getKeyringForAccount(from)) as EthKeyring;\n\n if (!keyring.signEip7702Authorization) {\n throw new Error(\n KeyringControllerError.UnsupportedSignEip7702Authorization,\n );\n }\n\n const { chainId, nonce } = params;\n const contractAddress = ethNormalize(params.contractAddress) as\n | Hex\n | undefined;\n\n if (contractAddress === undefined) {\n throw new Error(\n KeyringControllerError.MissingEip7702AuthorizationContractAddress,\n );\n }\n\n return await keyring.signEip7702Authorization(from, [\n chainId,\n contractAddress,\n nonce,\n ]);\n }\n\n /**\n * Signs personal message by calling down into a specific keyring.\n *\n * @param messageParams - PersonalMessageParams object to sign.\n * @returns Promise resolving to a signed message string.\n */\n async signPersonalMessage(messageParams: PersonalMessageParams) {\n this.#assertIsUnlocked();\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signPersonalMessage) {\n throw new Error(KeyringControllerError.UnsupportedSignPersonalMessage);\n }\n\n const normalizedData = normalize(messageParams.data) as Hex;\n\n return await keyring.signPersonalMessage(address, normalizedData);\n }\n\n /**\n * Signs typed message by calling down into a specific keyring.\n *\n * @param messageParams - TypedMessageParams object to sign.\n * @param version - Compatibility version EIP712.\n * @throws Will throw when passed an unrecognized version.\n * @returns Promise resolving to a signed message string or an error if any.\n */\n async signTypedMessage(\n messageParams: TypedMessageParams,\n version: SignTypedDataVersion,\n ): Promise<string> {\n this.#assertIsUnlocked();\n\n try {\n if (\n ![\n SignTypedDataVersion.V1,\n SignTypedDataVersion.V3,\n SignTypedDataVersion.V4,\n ].includes(version)\n ) {\n throw new Error(`Unexpected signTypedMessage version: '${version}'`);\n }\n\n // Cast to `Hex` here is safe here because `messageParams.from` is not nullish.\n // `normalize` returns `Hex` unless given a nullish value.\n const address = ethNormalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signTypedData) {\n throw new Error(KeyringControllerError.UnsupportedSignTypedMessage);\n }\n\n return await keyring.signTypedData(\n address,\n version !== SignTypedDataVersion.V1 &&\n typeof messageParams.data === 'string'\n ? JSON.parse(messageParams.data)\n : messageParams.data,\n { version },\n );\n } catch (error) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n throw new Error(`Keyring Controller signTypedMessage: ${error}`);\n }\n }\n\n /**\n * Signs a transaction by calling down into a specific keyring.\n *\n * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance.\n * @param from - Address to sign from, should be in keychain.\n * @param opts - An optional options object.\n * @returns Promise resolving to a signed transaction string.\n */\n async signTransaction(\n transaction: TypedTransaction,\n from: string,\n opts?: Record<string, unknown>,\n ): Promise<TypedTxData> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n if (!keyring.signTransaction) {\n throw new Error(KeyringControllerError.UnsupportedSignTransaction);\n }\n\n return await keyring.signTransaction(address, transaction, opts);\n }\n\n /**\n * Convert a base transaction to a base UserOperation.\n *\n * @param from - Address of the sender.\n * @param transactions - Base transactions to include in the UserOperation.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns A pseudo-UserOperation that can be used to construct a real.\n */\n async prepareUserOperation(\n from: string,\n transactions: EthBaseTransaction[],\n executionContext: KeyringExecutionContext,\n ): Promise<EthBaseUserOperation> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.prepareUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPrepareUserOperation);\n }\n\n return await keyring.prepareUserOperation(\n address,\n transactions,\n executionContext,\n );\n }\n\n /**\n * Patches properties of a UserOperation. Currently, only the\n * `paymasterAndData` can be patched.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to patch.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns A patch to apply to the UserOperation.\n */\n async patchUserOperation(\n from: string,\n userOp: EthUserOperation,\n executionContext: KeyringExecutionContext,\n ): Promise<EthUserOperationPatch> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.patchUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPatchUserOperation);\n }\n\n return await keyring.patchUserOperation(address, userOp, executionContext);\n }\n\n /**\n * Signs an UserOperation.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @param executionContext - The execution context to use for the UserOperation.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n from: string,\n userOp: EthUserOperation,\n executionContext: KeyringExecutionContext,\n ): Promise<string> {\n this.#assertIsUnlocked();\n const address = ethNormalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(address)) as EthKeyring;\n\n if (!keyring.signUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedSignUserOperation);\n }\n\n return await keyring.signUserOperation(address, userOp, executionContext);\n }\n\n /**\n * Changes the password used to encrypt the vault.\n *\n * @param password - The new password.\n * @returns Promise resolving when the operation completes.\n */\n changePassword(password: string): Promise<void> {\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n assertIsValidPassword(password);\n await this.#deriveEncryptionKey(password);\n });\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings, using the\n * given encryption key and salt. The optional salt can be used to check for\n * consistency with the vault salt.\n *\n * @param encryptionKey - Key to unlock the keychain.\n * @param keyDerivationSalt - Optional salt to unlock the keychain.\n * @returns Promise resolving when the operation completes.\n */\n async submitEncryptionKey(\n encryptionKey: string,\n keyDerivationSalt?: string,\n ): Promise<void> {\n const { newMetadata } = await this.#withRollback(async () => {\n const result = await this.#unlockKeyrings({\n encryptionKey,\n keyDerivationSalt,\n });\n this.#setUnlocked();\n return result;\n });\n\n try {\n // if new metadata has been generated during login, we\n // can attempt to upgrade the vault.\n await this.#withRollback(async () => {\n if (newMetadata) {\n await this.#updateVault();\n }\n });\n } catch (error) {\n // We don't want to throw an error if the upgrade fails\n // since the controller is already unlocked.\n console.error('Failed to update vault during login:', error);\n }\n }\n\n /**\n * Exports the vault encryption key.\n *\n * @returns The vault encryption key.\n */\n async exportEncryptionKey(): Promise<string> {\n this.#assertIsUnlocked();\n\n return await this.#withControllerLock(async () => {\n assertIsEncryptionKeySet(this.#encryptionKey?.serialized);\n return this.#encryptionKey.serialized;\n });\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings,\n * using the given password.\n *\n * @param password - Password to unlock the keychain.\n * @returns Promise resolving when the operation completes.\n */\n async submitPassword(password: string): Promise<void> {\n const { newMetadata } = await this.#withRollback(async () => {\n const result = await this.#unlockKeyrings({ password });\n this.#setUnlocked();\n return result;\n });\n\n try {\n // If there are stronger encryption params available, or\n // if new metadata has been generated during login, we\n // can attempt to upgrade the vault.\n await this.#withRollback(async () => {\n if (newMetadata || this.#isNewEncryptionAvailable()) {\n await this.#deriveEncryptionKey(password, {\n // If the vault is being upgraded, we want to ignore the metadata\n // that is already in the vault, so we can effectively\n // re-encrypt the vault with the new encryption config.\n useVaultKeyMetadata: false,\n });\n await this.#updateVault();\n }\n });\n } catch (error) {\n // We don't want to throw an error if the upgrade fails\n // since the controller is already unlocked.\n console.error('Failed to update vault during login:', error);\n }\n }\n\n /**\n * Verifies the that the seed phrase restores the current keychain's accounts.\n *\n * @param keyringId - The id of the keyring to verify.\n * @returns Promise resolving to the seed phrase as Uint8Array.\n */\n async verifySeedPhrase(keyringId?: string): Promise<Uint8Array> {\n this.#assertIsUnlocked();\n\n return this.#withControllerLock(async () =>\n this.#verifySeedPhrase(keyringId),\n );\n }\n\n /**\n * Select a keyring and execute the given operation with\n * the selected keyring, as a mutually exclusive atomic\n * operation.\n *\n * The method automatically persists changes at the end of the\n * function execution, or rolls back the changes if an error\n * is thrown.\n *\n * @param selector - Keyring selector object.\n * @param operation - Function to execute with the selected keyring.\n * @param options - Additional options.\n * @param options.createIfMissing - Whether to create a new keyring if the selected one is missing.\n * @param options.createWithData - Optional data to use when creating a new keyring.\n * @returns Promise resolving to the result of the function execution.\n * @template SelectedKeyring - The type of the selected keyring.\n * @template CallbackResult - The type of the value resolved by the callback function.\n * @deprecated This method overload is deprecated. Use `withKeyring` without options instead.\n */\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n options:\n | { createIfMissing?: false }\n | { createIfMissing: true; createWithData?: unknown },\n ): Promise<CallbackResult>;\n\n /**\n * Select a keyring and execute the given operation with\n * the selected keyring, as a mutually exclusive atomic\n * operation.\n *\n * The method automatically persists changes at the end of the\n * function execution, or rolls back the changes if an error\n * is thrown.\n *\n * @param selector - Keyring selector object.\n * @param operation - Function to execute with the selected keyring.\n * @returns Promise resolving to the result of the function execution.\n * @template SelectedKeyring - The type of the selected keyring.\n * @template CallbackResult - The type of the value resolved by the callback function.\n */\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult>;\n\n async withKeyring<\n SelectedKeyring extends EthKeyring = EthKeyring,\n CallbackResult = void,\n >(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n options:\n | { createIfMissing?: false }\n | { createIfMissing: true; createWithData?: unknown } = {\n createIfMissing: false,\n },\n ): Promise<CallbackResult> {\n this.#assertIsUnlocked();\n\n return this.#persistOrRollback(async () => {\n let keyring: SelectedKeyring | undefined;\n\n if ('address' in selector) {\n keyring = (await this.getKeyringForAccount(selector.address)) as\n | SelectedKeyring\n | undefined;\n } else if ('type' in selector) {\n keyring = this.getKeyringsByType(selector.type)[selector.index || 0] as\n | SelectedKeyring\n | undefined;\n\n if (!keyring && options.createIfMissing) {\n keyring = (await this.#newKeyring(\n selector.type,\n options.createWithData,\n )) as SelectedKeyring;\n }\n } else if ('id' in selector) {\n keyring = this.#getKeyringById(selector.id) as SelectedKeyring;\n }\n\n if (!keyring) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n\n const result = await operation({\n keyring,\n metadata: this.#getKeyringMetadata(keyring),\n });\n\n if (Object.is(result, keyring)) {\n // Access to a keyring instance outside of controller safeguards\n // should be discouraged, as it can lead to unexpected behavior.\n // This error is thrown to prevent consumers using `withKeyring`\n // as a way to get a reference to a keyring instance.\n throw new Error(KeyringControllerError.UnsafeDirectKeyringAccess);\n }\n\n return result;\n });\n }\n\n async getAccountKeyringType(account: string): Promise<string> {\n this.#assertIsUnlocked();\n\n const keyring = (await this.getKeyringForAccount(account)) as EthKeyring;\n return keyring.type;\n }\n\n /**\n * Constructor helper for registering this controller's messeger\n * actions.\n */\n #registerMessageHandlers() {\n this.messenger.registerActionHandler(\n `${name}:signMessage`,\n this.signMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signEip7702Authorization`,\n this.signEip7702Authorization.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signPersonalMessage`,\n this.signPersonalMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signTypedMessage`,\n this.signTypedMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:decryptMessage`,\n this.decryptMessage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getEncryptionPublicKey`,\n this.getEncryptionPublicKey.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getAccounts`,\n this.getAccounts.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getKeyringsByType`,\n this.getKeyringsByType.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:getKeyringForAccount`,\n this.getKeyringForAccount.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:persistAllKeyrings`,\n this.persistAllKeyrings.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:prepareUserOperation`,\n this.prepareUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:patchUserOperation`,\n this.patchUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:signUserOperation`,\n this.signUserOperation.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:addNewAccount`,\n this.addNewAccount.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:withKeyring`,\n this.withKeyring.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:addNewKeyring`,\n this.addNewKeyring.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:createNewVaultAndKeychain`,\n this.createNewVaultAndKeychain.bind(this),\n );\n\n this.messenger.registerActionHandler(\n `${name}:createNewVaultAndRestore`,\n this.createNewVaultAndRestore.bind(this),\n );\n }\n\n /**\n * Get the keyring by id.\n *\n * @param keyringId - The id of the keyring.\n * @returns The keyring.\n */\n #getKeyringById(keyringId: string): EthKeyring | undefined {\n return this.#keyrings.find(({ metadata }) => metadata.id === keyringId)\n ?.keyring;\n }\n\n /**\n * Get the keyring by id or return the first keyring if the id is not found.\n *\n * @param keyringId - The id of the keyring.\n * @returns The keyring.\n */\n #getKeyringByIdOrDefault(keyringId?: string): EthKeyring | undefined {\n if (!keyringId) {\n return this.#keyrings[0]?.keyring;\n }\n\n return this.#getKeyringById(keyringId);\n }\n\n /**\n * Get the metadata for the specified keyring.\n *\n * @param keyring - The keyring instance to get the metadata for.\n * @returns The keyring metadata.\n */\n #getKeyringMetadata(keyring: unknown): KeyringMetadata {\n const keyringWithMetadata = this.#keyrings.find(\n (candidate) => candidate.keyring === keyring,\n );\n if (!keyringWithMetadata) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n return keyringWithMetadata.metadata;\n }\n\n /**\n * Get the keyring builder for the given `type`.\n *\n * @param type - The type of keyring to get the builder for.\n * @returns The keyring builder, or undefined if none exists.\n */\n #getKeyringBuilderForType(\n type: string,\n ): { (): EthKeyring; type: string } | undefined {\n return this.#keyringBuilders.find(\n (keyringBuilder) => keyringBuilder.type === type,\n );\n }\n\n /**\n * Create new vault with an initial keyring\n *\n * Destroys any old encrypted storage,\n * creates a new encrypted store with the given password,\n * creates a new wallet with 1 account.\n *\n * @fires KeyringController:unlock\n * @param password - The password to encrypt the vault with.\n * @param keyring - A object containing the params to instantiate a new keyring.\n * @param keyring.type - The keyring type.\n * @param keyring.opts - Optional parameters required to instantiate the keyring.\n * @returns A promise that resolves to the state.\n */\n async #createNewVaultWithKeyring(\n password: string,\n keyring: {\n type: string;\n opts?: unknown;\n },\n ): Promise<void> {\n this.#assertControllerMutexIsLocked();\n\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n\n this.update((state) => {\n delete state.encryptionKey;\n delete state.encryptionSalt;\n });\n\n await this.#deriveEncryptionKey(password);\n\n await this.#clearKeyrings();\n await this.#createKeyringWithFirstAccount(keyring.type, keyring.opts);\n this.#setUnlocked();\n }\n\n /**\n * Derive the vault encryption key from the provided password, and\n * assign it to the instance variable for later use with cryptographic\n * functions.\n *\n * When the controller has a vault in its state, the key is derived\n * using the salt from the vault. If the vault is empty, a new salt\n * is generated and used to derive the key.\n *\n * @param password - The password to use for decryption or derivation.\n * @param options - Options for the key derivation.\n * @param options.useVaultKeyMetadata - Whether to use the vault key metadata\n */\n async #deriveEncryptionKey(\n password: string,\n options: { useVaultKeyMetadata: boolean } = {\n useVaultKeyMetadata: true,\n },\n ): Promise<void> {\n this.#assertControllerMutexIsLocked();\n const { vault } = this.state;\n\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n\n let salt: string, keyMetadata: SupportedKeyDerivationOptions | undefined;\n if (vault && options.useVaultKeyMetadata) {\n const parsedVault = JSON.parse(vault);\n salt = parsedVault.salt;\n keyMetadata = parsedVault.keyMetadata;\n } else {\n salt = this.#encryptor.generateSalt();\n }\n\n const serializedEncryptionKey = await this.#encryptor.exportKey(\n await this.#encryptor.keyFromPassword(password, salt, true, keyMetadata),\n );\n\n this.#encryptionKey = {\n salt,\n serialized: serializedEncryptionKey,\n };\n }\n\n /**\n * Set the the `#encryptionKey` instance variable.\n * This method is used when the user provides an encryption key and salt\n * to unlock the keychain, instead of using a password.\n *\n * @param encryptionKey - The encryption key to use.\n * @param keyDerivationSalt - The salt to use for the encryption key.\n */\n #setEncryptionKey(encryptionKey: string, keyDerivationSalt: string): void {\n this.#assertControllerMutexIsLocked();\n\n if (\n typeof encryptionKey !== 'string' ||\n typeof keyDerivationSalt !== 'string'\n ) {\n throw new TypeError(KeyringControllerError.WrongEncryptionKeyType);\n }\n\n const { vault } = this.state;\n if (vault && JSON.parse(vault).salt !== keyDerivationSalt) {\n throw new Error(KeyringControllerError.ExpiredCredentials);\n }\n\n this.#encryptionKey = {\n salt: keyDerivationSalt,\n serialized: encryptionKey,\n };\n }\n\n /**\n * Internal non-exclusive method to verify the seed phrase.\n *\n * @param keyringId - The id of the keyring to verify the seed phrase for.\n * @returns A promise resolving to the seed phrase as Uint8Array.\n */\n async #verifySeedPhrase(keyringId?: string): Promise<Uint8Array> {\n this.#assertControllerMutexIsLocked();\n\n const keyring = this.#getKeyringByIdOrDefault(keyringId);\n\n if (!keyring) {\n throw new Error(KeyringControllerError.KeyringNotFound);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (keyring.type !== KeyringTypes.hd) {\n throw new Error(KeyringControllerError.UnsupportedVerifySeedPhrase);\n }\n\n assertHasUint8ArrayMnemonic(keyring);\n\n const seedWords = keyring.mnemonic;\n const accounts = await keyring.getAccounts();\n /* istanbul ignore if */\n if (accounts.length === 0) {\n throw new Error('Cannot verify an empty keyring.');\n }\n\n // The HD Keyring Builder is a default keyring builder\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const hdKeyringBuilder = this.#getKeyringBuilderForType(KeyringTypes.hd)!;\n\n const hdKeyring = hdKeyringBuilder();\n // @ts-expect-error @metamask/eth-hd-keyring correctly handles\n // Uint8Array seed phrases in the `deserialize` method.\n await hdKeyring.deserialize({\n mnemonic: seedWords,\n numberOfAccounts: accounts.length,\n });\n const testAccounts = await hdKeyring.getAccounts();\n /* istanbul ignore if */\n if (testAccounts.length !== accounts.length) {\n throw new Error('Seed phrase imported incorrect number of accounts.');\n }\n\n testAccounts.forEach((account: string, i: number) => {\n /* istanbul ignore if */\n if (account.toLowerCase() !== accounts[i].toLowerCase()) {\n throw new Error('Seed phrase imported different accounts.');\n }\n });\n\n return seedWords;\n }\n\n /**\n * Get the updated array of each keyring's type and\n * accounts list.\n *\n * @returns A promise resolving to the updated keyrings array.\n */\n async #getUpdatedKeyrings(): Promise<KeyringObject[]> {\n return Promise.all(this.#keyrings.map(displayForKeyring));\n }\n\n /**\n * Serialize the current array of keyring instances,\n * including unsupported keyrings by default.\n *\n * @param options - Method options.\n * @param options.includeUnsupported - Whether to include unsupported keyrings.\n * @returns The serialized keyrings.\n */\n async #getSerializedKeyrings(\n { includeUnsupported }: { includeUnsupported: boolean } = {\n includeUnsupported: true,\n },\n ): Promise<SerializedKeyring[]> {\n const serializedKeyrings: SerializedKeyring[] = await Promise.all(\n this.#keyrings.map(async ({ keyring, metadata }) => {\n return {\n type: keyring.type,\n data: await keyring.serialize(),\n metadata,\n };\n }),\n );\n\n if (includeUnsupported) {\n serializedKeyrings.push(...this.#unsupportedKeyrings);\n }\n\n return serializedKeyrings;\n }\n\n /**\n * Get a snapshot of session data held by instance variables.\n *\n * @returns An object with serialized keyrings, keyrings metadata,\n * and the user password.\n */\n async #getSessionState(): Promise<SessionState> {\n return {\n keyrings: await this.#getSerializedKeyrings(),\n encryptionKey: this.#encryptionKey,\n };\n }\n\n /**\n * Restore a serialized keyrings array.\n *\n * @param serializedKeyrings - The serialized keyrings array.\n * @returns The restored keyrings.\n */\n async #restoreSerializedKeyrings(\n serializedKeyrings: SerializedKeyring[],\n ): Promise<{\n keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n newMetadata: boolean;\n }> {\n await this.#clearKeyrings();\n const keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[] = [];\n let newMetadata = false;\n\n for (const serializedKeyring of serializedKeyrings) {\n const result = await this.#restoreKeyring(serializedKeyring);\n if (result) {\n const { keyring, metadata } = result;\n keyrings.push({ keyring, metadata });\n if (result.newMetadata) {\n newMetadata = true;\n }\n }\n }\n\n return { keyrings, newMetadata };\n }\n\n /**\n * Unlock Keyrings, decrypting the vault and deserializing all\n * keyrings contained in it, using a password or an encryption key with salt.\n *\n * @param credentials - The credentials to unlock the keyrings.\n * @returns A promise resolving to the deserialized keyrings array.\n */\n async #unlockKeyrings(\n credentials:\n | {\n password: string;\n }\n | {\n encryptionKey: string;\n keyDerivationSalt?: string;\n },\n ): Promise<{\n keyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[];\n newMetadata: boolean;\n }> {\n return this.#withVaultLock(async () => {\n if (!this.state.vault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n const parsedEncryptedVault = JSON.parse(this.state.vault);\n\n if ('password' in credentials) {\n await this.#deriveEncryptionKey(credentials.password);\n } else {\n this.#setEncryptionKey(\n credentials.encryptionKey,\n credentials.keyDerivationSalt || parsedEncryptedVault.salt,\n );\n }\n\n const encryptionKey = this.#encryptionKey?.serialized;\n if (!encryptionKey) {\n throw new Error(KeyringControllerError.MissingCredentials);\n }\n\n const key = await this.#encryptor.importKey(encryptionKey);\n const vault = await this.#encryptor.decryptWithKey(\n key,\n parsedEncryptedVault,\n );\n\n if (!isSerializedKeyringsArray(vault)) {\n throw new Error(KeyringControllerError.VaultDataError);\n }\n\n const { keyrings, newMetadata } =\n await this.#restoreSerializedKeyrings(vault);\n\n const updatedKeyrings = await this.#getUpdatedKeyrings();\n\n this.update((state) => {\n state.keyrings = updatedKeyrings;\n state.encryptionKey = encryptionKey;\n state.encryptionSalt = parsedEncryptedVault.salt;\n });\n\n return { keyrings, newMetadata };\n });\n }\n\n /**\n * Update the vault with the current keyrings.\n *\n * @returns A promise resolving to `true` if the operation is successful.\n */\n #updateVault(): Promise<boolean> {\n return this.#withVaultLock(async () => {\n // Ensure no duplicate accounts are persisted.\n await this.#assertNoDuplicateAccounts();\n\n if (!this.#encryptionKey) {\n throw new Error(KeyringControllerError.MissingCredentials);\n }\n\n const serializedKeyrings = await this.#getSerializedKeyrings();\n\n if (\n !serializedKeyrings.some(\n (keyring) => keyring.type === (KeyringTypes.hd as string),\n )\n ) {\n throw new Error(KeyringControllerError.NoHdKeyring);\n }\n\n const key = await this.#encryptor.importKey(\n this.#encryptionKey.serialized,\n );\n const encryptedVault = await this.#encryptor.encryptWithKey(\n key,\n serializedKeyrings,\n );\n // We need to include the salt used to derive\n // the encryption key, to be able to derive it\n // from password again.\n encryptedVault.salt = this.#encryptionKey.salt;\n const updatedState: Partial<KeyringControllerState> = {\n vault: JSON.stringify(encryptedVault),\n encryptionKey: this.#encryptionKey.serialized,\n encryptionSalt: this.#encryptionKey.salt,\n };\n\n const updatedKeyrings = await this.#getUpdatedKeyrings();\n\n this.update((state) => {\n state.vault = updatedState.vault;\n state.keyrings = updatedKeyrings;\n state.encryptionKey = updatedState.encryptionKey;\n state.encryptionSalt = updatedState.encryptionSalt;\n });\n\n return true;\n });\n }\n\n /**\n * Check if there are new encryption parameters available.\n *\n * @returns A promise resolving to `void`.\n */\n #isNewEncryptionAvailable(): boolean {\n const { vault } = this.state;\n\n if (!vault || !this.#encryptor.isVaultUpdated) {\n return false;\n }\n\n return !this.#encryptor.isVaultUpdated(vault);\n }\n\n /**\n * Retrieves all the accounts from keyrings instances\n * that are currently in memory.\n *\n * @param additionalKeyrings - Additional keyrings to include in the search.\n * @returns A promise resolving to an array of accounts.\n */\n async #getAccountsFromKeyrings(\n additionalKeyrings: EthKeyring[] = [],\n ): Promise<string[]> {\n const keyrings = this.#keyrings.map(({ keyring }) => keyring);\n\n const keyringArrays = await Promise.all(\n [...keyrings, ...additionalKeyrings].map(async (keyring) =>\n keyring.getAccounts(),\n ),\n );\n const addresses = keyringArrays.reduce((res, arr) => {\n return res.concat(arr);\n }, []);\n\n // Cast to `string[]` here is safe here because `addresses` has no nullish\n // values, and `normalize` returns `string` unless given a nullish value\n return addresses.map(normalize) as string[];\n }\n\n /**\n * Create a new keyring, ensuring that the first account is\n * also created.\n *\n * @param type - Keyring type to instantiate.\n * @param opts - Optional parameters required to instantiate the keyring.\n * @returns A promise that resolves if the operation is successful.\n */\n async #createKeyringWithFirstAccount(type: string, opts?: unknown) {\n this.#assertControllerMutexIsLocked();\n\n const keyring = (await this.#newKeyring(type, opts)) as EthKeyring;\n\n const [firstAccount] = await keyring.getAccounts();\n if (!firstAccount) {\n throw new Error(KeyringControllerError.NoFirstAccount);\n }\n return firstAccount;\n }\n\n /**\n * Instantiate, initialize and return a new keyring of the given `type`,\n * using the given `opts`. The keyring is built using the keyring builder\n * registered for the given `type`.\n *\n * The internal keyring and keyring metadata arrays are updated with the new\n * keyring as well.\n *\n * @param type - The type of keyring to add.\n * @param data - Keyring initialization options.\n * @returns The new keyring.\n * @throws If the keyring includes duplicated accounts.\n */\n async #newKeyring(type: string, data?: unknown): Promise<EthKeyring> {\n const keyring = await this.#createKeyring(type, data);\n\n this.#keyrings.push({ keyring, metadata: getDefaultKeyringMetadata() });\n\n return keyring;\n }\n\n /**\n * Instantiate, initialize and return a keyring of the given `type` using the\n * given `opts`. The keyring is built using the keyring builder registered\n * for the given `type`.\n *\n * The keyring might be new, or it might be restored from the vault. This\n * function should only be called from `#newKeyring` or `#restoreKeyring`,\n * for the \"new\" and \"restore\" cases respectively.\n *\n * The internal keyring and keyring metadata arrays are *not* updated, the\n * caller is expected to update them.\n *\n * @param type - The type of keyring to add.\n * @param data - Keyring initialization options.\n * @returns The new keyring.\n * @throws If the keyring includes duplicated accounts.\n */\n async #createKeyring(type: string, data?: unknown): Promise<EthKeyring> {\n this.#assertControllerMutexIsLocked();\n\n const keyringBuilder = this.#getKeyringBuilderForType(type);\n\n if (!keyringBuilder) {\n throw new Error(\n `${KeyringControllerError.NoKeyringBuilder}. Keyring type: ${type}`,\n );\n }\n\n const keyring = keyringBuilder();\n if (data) {\n // @ts-expect-error Enforce data type after updating clients\n await keyring.deserialize(data);\n }\n\n if (keyring.init) {\n await keyring.init();\n }\n\n if (type === KeyringTypes.hd && (!isObject(data) || !data.mnemonic)) {\n if (!keyring.generateRandomMnemonic) {\n throw new Error(\n KeyringControllerError.UnsupportedGenerateRandomMnemonic,\n );\n }\n\n // NOTE: Not all keyrings implement this method in a asynchronous-way. Using `await` for\n // non-thenable will still be valid (despite not being really useful). It allows us to cover both\n // cases and allow retro-compatibility too.\n await keyring.generateRandomMnemonic();\n await keyring.addAccounts(1);\n }\n\n return keyring;\n }\n\n /**\n * Remove all managed keyrings, destroying all their\n * instances in memory.\n */\n async #clearKeyrings() {\n this.#assertControllerMutexIsLocked();\n for (const { keyring } of this.#keyrings) {\n await this.#destroyKeyring(keyring);\n }\n this.#keyrings = [];\n this.#unsupportedKeyrings = [];\n }\n\n /**\n * Restore a Keyring from a provided serialized payload.\n * On success, returns the resulting keyring instance.\n *\n * @param serialized - The serialized keyring.\n * @returns The deserialized keyring or undefined if the keyring type is unsupported.\n */\n async #restoreKeyring(\n serialized: SerializedKeyring,\n ): Promise<\n | { keyring: EthKeyring; metadata: KeyringMetadata; newMetadata: boolean }\n | undefined\n > {\n this.#assertControllerMutexIsLocked();\n\n try {\n const { type, data, metadata: serializedMetadata } = serialized;\n let newMetadata = false;\n let metadata = serializedMetadata;\n const keyring = await this.#createKeyring(type, data);\n await this.#assertNoDuplicateAccounts([keyring]);\n // If metadata is missing, assume the data is from an installation before\n // we had keyring metadata.\n if (!metadata) {\n newMetadata = true;\n metadata = getDefaultKeyringMetadata();\n }\n // The keyring is added to the keyrings array only if it's successfully restored\n // and the metadata is successfully added to the controller\n this.#keyrings.push({\n keyring,\n metadata,\n });\n return { keyring, metadata, newMetadata };\n } catch (error) {\n console.error(error);\n this.#unsupportedKeyrings.push(serialized);\n return undefined;\n }\n }\n\n /**\n * Destroy Keyring\n *\n * Some keyrings support a method called `destroy`, that destroys the\n * keyring along with removing all its event listeners and, in some cases,\n * clears the keyring bridge iframe from the DOM.\n *\n * @param keyring - The keyring to destroy.\n */\n async #destroyKeyring(keyring: EthKeyring) {\n await keyring.destroy?.();\n }\n\n /**\n * Remove empty keyrings.\n *\n * Loops through the keyrings and removes the ones with empty accounts\n * (usually after removing the last / only account) from a keyring.\n */\n async #removeEmptyKeyrings(): Promise<void> {\n this.#assertControllerMutexIsLocked();\n const validKeyrings: { keyring: EthKeyring; metadata: KeyringMetadata }[] =\n [];\n\n // Since getAccounts returns a Promise\n // We need to wait to hear back form each keyring\n // in order to decide which ones are now valid (accounts.length > 0)\n\n await Promise.all(\n this.#keyrings.map(async ({ keyring, metadata }) => {\n const accounts = await keyring.getAccounts();\n if (accounts.length > 0) {\n validKeyrings.push({ keyring, metadata });\n } else {\n await this.#destroyKeyring(keyring);\n }\n }),\n );\n this.#keyrings = validKeyrings;\n }\n\n /**\n * Assert that there are no duplicate accounts in the keyrings.\n *\n * @param additionalKeyrings - Additional keyrings to include in the check.\n * @throws If there are duplicate accounts.\n */\n async #assertNoDuplicateAccounts(\n additionalKeyrings: EthKeyring[] = [],\n ): Promise<void> {\n const accounts = await this.#getAccountsFromKeyrings(additionalKeyrings);\n\n if (new Set(accounts).size !== accounts.length) {\n throw new Error(KeyringControllerError.DuplicatedAccount);\n }\n }\n\n /**\n * Set the `isUnlocked` to true and notify listeners\n * through the messenger.\n *\n * @fires KeyringController:unlock\n */\n #setUnlocked(): void {\n this.#assertControllerMutexIsLocked();\n\n this.update((state) => {\n state.isUnlocked = true;\n });\n this.messenger.publish(`${name}:unlock`);\n }\n\n /**\n * Assert that the controller is unlocked.\n *\n * @throws If the controller is locked.\n */\n #assertIsUnlocked(): void {\n if (!this.state.isUnlocked) {\n throw new Error(KeyringControllerError.ControllerLocked);\n }\n }\n\n /**\n * Execute the given function after acquiring the controller lock\n * and save the vault to state after it (only if needed), or rollback to their\n * previous state in case of error.\n *\n * @param callback - The function to execute.\n * @returns The result of the function.\n */\n async #persistOrRollback<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return this.#withRollback(async ({ releaseLock }) => {\n const oldState = JSON.stringify(await this.#getSessionState());\n const callbackResult = await callback({ releaseLock });\n const newState = JSON.stringify(await this.#getSessionState());\n\n // State is committed only if the operation is successful and need to trigger a vault update.\n if (!isEqual(oldState, newState)) {\n await this.#updateVault();\n }\n\n return callbackResult;\n });\n }\n\n /**\n * Execute the given function after acquiring the controller lock\n * and rollback keyrings and password states in case of error.\n *\n * @param callback - The function to execute atomically.\n * @returns The result of the function.\n */\n async #withRollback<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return this.#withControllerLock(async ({ releaseLock }) => {\n const currentSerializedKeyrings = await this.#getSerializedKeyrings();\n const currentEncryptionKey = cloneDeep(this.#encryptionKey);\n\n try {\n return await callback({ releaseLock });\n } catch (e) {\n // Keyrings and encryption credentials are restored to their previous state\n this.#encryptionKey = currentEncryptionKey;\n await this.#restoreSerializedKeyrings(currentSerializedKeyrings);\n\n throw e;\n }\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(KeyringControllerError.ControllerLockRequired);\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n\n /**\n * Lock the vault mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This ensures that each operation that interacts with the vault\n * is executed in a mutually exclusive way.\n *\n * @param callback - The function to execute while the vault mutex is locked.\n * @returns The result of the function.\n */\n async #withVaultLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n this.#assertControllerMutexIsLocked();\n\n return withLock(this.#vaultOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n\n/**\n * Generate a new keyring metadata object.\n *\n * @returns Keyring metadata.\n */\nfunction getDefaultKeyringMetadata(): KeyringMetadata {\n return { id: ulid(), name: '' };\n}\n\nexport default KeyringController;\n"]}
@@ -7,6 +7,7 @@ var KeyringControllerError;
7
7
  KeyringControllerError["KeyringNotFound"] = "KeyringController - Keyring not found.";
8
8
  KeyringControllerError["UnsafeDirectKeyringAccess"] = "KeyringController - Returning keyring instances is unsafe";
9
9
  KeyringControllerError["WrongPasswordType"] = "KeyringController - Password must be of type string.";
10
+ KeyringControllerError["WrongEncryptionKeyType"] = "KeyringController - Encryption key must be of type string.";
10
11
  KeyringControllerError["InvalidEmptyPassword"] = "KeyringController - Password cannot be empty.";
11
12
  KeyringControllerError["NoFirstAccount"] = "KeyringController - First Account not found.";
12
13
  KeyringControllerError["DuplicatedAccount"] = "KeyringController - The account you are trying to import is a duplicate";