@metamask-previews/keyring-controller 12.0.0-preview.d357889 → 12.2.0-preview.0a7589e7

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.
@@ -42,15 +42,22 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
42
42
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
43
43
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
44
44
  };
45
- var _KeyringController_instances, _KeyringController_keyring, _KeyringController_qrKeyringStateListener, _KeyringController_registerMessageHandlers, _KeyringController_addQRKeyring, _KeyringController_subscribeToQRKeyringEvents, _KeyringController_unsubscribeFromQRKeyringsEvents, _KeyringController_fullUpdate, _KeyringController_handleLock, _KeyringController_handleUnlock, _KeyringController_getMemState;
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
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;
46
49
  Object.defineProperty(exports, "__esModule", { value: true });
47
- exports.KeyringController = 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");
48
52
  const base_controller_1 = require("@metamask/base-controller");
49
- const eth_keyring_controller_1 = require("@metamask/eth-keyring-controller");
53
+ const encryptorUtils = __importStar(require("@metamask/browser-passworder"));
54
+ const eth_hd_keyring_1 = __importDefault(require("@metamask/eth-hd-keyring"));
55
+ const eth_sig_util_1 = require("@metamask/eth-sig-util");
56
+ const eth_simple_keyring_1 = __importDefault(require("@metamask/eth-simple-keyring"));
50
57
  const utils_1 = require("@metamask/utils");
51
58
  const async_mutex_1 = require("async-mutex");
52
- const ethereumjs_util_1 = require("ethereumjs-util");
53
59
  const ethereumjs_wallet_1 = __importStar(require("ethereumjs-wallet"));
60
+ const constants_1 = require("./constants");
54
61
  const name = 'KeyringController';
55
62
  /**
56
63
  * Available keyring types
@@ -64,8 +71,17 @@ var KeyringTypes;
64
71
  KeyringTypes["ledger"] = "Ledger Hardware";
65
72
  KeyringTypes["lattice"] = "Lattice Hardware";
66
73
  KeyringTypes["snap"] = "Snap Keyring";
67
- KeyringTypes["custody"] = "Custody";
68
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;
69
85
  /**
70
86
  * A strategy for importing an account
71
87
  */
@@ -85,10 +101,31 @@ var SignTypedDataVersion;
85
101
  SignTypedDataVersion["V3"] = "V3";
86
102
  SignTypedDataVersion["V4"] = "V4";
87
103
  })(SignTypedDataVersion = exports.SignTypedDataVersion || (exports.SignTypedDataVersion = {}));
88
- const defaultState = {
89
- isUnlocked: false,
90
- keyrings: [],
104
+ /**
105
+ * Get builder function for `Keyring`
106
+ *
107
+ * Returns a builder function for `Keyring` with a `type` property.
108
+ *
109
+ * @param KeyringConstructor - The Keyring class for the builder.
110
+ * @returns A builder function for the given Keyring.
111
+ */
112
+ function keyringBuilderFactory(KeyringConstructor) {
113
+ const builder = () => new KeyringConstructor();
114
+ builder.type = KeyringConstructor.type;
115
+ return builder;
116
+ }
117
+ exports.keyringBuilderFactory = keyringBuilderFactory;
118
+ const defaultKeyringBuilders = [
119
+ keyringBuilderFactory(eth_simple_keyring_1.default),
120
+ keyringBuilderFactory(eth_hd_keyring_1.default),
121
+ ];
122
+ const getDefaultKeyringState = () => {
123
+ return {
124
+ isUnlocked: false,
125
+ keyrings: [],
126
+ };
91
127
  };
128
+ exports.getDefaultKeyringState = getDefaultKeyringState;
92
129
  /**
93
130
  * Assert that the given keyring has an exportable
94
131
  * mnemonic.
@@ -101,6 +138,53 @@ function assertHasUint8ArrayMnemonic(keyring) {
101
138
  throw new Error("Can't get mnemonic bytes from keyring");
102
139
  }
103
140
  }
141
+ /**
142
+ * Assert that the provided encryptor supports
143
+ * encryption and encryption key export.
144
+ *
145
+ * @param encryptor - The encryptor to check.
146
+ * @throws If the encryptor does not support key encryption.
147
+ */
148
+ function assertIsExportableKeyEncryptor(encryptor) {
149
+ if (!('importKey' in encryptor &&
150
+ typeof encryptor.importKey === 'function' &&
151
+ 'decryptWithKey' in encryptor &&
152
+ typeof encryptor.decryptWithKey === 'function' &&
153
+ 'encryptWithKey' in encryptor &&
154
+ typeof encryptor.encryptWithKey === 'function')) {
155
+ throw new Error(constants_1.KeyringControllerError.UnsupportedEncryptionKeyExport);
156
+ }
157
+ }
158
+ /**
159
+ * Checks if the provided value is a serialized keyrings array.
160
+ *
161
+ * @param array - The value to check.
162
+ * @returns True if the value is a serialized keyrings array.
163
+ */
164
+ function isSerializedKeyringsArray(array) {
165
+ return (typeof array === 'object' &&
166
+ Array.isArray(array) &&
167
+ array.every((value) => value.type && (0, utils_1.isValidJson)(value.data)));
168
+ }
169
+ /**
170
+ * Display For Keyring
171
+ *
172
+ * Is used for adding the current keyrings to the state object.
173
+ *
174
+ * @param keyring - The keyring to display.
175
+ * @returns A keyring display object, with type and accounts properties.
176
+ */
177
+ function displayForKeyring(keyring) {
178
+ return __awaiter(this, void 0, void 0, function* () {
179
+ const accounts = yield keyring.getAccounts();
180
+ return {
181
+ type: keyring.type,
182
+ // Cast to `Hex[]` here is safe here because `accounts` has no nullish
183
+ // values, and `normalize` returns `Hex` unless given a nullish value
184
+ accounts: accounts.map(eth_sig_util_1.normalize),
185
+ };
186
+ });
187
+ }
104
188
  /**
105
189
  * Controller responsible for establishing and managing user identity.
106
190
  *
@@ -115,10 +199,6 @@ class KeyringController extends base_controller_1.BaseController {
115
199
  * Creates a KeyringController instance.
116
200
  *
117
201
  * @param options - Initial options used to configure this controller
118
- * @param options.syncIdentities - Sync identities with the given list of addresses.
119
- * @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity.
120
- * @param options.setSelectedAddress - Set the selected address.
121
- * @param options.setAccountLabel - Set a new name for account.
122
202
  * @param options.encryptor - An optional object for defining encryption schemes.
123
203
  * @param options.keyringBuilders - Set a new name for account.
124
204
  * @param options.cacheEncryptionKey - Whether to cache or not encryption key.
@@ -126,8 +206,7 @@ class KeyringController extends base_controller_1.BaseController {
126
206
  * @param options.state - Initial state to set on this controller.
127
207
  */
128
208
  constructor(options) {
129
- var _a;
130
- const { syncIdentities, updateIdentities, setSelectedAddress, setAccountLabel, keyringBuilders, messenger, state, } = options;
209
+ const { encryptor = encryptorUtils, keyringBuilders, messenger, state, } = options;
131
210
  super({
132
211
  name,
133
212
  metadata: {
@@ -138,36 +217,29 @@ class KeyringController extends base_controller_1.BaseController {
138
217
  encryptionSalt: { persist: false, anonymous: false },
139
218
  },
140
219
  messenger,
141
- state: Object.assign(Object.assign({}, defaultState), state),
220
+ state: Object.assign(Object.assign({}, (0, exports.getDefaultKeyringState)()), state),
142
221
  });
143
222
  _KeyringController_instances.add(this);
144
223
  this.mutex = new async_mutex_1.Mutex();
145
- _KeyringController_keyring.set(this, void 0);
224
+ _KeyringController_keyringBuilders.set(this, void 0);
225
+ _KeyringController_keyrings.set(this, void 0);
226
+ _KeyringController_unsupportedKeyrings.set(this, void 0);
227
+ _KeyringController_password.set(this, void 0);
228
+ _KeyringController_encryptor.set(this, void 0);
229
+ _KeyringController_cacheEncryptionKey.set(this, void 0);
146
230
  _KeyringController_qrKeyringStateListener.set(this, void 0);
147
- if (options.cacheEncryptionKey) {
148
- __classPrivateFieldSet(this, _KeyringController_keyring, new eth_keyring_controller_1.KeyringController({
149
- initState: state,
150
- encryptor: options.encryptor,
151
- keyringBuilders,
152
- cacheEncryptionKey: options.cacheEncryptionKey,
153
- }), "f");
231
+ __classPrivateFieldSet(this, _KeyringController_keyringBuilders, keyringBuilders
232
+ ? defaultKeyringBuilders.concat(keyringBuilders)
233
+ : defaultKeyringBuilders, "f");
234
+ __classPrivateFieldSet(this, _KeyringController_encryptor, encryptor, "f");
235
+ __classPrivateFieldSet(this, _KeyringController_keyrings, [], "f");
236
+ __classPrivateFieldSet(this, _KeyringController_unsupportedKeyrings, [], "f");
237
+ // This option allows the controller to cache an exported key
238
+ // for use in decrypting and encrypting data without password
239
+ __classPrivateFieldSet(this, _KeyringController_cacheEncryptionKey, Boolean(options.cacheEncryptionKey), "f");
240
+ if (__classPrivateFieldGet(this, _KeyringController_cacheEncryptionKey, "f")) {
241
+ assertIsExportableKeyEncryptor(encryptor);
154
242
  }
155
- else {
156
- __classPrivateFieldSet(this, _KeyringController_keyring, new eth_keyring_controller_1.KeyringController({
157
- initState: state,
158
- encryptor: options.encryptor,
159
- keyringBuilders,
160
- cacheEncryptionKey: (_a = options.cacheEncryptionKey) !== null && _a !== void 0 ? _a : false,
161
- }), "f");
162
- }
163
- __classPrivateFieldGet(this, _KeyringController_keyring, "f").memStore.subscribe(__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_fullUpdate).bind(this));
164
- __classPrivateFieldGet(this, _KeyringController_keyring, "f").store.subscribe(__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_fullUpdate).bind(this));
165
- __classPrivateFieldGet(this, _KeyringController_keyring, "f").on('lock', __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_handleLock).bind(this));
166
- __classPrivateFieldGet(this, _KeyringController_keyring, "f").on('unlock', __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_handleUnlock).bind(this));
167
- this.syncIdentities = syncIdentities;
168
- this.updateIdentities = updateIdentities;
169
- this.setSelectedAddress = setSelectedAddress;
170
- this.setAccountLabel = setAccountLabel;
171
243
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_registerMessageHandlers).call(this);
172
244
  }
