@metamask-previews/keyring-controller 12.2.0-preview.dad68d4 → 13.0.0-preview.6dad403
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.
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [13.0.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add `isCustodyKeyring` function ([#3899](https://github.com/MetaMask/core/pull/3899))
|
|
15
|
+
- Add `keyringBuilderFactory` utility function ([#3830](https://github.com/MetaMask/core/pull/3830))
|
|
16
|
+
- Add `GenericEncryptor`, `ExportableKeyEncryptor`, and `SerializedKeyring` types ([#3830](https://github.com/MetaMask/core/pull/3830))
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Replace `ethereumjs-util` with `@ethereumjs/util` ([#3943](https://github.com/MetaMask/core/pull/3943))
|
|
21
|
+
- Bump `@metamask/message-manager` to `^7.3.9` ([#4007](https://github.com/MetaMask/core/pull/4007))
|
|
22
|
+
|
|
23
|
+
### Removed
|
|
24
|
+
|
|
25
|
+
- **BREAKING:** Remove callbacks `updateIdentities`, `syncIdentities`, `setSelectedAddress`, `setAccountLabel` from constructor options of the `KeyringController` class. These were previously used to update `PreferencesController` state, but are now replaced with `PreferencesController`'s subscription to the `KeyringController:stateChange` event. ([#3853](https://github.com/MetaMask/core/pull/3853))
|
|
26
|
+
- Methods `addNewAccount`, `addNewAccountForKeyring`, `createNewVaultAndRestore`, `createNewVaultAndKeychain`, `importAccountWithStrategy`, `restoreQRKeyring`, `unlockQRHardwareWalletAccount`, and `forgetQRDevice` no longer directly update `PreferencesController` state by calling the `updateIdentities` callback.
|
|
27
|
+
- Method `submitPassword` no longer directly updates `PreferencesController` state by calling the `syncIdentities` callback.
|
|
28
|
+
- Method `unlockQRHardwareWalletAccount` no longer directly updates `PreferencesController` state by calling the `setAccountLabel` or `setSelectedAddress` callbacks.
|
|
29
|
+
- Remove `@metamask/eth-keyring-controller` dependency, and transfer dependencies to this package instead ([#3830](https://github.com/MetaMask/core/pull/3830))
|
|
30
|
+
- `@metamask/eth-hd-keyring`
|
|
31
|
+
- `@metamask/eth-simple-keyring`
|
|
32
|
+
- `@metamask/eth-sig-util`
|
|
33
|
+
- `@metamask/browser-passworder`
|
|
34
|
+
|
|
10
35
|
## [12.2.0]
|
|
11
36
|
|
|
12
37
|
### Added
|
|
@@ -351,7 +376,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
351
376
|
|
|
352
377
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
353
378
|
|
|
354
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@
|
|
379
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@13.0.0...HEAD
|
|
380
|
+
[13.0.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@12.2.0...@metamask/keyring-controller@13.0.0
|
|
355
381
|
[12.2.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@12.1.0...@metamask/keyring-controller@12.2.0
|
|
356
382
|
[12.1.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@12.0.0...@metamask/keyring-controller@12.1.0
|
|
357
383
|
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@11.0.0...@metamask/keyring-controller@12.0.0
|
|
@@ -18,9 +18,15 @@ export declare enum KeyringTypes {
|
|
|
18
18
|
trezor = "Trezor Hardware",
|
|
19
19
|
ledger = "Ledger Hardware",
|
|
20
20
|
lattice = "Lattice Hardware",
|
|
21
|
-
snap = "Snap Keyring"
|
|
22
|
-
custody = "Custody - JSONRPC"
|
|
21
|
+
snap = "Snap Keyring"
|
|
23
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Custody keyring types are a special case, as they are not a single type
|
|
25
|
+
* but they all start with the prefix "Custody".
|
|
26
|
+
* @param keyringType - The type of the keyring.
|
|
27
|
+
* @returns Whether the keyring type is a custody keyring.
|
|
28
|
+
*/
|
|
29
|
+
export declare const isCustodyKeyring: (keyringType: string) => boolean;
|
|
24
30
|
/**
|
|
25
31
|
* @type KeyringControllerState
|
|
26
32
|
*
|
|
@@ -116,10 +122,6 @@ export declare type KeyringControllerActions = KeyringControllerGetStateAction |
|
|
|
116
122
|
export declare type KeyringControllerEvents = KeyringControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | KeyringControllerAccountRemovedEvent | KeyringControllerQRKeyringStateChangeEvent;
|
|
117
123
|
export declare type KeyringControllerMessenger = RestrictedControllerMessenger<typeof name, KeyringControllerActions, KeyringControllerEvents, string, string>;
|
|
118
124
|
export declare type KeyringControllerOptions = {
|
|
119
|
-
syncIdentities: (addresses: string[]) => string;
|
|
120
|
-
updateIdentities: (addresses: string[]) => void;
|
|
121
|
-
setSelectedAddress: (selectedAddress: string) => void;
|
|
122
|
-
setAccountLabel?: (address: string, label: string) => void;
|
|
123
125
|
keyringBuilders?: {
|
|
124
126
|
(): EthKeyring<Json>;
|
|
125
127
|
type: string;
|
|
@@ -276,18 +278,10 @@ export declare const getDefaultKeyringState: () => KeyringControllerState;
|
|
|
276
278
|
export declare class KeyringController extends BaseController<typeof name, KeyringControllerState, KeyringControllerMessenger> {
|
|
277
279
|
#private;
|
|
278
280
|
private readonly mutex;
|
|
279
|
-
private readonly syncIdentities;
|
|
280
|
-
private readonly updateIdentities;
|
|
281
|
-
private readonly setSelectedAddress;
|
|
282
|
-
private readonly setAccountLabel?;
|
|
283
281
|
/**
|
|
284
282
|
* Creates a KeyringController instance.
|
|
285
283
|
*
|
|
286
284
|
* @param options - Initial options used to configure this controller
|
|
287
|
-
* @param options.syncIdentities - Sync identities with the given list of addresses.
|
|
288
|
-
* @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity.
|
|
289
|
-
* @param options.setSelectedAddress - Set the selected address.
|
|
290
|
-
* @param options.setAccountLabel - Set a new name for account.
|
|
291
285
|
* @param options.encryptor - An optional object for defining encryption schemes.
|
|
292
286
|
* @param options.keyringBuilders - Set a new name for account.
|
|
293
287
|
* @param options.cacheEncryptionKey - Whether to cache or not encryption key.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyringController.d.ts","sourceRoot":"","sources":["../src/KeyringController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"KeyringController.d.ts","sourceRoot":"","sources":["../src/KeyringController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE/D,OAAO,KAAK,EACV,eAAe,IAAI,SAAS,EAC5B,aAAa,IAAI,eAAe,EACjC,MAAM,wCAAwC,CAAC;AAChD,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,cAAc,MAAM,8BAA8B,CAAC;AAI/D,OAAO,KAAK,EACV,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EACV,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,oBAAoB,EACpB,GAAG,EACH,IAAI,EACJ,YAAY,EACb,MAAM,iBAAiB,CAAC;AAazB,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAInC,QAAA,MAAM,IAAI,sBAAsB,CAAC;AAEjC;;GAEG;AACH,oBAAY,YAAY;IACtB,MAAM,oBAAoB;IAC1B,EAAE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B,CAAC"}
|
|
@@ -47,7 +47,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
47
47
|
};
|
|
48
48
|
var _KeyringController_instances, _KeyringController_keyringBuilders, _KeyringController_keyrings, _KeyringController_unsupportedKeyrings, _KeyringController_password, _KeyringController_encryptor, _KeyringController_cacheEncryptionKey, _KeyringController_qrKeyringStateListener, _KeyringController_registerMessageHandlers, _KeyringController_getKeyringBuilderForType, _KeyringController_addQRKeyring, _KeyringController_subscribeToQRKeyringEvents, _KeyringController_unsubscribeFromQRKeyringsEvents, _KeyringController_createNewVaultWithKeyring, _KeyringController_updateKeyringsInState, _KeyringController_unlockKeyrings, _KeyringController_createKeyringWithFirstAccount, _KeyringController_newKeyring, _KeyringController_clearKeyrings, _KeyringController_restoreKeyring, _KeyringController_destroyKeyring, _KeyringController_removeEmptyKeyrings, _KeyringController_checkForDuplicate, _KeyringController_setUnlocked, _KeyringController_getMemState;
|
|
49
49
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
50
|
-
exports.KeyringController = exports.getDefaultKeyringState = exports.keyringBuilderFactory = exports.SignTypedDataVersion = exports.AccountImportStrategy = exports.KeyringTypes = void 0;
|
|
50
|
+
exports.KeyringController = exports.getDefaultKeyringState = exports.keyringBuilderFactory = exports.SignTypedDataVersion = exports.AccountImportStrategy = exports.isCustodyKeyring = exports.KeyringTypes = void 0;
|
|
51
|
+
const util_1 = require("@ethereumjs/util");
|
|
51
52
|
const base_controller_1 = require("@metamask/base-controller");
|
|
52
53
|
const encryptorUtils = __importStar(require("@metamask/browser-passworder"));
|
|
53
54
|
const eth_hd_keyring_1 = __importDefault(require("@metamask/eth-hd-keyring"));
|
|
@@ -55,7 +56,6 @@ const eth_sig_util_1 = require("@metamask/eth-sig-util");
|
|
|
55
56
|
const eth_simple_keyring_1 = __importDefault(require("@metamask/eth-simple-keyring"));
|
|
56
57
|
const utils_1 = require("@metamask/utils");
|
|
57
58
|
const async_mutex_1 = require("async-mutex");
|
|
58
|
-
const ethereumjs_util_1 = require("ethereumjs-util");
|
|
59
59
|
const ethereumjs_wallet_1 = __importStar(require("ethereumjs-wallet"));
|
|
60
60
|
const constants_1 = require("./constants");
|
|
61
61
|
const name = 'KeyringController';
|
|
@@ -71,8 +71,17 @@ var KeyringTypes;
|
|
|
71
71
|
KeyringTypes["ledger"] = "Ledger Hardware";
|
|
72
72
|
KeyringTypes["lattice"] = "Lattice Hardware";
|
|
73
73
|
KeyringTypes["snap"] = "Snap Keyring";
|
|
74
|
-
KeyringTypes["custody"] = "Custody - JSONRPC";
|
|
75
74
|
})(KeyringTypes = exports.KeyringTypes || (exports.KeyringTypes = {}));
|
|
75
|
+
/**
|
|
76
|
+
* Custody keyring types are a special case, as they are not a single type
|
|
77
|
+
* but they all start with the prefix "Custody".
|
|
78
|
+
* @param keyringType - The type of the keyring.
|
|
79
|
+
* @returns Whether the keyring type is a custody keyring.
|
|
80
|
+
*/
|
|
81
|
+
const isCustodyKeyring = (keyringType) => {
|
|
82
|
+
return keyringType.startsWith('Custody');
|
|
83
|
+
};
|
|
84
|
+
exports.isCustodyKeyring = isCustodyKeyring;
|
|
76
85
|
/**
|
|
77
86
|
* A strategy for importing an account
|
|
78
87
|
*/
|
|
@@ -190,10 +199,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
190
199
|
* Creates a KeyringController instance.
|
|
191
200
|
*
|
|
192
201
|
* @param options - Initial options used to configure this controller
|
|
193
|
-
* @param options.syncIdentities - Sync identities with the given list of addresses.
|
|
194
|
-
* @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity.
|
|
195
|
-
* @param options.setSelectedAddress - Set the selected address.
|
|
196
|
-
* @param options.setAccountLabel - Set a new name for account.
|
|
197
202
|
* @param options.encryptor - An optional object for defining encryption schemes.
|
|
198
203
|
* @param options.keyringBuilders - Set a new name for account.
|
|
199
204
|
* @param options.cacheEncryptionKey - Whether to cache or not encryption key.
|
|
@@ -201,7 +206,7 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
201
206
|
* @param options.state - Initial state to set on this controller.
|
|
202
207
|
*/
|
|
203
208
|
constructor(options) {
|
|
204
|
-
const {
|
|
209
|
+
const { encryptor = encryptorUtils, keyringBuilders, messenger, state, } = options;
|
|
205
210
|
super({
|
|
206
211
|
name,
|
|
207
212
|
metadata: {
|
|
@@ -235,10 +240,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
235
240
|
if (__classPrivateFieldGet(this, _KeyringController_cacheEncryptionKey, "f")) {
|
|
236
241
|
assertIsExportableKeyEncryptor(encryptor);
|
|
237
242
|
}
|
|
238
|
-
this.syncIdentities = syncIdentities;
|
|
239
|
-
this.updateIdentities = updateIdentities;
|
|
240
|
-
this.setSelectedAddress = setSelectedAddress;
|
|
241
|
-
this.setAccountLabel = setAccountLabel;
|
|
242
243
|
__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_registerMessageHandlers).call(this);
|
|
243
244
|
}
|
|
244
245
|
/**
|
|
@@ -269,7 +270,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
269
270
|
}
|
|
270
271
|
const addedAccountAddress = yield this.addNewAccountForKeyring(primaryKeyring);
|
|
271
272
|
yield this.verifySeedPhrase();
|
|
272
|
-
this.updateIdentities(yield this.getAccounts());
|
|
273
273
|
return {
|
|
274
274
|
keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
|
|
275
275
|
addedAccountAddress,
|
|
@@ -298,7 +298,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
298
298
|
yield this.persistAllKeyrings();
|
|
299
299
|
const addedAccountAddress = (yield this.getAccounts()).find((selectedAddress) => !oldAccounts.includes(selectedAddress));
|
|
300
300
|
(0, utils_1.assertIsStrictHexString)(addedAccountAddress);
|
|
301
|
-
this.updateIdentities(yield this.getAccounts());
|
|
302
301
|
return addedAccountAddress;
|
|
303
302
|
});
|
|
304
303
|
}
|
|
@@ -335,7 +334,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
335
334
|
throw new Error('Invalid password');
|
|
336
335
|
}
|
|
337
336
|
try {
|
|
338
|
-
this.updateIdentities([]);
|
|
339
337
|
yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createNewVaultWithKeyring).call(this, password, {
|
|
340
338
|
type: KeyringTypes.hd,
|
|
341
339
|
opts: {
|
|
@@ -343,7 +341,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
343
341
|
numberOfAccounts: 1,
|
|
344
342
|
},
|
|
345
343
|
});
|
|
346
|
-
this.updateIdentities(yield this.getAccounts());
|
|
347
344
|
return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
|
|
348
345
|
}
|
|
349
346
|
finally {
|
|
@@ -366,7 +363,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
366
363
|
yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createNewVaultWithKeyring).call(this, password, {
|
|
367
364
|
type: KeyringTypes.hd,
|
|
368
365
|
});
|
|
369
|
-
this.updateIdentities(yield this.getAccounts());
|
|
370
366
|
}
|
|
371
367
|
return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
|
|
372
368
|
}
|
|
@@ -643,20 +639,20 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
643
639
|
if (!importedKey) {
|
|
644
640
|
throw new Error('Cannot import an empty key.');
|
|
645
641
|
}
|
|
646
|
-
const prefixed = (0,
|
|
642
|
+
const prefixed = (0, utils_1.add0x)(importedKey);
|
|
647
643
|
let bufferedPrivateKey;
|
|
648
644
|
try {
|
|
649
|
-
bufferedPrivateKey = (0,
|
|
645
|
+
bufferedPrivateKey = (0, util_1.toBuffer)(prefixed);
|
|
650
646
|
}
|
|
651
647
|
catch (_a) {
|
|
652
648
|
throw new Error('Cannot import invalid private key.');
|
|
653
649
|
}
|
|
654
|
-
if (!(0,
|
|
650
|
+
if (!(0, util_1.isValidPrivate)(bufferedPrivateKey) ||
|
|
655
651
|
// ensures that the key is 64 bytes long
|
|
656
|
-
(0,
|
|
652
|
+
(0, util_1.getBinarySize)(prefixed) !== 64 + '0x'.length) {
|
|
657
653
|
throw new Error('Cannot import invalid private key.');
|
|
658
654
|
}
|
|
659
|
-
privateKey = (0,
|
|
655
|
+
privateKey = (0, utils_1.remove0x)(prefixed);
|
|
660
656
|
break;
|
|
661
657
|
case 'json':
|
|
662
658
|
let wallet;
|
|
@@ -667,7 +663,7 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
667
663
|
catch (e) {
|
|
668
664
|
wallet = wallet || (yield ethereumjs_wallet_1.default.fromV3(input, password, true));
|
|
669
665
|
}
|
|
670
|
-
privateKey = (0,
|
|
666
|
+
privateKey = (0, utils_1.bytesToHex)(wallet.getPrivateKey());
|
|
671
667
|
break;
|
|
672
668
|
default:
|
|
673
669
|
throw new Error(`Unexpected import strategy: '${strategy}'`);
|
|
@@ -676,8 +672,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
676
672
|
privateKey,
|
|
677
673
|
]));
|
|
678
674
|
const accounts = yield newKeyring.getAccounts();
|
|
679
|
-
const allAccounts = yield this.getAccounts();
|
|
680
|
-
this.updateIdentities(allAccounts);
|
|
681
675
|
return {
|
|
682
676
|
keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
|
|
683
677
|
importedAccountAddress: accounts[0],
|
|
@@ -903,14 +897,12 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
903
897
|
return __awaiter(this, void 0, void 0, function* () {
|
|
904
898
|
__classPrivateFieldSet(this, _KeyringController_keyrings, yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_unlockKeyrings).call(this, password), "f");
|
|
905
899
|
__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_setUnlocked).call(this);
|
|
906
|
-
const accounts = yield this.getAccounts();
|
|
907
900
|
const qrKeyring = this.getQRKeyring();
|
|
908
901
|
if (qrKeyring) {
|
|
909
902
|
// if there is a QR keyring, we need to subscribe
|
|
910
903
|
// to its events after unlocking the vault
|
|
911
904
|
__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_subscribeToQRKeyringEvents).call(this, qrKeyring);
|
|
912
905
|
}
|
|
913
|
-
yield this.syncIdentities(accounts);
|
|
914
906
|
return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
|
|
915
907
|
});
|
|
916
908
|
}
|
|
@@ -982,7 +974,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
982
974
|
return __awaiter(this, void 0, void 0, function* () {
|
|
983
975
|
(yield this.getOrAddQRKeyring()).deserialize(serialized);
|
|
984
976
|
yield this.persistAllKeyrings();
|
|
985
|
-
this.updateIdentities(yield this.getAccounts());
|
|
986
977
|
});
|
|
987
978
|
}
|
|
988
979
|
resetQRKeyringState() {
|
|
@@ -1056,22 +1047,11 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
1056
1047
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1057
1048
|
const keyring = yield this.getOrAddQRKeyring();
|
|
1058
1049
|
keyring.setAccountToUnlock(index);
|
|
1059
|
-
const oldAccounts = yield this.getAccounts();
|
|
1060
1050
|
// QRKeyring is not yet compatible with Keyring from
|
|
1061
1051
|
// @metamask/utils, but we can use the `addNewAccount` method
|
|
1062
1052
|
// as it internally calls `addAccounts` from on the keyring instance,
|
|
1063
1053
|
// which is supported by QRKeyring API.
|
|
1064
1054
|
yield this.addNewAccountForKeyring(keyring);
|
|
1065
|
-
const newAccounts = yield this.getAccounts();
|
|
1066
|
-
this.updateIdentities(newAccounts);
|
|
1067
|
-
newAccounts.forEach((address) => {
|
|
1068
|
-
if (!oldAccounts.includes(address)) {
|
|
1069
|
-
if (this.setAccountLabel) {
|
|
1070
|
-
this.setAccountLabel(address, `${keyring.getName()} ${index}`);
|
|
1071
|
-
}
|
|
1072
|
-
this.setSelectedAddress(address);
|
|
1073
|
-
}
|
|
1074
|
-
});
|
|
1075
1055
|
yield this.persistAllKeyrings();
|
|
1076
1056
|
});
|
|
1077
1057
|
}
|
|
@@ -1088,7 +1068,6 @@ class KeyringController extends base_controller_1.BaseController {
|
|
|
1088
1068
|
keyring.forgetDevice();
|
|
1089
1069
|
const remainingAccounts = (yield this.getAccounts());
|
|
1090
1070
|
const removedAccounts = allAccounts.filter((address) => !remainingAccounts.includes(address));
|
|
1091
|
-
this.updateIdentities(remainingAccounts);
|
|
1092
1071
|
yield this.persistAllKeyrings();
|
|
1093
1072
|
return { removedAccounts, remainingAccounts };
|
|
1094
1073
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyringController.js","sourceRoot":"","sources":["../src/KeyringController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,+DAA2D;AAC3D,6EAA+D;AAC/D,8EAAiD;AACjD,yDAAmD;AACnD,sFAAyD;AAkBzD,2CAOyB;AACzB,6CAAoC;AACpC,qDAOyB;AACzB,uEAAoE;AAGpE,2CAAqD;AAErD,MAAM,IAAI,GAAG,mBAAmB,CAAC;AAEjC;;GAEG;AACH,IAAY,YASX;AATD,WAAY,YAAY;IACtB,0CAA0B,CAAA;IAC1B,kCAAkB,CAAA;IAClB,gDAAgC,CAAA;IAChC,0CAA0B,CAAA;IAC1B,0CAA0B,CAAA;IAC1B,4CAA4B,CAAA;IAC5B,qCAAqB,CAAA;IACrB,6CAA6B,CAAA;AAC/B,CAAC,EATW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QASvB;AAiLD;;GAEG;AACH,IAAY,qBAGX;AAHD,WAAY,qBAAqB;IAC/B,kDAAyB,CAAA;IACzB,sCAAa,CAAA;AACf,CAAC,EAHW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAGhC;AAED;;;;GAIG;AACH,IAAY,oBAIX;AAJD,WAAY,oBAAoB;IAC9B,iCAAS,CAAA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AAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;IAC1B,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,IAAI,SAAS,CAAC,CAAC;AACjD,CAAC;IAGC,OAAO;QACL,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU;QACjC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ;KAC9B,CAAC;AACJ,CAAC;AAGH,kBAAe,iBAAiB,CAAC","sourcesContent":["import type { TxData, TypedTransaction } from '@ethereumjs/tx';\nimport type {\n MetaMaskKeyring as QRKeyring,\n IKeyringState as IQRKeyringState,\n} from '@keystonehq/metamask-airgapped-keyring';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport * as encryptorUtils from '@metamask/browser-passworder';\nimport HDKeyring from '@metamask/eth-hd-keyring';\nimport { normalize } from '@metamask/eth-sig-util';\nimport SimpleKeyring from '@metamask/eth-simple-keyring';\nimport type {\n EthBaseTransaction,\n EthBaseUserOperation,\n EthKeyring,\n EthUserOperation,\n EthUserOperationPatch,\n} from '@metamask/keyring-api';\nimport type {\n PersonalMessageParams,\n TypedMessageParams,\n} from '@metamask/message-manager';\nimport type {\n Eip1024EncryptedData,\n Hex,\n Json,\n KeyringClass,\n} from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isObject,\n isValidHexAddress,\n isValidJson,\n remove0x,\n} from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport {\n addHexPrefix,\n bufferToHex,\n isValidPrivate,\n toBuffer,\n stripHexPrefix,\n getBinarySize,\n} from 'ethereumjs-util';\nimport Wallet, { thirdparty as importers } from 'ethereumjs-wallet';\nimport type { Patch } from 'immer';\n\nimport { KeyringControllerError } from './constants';\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 ledger = 'Ledger Hardware',\n lattice = 'Lattice Hardware',\n snap = 'Snap Keyring',\n custody = 'Custody - JSONRPC',\n}\n\n/**\n * @type KeyringControllerState\n *\n * Keyring controller state\n * @property vault - Encrypted string representing keyring data\n * @property isUnlocked - Whether vault is unlocked\n * @property keyringTypes - Account types\n * @property keyrings - Group of accounts\n * @property encryptionKey - Keyring encryption key\n * @property encryptionSalt - Keyring encryption salt\n */\nexport type KeyringControllerState = {\n vault?: string;\n isUnlocked: boolean;\n keyrings: KeyringObject[];\n encryptionKey?: string;\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 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 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 KeyringControllerQRKeyringStateChangeEvent = {\n type: `${typeof name}:qrKeyringStateChange`;\n payload: [ReturnType<IQRKeyringState['getState']>];\n};\n\nexport type KeyringControllerActions =\n | KeyringControllerGetStateAction\n | KeyringControllerSignMessageAction\n | KeyringControllerSignPersonalMessageAction\n | KeyringControllerSignTypedMessageAction\n | KeyringControllerDecryptMessageAction\n | KeyringControllerGetEncryptionPublicKeyAction\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetKeyringsByTypeAction\n | KeyringControllerGetKeyringForAccountAction\n | KeyringControllerPersistAllKeyringsAction\n | KeyringControllerPrepareUserOperationAction\n | KeyringControllerPatchUserOperationAction\n | KeyringControllerSignUserOperationAction;\n\nexport type KeyringControllerEvents =\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | KeyringControllerAccountRemovedEvent\n | KeyringControllerQRKeyringStateChangeEvent;\n\nexport type KeyringControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n KeyringControllerActions,\n KeyringControllerEvents,\n string,\n string\n>;\n\nexport type KeyringControllerOptions = {\n syncIdentities: (addresses: string[]) => string;\n updateIdentities: (addresses: string[]) => void;\n setSelectedAddress: (selectedAddress: string) => void;\n setAccountLabel?: (address: string, label: string) => void;\n keyringBuilders?: { (): EthKeyring<Json>; type: string }[];\n messenger: KeyringControllerMessenger;\n state?: { vault?: string };\n} & (\n | {\n cacheEncryptionKey: true;\n encryptor?: ExportableKeyEncryptor;\n }\n | {\n cacheEncryptionKey?: false;\n encryptor?: GenericEncryptor | ExportableKeyEncryptor;\n }\n);\n\n/**\n * @type KeyringObject\n *\n * Keyring object to return in fullUpdate\n * @property type - Keyring type\n * @property accounts - Associated accounts\n */\nexport type KeyringObject = {\n accounts: string[];\n type: 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};\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 = 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: unknown,\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: (key: unknown, encryptedString: string) => 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<unknown>;\n};\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<Json>) {\n const builder = () => new KeyringConstructor();\n\n builder.type = KeyringConstructor.type;\n\n return builder;\n}\n\nconst defaultKeyringBuilders = [\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<Json>,\n): asserts keyring is EthKeyring<Json> & { 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 * 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 keyring - The keyring to display.\n * @returns A keyring display object, with type and accounts properties.\n */\nasync function displayForKeyring(\n keyring: EthKeyring<Json>,\n): Promise<{ type: string; accounts: string[] }> {\n const accounts = await keyring.getAccounts();\n\n return {\n type: keyring.type,\n // Cast to `Hex[]` here is safe here because `accounts` has no nullish\n // values, and `normalize` returns `Hex` unless given a nullish value\n accounts: accounts.map(normalize) as Hex[],\n };\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 private readonly mutex = new Mutex();\n\n private readonly syncIdentities: (addresses: string[]) => string;\n\n private readonly updateIdentities: (addresses: string[]) => void;\n\n private readonly setSelectedAddress: (selectedAddress: string) => void;\n\n private readonly setAccountLabel?: (address: string, label: string) => void;\n\n #keyringBuilders: { (): EthKeyring<Json>; type: string }[];\n\n #keyrings: EthKeyring<Json>[];\n\n #unsupportedKeyrings: SerializedKeyring[];\n\n #password?: string;\n\n #encryptor: GenericEncryptor | ExportableKeyEncryptor;\n\n #cacheEncryptionKey: boolean;\n\n #qrKeyringStateListener?: (\n state: ReturnType<IQRKeyringState['getState']>,\n ) => void;\n\n /**\n * Creates a KeyringController instance.\n *\n * @param options - Initial options used to configure this controller\n * @param options.syncIdentities - Sync identities with the given list of addresses.\n * @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity.\n * @param options.setSelectedAddress - Set the selected address.\n * @param options.setAccountLabel - Set a new name for account.\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 controller messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor(options: KeyringControllerOptions) {\n const {\n syncIdentities,\n updateIdentities,\n setSelectedAddress,\n setAccountLabel,\n encryptor = encryptorUtils,\n keyringBuilders,\n messenger,\n state,\n } = options;\n\n super({\n name,\n metadata: {\n vault: { persist: true, anonymous: false },\n isUnlocked: { persist: false, anonymous: true },\n keyrings: { persist: false, anonymous: false },\n encryptionKey: { persist: false, anonymous: false },\n encryptionSalt: { persist: false, anonymous: false },\n },\n messenger,\n state: {\n ...getDefaultKeyringState(),\n ...state,\n },\n });\n\n this.#keyringBuilders = keyringBuilders\n ? defaultKeyringBuilders.concat(keyringBuilders)\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.syncIdentities = syncIdentities;\n this.updateIdentities = updateIdentities;\n this.setSelectedAddress = setSelectedAddress;\n this.setAccountLabel = setAccountLabel;\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 keyring current state and added account\n * address.\n */\n async addNewAccount(accountCount?: number): Promise<{\n keyringState: KeyringControllerMemState;\n addedAccountAddress: string;\n }> {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n const oldAccounts = await this.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 primaryKeyringAccounts = await primaryKeyring.getAccounts();\n return {\n keyringState: this.#getMemState(),\n addedAccountAddress: primaryKeyringAccounts[accountCount],\n };\n }\n\n const addedAccountAddress = await this.addNewAccountForKeyring(\n primaryKeyring,\n );\n await this.verifySeedPhrase();\n\n this.updateIdentities(await this.getAccounts());\n\n return {\n keyringState: this.#getMemState(),\n 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 keyring current state and added account\n */\n async addNewAccountForKeyring(\n keyring: EthKeyring<Json>,\n accountCount?: number,\n ): Promise<Hex> {\n const oldAccounts = await this.getAccounts();\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 await this.persistAllKeyrings();\n\n const addedAccountAddress = (await this.getAccounts()).find(\n (selectedAddress) => !oldAccounts.includes(selectedAddress),\n );\n assertIsStrictHexString(addedAccountAddress);\n\n this.updateIdentities(await this.getAccounts());\n\n return addedAccountAddress;\n }\n\n /**\n * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences.\n *\n * @returns Promise resolving to current state when the account is added.\n */\n async addNewAccountWithoutUpdate(): Promise<KeyringControllerMemState> {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n await primaryKeyring.addAccounts(1);\n await this.persistAllKeyrings();\n await this.verifySeedPhrase();\n return this.#getMemState();\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 to the restored keychain object.\n */\n async createNewVaultAndRestore(\n password: string,\n seed: Uint8Array,\n ): Promise<KeyringControllerMemState> {\n const releaseLock = await this.mutex.acquire();\n if (!password || !password.length) {\n throw new Error('Invalid password');\n }\n\n try {\n this.updateIdentities([]);\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n opts: {\n mnemonic: seed,\n numberOfAccounts: 1,\n },\n });\n this.updateIdentities(await this.getAccounts());\n return this.#getMemState();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Create a new primary keychain and wipe any previous keychains.\n *\n * @param password - Password to unlock the new vault.\n * @returns Newly-created keychain object.\n */\n async createNewVaultAndKeychain(password: string) {\n const releaseLock = await this.mutex.acquire();\n try {\n const accounts = await this.getAccounts();\n if (!accounts.length) {\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n });\n this.updateIdentities(await this.getAccounts());\n }\n return this.#getMemState();\n } finally {\n releaseLock();\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 added keyring.\n */\n async addNewKeyring(\n type: KeyringTypes | string,\n opts?: unknown,\n ): Promise<unknown> {\n if (type === KeyringTypes.qr) {\n return this.getOrAddQRKeyring();\n }\n\n const keyring = await this.#newKeyring(type, opts);\n\n if (type === KeyringTypes.hd && (!isObject(opts) || !opts.mnemonic)) {\n if (!keyring.generateRandomMnemonic) {\n throw new Error(\n KeyringControllerError.UnsupportedGenerateRandomMnemonic,\n );\n }\n\n keyring.generateRandomMnemonic();\n await keyring.addAccounts(1);\n }\n\n const accounts = await keyring.getAccounts();\n await this.#checkForDuplicate(type, accounts);\n\n this.#keyrings.push(keyring);\n await this.persistAllKeyrings();\n\n return keyring;\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 * @returns Promise resolving to the seed phrase.\n */\n async exportSeedPhrase(password: string): Promise<Uint8Array> {\n await this.verifyPassword(password);\n assertHasUint8ArrayMnemonic(this.#keyrings[0]);\n return this.#keyrings[0].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(\n address,\n )) as EthKeyring<Json>;\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 for the current keyring.\n *\n * @returns A promise resolving to an array of addresses.\n */\n async getAccounts(): Promise<string[]> {\n const keyrings = this.#keyrings;\n\n const keyringArrays = await Promise.all(\n keyrings.map(async (keyring) => keyring.getAccounts()),\n );\n const addresses = keyringArrays.reduce((res, arr) => {\n return res.concat(arr);\n }, []);\n\n // Cast to `Hex[]` here is safe here because `addresses` has no nullish\n // values, and `normalize` returns `Hex` unless given a nullish value\n return addresses.map(normalize) as Hex[];\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 const normalizedAddress = normalize(account) as Hex;\n const keyring = (await this.getKeyringForAccount(\n account,\n )) as EthKeyring<Json>;\n if (!keyring.getEncryptionPublicKey) {\n throw new Error(KeyringControllerError.UnsupportedGetEncryptionPublicKey);\n }\n\n return await keyring.getEncryptionPublicKey(normalizedAddress, 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 const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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.\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 // Cast to `Hex` here is safe here because `address` is not nullish.\n // `normalizeToHex` returns `Hex` unless given a nullish value.\n const hexed = normalize(account) as Hex;\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(hexed);\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 (!isValidHexAddress(hexed)) {\n errorInfo = 'The address passed in is invalid/empty';\n } else 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.\n * @param type - Keyring type name.\n * @returns An array of keyrings of the given type.\n */\n getKeyringsByType(type: KeyringTypes | string): unknown[] {\n return this.#keyrings.filter((keyring) => keyring.type === type);\n }\n\n /**\n * Persist all serialized keyrings in the vault.\n *\n * @returns Promise resolving with `true` value when the\n * operation completes.\n */\n async persistAllKeyrings(): Promise<boolean> {\n const { encryptionKey, encryptionSalt } = this.state;\n\n if (!this.#password && !encryptionKey) {\n throw new Error(KeyringControllerError.MissingCredentials);\n }\n\n const serializedKeyrings = await Promise.all(\n this.#keyrings.map(async (keyring) => {\n const [type, data] = await Promise.all([\n keyring.type,\n keyring.serialize(),\n ]);\n return { type, data };\n }),\n );\n\n serializedKeyrings.push(...this.#unsupportedKeyrings);\n\n let vault: string | undefined;\n let newEncryptionKey: string | undefined;\n\n if (this.#cacheEncryptionKey) {\n assertIsExportableKeyEncryptor(this.#encryptor);\n\n if (encryptionKey) {\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 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 vault = newVault;\n newEncryptionKey = exportedKeyString;\n }\n } else {\n if (typeof this.#password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n vault = await this.#encryptor.encrypt(this.#password, serializedKeyrings);\n }\n\n if (!vault) {\n throw new Error(KeyringControllerError.MissingVaultData);\n }\n\n this.update((state) => {\n state.vault = vault;\n });\n\n // The keyring updates need to be announced before updating the encryptionKey\n // so that the updated keyring gets propagated to the extension first.\n // Not calling {@link updateKeyringsInState} results in the wrong account being selected\n // in the extension.\n await this.#updateKeyringsInState();\n if (newEncryptionKey) {\n this.update((state) => {\n state.encryptionKey = newEncryptionKey;\n state.encryptionSalt = JSON.parse(vault as string).salt;\n });\n }\n\n return true;\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 keyring current state and imported account\n * 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<{\n keyringState: KeyringControllerMemState;\n importedAccountAddress: string;\n }> {\n let privateKey;\n switch (strategy) {\n case 'privateKey':\n const [importedKey] = args;\n if (!importedKey) {\n throw new Error('Cannot import an empty key.');\n }\n const prefixed = addHexPrefix(importedKey);\n\n let bufferedPrivateKey;\n try {\n bufferedPrivateKey = toBuffer(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 = stripHexPrefix(prefixed);\n break;\n case '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 = bufferToHex(wallet.getPrivateKey());\n break;\n default:\n throw new Error(`Unexpected import strategy: '${strategy}'`);\n }\n const newKeyring = (await this.addNewKeyring(KeyringTypes.simple, [\n privateKey,\n ])) as EthKeyring<Json>;\n const accounts = await newKeyring.getAccounts();\n const allAccounts = await this.getAccounts();\n this.updateIdentities(allAccounts);\n return {\n keyringState: this.#getMemState(),\n importedAccountAddress: 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 current state when this account removal completes.\n */\n async removeAccount(address: Hex): Promise<KeyringControllerMemState> {\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 // eslint-disable-next-line @typescript-eslint/await-thenable\n await keyring.removeAccount(address);\n\n const accounts = await keyring.getAccounts();\n // Check if this was the last/only account\n if (accounts.length === 0) {\n await this.#removeEmptyKeyrings();\n }\n\n await this.persistAllKeyrings();\n\n this.messagingSystem.publish(`${name}:accountRemoved`, address);\n return this.#getMemState();\n }\n\n /**\n * Deallocates all secrets and locks the wallet.\n *\n * @returns Promise resolving to current state.\n */\n async setLocked(): Promise<KeyringControllerMemState> {\n this.#unsubscribeFromQRKeyringsEvents();\n\n this.#password = undefined;\n this.update((state) => {\n state.isUnlocked = false;\n state.keyrings = [];\n });\n await this.#clearKeyrings();\n\n this.messagingSystem.publish(`${name}:lock`);\n\n return this.#getMemState();\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 if (!messageParams.data) {\n throw new Error(\"Can't sign an empty message\");\n }\n\n const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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 const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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 = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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<TxData> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 * @returns A pseudo-UserOperation that can be used to construct a real.\n */\n async prepareUserOperation(\n from: string,\n transactions: EthBaseTransaction[],\n ): Promise<EthBaseUserOperation> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.prepareUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPrepareUserOperation);\n }\n\n return await keyring.prepareUserOperation(address, transactions);\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 * @returns A patch to apply to the UserOperation.\n */\n async patchUserOperation(\n from: string,\n userOp: EthUserOperation,\n ): Promise<EthUserOperationPatch> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.patchUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPatchUserOperation);\n }\n\n return await keyring.patchUserOperation(address, userOp);\n }\n\n /**\n * Signs an UserOperation.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n from: string,\n userOp: EthUserOperation,\n ): Promise<string> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.signUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedSignUserOperation);\n }\n\n return await keyring.signUserOperation(address, userOp);\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings,\n * using the given encryption key and salt.\n *\n * @param encryptionKey - Key to unlock the keychain.\n * @param encryptionSalt - Salt to unlock the keychain.\n * @returns Promise resolving to the current state.\n */\n async submitEncryptionKey(\n encryptionKey: string,\n encryptionSalt: string,\n ): Promise<KeyringControllerMemState> {\n this.#keyrings = await this.#unlockKeyrings(\n undefined,\n encryptionKey,\n encryptionSalt,\n );\n this.#setUnlocked();\n\n const qrKeyring = this.getQRKeyring();\n if (qrKeyring) {\n // if there is a QR keyring, we need to subscribe\n // to its events after unlocking the vault\n this.#subscribeToQRKeyringEvents(qrKeyring);\n }\n\n return this.#getMemState();\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 to the current state.\n */\n async submitPassword(password: string): Promise<KeyringControllerMemState> {\n this.#keyrings = await this.#unlockKeyrings(password);\n this.#setUnlocked();\n\n const accounts = await this.getAccounts();\n\n const qrKeyring = this.getQRKeyring();\n if (qrKeyring) {\n // if there is a QR keyring, we need to subscribe\n // to its events after unlocking the vault\n this.#subscribeToQRKeyringEvents(qrKeyring);\n }\n\n await this.syncIdentities(accounts);\n return this.#getMemState();\n }\n\n /**\n * Verifies the that the seed phrase restores the current keychain's accounts.\n *\n * @returns Promise resolving to the seed phrase as Uint8Array.\n */\n async verifySeedPhrase(): Promise<Uint8Array> {\n const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found.');\n }\n\n assertHasUint8ArrayMnemonic(primaryKeyring);\n\n const seedWords = primaryKeyring.mnemonic;\n const accounts = await primaryKeyring.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 // QR Hardware related methods\n\n /**\n * Get QR Hardware keyring.\n *\n * @returns The QR Keyring if defined, otherwise undefined\n */\n getQRKeyring(): QRKeyring | undefined {\n // QRKeyring is not yet compatible with Keyring type from @metamask/utils\n return this.getKeyringsByType(KeyringTypes.qr)[0] as unknown as QRKeyring;\n }\n\n /**\n * Get QR hardware keyring. If it doesn't exist, add it.\n *\n * @returns The added keyring\n */\n async getOrAddQRKeyring(): Promise<QRKeyring> {\n return this.getQRKeyring() || (await this.#addQRKeyring());\n }\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async restoreQRKeyring(serialized: any): Promise<void> {\n (await this.getOrAddQRKeyring()).deserialize(serialized);\n await this.persistAllKeyrings();\n this.updateIdentities(await this.getAccounts());\n }\n\n async resetQRKeyringState(): Promise<void> {\n (await this.getOrAddQRKeyring()).resetStore();\n }\n\n async getQRKeyringState(): Promise<IQRKeyringState> {\n return (await this.getOrAddQRKeyring()).getMemStore();\n }\n\n async submitQRCryptoHDKey(cryptoHDKey: string): Promise<void> {\n (await this.getOrAddQRKeyring()).submitCryptoHDKey(cryptoHDKey);\n }\n\n async submitQRCryptoAccount(cryptoAccount: string): Promise<void> {\n (await this.getOrAddQRKeyring()).submitCryptoAccount(cryptoAccount);\n }\n\n async submitQRSignature(\n requestId: string,\n ethSignature: string,\n ): Promise<void> {\n (await this.getOrAddQRKeyring()).submitSignature(requestId, ethSignature);\n }\n\n async cancelQRSignRequest(): Promise<void> {\n (await this.getOrAddQRKeyring()).cancelSignRequest();\n }\n\n /**\n * Cancels qr keyring sync.\n */\n async cancelQRSynchronization(): Promise<void> {\n // eslint-disable-next-line n/no-sync\n (await this.getOrAddQRKeyring()).cancelSync();\n }\n\n async connectQRHardware(\n page: number,\n ): Promise<{ balance: string; address: string; index: number }[]> {\n try {\n const keyring = await this.getOrAddQRKeyring();\n let accounts;\n switch (page) {\n case -1:\n accounts = await keyring.getPreviousPage();\n break;\n case 1:\n accounts = await keyring.getNextPage();\n break;\n default:\n accounts = await keyring.getFirstPage();\n }\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return accounts.map((account: any) => {\n return {\n ...account,\n balance: '0x0',\n };\n });\n } catch (e) {\n // TODO: Add test case for when keyring throws\n /* istanbul ignore next */\n throw new Error(`Unspecified error when connect QR Hardware, ${e}`);\n }\n }\n\n async unlockQRHardwareWalletAccount(index: number): Promise<void> {\n const keyring = await this.getOrAddQRKeyring();\n\n keyring.setAccountToUnlock(index);\n const oldAccounts = await this.getAccounts();\n // QRKeyring is not yet compatible with Keyring from\n // @metamask/utils, but we can use the `addNewAccount` method\n // as it internally calls `addAccounts` from on the keyring instance,\n // which is supported by QRKeyring API.\n await this.addNewAccountForKeyring(keyring as unknown as EthKeyring<Json>);\n const newAccounts = await this.getAccounts();\n this.updateIdentities(newAccounts);\n newAccounts.forEach((address: string) => {\n if (!oldAccounts.includes(address)) {\n if (this.setAccountLabel) {\n this.setAccountLabel(address, `${keyring.getName()} ${index}`);\n }\n this.setSelectedAddress(address);\n }\n });\n await this.persistAllKeyrings();\n }\n\n async getAccountKeyringType(account: string): Promise<string> {\n const keyring = (await this.getKeyringForAccount(\n account,\n )) as EthKeyring<Json>;\n return keyring.type;\n }\n\n async forgetQRDevice(): Promise<{\n removedAccounts: string[];\n remainingAccounts: string[];\n }> {\n const keyring = await this.getOrAddQRKeyring();\n const allAccounts = (await this.getAccounts()) as string[];\n keyring.forgetDevice();\n const remainingAccounts = (await this.getAccounts()) as string[];\n const removedAccounts = allAccounts.filter(\n (address: string) => !remainingAccounts.includes(address),\n );\n this.updateIdentities(remainingAccounts);\n await this.persistAllKeyrings();\n return { removedAccounts, remainingAccounts };\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${name}:signMessage`,\n this.signMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signPersonalMessage`,\n this.signPersonalMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signTypedMessage`,\n this.signTypedMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:decryptMessage`,\n this.decryptMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getEncryptionPublicKey`,\n this.getEncryptionPublicKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getAccounts`,\n this.getAccounts.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getKeyringsByType`,\n this.getKeyringsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getKeyringForAccount`,\n this.getKeyringForAccount.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:persistAllKeyrings`,\n this.persistAllKeyrings.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:prepareUserOperation`,\n this.prepareUserOperation.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:patchUserOperation`,\n this.patchUserOperation.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signUserOperation`,\n this.signUserOperation.bind(this),\n );\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<Json>; type: string } | undefined {\n return this.#keyringBuilders.find(\n (keyringBuilder) => keyringBuilder.type === type,\n );\n }\n\n /**\n * Add qr hardware keyring.\n *\n * @returns The added keyring\n * @throws If a QRKeyring builder is not provided\n * when initializing the controller\n */\n async #addQRKeyring(): Promise<QRKeyring> {\n // QRKeyring is not yet compatible with Keyring type from @metamask/utils\n const qrKeyring = (await this.#newKeyring(KeyringTypes.qr, {\n accounts: [],\n })) as unknown as QRKeyring;\n\n const accounts = await qrKeyring.getAccounts();\n await this.#checkForDuplicate(KeyringTypes.qr, accounts);\n\n this.#keyrings.push(qrKeyring as unknown as EthKeyring<Json>);\n await this.persistAllKeyrings();\n\n this.#subscribeToQRKeyringEvents(qrKeyring);\n\n return qrKeyring;\n }\n\n /**\n * Subscribe to a QRKeyring state change events and\n * forward them through the messaging system.\n *\n * @param qrKeyring - The QRKeyring instance to subscribe to\n */\n #subscribeToQRKeyringEvents(qrKeyring: QRKeyring) {\n this.#qrKeyringStateListener = (state) => {\n this.messagingSystem.publish(`${name}:qrKeyringStateChange`, state);\n };\n\n qrKeyring.getMemStore().subscribe(this.#qrKeyringStateListener);\n }\n\n #unsubscribeFromQRKeyringsEvents() {\n const qrKeyrings = this.getKeyringsByType(\n KeyringTypes.qr,\n ) as unknown as QRKeyring[];\n\n qrKeyrings.forEach((qrKeyring) => {\n if (this.#qrKeyringStateListener) {\n qrKeyring.getMemStore().unsubscribe(this.#qrKeyringStateListener);\n }\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<KeyringControllerMemState> {\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n this.#password = password;\n\n await this.#clearKeyrings();\n await this.#createKeyringWithFirstAccount(keyring.type, keyring.opts);\n this.#setUnlocked();\n return this.#getMemState();\n }\n\n /**\n * Update the controller state with its current keyrings.\n */\n async #updateKeyringsInState(): Promise<void> {\n const keyrings = await Promise.all(this.#keyrings.map(displayForKeyring));\n this.update((state) => {\n state.keyrings = keyrings;\n });\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<EthKeyring<Json>[]> {\n const encryptedVault = this.state.vault;\n if (!encryptedVault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n\n await this.#clearKeyrings();\n\n let vault;\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 this.update((state) => {\n state.encryptionKey = result.exportedKeyString;\n state.encryptionSalt = result.salt;\n });\n } else {\n const parsedEncryptedVault = JSON.parse(encryptedVault);\n\n if (encryptionSalt !== parsedEncryptedVault.salt) {\n throw new Error(KeyringControllerError.ExpiredCredentials);\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(key, parsedEncryptedVault);\n\n // This call is required on the first call because encryptionKey\n // is not yet inside the memStore\n this.update((state) => {\n state.encryptionKey = encryptionKey;\n // we can safely assume that encryptionSalt is defined here\n // because we compare it with the salt from the vault\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n state.encryptionSalt = encryptionSalt!;\n });\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 await Promise.all(vault.map(this.#restoreKeyring.bind(this)));\n await this.#updateKeyringsInState();\n\n if (\n this.#password &&\n (!this.#cacheEncryptionKey || !encryptionKey) &&\n this.#encryptor.isVaultUpdated &&\n !this.#encryptor.isVaultUpdated(encryptedVault)\n ) {\n // Re-encrypt the vault with safer method if one is available\n await this.persistAllKeyrings();\n }\n\n return this.#keyrings;\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 const keyring = (await this.addNewKeyring(type, opts)) as EthKeyring<Json>;\n\n const [firstAccount] = await keyring.getAccounts();\n if (!firstAccount) {\n throw new Error(KeyringControllerError.NoFirstAccount);\n }\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 * @param type - The type of keyring to add.\n * @param data - The data to restore a previously serialized keyring.\n * @returns The new keyring.\n */\n async #newKeyring(type: string, data: unknown): Promise<EthKeyring<Json>> {\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\n // @ts-expect-error Enforce data type after updating clients\n await keyring.deserialize(data);\n\n if (keyring.init) {\n await keyring.init();\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 for (const keyring of this.#keyrings) {\n await this.#destroyKeyring(keyring);\n }\n this.#keyrings = [];\n this.update((state) => {\n state.keyrings = [];\n });\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<EthKeyring<Json> | undefined> {\n try {\n const { type, data } = serialized;\n const keyring = await this.#newKeyring(type, data);\n\n // getAccounts also validates the accounts for some keyrings\n await keyring.getAccounts();\n this.#keyrings.push(keyring);\n\n return keyring;\n } catch (_) {\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<Json>) {\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 const validKeyrings: EthKeyring<Json>[] = [];\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: EthKeyring<Json>) => {\n const accounts = await keyring.getAccounts();\n if (accounts.length > 0) {\n validKeyrings.push(keyring);\n } else {\n await this.#destroyKeyring(keyring);\n }\n }),\n );\n this.#keyrings = validKeyrings;\n }\n\n /**\n * Checks for duplicate keypairs, using the the first account in the given\n * array. Rejects if a duplicate is found.\n *\n * Only supports 'Simple Key Pair'.\n *\n * @param type - The key pair type to check for.\n * @param newAccountArray - Array of new accounts.\n * @returns The account, if no duplicate is found.\n */\n async #checkForDuplicate(\n type: string,\n newAccountArray: string[],\n ): Promise<string[]> {\n const accounts = await this.getAccounts();\n\n switch (type) {\n case KeyringTypes.simple: {\n const isIncluded = Boolean(\n accounts.find(\n (key) =>\n newAccountArray[0] &&\n (key === newAccountArray[0] ||\n key === remove0x(newAccountArray[0])),\n ),\n );\n\n if (isIncluded) {\n throw new Error(KeyringControllerError.DuplicatedAccount);\n }\n return newAccountArray;\n }\n\n default: {\n return newAccountArray;\n }\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.update((state) => {\n state.isUnlocked = true;\n });\n this.messagingSystem.publish(`${name}:unlock`);\n }\n\n #getMemState(): KeyringControllerMemState {\n return {\n isUnlocked: this.state.isUnlocked,\n keyrings: this.state.keyrings,\n };\n }\n}\n\nexport default KeyringController;\n"]}
|
|
1
|
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AAC;aACrC;QACH,CAAC,CAAA,CAAC,CACH,CAAC;QACF,uBAAA,IAAI,+BAAa,aAAa,MAAA,CAAC;IACjC,CAAC;wFAaC,IAAY,EACZ,eAAyB;;QAEzB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC;QAE1C,QAAQ,IAAI,EAAE;YACZ,KAAK,YAAY,CAAC,MAAM,CAAC,CAAC;gBACxB,MAAM,UAAU,GAAG,OAAO,CACxB,QAAQ,CAAC,IAAI,CACX,CAAC,GAAG,EAAE,EAAE,CACN,eAAe,CAAC,CAAC,CAAC;oBAClB,CAAC,GAAG,KAAK,eAAe,CAAC,CAAC,CAAC;wBACzB,GAAG,KAAK,IAAA,gBAAQ,EAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC1C,CACF,CAAC;gBAEF,IAAI,UAAU,EAAE;oBACd,MAAM,IAAI,KAAK,CAAC,kCAAsB,CAAC,iBAAiB,CAAC,CAAC;iBAC3D;gBACD,OAAO,eAAe,CAAC;aACxB;YAED,OAAO,CAAC,CAAC;gBACP,OAAO,eAAe,CAAC;aACxB;SACF;IACH,CAAC;;IASC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;IAC1B,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,IAAI,SAAS,CAAC,CAAC;AACjD,CAAC;IAGC,OAAO;QACL,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU;QACjC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ;KAC9B,CAAC;AACJ,CAAC;AAGH,kBAAe,iBAAiB,CAAC","sourcesContent":["import type { TxData, TypedTransaction } from '@ethereumjs/tx';\nimport { isValidPrivate, toBuffer, getBinarySize } from '@ethereumjs/util';\nimport type {\n MetaMaskKeyring as QRKeyring,\n IKeyringState as IQRKeyringState,\n} from '@keystonehq/metamask-airgapped-keyring';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport * as encryptorUtils from '@metamask/browser-passworder';\nimport HDKeyring from '@metamask/eth-hd-keyring';\nimport { normalize } from '@metamask/eth-sig-util';\nimport SimpleKeyring from '@metamask/eth-simple-keyring';\nimport type {\n EthBaseTransaction,\n EthBaseUserOperation,\n EthKeyring,\n EthUserOperation,\n EthUserOperationPatch,\n} from '@metamask/keyring-api';\nimport type {\n PersonalMessageParams,\n TypedMessageParams,\n} from '@metamask/message-manager';\nimport type {\n Eip1024EncryptedData,\n Hex,\n Json,\n KeyringClass,\n} from '@metamask/utils';\nimport {\n add0x,\n assertIsStrictHexString,\n bytesToHex,\n hasProperty,\n isObject,\n isValidHexAddress,\n isValidJson,\n remove0x,\n} from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport Wallet, { thirdparty as importers } from 'ethereumjs-wallet';\nimport type { Patch } from 'immer';\n\nimport { KeyringControllerError } from './constants';\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 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 * @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 * @type KeyringControllerState\n *\n * Keyring controller state\n * @property vault - Encrypted string representing keyring data\n * @property isUnlocked - Whether vault is unlocked\n * @property keyringTypes - Account types\n * @property keyrings - Group of accounts\n * @property encryptionKey - Keyring encryption key\n * @property encryptionSalt - Keyring encryption salt\n */\nexport type KeyringControllerState = {\n vault?: string;\n isUnlocked: boolean;\n keyrings: KeyringObject[];\n encryptionKey?: string;\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 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 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 KeyringControllerQRKeyringStateChangeEvent = {\n type: `${typeof name}:qrKeyringStateChange`;\n payload: [ReturnType<IQRKeyringState['getState']>];\n};\n\nexport type KeyringControllerActions =\n | KeyringControllerGetStateAction\n | KeyringControllerSignMessageAction\n | KeyringControllerSignPersonalMessageAction\n | KeyringControllerSignTypedMessageAction\n | KeyringControllerDecryptMessageAction\n | KeyringControllerGetEncryptionPublicKeyAction\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetKeyringsByTypeAction\n | KeyringControllerGetKeyringForAccountAction\n | KeyringControllerPersistAllKeyringsAction\n | KeyringControllerPrepareUserOperationAction\n | KeyringControllerPatchUserOperationAction\n | KeyringControllerSignUserOperationAction;\n\nexport type KeyringControllerEvents =\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | KeyringControllerAccountRemovedEvent\n | KeyringControllerQRKeyringStateChangeEvent;\n\nexport type KeyringControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n KeyringControllerActions,\n KeyringControllerEvents,\n string,\n string\n>;\n\nexport type KeyringControllerOptions = {\n keyringBuilders?: { (): EthKeyring<Json>; type: string }[];\n messenger: KeyringControllerMessenger;\n state?: { vault?: string };\n} & (\n | {\n cacheEncryptionKey: true;\n encryptor?: ExportableKeyEncryptor;\n }\n | {\n cacheEncryptionKey?: false;\n encryptor?: GenericEncryptor | ExportableKeyEncryptor;\n }\n);\n\n/**\n * @type KeyringObject\n *\n * Keyring object to return in fullUpdate\n * @property type - Keyring type\n * @property accounts - Associated accounts\n */\nexport type KeyringObject = {\n accounts: string[];\n type: 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};\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 = 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: unknown,\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: (key: unknown, encryptedString: string) => 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<unknown>;\n};\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<Json>) {\n const builder = () => new KeyringConstructor();\n\n builder.type = KeyringConstructor.type;\n\n return builder;\n}\n\nconst defaultKeyringBuilders = [\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<Json>,\n): asserts keyring is EthKeyring<Json> & { 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 * 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 keyring - The keyring to display.\n * @returns A keyring display object, with type and accounts properties.\n */\nasync function displayForKeyring(\n keyring: EthKeyring<Json>,\n): Promise<{ type: string; accounts: string[] }> {\n const accounts = await keyring.getAccounts();\n\n return {\n type: keyring.type,\n // Cast to `Hex[]` here is safe here because `accounts` has no nullish\n // values, and `normalize` returns `Hex` unless given a nullish value\n accounts: accounts.map(normalize) as Hex[],\n };\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 private readonly mutex = new Mutex();\n\n #keyringBuilders: { (): EthKeyring<Json>; type: string }[];\n\n #keyrings: EthKeyring<Json>[];\n\n #unsupportedKeyrings: SerializedKeyring[];\n\n #password?: string;\n\n #encryptor: GenericEncryptor | ExportableKeyEncryptor;\n\n #cacheEncryptionKey: boolean;\n\n #qrKeyringStateListener?: (\n state: ReturnType<IQRKeyringState['getState']>,\n ) => void;\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 controller 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: { persist: true, anonymous: false },\n isUnlocked: { persist: false, anonymous: true },\n keyrings: { persist: false, anonymous: false },\n encryptionKey: { persist: false, anonymous: false },\n encryptionSalt: { persist: false, anonymous: false },\n },\n messenger,\n state: {\n ...getDefaultKeyringState(),\n ...state,\n },\n });\n\n this.#keyringBuilders = keyringBuilders\n ? defaultKeyringBuilders.concat(keyringBuilders)\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 keyring current state and added account\n * address.\n */\n async addNewAccount(accountCount?: number): Promise<{\n keyringState: KeyringControllerMemState;\n addedAccountAddress: string;\n }> {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n const oldAccounts = await this.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 primaryKeyringAccounts = await primaryKeyring.getAccounts();\n return {\n keyringState: this.#getMemState(),\n addedAccountAddress: primaryKeyringAccounts[accountCount],\n };\n }\n\n const addedAccountAddress = await this.addNewAccountForKeyring(\n primaryKeyring,\n );\n await this.verifySeedPhrase();\n\n return {\n keyringState: this.#getMemState(),\n 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 keyring current state and added account\n */\n async addNewAccountForKeyring(\n keyring: EthKeyring<Json>,\n accountCount?: number,\n ): Promise<Hex> {\n const oldAccounts = await this.getAccounts();\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 await this.persistAllKeyrings();\n\n const addedAccountAddress = (await this.getAccounts()).find(\n (selectedAddress) => !oldAccounts.includes(selectedAddress),\n );\n assertIsStrictHexString(addedAccountAddress);\n\n return addedAccountAddress;\n }\n\n /**\n * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences.\n *\n * @returns Promise resolving to current state when the account is added.\n */\n async addNewAccountWithoutUpdate(): Promise<KeyringControllerMemState> {\n const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found');\n }\n await primaryKeyring.addAccounts(1);\n await this.persistAllKeyrings();\n await this.verifySeedPhrase();\n return this.#getMemState();\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 to the restored keychain object.\n */\n async createNewVaultAndRestore(\n password: string,\n seed: Uint8Array,\n ): Promise<KeyringControllerMemState> {\n const releaseLock = await this.mutex.acquire();\n if (!password || !password.length) {\n throw new Error('Invalid password');\n }\n\n try {\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n opts: {\n mnemonic: seed,\n numberOfAccounts: 1,\n },\n });\n return this.#getMemState();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Create a new primary keychain and wipe any previous keychains.\n *\n * @param password - Password to unlock the new vault.\n * @returns Newly-created keychain object.\n */\n async createNewVaultAndKeychain(password: string) {\n const releaseLock = await this.mutex.acquire();\n try {\n const accounts = await this.getAccounts();\n if (!accounts.length) {\n await this.#createNewVaultWithKeyring(password, {\n type: KeyringTypes.hd,\n });\n }\n return this.#getMemState();\n } finally {\n releaseLock();\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 added keyring.\n */\n async addNewKeyring(\n type: KeyringTypes | string,\n opts?: unknown,\n ): Promise<unknown> {\n if (type === KeyringTypes.qr) {\n return this.getOrAddQRKeyring();\n }\n\n const keyring = await this.#newKeyring(type, opts);\n\n if (type === KeyringTypes.hd && (!isObject(opts) || !opts.mnemonic)) {\n if (!keyring.generateRandomMnemonic) {\n throw new Error(\n KeyringControllerError.UnsupportedGenerateRandomMnemonic,\n );\n }\n\n keyring.generateRandomMnemonic();\n await keyring.addAccounts(1);\n }\n\n const accounts = await keyring.getAccounts();\n await this.#checkForDuplicate(type, accounts);\n\n this.#keyrings.push(keyring);\n await this.persistAllKeyrings();\n\n return keyring;\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 * @returns Promise resolving to the seed phrase.\n */\n async exportSeedPhrase(password: string): Promise<Uint8Array> {\n await this.verifyPassword(password);\n assertHasUint8ArrayMnemonic(this.#keyrings[0]);\n return this.#keyrings[0].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(\n address,\n )) as EthKeyring<Json>;\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 for the current keyring.\n *\n * @returns A promise resolving to an array of addresses.\n */\n async getAccounts(): Promise<string[]> {\n const keyrings = this.#keyrings;\n\n const keyringArrays = await Promise.all(\n keyrings.map(async (keyring) => keyring.getAccounts()),\n );\n const addresses = keyringArrays.reduce((res, arr) => {\n return res.concat(arr);\n }, []);\n\n // Cast to `Hex[]` here is safe here because `addresses` has no nullish\n // values, and `normalize` returns `Hex` unless given a nullish value\n return addresses.map(normalize) as Hex[];\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 const normalizedAddress = normalize(account) as Hex;\n const keyring = (await this.getKeyringForAccount(\n account,\n )) as EthKeyring<Json>;\n if (!keyring.getEncryptionPublicKey) {\n throw new Error(KeyringControllerError.UnsupportedGetEncryptionPublicKey);\n }\n\n return await keyring.getEncryptionPublicKey(normalizedAddress, 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 const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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.\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 // Cast to `Hex` here is safe here because `address` is not nullish.\n // `normalizeToHex` returns `Hex` unless given a nullish value.\n const hexed = normalize(account) as Hex;\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(hexed);\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 (!isValidHexAddress(hexed)) {\n errorInfo = 'The address passed in is invalid/empty';\n } else 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.\n * @param type - Keyring type name.\n * @returns An array of keyrings of the given type.\n */\n getKeyringsByType(type: KeyringTypes | string): unknown[] {\n return this.#keyrings.filter((keyring) => keyring.type === type);\n }\n\n /**\n * Persist all serialized keyrings in the vault.\n *\n * @returns Promise resolving with `true` value when the\n * operation completes.\n */\n async persistAllKeyrings(): Promise<boolean> {\n const { encryptionKey, encryptionSalt } = this.state;\n\n if (!this.#password && !encryptionKey) {\n throw new Error(KeyringControllerError.MissingCredentials);\n }\n\n const serializedKeyrings = await Promise.all(\n this.#keyrings.map(async (keyring) => {\n const [type, data] = await Promise.all([\n keyring.type,\n keyring.serialize(),\n ]);\n return { type, data };\n }),\n );\n\n serializedKeyrings.push(...this.#unsupportedKeyrings);\n\n let vault: string | undefined;\n let newEncryptionKey: string | undefined;\n\n if (this.#cacheEncryptionKey) {\n assertIsExportableKeyEncryptor(this.#encryptor);\n\n if (encryptionKey) {\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 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 vault = newVault;\n newEncryptionKey = exportedKeyString;\n }\n } else {\n if (typeof this.#password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n vault = await this.#encryptor.encrypt(this.#password, serializedKeyrings);\n }\n\n if (!vault) {\n throw new Error(KeyringControllerError.MissingVaultData);\n }\n\n this.update((state) => {\n state.vault = vault;\n });\n\n // The keyring updates need to be announced before updating the encryptionKey\n // so that the updated keyring gets propagated to the extension first.\n // Not calling {@link updateKeyringsInState} results in the wrong account being selected\n // in the extension.\n await this.#updateKeyringsInState();\n if (newEncryptionKey) {\n this.update((state) => {\n state.encryptionKey = newEncryptionKey;\n state.encryptionSalt = JSON.parse(vault as string).salt;\n });\n }\n\n return true;\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 keyring current state and imported account\n * 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<{\n keyringState: KeyringControllerMemState;\n importedAccountAddress: string;\n }> {\n let privateKey;\n switch (strategy) {\n case '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 = toBuffer(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 '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: '${strategy}'`);\n }\n const newKeyring = (await this.addNewKeyring(KeyringTypes.simple, [\n privateKey,\n ])) as EthKeyring<Json>;\n const accounts = await newKeyring.getAccounts();\n return {\n keyringState: this.#getMemState(),\n importedAccountAddress: 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 current state when this account removal completes.\n */\n async removeAccount(address: Hex): Promise<KeyringControllerMemState> {\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 // eslint-disable-next-line @typescript-eslint/await-thenable\n await keyring.removeAccount(address);\n\n const accounts = await keyring.getAccounts();\n // Check if this was the last/only account\n if (accounts.length === 0) {\n await this.#removeEmptyKeyrings();\n }\n\n await this.persistAllKeyrings();\n\n this.messagingSystem.publish(`${name}:accountRemoved`, address);\n return this.#getMemState();\n }\n\n /**\n * Deallocates all secrets and locks the wallet.\n *\n * @returns Promise resolving to current state.\n */\n async setLocked(): Promise<KeyringControllerMemState> {\n this.#unsubscribeFromQRKeyringsEvents();\n\n this.#password = undefined;\n this.update((state) => {\n state.isUnlocked = false;\n state.keyrings = [];\n });\n await this.#clearKeyrings();\n\n this.messagingSystem.publish(`${name}:lock`);\n\n return this.#getMemState();\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 if (!messageParams.data) {\n throw new Error(\"Can't sign an empty message\");\n }\n\n const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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 const address = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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 = normalize(messageParams.from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 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<TxData> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\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 * @returns A pseudo-UserOperation that can be used to construct a real.\n */\n async prepareUserOperation(\n from: string,\n transactions: EthBaseTransaction[],\n ): Promise<EthBaseUserOperation> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.prepareUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPrepareUserOperation);\n }\n\n return await keyring.prepareUserOperation(address, transactions);\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 * @returns A patch to apply to the UserOperation.\n */\n async patchUserOperation(\n from: string,\n userOp: EthUserOperation,\n ): Promise<EthUserOperationPatch> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.patchUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedPatchUserOperation);\n }\n\n return await keyring.patchUserOperation(address, userOp);\n }\n\n /**\n * Signs an UserOperation.\n *\n * @param from - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n from: string,\n userOp: EthUserOperation,\n ): Promise<string> {\n const address = normalize(from) as Hex;\n const keyring = (await this.getKeyringForAccount(\n address,\n )) as EthKeyring<Json>;\n\n if (!keyring.signUserOperation) {\n throw new Error(KeyringControllerError.UnsupportedSignUserOperation);\n }\n\n return await keyring.signUserOperation(address, userOp);\n }\n\n /**\n * Attempts to decrypt the current vault and load its keyrings,\n * using the given encryption key and salt.\n *\n * @param encryptionKey - Key to unlock the keychain.\n * @param encryptionSalt - Salt to unlock the keychain.\n * @returns Promise resolving to the current state.\n */\n async submitEncryptionKey(\n encryptionKey: string,\n encryptionSalt: string,\n ): Promise<KeyringControllerMemState> {\n this.#keyrings = await this.#unlockKeyrings(\n undefined,\n encryptionKey,\n encryptionSalt,\n );\n this.#setUnlocked();\n\n const qrKeyring = this.getQRKeyring();\n if (qrKeyring) {\n // if there is a QR keyring, we need to subscribe\n // to its events after unlocking the vault\n this.#subscribeToQRKeyringEvents(qrKeyring);\n }\n\n return this.#getMemState();\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 to the current state.\n */\n async submitPassword(password: string): Promise<KeyringControllerMemState> {\n this.#keyrings = await this.#unlockKeyrings(password);\n this.#setUnlocked();\n\n const qrKeyring = this.getQRKeyring();\n if (qrKeyring) {\n // if there is a QR keyring, we need to subscribe\n // to its events after unlocking the vault\n this.#subscribeToQRKeyringEvents(qrKeyring);\n }\n\n return this.#getMemState();\n }\n\n /**\n * Verifies the that the seed phrase restores the current keychain's accounts.\n *\n * @returns Promise resolving to the seed phrase as Uint8Array.\n */\n async verifySeedPhrase(): Promise<Uint8Array> {\n const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0] as\n | EthKeyring<Json>\n | undefined;\n if (!primaryKeyring) {\n throw new Error('No HD keyring found.');\n }\n\n assertHasUint8ArrayMnemonic(primaryKeyring);\n\n const seedWords = primaryKeyring.mnemonic;\n const accounts = await primaryKeyring.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 // QR Hardware related methods\n\n /**\n * Get QR Hardware keyring.\n *\n * @returns The QR Keyring if defined, otherwise undefined\n */\n getQRKeyring(): QRKeyring | undefined {\n // QRKeyring is not yet compatible with Keyring type from @metamask/utils\n return this.getKeyringsByType(KeyringTypes.qr)[0] as unknown as QRKeyring;\n }\n\n /**\n * Get QR hardware keyring. If it doesn't exist, add it.\n *\n * @returns The added keyring\n */\n async getOrAddQRKeyring(): Promise<QRKeyring> {\n return this.getQRKeyring() || (await this.#addQRKeyring());\n }\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async restoreQRKeyring(serialized: any): Promise<void> {\n (await this.getOrAddQRKeyring()).deserialize(serialized);\n await this.persistAllKeyrings();\n }\n\n async resetQRKeyringState(): Promise<void> {\n (await this.getOrAddQRKeyring()).resetStore();\n }\n\n async getQRKeyringState(): Promise<IQRKeyringState> {\n return (await this.getOrAddQRKeyring()).getMemStore();\n }\n\n async submitQRCryptoHDKey(cryptoHDKey: string): Promise<void> {\n (await this.getOrAddQRKeyring()).submitCryptoHDKey(cryptoHDKey);\n }\n\n async submitQRCryptoAccount(cryptoAccount: string): Promise<void> {\n (await this.getOrAddQRKeyring()).submitCryptoAccount(cryptoAccount);\n }\n\n async submitQRSignature(\n requestId: string,\n ethSignature: string,\n ): Promise<void> {\n (await this.getOrAddQRKeyring()).submitSignature(requestId, ethSignature);\n }\n\n async cancelQRSignRequest(): Promise<void> {\n (await this.getOrAddQRKeyring()).cancelSignRequest();\n }\n\n /**\n * Cancels qr keyring sync.\n */\n async cancelQRSynchronization(): Promise<void> {\n // eslint-disable-next-line n/no-sync\n (await this.getOrAddQRKeyring()).cancelSync();\n }\n\n async connectQRHardware(\n page: number,\n ): Promise<{ balance: string; address: string; index: number }[]> {\n try {\n const keyring = await this.getOrAddQRKeyring();\n let accounts;\n switch (page) {\n case -1:\n accounts = await keyring.getPreviousPage();\n break;\n case 1:\n accounts = await keyring.getNextPage();\n break;\n default:\n accounts = await keyring.getFirstPage();\n }\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return accounts.map((account: any) => {\n return {\n ...account,\n balance: '0x0',\n };\n });\n } catch (e) {\n // TODO: Add test case for when keyring throws\n /* istanbul ignore next */\n throw new Error(`Unspecified error when connect QR Hardware, ${e}`);\n }\n }\n\n async unlockQRHardwareWalletAccount(index: number): Promise<void> {\n const keyring = await this.getOrAddQRKeyring();\n\n keyring.setAccountToUnlock(index);\n // QRKeyring is not yet compatible with Keyring from\n // @metamask/utils, but we can use the `addNewAccount` method\n // as it internally calls `addAccounts` from on the keyring instance,\n // which is supported by QRKeyring API.\n await this.addNewAccountForKeyring(keyring as unknown as EthKeyring<Json>);\n await this.persistAllKeyrings();\n }\n\n async getAccountKeyringType(account: string): Promise<string> {\n const keyring = (await this.getKeyringForAccount(\n account,\n )) as EthKeyring<Json>;\n return keyring.type;\n }\n\n async forgetQRDevice(): Promise<{\n removedAccounts: string[];\n remainingAccounts: string[];\n }> {\n const keyring = await this.getOrAddQRKeyring();\n const allAccounts = (await this.getAccounts()) as string[];\n keyring.forgetDevice();\n const remainingAccounts = (await this.getAccounts()) as string[];\n const removedAccounts = allAccounts.filter(\n (address: string) => !remainingAccounts.includes(address),\n );\n await this.persistAllKeyrings();\n return { removedAccounts, remainingAccounts };\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${name}:signMessage`,\n this.signMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signPersonalMessage`,\n this.signPersonalMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signTypedMessage`,\n this.signTypedMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:decryptMessage`,\n this.decryptMessage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getEncryptionPublicKey`,\n this.getEncryptionPublicKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getAccounts`,\n this.getAccounts.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getKeyringsByType`,\n this.getKeyringsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:getKeyringForAccount`,\n this.getKeyringForAccount.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:persistAllKeyrings`,\n this.persistAllKeyrings.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:prepareUserOperation`,\n this.prepareUserOperation.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:patchUserOperation`,\n this.patchUserOperation.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${name}:signUserOperation`,\n this.signUserOperation.bind(this),\n );\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<Json>; type: string } | undefined {\n return this.#keyringBuilders.find(\n (keyringBuilder) => keyringBuilder.type === type,\n );\n }\n\n /**\n * Add qr hardware keyring.\n *\n * @returns The added keyring\n * @throws If a QRKeyring builder is not provided\n * when initializing the controller\n */\n async #addQRKeyring(): Promise<QRKeyring> {\n // QRKeyring is not yet compatible with Keyring type from @metamask/utils\n const qrKeyring = (await this.#newKeyring(KeyringTypes.qr, {\n accounts: [],\n })) as unknown as QRKeyring;\n\n const accounts = await qrKeyring.getAccounts();\n await this.#checkForDuplicate(KeyringTypes.qr, accounts);\n\n this.#keyrings.push(qrKeyring as unknown as EthKeyring<Json>);\n await this.persistAllKeyrings();\n\n this.#subscribeToQRKeyringEvents(qrKeyring);\n\n return qrKeyring;\n }\n\n /**\n * Subscribe to a QRKeyring state change events and\n * forward them through the messaging system.\n *\n * @param qrKeyring - The QRKeyring instance to subscribe to\n */\n #subscribeToQRKeyringEvents(qrKeyring: QRKeyring) {\n this.#qrKeyringStateListener = (state) => {\n this.messagingSystem.publish(`${name}:qrKeyringStateChange`, state);\n };\n\n qrKeyring.getMemStore().subscribe(this.#qrKeyringStateListener);\n }\n\n #unsubscribeFromQRKeyringsEvents() {\n const qrKeyrings = this.getKeyringsByType(\n KeyringTypes.qr,\n ) as unknown as QRKeyring[];\n\n qrKeyrings.forEach((qrKeyring) => {\n if (this.#qrKeyringStateListener) {\n qrKeyring.getMemStore().unsubscribe(this.#qrKeyringStateListener);\n }\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<KeyringControllerMemState> {\n if (typeof password !== 'string') {\n throw new TypeError(KeyringControllerError.WrongPasswordType);\n }\n this.#password = password;\n\n await this.#clearKeyrings();\n await this.#createKeyringWithFirstAccount(keyring.type, keyring.opts);\n this.#setUnlocked();\n return this.#getMemState();\n }\n\n /**\n * Update the controller state with its current keyrings.\n */\n async #updateKeyringsInState(): Promise<void> {\n const keyrings = await Promise.all(this.#keyrings.map(displayForKeyring));\n this.update((state) => {\n state.keyrings = keyrings;\n });\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<EthKeyring<Json>[]> {\n const encryptedVault = this.state.vault;\n if (!encryptedVault) {\n throw new Error(KeyringControllerError.VaultError);\n }\n\n await this.#clearKeyrings();\n\n let vault;\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 this.update((state) => {\n state.encryptionKey = result.exportedKeyString;\n state.encryptionSalt = result.salt;\n });\n } else {\n const parsedEncryptedVault = JSON.parse(encryptedVault);\n\n if (encryptionSalt !== parsedEncryptedVault.salt) {\n throw new Error(KeyringControllerError.ExpiredCredentials);\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(key, parsedEncryptedVault);\n\n // This call is required on the first call because encryptionKey\n // is not yet inside the memStore\n this.update((state) => {\n state.encryptionKey = encryptionKey;\n // we can safely assume that encryptionSalt is defined here\n // because we compare it with the salt from the vault\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n state.encryptionSalt = encryptionSalt!;\n });\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 await Promise.all(vault.map(this.#restoreKeyring.bind(this)));\n await this.#updateKeyringsInState();\n\n if (\n this.#password &&\n (!this.#cacheEncryptionKey || !encryptionKey) &&\n this.#encryptor.isVaultUpdated &&\n !this.#encryptor.isVaultUpdated(encryptedVault)\n ) {\n // Re-encrypt the vault with safer method if one is available\n await this.persistAllKeyrings();\n }\n\n return this.#keyrings;\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 const keyring = (await this.addNewKeyring(type, opts)) as EthKeyring<Json>;\n\n const [firstAccount] = await keyring.getAccounts();\n if (!firstAccount) {\n throw new Error(KeyringControllerError.NoFirstAccount);\n }\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 * @param type - The type of keyring to add.\n * @param data - The data to restore a previously serialized keyring.\n * @returns The new keyring.\n */\n async #newKeyring(type: string, data: unknown): Promise<EthKeyring<Json>> {\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\n // @ts-expect-error Enforce data type after updating clients\n await keyring.deserialize(data);\n\n if (keyring.init) {\n await keyring.init();\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 for (const keyring of this.#keyrings) {\n await this.#destroyKeyring(keyring);\n }\n this.#keyrings = [];\n this.update((state) => {\n state.keyrings = [];\n });\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<EthKeyring<Json> | undefined> {\n try {\n const { type, data } = serialized;\n const keyring = await this.#newKeyring(type, data);\n\n // getAccounts also validates the accounts for some keyrings\n await keyring.getAccounts();\n this.#keyrings.push(keyring);\n\n return keyring;\n } catch (_) {\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<Json>) {\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 const validKeyrings: EthKeyring<Json>[] = [];\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: EthKeyring<Json>) => {\n const accounts = await keyring.getAccounts();\n if (accounts.length > 0) {\n validKeyrings.push(keyring);\n } else {\n await this.#destroyKeyring(keyring);\n }\n }),\n );\n this.#keyrings = validKeyrings;\n }\n\n /**\n * Checks for duplicate keypairs, using the the first account in the given\n * array. Rejects if a duplicate is found.\n *\n * Only supports 'Simple Key Pair'.\n *\n * @param type - The key pair type to check for.\n * @param newAccountArray - Array of new accounts.\n * @returns The account, if no duplicate is found.\n */\n async #checkForDuplicate(\n type: string,\n newAccountArray: string[],\n ): Promise<string[]> {\n const accounts = await this.getAccounts();\n\n switch (type) {\n case KeyringTypes.simple: {\n const isIncluded = Boolean(\n accounts.find(\n (key) =>\n newAccountArray[0] &&\n (key === newAccountArray[0] ||\n key === remove0x(newAccountArray[0])),\n ),\n );\n\n if (isIncluded) {\n throw new Error(KeyringControllerError.DuplicatedAccount);\n }\n return newAccountArray;\n }\n\n default: {\n return newAccountArray;\n }\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.update((state) => {\n state.isUnlocked = true;\n });\n this.messagingSystem.publish(`${name}:unlock`);\n }\n\n #getMemState(): KeyringControllerMemState {\n return {\n isUnlocked: this.state.isUnlocked,\n keyrings: this.state.keyrings,\n };\n }\n}\n\nexport default KeyringController;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/keyring-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "13.0.0-preview.6dad403",
|
|
4
4
|
"description": "Stores identities seen in the wallet and manages interactions such as signing",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"test:watch": "jest --watch"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
+
"@ethereumjs/util": "^8.1.0",
|
|
34
35
|
"@keystonehq/metamask-airgapped-keyring": "^0.13.1",
|
|
35
36
|
"@metamask/base-controller": "^4.1.1",
|
|
36
37
|
"@metamask/browser-passworder": "^4.3.0",
|
|
@@ -38,10 +39,9 @@
|
|
|
38
39
|
"@metamask/eth-sig-util": "^7.0.1",
|
|
39
40
|
"@metamask/eth-simple-keyring": "^6.0.1",
|
|
40
41
|
"@metamask/keyring-api": "^3.0.0",
|
|
41
|
-
"@metamask/message-manager": "^7.3.
|
|
42
|
+
"@metamask/message-manager": "^7.3.9",
|
|
42
43
|
"@metamask/utils": "^8.3.0",
|
|
43
44
|
"async-mutex": "^0.2.6",
|
|
44
|
-
"ethereumjs-util": "^7.0.10",
|
|
45
45
|
"ethereumjs-wallet": "^1.0.1",
|
|
46
46
|
"immer": "^9.0.6"
|
|
47
47
|
},
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"@ethereumjs/common": "^3.2.0",
|
|
50
50
|
"@ethereumjs/tx": "^4.2.0",
|
|
51
51
|
"@keystonehq/bc-ur-registry-eth": "^0.9.0",
|
|
52
|
-
"@lavamoat/allow-scripts": "^
|
|
52
|
+
"@lavamoat/allow-scripts": "^3.0.2",
|
|
53
53
|
"@metamask/auto-changelog": "^3.4.4",
|
|
54
54
|
"@metamask/scure-bip39": "^2.1.1",
|
|
55
55
|
"@types/jest": "^27.4.1",
|
|
@@ -71,9 +71,6 @@
|
|
|
71
71
|
"registry": "https://registry.npmjs.org/"
|
|
72
72
|
},
|
|
73
73
|
"lavamoat": {
|
|
74
|
-
"allowScripts": {
|
|
75
|
-
"ethereumjs-util>ethereum-cryptography>keccak": false,
|
|
76
|
-
"ethereumjs-util>ethereum-cryptography>secp256k1": false
|
|
77
|
-
}
|
|
74
|
+
"allowScripts": {}
|
|
78
75
|
}
|
|
79
76
|
}
|