173
245
  /**
@@ -180,12 +252,11 @@ class KeyringController extends base_controller_1.BaseController {
180
252
  */
181
253
  addNewAccount(accountCount) {
182
254
  return __awaiter(this, void 0, void 0, function* () {
183
- const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType('HD Key Tree')[0];
184
- /* istanbul ignore if */
255
+ const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0];
185
256
  if (!primaryKeyring) {
186
257
  throw new Error('No HD keyring found');
187
258
  }
188
- const oldAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
259
+ const oldAccounts = yield this.getAccounts();
189
260
  if (accountCount && oldAccounts.length !== accountCount) {
190
261
  if (accountCount > oldAccounts.length) {
191
262
  throw new Error('Account out of sequence');
@@ -197,12 +268,8 @@ class KeyringController extends base_controller_1.BaseController {
197
268
  addedAccountAddress: primaryKeyringAccounts[accountCount],
198
269
  };
199
270
  }
200
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(primaryKeyring);
201
- const newAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
271
+ const addedAccountAddress = yield this.addNewAccountForKeyring(primaryKeyring);
202
272
  yield this.verifySeedPhrase();
203
- this.updateIdentities(newAccounts);
204
- const addedAccountAddress = newAccounts.find((selectedAddress) => !oldAccounts.includes(selectedAddress));
205
- (0, utils_1.assertIsStrictHexString)(addedAccountAddress);
206
273
  return {
207
274
  keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
208
275
  addedAccountAddress,
@@ -227,10 +294,10 @@ class KeyringController extends base_controller_1.BaseController {
227
294
  (0, utils_1.assertIsStrictHexString)(existingAccount);
228
295
  return existingAccount;
229
296
  }
230
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(keyring);
297
+ yield keyring.addAccounts(1);
298
+ yield this.persistAllKeyrings();
231
299
  const addedAccountAddress = (yield this.getAccounts()).find((selectedAddress) => !oldAccounts.includes(selectedAddress));
232
300
  (0, utils_1.assertIsStrictHexString)(addedAccountAddress);
233
- this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
234
301
  return addedAccountAddress;
235
302
  });
236
303
  }
@@ -241,12 +308,12 @@ class KeyringController extends base_controller_1.BaseController {
241
308
  */
242
309
  addNewAccountWithoutUpdate() {
243
310
  return __awaiter(this, void 0, void 0, function* () {
244
- const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType('HD Key Tree')[0];
245
- /* istanbul ignore if */
311
+ const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0];
246
312
  if (!primaryKeyring) {
247
313
  throw new Error('No HD keyring found');
248
314
  }
249
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(primaryKeyring);
315
+ yield primaryKeyring.addAccounts(1);
316
+ yield this.persistAllKeyrings();
250
317
  yield this.verifySeedPhrase();
251
318
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
252
319
  });
@@ -267,9 +334,13 @@ class KeyringController extends base_controller_1.BaseController {
267
334
  throw new Error('Invalid password');
268
335
  }
269
336
  try {
270
- this.updateIdentities([]);
271
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").createNewVaultAndRestore(password, seed);
272
- this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
337
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createNewVaultWithKeyring).call(this, password, {
338
+ type: KeyringTypes.hd,
339
+ opts: {
340
+ mnemonic: seed,
341
+ numberOfAccounts: 1,
342
+ },
343
+ });
273
344
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
274
345
  }
275
346
  finally {
@@ -289,8 +360,9 @@ class KeyringController extends base_controller_1.BaseController {
289
360
  try {
290
361
  const accounts = yield this.getAccounts();
291
362
  if (!accounts.length) {
292
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").createNewVaultAndKeychain(password);
293
- this.updateIdentities(yield this.getAccounts());
363
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createNewVaultWithKeyring).call(this, password, {
364
+ type: KeyringTypes.hd,
365
+ });
294
366
  }
295
367
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
296
368
  }
@@ -312,7 +384,19 @@ class KeyringController extends base_controller_1.BaseController {
312
384
  if (type === KeyringTypes.qr) {
313
385
  return this.getOrAddQRKeyring();
314
386
  }
315
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(type, opts);
387
+ const keyring = yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_newKeyring).call(this, type, opts);
388
+ if (type === KeyringTypes.hd && (!(0, utils_1.isObject)(opts) || !opts.mnemonic)) {
389
+ if (!keyring.generateRandomMnemonic) {
390
+ throw new Error(constants_1.KeyringControllerError.UnsupportedGenerateRandomMnemonic);
391
+ }
392
+ keyring.generateRandomMnemonic();
393
+ yield keyring.addAccounts(1);
394
+ }
395
+ const accounts = yield keyring.getAccounts();
396
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_checkForDuplicate).call(this, type, accounts);
397
+ __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(keyring);
398
+ yield this.persistAllKeyrings();
399
+ return keyring;
316
400
  });
317
401
  }
318
402
  /**
@@ -323,7 +407,10 @@ class KeyringController extends base_controller_1.BaseController {
323
407
  */
324
408
  verifyPassword(password) {
325
409
  return __awaiter(this, void 0, void 0, function* () {
326
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").verifyPassword(password);
410
+ if (!this.state.vault) {
411
+ throw new Error(constants_1.KeyringControllerError.VaultError);
412
+ }
413
+ yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").decrypt(password, this.state.vault);
327
414
  });
328
415
  }
329
416
  /**
@@ -343,8 +430,8 @@ class KeyringController extends base_controller_1.BaseController {
343
430
  exportSeedPhrase(password) {
344
431
  return __awaiter(this, void 0, void 0, function* () {
345
432
  yield this.verifyPassword(password);
346
- assertHasUint8ArrayMnemonic(__classPrivateFieldGet(this, _KeyringController_keyring, "f").keyrings[0]);
347
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").keyrings[0].mnemonic;
433
+ assertHasUint8ArrayMnemonic(__classPrivateFieldGet(this, _KeyringController_keyrings, "f")[0]);
434
+ return __classPrivateFieldGet(this, _KeyringController_keyrings, "f")[0].mnemonic;
348
435
  });
349
436
  }
350
437
  /**
@@ -357,7 +444,11 @@ class KeyringController extends base_controller_1.BaseController {
357
444
  exportAccount(password, address) {
358
445
  return __awaiter(this, void 0, void 0, function* () {
359
446
  yield this.verifyPassword(password);
360
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").exportAccount(address);
447
+ const keyring = (yield this.getKeyringForAccount(address));
448
+ if (!keyring.exportAccount) {
449
+ throw new Error(constants_1.KeyringControllerError.UnsupportedExportAccount);
450
+ }
451
+ return yield keyring.exportAccount((0, eth_sig_util_1.normalize)(address));
361
452
  });
362
453
  }
363
454
  /**
@@ -366,7 +457,16 @@ class KeyringController extends base_controller_1.BaseController {
366
457
  * @returns A promise resolving to an array of addresses.
367
458
  */
368
459
  getAccounts() {
369
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
460
+ return __awaiter(this, void 0, void 0, function* () {
461
+ const keyrings = __classPrivateFieldGet(this, _KeyringController_keyrings, "f");
462
+ const keyringArrays = yield Promise.all(keyrings.map((keyring) => __awaiter(this, void 0, void 0, function* () { return keyring.getAccounts(); })));
463
+ const addresses = keyringArrays.reduce((res, arr) => {
464
+ return res.concat(arr);
465
+ }, []);
466
+ // Cast to `Hex[]` here is safe here because `addresses` has no nullish
467
+ // values, and `normalize` returns `Hex` unless given a nullish value
468
+ return addresses.map(eth_sig_util_1.normalize);
469
+ });
370
470
  }
371
471
  /**
372
472
  * Get encryption public key.
@@ -378,7 +478,12 @@ class KeyringController extends base_controller_1.BaseController {
378
478
  */
379
479
  getEncryptionPublicKey(account, opts) {
380
480
  return __awaiter(this, void 0, void 0, function* () {
381
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getEncryptionPublicKey(account, opts);
481
+ const normalizedAddress = (0, eth_sig_util_1.normalize)(account);
482
+ const keyring = (yield this.getKeyringForAccount(account));
483
+ if (!keyring.getEncryptionPublicKey) {
484
+ throw new Error(constants_1.KeyringControllerError.UnsupportedGetEncryptionPublicKey);
485
+ }
486
+ return yield keyring.getEncryptionPublicKey(normalizedAddress, opts);
382
487
  });
383
488
  }
384
489
  /**
@@ -391,7 +496,12 @@ class KeyringController extends base_controller_1.BaseController {
391
496
  */
392
497
  decryptMessage(messageParams) {
393
498
  return __awaiter(this, void 0, void 0, function* () {
394
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").decryptMessage(messageParams);
499
+ const address = (0, eth_sig_util_1.normalize)(messageParams.from);
500
+ const keyring = (yield this.getKeyringForAccount(address));
501
+ if (!keyring.decryptMessage) {
502
+ throw new Error(constants_1.KeyringControllerError.UnsupportedDecryptMessage);
503
+ }
504
+ return keyring.decryptMessage(address, messageParams.data);
395
505
  });
396
506
  }
397
507
  /**
@@ -405,8 +515,33 @@ class KeyringController extends base_controller_1.BaseController {
405
515
  * @returns Promise resolving to keyring of the `account` if one exists.
406
516
  */
407
517
  getKeyringForAccount(account) {
518
+ var _a;
408
519
  return __awaiter(this, void 0, void 0, function* () {
409
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringForAccount(account);
520
+ // Cast to `Hex` here is safe here because `address` is not nullish.
521
+ // `normalizeToHex` returns `Hex` unless given a nullish value.
522
+ const hexed = (0, eth_sig_util_1.normalize)(account);
523
+ const candidates = yield Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map((keyring) => __awaiter(this, void 0, void 0, function* () {
524
+ return Promise.all([keyring, keyring.getAccounts()]);
525
+ })));
526
+ const winners = candidates.filter((candidate) => {
527
+ const accounts = candidate[1].map(eth_sig_util_1.normalize);
528
+ return accounts.includes(hexed);
529
+ });
530
+ if (winners.length && ((_a = winners[0]) === null || _a === void 0 ? void 0 : _a.length)) {
531
+ return winners[0][0];
532
+ }
533
+ // Adding more info to the error
534
+ let errorInfo = '';
535
+ if (!(0, utils_1.isValidHexAddress)(hexed)) {
536
+ errorInfo = 'The address passed in is invalid/empty';
537
+ }
538
+ else if (!candidates.length) {
539
+ errorInfo = 'There are no keyrings';
540
+ }
541
+ else if (!winners.length) {
542
+ errorInfo = 'There are keyrings, but none match the address';
543
+ }
544
+ throw new Error(`${constants_1.KeyringControllerError.NoKeyring}. Error info: ${errorInfo}`);
410
545
  });
411
546
  }
412
547
  /**
@@ -419,7 +554,7 @@ class KeyringController extends base_controller_1.BaseController {
419
554
  * @returns An array of keyrings of the given type.
420
555
  */
421
556
  getKeyringsByType(type) {
422
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(type);
557
+ return __classPrivateFieldGet(this, _KeyringController_keyrings, "f").filter((keyring) => keyring.type === type);
423
558
  }
424
559
  /**
425
560
  * Persist all serialized keyrings in the vault.
@@ -429,7 +564,58 @@ class KeyringController extends base_controller_1.BaseController {
429
564
  */
430
565
  persistAllKeyrings() {
431
566
  return __awaiter(this, void 0, void 0, function* () {
432
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
567
+ const { encryptionKey, encryptionSalt } = this.state;
568
+ if (!__classPrivateFieldGet(this, _KeyringController_password, "f") && !encryptionKey) {
569
+ throw new Error(constants_1.KeyringControllerError.MissingCredentials);
570
+ }
571
+ const serializedKeyrings = yield Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map((keyring) => __awaiter(this, void 0, void 0, function* () {
572
+ const [type, data] = yield Promise.all([
573
+ keyring.type,
574
+ keyring.serialize(),
575
+ ]);
576
+ return { type, data };
577
+ })));
578
+ serializedKeyrings.push(...__classPrivateFieldGet(this, _KeyringController_unsupportedKeyrings, "f"));
579
+ let vault;
580
+ let newEncryptionKey;
581
+ if (__classPrivateFieldGet(this, _KeyringController_cacheEncryptionKey, "f")) {
582
+ assertIsExportableKeyEncryptor(__classPrivateFieldGet(this, _KeyringController_encryptor, "f"));
583
+ if (encryptionKey) {
584
+ const key = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").importKey(encryptionKey);
585
+ const vaultJSON = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").encryptWithKey(key, serializedKeyrings);
586
+ vaultJSON.salt = encryptionSalt;
587
+ vault = JSON.stringify(vaultJSON);
588
+ }
589
+ else if (__classPrivateFieldGet(this, _KeyringController_password, "f")) {
590
+ const { vault: newVault, exportedKeyString } = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").encryptWithDetail(__classPrivateFieldGet(this, _KeyringController_password, "f"), serializedKeyrings);
591
+ vault = newVault;
592
+ newEncryptionKey = exportedKeyString;
593
+ }
594
+ }
595
+ else {
596
+ if (typeof __classPrivateFieldGet(this, _KeyringController_password, "f") !== 'string') {
597
+ throw new TypeError(constants_1.KeyringControllerError.WrongPasswordType);
598
+ }
599
+ vault = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").encrypt(__classPrivateFieldGet(this, _KeyringController_password, "f"), serializedKeyrings);
600
+ }
601
+ if (!vault) {
602
+ throw new Error(constants_1.KeyringControllerError.MissingVaultData);
603
+ }
604
+ this.update((state) => {
605
+ state.vault = vault;
606
+ });
607
+ // The keyring updates need to be announced before updating the encryptionKey
608
+ // so that the updated keyring gets propagated to the extension first.
609
+ // Not calling {@link updateKeyringsInState} results in the wrong account being selected
610
+ // in the extension.
611
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_updateKeyringsInState).call(this);
612
+ if (newEncryptionKey) {
613
+ this.update((state) => {
614
+ state.encryptionKey = newEncryptionKey;
615
+ state.encryptionSalt = JSON.parse(vault).salt;
616
+ });
617
+ }
618
+ return true;
433
619
  });
434
620
  }
435
621
  /**
@@ -453,21 +639,20 @@ class KeyringController extends base_controller_1.BaseController {
453
639
  if (!importedKey) {
454
640
  throw new Error('Cannot import an empty key.');
455
641
  }
456
- const prefixed = (0, ethereumjs_util_1.addHexPrefix)(importedKey);
642
+ const prefixed = (0, utils_1.add0x)(importedKey);
457
643
  let bufferedPrivateKey;
458
644
  try {
459
- bufferedPrivateKey = (0, ethereumjs_util_1.toBuffer)(prefixed);
645
+ bufferedPrivateKey = (0, util_1.toBuffer)(prefixed);
460
646
  }
461
647
  catch (_a) {
462
648
  throw new Error('Cannot import invalid private key.');
463
649
  }
464
- /* istanbul ignore if */
465
- if (!(0, ethereumjs_util_1.isValidPrivate)(bufferedPrivateKey) ||
650
+ if (!(0, util_1.isValidPrivate)(bufferedPrivateKey) ||
466
651
  // ensures that the key is 64 bytes long
467
- (0, ethereumjs_util_1.getBinarySize)(prefixed) !== 64 + '0x'.length) {
652
+ (0, util_1.getBinarySize)(prefixed) !== 64 + '0x'.length) {
468
653
  throw new Error('Cannot import invalid private key.');
469
654
  }
470
- privateKey = (0, ethereumjs_util_1.stripHexPrefix)(prefixed);
655
+ privateKey = (0, utils_1.remove0x)(prefixed);
471
656
  break;
472
657
  case 'json':
473
658
  let wallet;
@@ -478,17 +663,15 @@ class KeyringController extends base_controller_1.BaseController {
478
663
  catch (e) {
479
664
  wallet = wallet || (yield ethereumjs_wallet_1.default.fromV3(input, password, true));
480
665
  }
481
- privateKey = (0, ethereumjs_util_1.bufferToHex)(wallet.getPrivateKey());
666
+ privateKey = (0, utils_1.bytesToHex)(wallet.getPrivateKey());
482
667
  break;
483
668
  default:
484
669
  throw new Error(`Unexpected import strategy: '${strategy}'`);
485
670
  }
486
- const newKeyring = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(KeyringTypes.simple, [
671
+ const newKeyring = (yield this.addNewKeyring(KeyringTypes.simple, [
487
672
  privateKey,
488
- ]);
673
+ ]));
489
674
  const accounts = yield newKeyring.getAccounts();
490
- const allAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
491
- this.updateIdentities(allAccounts);
492
675
  return {
493
676
  keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
494
677
  importedAccountAddress: accounts[0],
@@ -504,7 +687,21 @@ class KeyringController extends base_controller_1.BaseController {
504
687
  */
505
688
  removeAccount(address) {
506
689
  return __awaiter(this, void 0, void 0, function* () {
507
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").removeAccount(address);
690
+ const keyring = (yield this.getKeyringForAccount(address));
691
+ // Not all the keyrings support this, so we have to check
692
+ if (!keyring.removeAccount) {
693
+ throw new Error(constants_1.KeyringControllerError.UnsupportedRemoveAccount);
694
+ }
695
+ // The `removeAccount` method of snaps keyring is async. We have to update
696
+ // the interface of the other keyrings to be async as well.
697
+ // eslint-disable-next-line @typescript-eslint/await-thenable
698
+ yield keyring.removeAccount(address);
699
+ const accounts = yield keyring.getAccounts();
700
+ // Check if this was the last/only account
701
+ if (accounts.length === 0) {
702
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_removeEmptyKeyrings).call(this);
703
+ }
704
+ yield this.persistAllKeyrings();
508
705
  this.messagingSystem.publish(`${name}:accountRemoved`, address);
509
706
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
510
707
  });
@@ -517,7 +714,13 @@ class KeyringController extends base_controller_1.BaseController {
517
714
  setLocked() {
518
715
  return __awaiter(this, void 0, void 0, function* () {
519
716
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_unsubscribeFromQRKeyringsEvents).call(this);
520
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").setLocked();
717
+ __classPrivateFieldSet(this, _KeyringController_password, undefined, "f");
718
+ this.update((state) => {
719
+ state.isUnlocked = false;
720
+ state.keyrings = [];
721
+ });
722
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_clearKeyrings).call(this);
723
+ this.messagingSystem.publish(`${name}:lock`);
521
724
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
522
725
  });
523
726
  }
@@ -528,10 +731,17 @@ class KeyringController extends base_controller_1.BaseController {
528
731
  * @returns Promise resolving to a signed message string.
529
732
  */
530
733
  signMessage(messageParams) {
531
- if (!messageParams.data) {
532
- throw new Error("Can't sign an empty message");
533
- }
534
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signMessage(messageParams);
734
+ return __awaiter(this, void 0, void 0, function* () {
735
+ if (!messageParams.data) {
736
+ throw new Error("Can't sign an empty message");
737
+ }
738
+ const address = (0, eth_sig_util_1.normalize)(messageParams.from);
739
+ const keyring = (yield this.getKeyringForAccount(address));
740
+ if (!keyring.signMessage) {
741
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignMessage);
742
+ }
743
+ return yield keyring.signMessage(address, messageParams.data);
744
+ });
535
745
  }
536
746
  /**
537
747
  * Signs personal message by calling down into a specific keyring.
@@ -540,7 +750,15 @@ class KeyringController extends base_controller_1.BaseController {
540
750
  * @returns Promise resolving to a signed message string.
541
751
  */
542
752
  signPersonalMessage(messageParams) {
543
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signPersonalMessage(messageParams);
753
+ return __awaiter(this, void 0, void 0, function* () {
754
+ const address = (0, eth_sig_util_1.normalize)(messageParams.from);
755
+ const keyring = (yield this.getKeyringForAccount(address));
756
+ if (!keyring.signPersonalMessage) {
757
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignPersonalMessage);
758
+ }
759
+ const normalizedData = (0, eth_sig_util_1.normalize)(messageParams.data);
760
+ return yield keyring.signPersonalMessage(address, normalizedData);
761
+ });
544
762
  }
545
763
  /**
546
764
  * Signs typed message by calling down into a specific keyring.
@@ -560,13 +778,17 @@ class KeyringController extends base_controller_1.BaseController {
560
778
  ].includes(version)) {
561
779
  throw new Error(`Unexpected signTypedMessage version: '${version}'`);
562
780
  }
563
- return yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").signTypedMessage({
564
- from: messageParams.from,
565
- data: version !== SignTypedDataVersion.V1 &&
566
- typeof messageParams.data === 'string'
567
- ? JSON.parse(messageParams.data)
568
- : messageParams.data,
569
- }, { version });
781
+ // Cast to `Hex` here is safe here because `messageParams.from` is not nullish.
782
+ // `normalize` returns `Hex` unless given a nullish value.
783
+ const address = (0, eth_sig_util_1.normalize)(messageParams.from);
784
+ const keyring = (yield this.getKeyringForAccount(address));
785
+ if (!keyring.signTypedData) {
786
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignTypedMessage);
787
+ }
788
+ return yield keyring.signTypedData(address, version !== SignTypedDataVersion.V1 &&
789
+ typeof messageParams.data === 'string'
790
+ ? JSON.parse(messageParams.data)
791
+ : messageParams.data, { version });
570
792
  }
571
793
  catch (error) {
572
794
  throw new Error(`Keyring Controller signTypedMessage: ${error}`);
@@ -582,7 +804,66 @@ class KeyringController extends base_controller_1.BaseController {
582
804
  * @returns Promise resolving to a signed transaction string.
583
805
  */
584
806
  signTransaction(transaction, from, opts) {
585
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signTransaction(transaction, from, opts);
807
+ return __awaiter(this, void 0, void 0, function* () {
808
+ const address = (0, eth_sig_util_1.normalize)(from);
809
+ const keyring = (yield this.getKeyringForAccount(address));
810
+ if (!keyring.signTransaction) {
811
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignTransaction);
812
+ }
813
+ return yield keyring.signTransaction(address, transaction, opts);
814
+ });
815
+ }
816
+ /**
817
+ * Convert a base transaction to a base UserOperation.
818
+ *
819
+ * @param from - Address of the sender.
820
+ * @param transactions - Base transactions to include in the UserOperation.
821
+ * @returns A pseudo-UserOperation that can be used to construct a real.
822
+ */
823
+ prepareUserOperation(from, transactions) {
824
+ return __awaiter(this, void 0, void 0, function* () {
825
+ const address = (0, eth_sig_util_1.normalize)(from);
826
+ const keyring = (yield this.getKeyringForAccount(address));
827
+ if (!keyring.prepareUserOperation) {
828
+ throw new Error(constants_1.KeyringControllerError.UnsupportedPrepareUserOperation);
829
+ }
830
+ return yield keyring.prepareUserOperation(address, transactions);
831
+ });
832
+ }
833
+ /**
834
+ * Patches properties of a UserOperation. Currently, only the
835
+ * `paymasterAndData` can be patched.
836
+ *
837
+ * @param from - Address of the sender.
838
+ * @param userOp - UserOperation to patch.
839
+ * @returns A patch to apply to the UserOperation.
840
+ */
841
+ patchUserOperation(from, userOp) {
842
+ return __awaiter(this, void 0, void 0, function* () {
843
+ const address = (0, eth_sig_util_1.normalize)(from);
844
+ const keyring = (yield this.getKeyringForAccount(address));
845
+ if (!keyring.patchUserOperation) {
846
+ throw new Error(constants_1.KeyringControllerError.UnsupportedPatchUserOperation);
847
+ }
848
+ return yield keyring.patchUserOperation(address, userOp);
849
+ });
850
+ }
851
+ /**
852
+ * Signs an UserOperation.
853
+ *
854
+ * @param from - Address of the sender.
855
+ * @param userOp - UserOperation to sign.
856
+ * @returns The signature of the UserOperation.
857
+ */
858
+ signUserOperation(from, userOp) {
859
+ return __awaiter(this, void 0, void 0, function* () {
860
+ const address = (0, eth_sig_util_1.normalize)(from);
861
+ const keyring = (yield this.getKeyringForAccount(address));
862
+ if (!keyring.signUserOperation) {
863
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignUserOperation);
864
+ }
865
+ return yield keyring.signUserOperation(address, userOp);
866
+ });
586
867
  }
587
868
  /**
588
869
  * Attempts to decrypt the current vault and load its keyrings,
@@ -594,7 +875,8 @@ class KeyringController extends base_controller_1.BaseController {
594
875
  */
595
876
  submitEncryptionKey(encryptionKey, encryptionSalt) {
596
877
  return __awaiter(this, void 0, void 0, function* () {
597
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").submitEncryptionKey(encryptionKey, encryptionSalt);
878
+ __classPrivateFieldSet(this, _KeyringController_keyrings, yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_unlockKeyrings).call(this, undefined, encryptionKey, encryptionSalt), "f");
879
+ __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_setUnlocked).call(this);
598
880
  const qrKeyring = this.getQRKeyring();
599
881
  if (qrKeyring) {
600
882
  // if there is a QR keyring, we need to subscribe
@@ -613,15 +895,14 @@ class KeyringController extends base_controller_1.BaseController {
613
895
  */
614
896
  submitPassword(password) {
615
897
  return __awaiter(this, void 0, void 0, function* () {
616
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").submitPassword(password);
617
- const accounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
898
+ __classPrivateFieldSet(this, _KeyringController_keyrings, yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_unlockKeyrings).call(this, password), "f");
899
+ __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_setUnlocked).call(this);
618
900
  const qrKeyring = this.getQRKeyring();
619
901
  if (qrKeyring) {
620
902
  // if there is a QR keyring, we need to subscribe
621
903
  // to its events after unlocking the vault
622
904
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_subscribeToQRKeyringEvents).call(this, qrKeyring);
623
905
  }
624
- yield this.syncIdentities(accounts);
625
906
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
626
907
  });
627
908
  }
@@ -632,8 +913,7 @@ class KeyringController extends base_controller_1.BaseController {
632
913
  */
633
914
  verifySeedPhrase() {
634
915
  return __awaiter(this, void 0, void 0, function* () {
635
- const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(KeyringTypes.hd)[0];
636
- /* istanbul ignore if */
916
+ const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0];
637
917
  if (!primaryKeyring) {
638
918
  throw new Error('No HD keyring found.');
639
919
  }
@@ -646,11 +926,11 @@ class KeyringController extends base_controller_1.BaseController {
646
926
  }
647
927
  // The HD Keyring Builder is a default keyring builder
648
928
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
649
- const hdKeyringBuilder = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringBuilderForType(KeyringTypes.hd);
929
+ const hdKeyringBuilder = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringBuilderForType).call(this, KeyringTypes.hd);
650
930
  const hdKeyring = hdKeyringBuilder();
651
931
  // @ts-expect-error @metamask/eth-hd-keyring correctly handles
652
932
  // Uint8Array seed phrases in the `deserialize` method.
653
- hdKeyring.deserialize({
933
+ yield hdKeyring.deserialize({
654
934
  mnemonic: seedWords,
655
935
  numberOfAccounts: accounts.length,
656
936
  });
@@ -676,7 +956,7 @@ class KeyringController extends base_controller_1.BaseController {
676
956
  */
677
957
  getQRKeyring() {
678
958
  // QRKeyring is not yet compatible with Keyring type from @metamask/utils
679
- return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(KeyringTypes.qr)[0];
959
+ return this.getKeyringsByType(KeyringTypes.qr)[0];
680
960
  }
681
961
  /**
682
962
  * Get QR hardware keyring. If it doesn't exist, add it.
@@ -693,8 +973,7 @@ class KeyringController extends base_controller_1.BaseController {
693
973
  restoreQRKeyring(serialized) {
694
974
  return __awaiter(this, void 0, void 0, function* () {
695
975
  (yield this.getOrAddQRKeyring()).deserialize(serialized);
696
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
697
- this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
976
+ yield this.persistAllKeyrings();
698
977
  });
699
978
  }
700
979
  resetQRKeyringState() {
@@ -768,45 +1047,34 @@ class KeyringController extends base_controller_1.BaseController {
768
1047
  return __awaiter(this, void 0, void 0, function* () {
769
1048
  const keyring = yield this.getOrAddQRKeyring();
770
1049
  keyring.setAccountToUnlock(index);
771
- const oldAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
772
1050
  // QRKeyring is not yet compatible with Keyring from
773
1051
  // @metamask/utils, but we can use the `addNewAccount` method
774
1052
  // as it internally calls `addAccounts` from on the keyring instance,
775
1053
  // which is supported by QRKeyring API.
776
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(keyring);
777
- const newAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
778
- this.updateIdentities(newAccounts);
779
- newAccounts.forEach((address) => {
780
- if (!oldAccounts.includes(address)) {
781
- if (this.setAccountLabel) {
782
- this.setAccountLabel(address, `${keyring.getName()} ${index}`);
783
- }
784
- this.setSelectedAddress(address);
785
- }
786
- });
787
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
1054
+ yield this.addNewAccountForKeyring(keyring);
1055
+ yield this.persistAllKeyrings();
788
1056
  });
789
1057
  }
790
1058
  getAccountKeyringType(account) {
791
1059
  return __awaiter(this, void 0, void 0, function* () {
792
- return (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringForAccount(account)).type;
1060
+ const keyring = (yield this.getKeyringForAccount(account));
1061
+ return keyring.type;
793
1062
  });
794
1063
  }
795
1064
  forgetQRDevice() {
796
1065
  return __awaiter(this, void 0, void 0, function* () {
797
1066
  const keyring = yield this.getOrAddQRKeyring();
798
- const allAccounts = (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
1067
+ const allAccounts = (yield this.getAccounts());
799
1068
  keyring.forgetDevice();
800
- const remainingAccounts = (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
1069
+ const remainingAccounts = (yield this.getAccounts());
801
1070
  const removedAccounts = allAccounts.filter((address) => !remainingAccounts.includes(address));
802
- this.updateIdentities(remainingAccounts);
803
- yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
1071
+ yield this.persistAllKeyrings();
804
1072
  return { removedAccounts, remainingAccounts };
805
1073
  });
806
1074
  }
807
1075
  }
808
1076
  exports.KeyringController = KeyringController;
809
- _KeyringController_keyring = new WeakMap(), _KeyringController_qrKeyringStateListener = new WeakMap(), _KeyringController_instances = new WeakSet(), _KeyringController_registerMessageHandlers = function _KeyringController_registerMessageHandlers() {
1077
+ _KeyringController_keyringBuilders = new WeakMap(), _KeyringController_keyrings = new WeakMap(), _KeyringController_unsupportedKeyrings = new WeakMap(), _KeyringController_password = new WeakMap(), _KeyringController_encryptor = new WeakMap(), _KeyringController_cacheEncryptionKey = new WeakMap(), _KeyringController_qrKeyringStateListener = new WeakMap(), _KeyringController_instances = new WeakSet(), _KeyringController_registerMessageHandlers = function _KeyringController_registerMessageHandlers() {
810
1078
  this.messagingSystem.registerActionHandler(`${name}:signMessage`, this.signMessage.bind(this));
811
1079
  this.messagingSystem.registerActionHandler(`${name}:signPersonalMessage`, this.signPersonalMessage.bind(this));
812
1080
  this.messagingSystem.registerActionHandler(`${name}:signTypedMessage`, this.signTypedMessage.bind(this));
@@ -816,10 +1084,21 @@ _KeyringController_keyring = new WeakMap(), _KeyringController_qrKeyringStateLis
816
1084
  this.messagingSystem.registerActionHandler(`${name}:getKeyringsByType`, this.getKeyringsByType.bind(this));
817
1085
  this.messagingSystem.registerActionHandler(`${name}:getKeyringForAccount`, this.getKeyringForAccount.bind(this));
818
1086
  this.messagingSystem.registerActionHandler(`${name}:persistAllKeyrings`, this.persistAllKeyrings.bind(this));
1087
+ this.messagingSystem.registerActionHandler(`${name}:prepareUserOperation`, this.prepareUserOperation.bind(this));
1088
+ this.messagingSystem.registerActionHandler(`${name}:patchUserOperation`, this.patchUserOperation.bind(this));
1089
+ this.messagingSystem.registerActionHandler(`${name}:signUserOperation`, this.signUserOperation.bind(this));
1090
+ }, _KeyringController_getKeyringBuilderForType = function _KeyringController_getKeyringBuilderForType(type) {
1091
+ return __classPrivateFieldGet(this, _KeyringController_keyringBuilders, "f").find((keyringBuilder) => keyringBuilder.type === type);
819
1092
  }, _KeyringController_addQRKeyring = function _KeyringController_addQRKeyring() {
820
1093
  return __awaiter(this, void 0, void 0, function* () {
821
1094
  // QRKeyring is not yet compatible with Keyring type from @metamask/utils
822
- const qrKeyring = (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(KeyringTypes.qr));
1095
+ const qrKeyring = (yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_newKeyring).call(this, KeyringTypes.qr, {
1096
+ accounts: [],
1097
+ }));
1098
+ const accounts = yield qrKeyring.getAccounts();
1099
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_checkForDuplicate).call(this, KeyringTypes.qr, accounts);
1100
+ __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(qrKeyring);
1101
+ yield this.persistAllKeyrings();
823
1102
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_subscribeToQRKeyringEvents).call(this, qrKeyring);
824
1103
  return qrKeyring;
825
1104
  });
@@ -829,25 +1108,182 @@ _KeyringController_keyring = new WeakMap(), _KeyringController_qrKeyringStateLis
829
1108
  }, "f");
830
1109
  qrKeyring.getMemStore().subscribe(__classPrivateFieldGet(this, _KeyringController_qrKeyringStateListener, "f"));
831
1110
  }, _KeyringController_unsubscribeFromQRKeyringsEvents = function _KeyringController_unsubscribeFromQRKeyringsEvents() {
832
- const qrKeyrings = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(KeyringTypes.qr);
1111
+ const qrKeyrings = this.getKeyringsByType(KeyringTypes.qr);
833
1112
  qrKeyrings.forEach((qrKeyring) => {
834
1113
  if (__classPrivateFieldGet(this, _KeyringController_qrKeyringStateListener, "f")) {
835
1114
  qrKeyring.getMemStore().unsubscribe(__classPrivateFieldGet(this, _KeyringController_qrKeyringStateListener, "f"));
836
1115
  }
837
1116
  });
838
- }, _KeyringController_fullUpdate = function _KeyringController_fullUpdate() {
839
- const { vault } = __classPrivateFieldGet(this, _KeyringController_keyring, "f").store.getState();
840
- const { keyrings, isUnlocked, encryptionKey, encryptionSalt } = __classPrivateFieldGet(this, _KeyringController_keyring, "f").memStore.getState();
841
- this.update(() => ({
842
- vault,
843
- keyrings,
844
- isUnlocked,
845
- encryptionKey,
846
- encryptionSalt,
847
- }));
848
- }, _KeyringController_handleLock = function _KeyringController_handleLock() {
849
- this.messagingSystem.publish(`${name}:lock`);
850
- }, _KeyringController_handleUnlock = function _KeyringController_handleUnlock() {
1117
+ }, _KeyringController_createNewVaultWithKeyring = function _KeyringController_createNewVaultWithKeyring(password, keyring) {
1118
+ return __awaiter(this, void 0, void 0, function* () {
1119
+ if (typeof password !== 'string') {
1120
+ throw new TypeError(constants_1.KeyringControllerError.WrongPasswordType);
1121
+ }
1122
+ __classPrivateFieldSet(this, _KeyringController_password, password, "f");
1123
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_clearKeyrings).call(this);
1124
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createKeyringWithFirstAccount).call(this, keyring.type, keyring.opts);
1125
+ __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_setUnlocked).call(this);
1126
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
1127
+ });
1128
+ }, _KeyringController_updateKeyringsInState = function _KeyringController_updateKeyringsInState() {
1129
+ return __awaiter(this, void 0, void 0, function* () {
1130
+ const keyrings = yield Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map(displayForKeyring));
1131
+ this.update((state) => {
1132
+ state.keyrings = keyrings;
1133
+ });
1134
+ });
1135
+ }, _KeyringController_unlockKeyrings = function _KeyringController_unlockKeyrings(password, encryptionKey, encryptionSalt) {
1136
+ return __awaiter(this, void 0, void 0, function* () {
1137
+ const encryptedVault = this.state.vault;
1138
+ if (!encryptedVault) {
1139
+ throw new Error(constants_1.KeyringControllerError.VaultError);
1140
+ }
1141
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_clearKeyrings).call(this);
1142
+ let vault;
1143
+ if (__classPrivateFieldGet(this, _KeyringController_cacheEncryptionKey, "f")) {
1144
+ assertIsExportableKeyEncryptor(__classPrivateFieldGet(this, _KeyringController_encryptor, "f"));
1145
+ if (password) {
1146
+ const result = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").decryptWithDetail(password, encryptedVault);
1147
+ vault = result.vault;
1148
+ __classPrivateFieldSet(this, _KeyringController_password, password, "f");
1149
+ this.update((state) => {
1150
+ state.encryptionKey = result.exportedKeyString;
1151
+ state.encryptionSalt = result.salt;
1152
+ });
1153
+ }
1154
+ else {
1155
+ const parsedEncryptedVault = JSON.parse(encryptedVault);
1156
+ if (encryptionSalt !== parsedEncryptedVault.salt) {
1157
+ throw new Error(constants_1.KeyringControllerError.ExpiredCredentials);
1158
+ }
1159
+ if (typeof encryptionKey !== 'string') {
1160
+ throw new TypeError(constants_1.KeyringControllerError.WrongPasswordType);
1161
+ }
1162
+ const key = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").importKey(encryptionKey);
1163
+ vault = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").decryptWithKey(key, parsedEncryptedVault);
1164
+ // This call is required on the first call because encryptionKey
1165
+ // is not yet inside the memStore
1166
+ this.update((state) => {
1167
+ state.encryptionKey = encryptionKey;
1168
+ // we can safely assume that encryptionSalt is defined here
1169
+ // because we compare it with the salt from the vault
1170
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1171
+ state.encryptionSalt = encryptionSalt;
1172
+ });
1173
+ }
1174
+ }
1175
+ else {
1176
+ if (typeof password !== 'string') {
1177
+ throw new TypeError(constants_1.KeyringControllerError.WrongPasswordType);
1178
+ }
1179
+ vault = yield __classPrivateFieldGet(this, _KeyringController_encryptor, "f").decrypt(password, encryptedVault);
1180
+ __classPrivateFieldSet(this, _KeyringController_password, password, "f");
1181
+ }
1182
+ if (!isSerializedKeyringsArray(vault)) {
1183
+ throw new Error(constants_1.KeyringControllerError.VaultDataError);
1184
+ }
1185
+ yield Promise.all(vault.map(__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_restoreKeyring).bind(this)));
1186
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_updateKeyringsInState).call(this);
1187
+ if (__classPrivateFieldGet(this, _KeyringController_password, "f") &&
1188
+ (!__classPrivateFieldGet(this, _KeyringController_cacheEncryptionKey, "f") || !encryptionKey) &&
1189
+ __classPrivateFieldGet(this, _KeyringController_encryptor, "f").isVaultUpdated &&
1190
+ !__classPrivateFieldGet(this, _KeyringController_encryptor, "f").isVaultUpdated(encryptedVault)) {
1191
+ // Re-encrypt the vault with safer method if one is available
1192
+ yield this.persistAllKeyrings();
1193
+ }
1194
+ return __classPrivateFieldGet(this, _KeyringController_keyrings, "f");
1195
+ });
1196
+ }, _KeyringController_createKeyringWithFirstAccount = function _KeyringController_createKeyringWithFirstAccount(type, opts) {
1197
+ return __awaiter(this, void 0, void 0, function* () {
1198
+ const keyring = (yield this.addNewKeyring(type, opts));
1199
+ const [firstAccount] = yield keyring.getAccounts();
1200
+ if (!firstAccount) {
1201
+ throw new Error(constants_1.KeyringControllerError.NoFirstAccount);
1202
+ }
1203
+ });
1204
+ }, _KeyringController_newKeyring = function _KeyringController_newKeyring(type, data) {
1205
+ return __awaiter(this, void 0, void 0, function* () {
1206
+ const keyringBuilder = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringBuilderForType).call(this, type);
1207
+ if (!keyringBuilder) {
1208
+ throw new Error(`${constants_1.KeyringControllerError.NoKeyringBuilder}. Keyring type: ${type}`);
1209
+ }
1210
+ const keyring = keyringBuilder();
1211
+ // @ts-expect-error Enforce data type after updating clients
1212
+ yield keyring.deserialize(data);
1213
+ if (keyring.init) {
1214
+ yield keyring.init();
1215
+ }
1216
+ return keyring;
1217
+ });
1218
+ }, _KeyringController_clearKeyrings = function _KeyringController_clearKeyrings() {
1219
+ return __awaiter(this, void 0, void 0, function* () {
1220
+ for (const keyring of __classPrivateFieldGet(this, _KeyringController_keyrings, "f")) {
1221
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_destroyKeyring).call(this, keyring);
1222
+ }
1223
+ __classPrivateFieldSet(this, _KeyringController_keyrings, [], "f");
1224
+ this.update((state) => {
1225
+ state.keyrings = [];
1226
+ });
1227
+ });
1228
+ }, _KeyringController_restoreKeyring = function _KeyringController_restoreKeyring(serialized) {
1229
+ return __awaiter(this, void 0, void 0, function* () {
1230
+ try {
1231
+ const { type, data } = serialized;
1232
+ const keyring = yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_newKeyring).call(this, type, data);
1233
+ // getAccounts also validates the accounts for some keyrings
1234
+ yield keyring.getAccounts();
1235
+ __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(keyring);
1236
+ return keyring;
1237
+ }
1238
+ catch (_) {
1239
+ __classPrivateFieldGet(this, _KeyringController_unsupportedKeyrings, "f").push(serialized);
1240
+ return undefined;
1241
+ }
1242
+ });
1243
+ }, _KeyringController_destroyKeyring = function _KeyringController_destroyKeyring(keyring) {
1244
+ var _a;
1245
+ return __awaiter(this, void 0, void 0, function* () {
1246
+ yield ((_a = keyring.destroy) === null || _a === void 0 ? void 0 : _a.call(keyring));
1247
+ });
1248
+ }, _KeyringController_removeEmptyKeyrings = function _KeyringController_removeEmptyKeyrings() {
1249
+ return __awaiter(this, void 0, void 0, function* () {
1250
+ const validKeyrings = [];
1251
+ // Since getAccounts returns a Promise
1252
+ // We need to wait to hear back form each keyring
1253
+ // in order to decide which ones are now valid (accounts.length > 0)
1254
+ yield Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map((keyring) => __awaiter(this, void 0, void 0, function* () {
1255
+ const accounts = yield keyring.getAccounts();
1256
+ if (accounts.length > 0) {
1257
+ validKeyrings.push(keyring);
1258
+ }
1259
+ else {
1260
+ yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_destroyKeyring).call(this, keyring);
1261
+ }
1262
+ })));
1263
+ __classPrivateFieldSet(this, _KeyringController_keyrings, validKeyrings, "f");
1264
+ });
1265
+ }, _KeyringController_checkForDuplicate = function _KeyringController_checkForDuplicate(type, newAccountArray) {
1266
+ return __awaiter(this, void 0, void 0, function* () {
1267
+ const accounts = yield this.getAccounts();
1268
+ switch (type) {
1269
+ case KeyringTypes.simple: {
1270
+ const isIncluded = Boolean(accounts.find((key) => newAccountArray[0] &&
1271
+ (key === newAccountArray[0] ||
1272
+ key === (0, utils_1.remove0x)(newAccountArray[0]))));
1273
+ if (isIncluded) {
1274
+ throw new Error(constants_1.KeyringControllerError.DuplicatedAccount);
1275
+ }
1276
+ return newAccountArray;
1277
+ }
1278
+ default: {
1279
+ return newAccountArray;
1280
+ }
1281
+ }
1282
+ });
1283
+ }, _KeyringController_setUnlocked = function _KeyringController_setUnlocked() {
1284
+ this.update((state) => {
1285
+ state.isUnlocked = true;
1286
+ });
851
1287
  this.messagingSystem.publish(`${name}:unlock`);
852
1288
  }, _KeyringController_getMemState = function _KeyringController_getMemState() {
853
1289
  return {