@metamask-previews/keyring-controller 19.1.0-preview-52c28555 → 19.2.0-preview-37b05a4

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,10 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+
12
+ - Bump `@metamask/keyring-internal-api` from `^4.0.1` to `^4.0.2` ([#5356](https://github.com/MetaMask/core/pull/5356))
13
+
14
+ ## [19.2.0]
15
+
10
16
  ### Added
11
17
 
18
+ - Add `signEip7702Authorization` to `KeyringController` ([#5301](https://github.com/MetaMask/core/pull/5301))
12
19
  - Add `KeyringController:withKeyring` action ([#5332](https://github.com/MetaMask/core/pull/5332))
13
20
  - The action can be used to consume the `withKeyring` method of the `KeyringController` class
21
+ - Support keyring metadata in KeyringController ([#5112](https://github.com/MetaMask/core/pull/5112))
14
22
 
15
23
  ## [19.1.0]
16
24
 
@@ -675,7 +683,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
675
683
 
676
684
  All changes listed after this point were applied to this package following the monorepo conversion.
677
685
 
678
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.1.0...HEAD
686
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.2.0...HEAD
687
+ [19.2.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.1.0...@metamask/keyring-controller@19.2.0
679
688
  [19.1.0]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.0.7...@metamask/keyring-controller@19.1.0
680
689
  [19.0.7]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.0.6...@metamask/keyring-controller@19.0.7
681
690
  [19.0.6]: https://github.com/MetaMask/core/compare/@metamask/keyring-controller@19.0.5...@metamask/keyring-controller@19.0.6
@@ -36,7 +36,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
36
36
  var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
38
38
  };
39
- var _KeyringController_instances, _KeyringController_controllerOperationMutex, _KeyringController_vaultOperationMutex, _KeyringController_keyringBuilders, _KeyringController_unsupportedKeyrings, _KeyringController_encryptor, _KeyringController_cacheEncryptionKey, _KeyringController_keyrings, _KeyringController_password, _KeyringController_qrKeyringStateListener, _KeyringController_registerMessageHandlers, _KeyringController_getKeyringBuilderForType, _KeyringController_addQRKeyring, _KeyringController_subscribeToQRKeyringEvents, _KeyringController_unsubscribeFromQRKeyringsEvents, _KeyringController_createNewVaultWithKeyring, _KeyringController_verifySeedPhrase, _KeyringController_getUpdatedKeyrings, _KeyringController_getSerializedKeyrings, _KeyringController_restoreSerializedKeyrings, _KeyringController_unlockKeyrings, _KeyringController_updateVault, _KeyringController_getAccountsFromKeyrings, _KeyringController_createKeyringWithFirstAccount, _KeyringController_newKeyring, _KeyringController_clearKeyrings, _KeyringController_restoreKeyring, _KeyringController_destroyKeyring, _KeyringController_removeEmptyKeyrings, _KeyringController_checkForDuplicate, _KeyringController_setUnlocked, _KeyringController_assertIsUnlocked, _KeyringController_persistOrRollback, _KeyringController_withRollback, _KeyringController_assertControllerMutexIsLocked, _KeyringController_withControllerLock, _KeyringController_withVaultLock;
39
+ var _KeyringController_instances, _KeyringController_controllerOperationMutex, _KeyringController_vaultOperationMutex, _KeyringController_keyringBuilders, _KeyringController_unsupportedKeyrings, _KeyringController_encryptor, _KeyringController_cacheEncryptionKey, _KeyringController_keyrings, _KeyringController_keyringsMetadata, _KeyringController_password, _KeyringController_qrKeyringStateListener, _KeyringController_registerMessageHandlers, _KeyringController_getKeyringById, _KeyringController_getKeyringByIdOrDefault, _KeyringController_getKeyringBuilderForType, _KeyringController_addQRKeyring, _KeyringController_subscribeToQRKeyringEvents, _KeyringController_unsubscribeFromQRKeyringsEvents, _KeyringController_createNewVaultWithKeyring, _KeyringController_verifySeedPhrase, _KeyringController_getUpdatedKeyrings, _KeyringController_getSerializedKeyrings, _KeyringController_restoreSerializedKeyrings, _KeyringController_unlockKeyrings, _KeyringController_updateVault, _KeyringController_getAccountsFromKeyrings, _KeyringController_createKeyringWithFirstAccount, _KeyringController_newKeyring, _KeyringController_createKeyring, _KeyringController_clearKeyrings, _KeyringController_restoreKeyring, _KeyringController_destroyKeyring, _KeyringController_removeEmptyKeyrings, _KeyringController_checkForDuplicate, _KeyringController_setUnlocked, _KeyringController_assertIsUnlocked, _KeyringController_persistOrRollback, _KeyringController_withRollback, _KeyringController_assertControllerMutexIsLocked, _KeyringController_withControllerLock, _KeyringController_withVaultLock;
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.KeyringController = exports.getDefaultKeyringState = exports.keyringBuilderFactory = exports.SignTypedDataVersion = exports.AccountImportStrategy = exports.isCustodyKeyring = exports.KeyringTypes = void 0;
42
42
  const util_1 = require("@ethereumjs/util");
@@ -48,6 +48,8 @@ const eth_simple_keyring_1 = __importDefault(require("@metamask/eth-simple-keyri
48
48
  const utils_1 = require("@metamask/utils");
49
49
  const async_mutex_1 = require("async-mutex");
50
50
  const ethereumjs_wallet_1 = __importStar(require("ethereumjs-wallet"));
51
+ // When generating a ULID within the same millisecond, monotonicFactory provides some guarantees regarding sort order.
52
+ const ulid_1 = require("ulid");
51
53
  const constants_1 = require("./constants.cjs");
52
54
  const name = 'KeyringController';
53
55
  /**
@@ -109,13 +111,17 @@ function keyringBuilderFactory(KeyringConstructor) {
109
111
  }
110
112
  exports.keyringBuilderFactory = keyringBuilderFactory;
111
113
  const defaultKeyringBuilders = [
114
+ // todo: keyring types are mismatched, this should be fixed in they keyrings themselves
115
+ // @ts-expect-error keyring types are mismatched
112
116
  keyringBuilderFactory(eth_simple_keyring_1.default),
117
+ // @ts-expect-error keyring types are mismatched
113
118
  keyringBuilderFactory(eth_hd_keyring_1.default),
114
119
  ];
115
120
  const getDefaultKeyringState = () => {
116
121
  return {
117
122
  isUnlocked: false,
118
123
  keyrings: [],
124
+ keyringsMetadata: [],
119
125
  };
120
126
  };
121
127
  exports.getDefaultKeyringState = getDefaultKeyringState;
@@ -247,6 +253,7 @@ class KeyringController extends base_controller_1.BaseController {
247
253
  vault: { persist: true, anonymous: false },
248
254
  isUnlocked: { persist: false, anonymous: true },
249
255
  keyrings: { persist: false, anonymous: false },
256
+ keyringsMetadata: { persist: true, anonymous: false },
250
257
  encryptionKey: { persist: false, anonymous: false },
251
258
  encryptionSalt: { persist: false, anonymous: false },
252
259
  },
@@ -264,6 +271,7 @@ class KeyringController extends base_controller_1.BaseController {
264
271
  _KeyringController_encryptor.set(this, void 0);
265
272
  _KeyringController_cacheEncryptionKey.set(this, void 0);
266
273
  _KeyringController_keyrings.set(this, void 0);
274
+ _KeyringController_keyringsMetadata.set(this, void 0);
267
275
  _KeyringController_password.set(this, void 0);
268
276
  _KeyringController_qrKeyringStateListener.set(this, void 0);
269
277
  __classPrivateFieldSet(this, _KeyringController_keyringBuilders, keyringBuilders
@@ -271,6 +279,7 @@ class KeyringController extends base_controller_1.BaseController {
271
279
  : defaultKeyringBuilders, "f");
272
280
  __classPrivateFieldSet(this, _KeyringController_encryptor, encryptor, "f");
273
281
  __classPrivateFieldSet(this, _KeyringController_keyrings, [], "f");
282
+ __classPrivateFieldSet(this, _KeyringController_keyringsMetadata, state?.keyringsMetadata ?? [], "f");
274
283
  __classPrivateFieldSet(this, _KeyringController_unsupportedKeyrings, [], "f");
275
284
  // This option allows the controller to cache an exported key
276
285
  // for use in decrypting and encrypting data without password
@@ -419,13 +428,18 @@ class KeyringController extends base_controller_1.BaseController {
419
428
  * Gets the seed phrase of the HD keyring.
420
429
  *
421
430
  * @param password - Password of the keyring.
431
+ * @param keyringId - The id of the keyring.
422
432
  * @returns Promise resolving to the seed phrase.
423
433
  */
424
- async exportSeedPhrase(password) {
434
+ async exportSeedPhrase(password, keyringId) {
425
435
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertIsUnlocked).call(this);
426
436
  await this.verifyPassword(password);
427
- assertHasUint8ArrayMnemonic(__classPrivateFieldGet(this, _KeyringController_keyrings, "f")[0]);
428
- return __classPrivateFieldGet(this, _KeyringController_keyrings, "f")[0].mnemonic;
437
+ const selectedKeyring = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringByIdOrDefault).call(this, keyringId);
438
+ if (!selectedKeyring) {
439
+ throw new Error('Keyring not found');
440
+ }
441
+ assertHasUint8ArrayMnemonic(selectedKeyring);
442
+ return selectedKeyring.mnemonic;
429
443
  }
430
444
  /**
431
445
  * Gets the private key from the keyring controlling an address.
@@ -610,6 +624,13 @@ class KeyringController extends base_controller_1.BaseController {
610
624
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertIsUnlocked).call(this);
611
625
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_persistOrRollback).call(this, async () => {
612
626
  const keyring = (await this.getKeyringForAccount(address));
627
+ const keyringIndex = this.state.keyrings.findIndex((kr) => kr.accounts.includes(address));
628
+ const isPrimaryKeyring = keyringIndex === 0;
629
+ const shouldRemoveKeyring = (await keyring.getAccounts()).length === 1;
630
+ // Primary keyring should never be removed, so we need to keep at least one account in it
631
+ if (isPrimaryKeyring && shouldRemoveKeyring) {
632
+ throw new Error(constants_1.KeyringControllerError.LastAccountInPrimaryKeyring);
633
+ }
613
634
  // Not all the keyrings support this, so we have to check
614
635
  if (!keyring.removeAccount) {
615
636
  throw new Error(constants_1.KeyringControllerError.UnsupportedRemoveAccount);
@@ -620,9 +641,7 @@ class KeyringController extends base_controller_1.BaseController {
620
641
  // because `Keyring<State>.removeAccount` requires address to be `Hex`. Those
621
642
  // type would need to be updated for a full non-EVM support.
622
643
  keyring.removeAccount(address);
623
- const accounts = await keyring.getAccounts();
624
- // Check if this was the last/only account
625
- if (accounts.length === 0) {
644
+ if (shouldRemoveKeyring) {
626
645
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_removeEmptyKeyrings).call(this);
627
646
  }
628
647
  });
@@ -666,6 +685,30 @@ class KeyringController extends base_controller_1.BaseController {
666
685
  }
667
686
  return await keyring.signMessage(address, messageParams.data);
668
687
  }
688
+ /**
689
+ * Signs EIP-7702 Authorization message by calling down into a specific keyring.
690
+ *
691
+ * @param params - EIP7702AuthorizationParams object to sign.
692
+ * @returns Promise resolving to an EIP-7702 Authorization signature.
693
+ * @throws Will throw UnsupportedSignEIP7702Authorization if the keyring does not support signing EIP-7702 Authorization messages.
694
+ */
695
+ async signEip7702Authorization(params) {
696
+ const from = (0, eth_sig_util_1.normalize)(params.from);
697
+ const keyring = (await this.getKeyringForAccount(from));
698
+ if (!keyring.signEip7702Authorization) {
699
+ throw new Error(constants_1.KeyringControllerError.UnsupportedSignEip7702Authorization);
700
+ }
701
+ const { chainId, nonce } = params;
702
+ const contractAddress = (0, eth_sig_util_1.normalize)(params.contractAddress);
703
+ if (contractAddress === undefined) {
704
+ throw new Error(constants_1.KeyringControllerError.MissingEip7702AuthorizationContractAddress);
705
+ }
706
+ return await keyring.signEip7702Authorization(from, [
707
+ chainId,
708
+ contractAddress,
709
+ nonce,
710
+ ]);
711
+ }
669
712
  /**
670
713
  * Signs personal message by calling down into a specific keyring.
671
714
  *
@@ -839,11 +882,12 @@ class KeyringController extends base_controller_1.BaseController {
839
882
  /**
840
883
  * Verifies the that the seed phrase restores the current keychain's accounts.
841
884
  *
885
+ * @param keyringId - The id of the keyring to verify.
842
886
  * @returns Promise resolving to the seed phrase as Uint8Array.
843
887
  */
844
- async verifySeedPhrase() {
888
+ async verifySeedPhrase(keyringId) {
845
889
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertIsUnlocked).call(this);
846
- return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_withControllerLock).call(this, async () => __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_verifySeedPhrase).call(this));
890
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_withControllerLock).call(this, async () => __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_verifySeedPhrase).call(this, keyringId));
847
891
  }
848
892
  async withKeyring(selector, operation, options = {
849
893
  createIfMissing: false,
@@ -854,12 +898,15 @@ class KeyringController extends base_controller_1.BaseController {
854
898
  if ('address' in selector) {
855
899
  keyring = (await this.getKeyringForAccount(selector.address));
856
900
  }
857
- else {
901
+ else if ('type' in selector) {
858
902
  keyring = this.getKeyringsByType(selector.type)[selector.index || 0];
859
903
  if (!keyring && options.createIfMissing) {
860
904
  keyring = (await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_newKeyring).call(this, selector.type, options.createWithData));
861
905
  }
862
906
  }
907
+ else if ('id' in selector) {
908
+ keyring = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringById).call(this, selector.id);
909
+ }
863
910
  if (!keyring) {
864
911
  throw new Error(constants_1.KeyringControllerError.KeyringNotFound);
865
912
  }
@@ -1073,8 +1120,9 @@ class KeyringController extends base_controller_1.BaseController {
1073
1120
  }
1074
1121
  }
1075
1122
  exports.KeyringController = KeyringController;
1076
- _KeyringController_controllerOperationMutex = new WeakMap(), _KeyringController_vaultOperationMutex = new WeakMap(), _KeyringController_keyringBuilders = new WeakMap(), _KeyringController_unsupportedKeyrings = new WeakMap(), _KeyringController_encryptor = new WeakMap(), _KeyringController_cacheEncryptionKey = new WeakMap(), _KeyringController_keyrings = new WeakMap(), _KeyringController_password = new WeakMap(), _KeyringController_qrKeyringStateListener = new WeakMap(), _KeyringController_instances = new WeakSet(), _KeyringController_registerMessageHandlers = function _KeyringController_registerMessageHandlers() {
1123
+ _KeyringController_controllerOperationMutex = new WeakMap(), _KeyringController_vaultOperationMutex = new WeakMap(), _KeyringController_keyringBuilders = new WeakMap(), _KeyringController_unsupportedKeyrings = new WeakMap(), _KeyringController_encryptor = new WeakMap(), _KeyringController_cacheEncryptionKey = new WeakMap(), _KeyringController_keyrings = new WeakMap(), _KeyringController_keyringsMetadata = new WeakMap(), _KeyringController_password = new WeakMap(), _KeyringController_qrKeyringStateListener = new WeakMap(), _KeyringController_instances = new WeakSet(), _KeyringController_registerMessageHandlers = function _KeyringController_registerMessageHandlers() {
1077
1124
  this.messagingSystem.registerActionHandler(`${name}:signMessage`, this.signMessage.bind(this));
1125
+ this.messagingSystem.registerActionHandler(`${name}:signEip7702Authorization`, this.signEip7702Authorization.bind(this));
1078
1126
  this.messagingSystem.registerActionHandler(`${name}:signPersonalMessage`, this.signPersonalMessage.bind(this));
1079
1127
  this.messagingSystem.registerActionHandler(`${name}:signTypedMessage`, this.signTypedMessage.bind(this));
1080
1128
  this.messagingSystem.registerActionHandler(`${name}:decryptMessage`, this.decryptMessage.bind(this));
@@ -1088,6 +1136,14 @@ _KeyringController_controllerOperationMutex = new WeakMap(), _KeyringController_
1088
1136
  this.messagingSystem.registerActionHandler(`${name}:signUserOperation`, this.signUserOperation.bind(this));
1089
1137
  this.messagingSystem.registerActionHandler(`${name}:addNewAccount`, this.addNewAccount.bind(this));
1090
1138
  this.messagingSystem.registerActionHandler(`${name}:withKeyring`, this.withKeyring.bind(this));
1139
+ }, _KeyringController_getKeyringById = function _KeyringController_getKeyringById(keyringId) {
1140
+ const index = this.state.keyringsMetadata.findIndex((metadata) => metadata.id === keyringId);
1141
+ return __classPrivateFieldGet(this, _KeyringController_keyrings, "f")[index];
1142
+ }, _KeyringController_getKeyringByIdOrDefault = function _KeyringController_getKeyringByIdOrDefault(keyringId) {
1143
+ if (!keyringId) {
1144
+ return __classPrivateFieldGet(this, _KeyringController_keyrings, "f")[0];
1145
+ }
1146
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringById).call(this, keyringId);
1091
1147
  }, _KeyringController_getKeyringBuilderForType = function _KeyringController_getKeyringBuilderForType(type) {
1092
1148
  return __classPrivateFieldGet(this, _KeyringController_keyringBuilders, "f").find((keyringBuilder) => keyringBuilder.type === type);
1093
1149
  }, _KeyringController_addQRKeyring =
@@ -1140,23 +1196,29 @@ async function _KeyringController_createNewVaultWithKeyring(password, keyring) {
1140
1196
  });
1141
1197
  __classPrivateFieldSet(this, _KeyringController_password, password, "f");
1142
1198
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_clearKeyrings).call(this);
1199
+ __classPrivateFieldSet(this, _KeyringController_keyringsMetadata, [], "f");
1143
1200
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createKeyringWithFirstAccount).call(this, keyring.type, keyring.opts);
1144
1201
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_setUnlocked).call(this);
1145
1202
  }, _KeyringController_verifySeedPhrase =
1146
1203
  /**
1147
1204
  * Internal non-exclusive method to verify the seed phrase.
1148
1205
  *
1206
+ * @param keyringId - The id of the keyring to verify the seed phrase for.
1149
1207
  * @returns A promise resolving to the seed phrase as Uint8Array.
1150
1208
  */
1151
- async function _KeyringController_verifySeedPhrase() {
1209
+ async function _KeyringController_verifySeedPhrase(keyringId) {
1152
1210
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertControllerMutexIsLocked).call(this);
1153
- const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0];
1154
- if (!primaryKeyring) {
1155
- throw new Error('No HD keyring found.');
1211
+ const keyring = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringByIdOrDefault).call(this, keyringId);
1212
+ if (!keyring) {
1213
+ throw new Error(constants_1.KeyringControllerError.KeyringNotFound);
1214
+ }
1215
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
1216
+ if (keyring.type !== KeyringTypes.hd) {
1217
+ throw new Error(constants_1.KeyringControllerError.UnsupportedVerifySeedPhrase);
1156
1218
  }
1157
- assertHasUint8ArrayMnemonic(primaryKeyring);
1158
- const seedWords = primaryKeyring.mnemonic;
1159
- const accounts = await primaryKeyring.getAccounts();
1219
+ assertHasUint8ArrayMnemonic(keyring);
1220
+ const seedWords = keyring.mnemonic;
1221
+ const accounts = await keyring.getAccounts();
1160
1222
  /* istanbul ignore if */
1161
1223
  if (accounts.length === 0) {
1162
1224
  throw new Error('Cannot verify an empty keyring.');
@@ -1336,9 +1398,13 @@ async function _KeyringController_unlockKeyrings(password, encryptionKey, encryp
1336
1398
  throw new Error(constants_1.KeyringControllerError.MissingVaultData);
1337
1399
  }
1338
1400
  const updatedKeyrings = await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getUpdatedKeyrings).call(this);
1401
+ if (updatedKeyrings.length !== __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").length) {
1402
+ throw new Error(constants_1.KeyringControllerError.KeyringMetadataLengthMismatch);
1403
+ }
1339
1404
  this.update((state) => {
1340
1405
  state.vault = updatedState.vault;
1341
1406
  state.keyrings = updatedKeyrings;
1407
+ state.keyringsMetadata = __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").slice();
1342
1408
  if (updatedState.encryptionKey) {
1343
1409
  state.encryptionKey = updatedState.encryptionKey;
1344
1410
  state.encryptionSalt = JSON.parse(updatedState.vault).salt;
@@ -1378,19 +1444,48 @@ async function _KeyringController_createKeyringWithFirstAccount(type, opts) {
1378
1444
  if (!firstAccount) {
1379
1445
  throw new Error(constants_1.KeyringControllerError.NoFirstAccount);
1380
1446
  }
1447
+ return firstAccount;
1381
1448
  }, _KeyringController_newKeyring =
1382
1449
  /**
1383
1450
  * Instantiate, initialize and return a new keyring of the given `type`,
1384
1451
  * using the given `opts`. The keyring is built using the keyring builder
1385
1452
  * registered for the given `type`.
1386
1453
  *
1454
+ * The internal keyring and keyring metadata arrays are updated with the new
1455
+ * keyring as well.
1387
1456
  *
1388
1457
  * @param type - The type of keyring to add.
1389
- * @param data - The data to restore a previously serialized keyring.
1458
+ * @param data - Keyring initialization options.
1390
1459
  * @returns The new keyring.
1391
1460
  * @throws If the keyring includes duplicated accounts.
1392
1461
  */
1393
1462
  async function _KeyringController_newKeyring(type, data) {
1463
+ const keyring = await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createKeyring).call(this, type, data);
1464
+ if (__classPrivateFieldGet(this, _KeyringController_keyrings, "f").length !== __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").length) {
1465
+ throw new Error('Keyring metadata missing');
1466
+ }
1467
+ __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(keyring);
1468
+ __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").push(getDefaultKeyringMetadata());
1469
+ return keyring;
1470
+ }, _KeyringController_createKeyring =
1471
+ /**
1472
+ * Instantiate, initialize and return a keyring of the given `type` using the
1473
+ * given `opts`. The keyring is built using the keyring builder registered
1474
+ * for the given `type`.
1475
+ *
1476
+ * The keyring might be new, or it might be restored from the vault. This
1477
+ * function should only be called from `#newKeyring` or `#restoreKeyring`,
1478
+ * for the "new" and "restore" cases respectively.
1479
+ *
1480
+ * The internal keyring and keyring metadata arrays are *not* updated, the
1481
+ * caller is expected to update them.
1482
+ *
1483
+ * @param type - The type of keyring to add.
1484
+ * @param data - Keyring initialization options.
1485
+ * @returns The new keyring.
1486
+ * @throws If the keyring includes duplicated accounts.
1487
+ */
1488
+ async function _KeyringController_createKeyring(type, data) {
1394
1489
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertControllerMutexIsLocked).call(this);
1395
1490
  const keyringBuilder = __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getKeyringBuilderForType).call(this, type);
1396
1491
  if (!keyringBuilder) {
@@ -1418,7 +1513,6 @@ async function _KeyringController_newKeyring(type, data) {
1418
1513
  // to its events after creating it
1419
1514
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_subscribeToQRKeyringEvents).call(this, keyring);
1420
1515
  }
1421
- __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(keyring);
1422
1516
  return keyring;
1423
1517
  }, _KeyringController_clearKeyrings =
1424
1518
  /**
@@ -1443,7 +1537,15 @@ async function _KeyringController_restoreKeyring(serialized) {
1443
1537
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertControllerMutexIsLocked).call(this);
1444
1538
  try {
1445
1539
  const { type, data } = serialized;
1446
- return await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_newKeyring).call(this, type, data);
1540
+ const keyring = await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_createKeyring).call(this, type, data);
1541
+ __classPrivateFieldGet(this, _KeyringController_keyrings, "f").push(keyring);
1542
+ // If metadata is missing, assume the data is from an installation before
1543
+ // we had keyring metadata.
1544
+ if (__classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").length < __classPrivateFieldGet(this, _KeyringController_keyrings, "f").length) {
1545
+ console.log(`Adding missing metadata for '${type}' keyring`);
1546
+ __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").push(getDefaultKeyringMetadata());
1547
+ }
1548
+ return keyring;
1447
1549
  }
1448
1550
  catch (_) {
1449
1551
  __classPrivateFieldGet(this, _KeyringController_unsupportedKeyrings, "f").push(serialized);
@@ -1471,19 +1573,22 @@ async function _KeyringController_destroyKeyring(keyring) {
1471
1573
  async function _KeyringController_removeEmptyKeyrings() {
1472
1574
  __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_assertControllerMutexIsLocked).call(this);
1473
1575
  const validKeyrings = [];
1576
+ const validKeyringMetadata = [];
1474
1577
  // Since getAccounts returns a Promise
1475
1578
  // We need to wait to hear back form each keyring
1476
1579
  // in order to decide which ones are now valid (accounts.length > 0)
1477
- await Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map(async (keyring) => {
1580
+ await Promise.all(__classPrivateFieldGet(this, _KeyringController_keyrings, "f").map(async (keyring, index) => {
1478
1581
  const accounts = await keyring.getAccounts();
1479
1582
  if (accounts.length > 0) {
1480
1583
  validKeyrings.push(keyring);
1584
+ validKeyringMetadata.push(__classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f")[index]);
1481
1585
  }
1482
1586
  else {
1483
1587
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_destroyKeyring).call(this, keyring);
1484
1588
  }
1485
1589
  }));
1486
1590
  __classPrivateFieldSet(this, _KeyringController_keyrings, validKeyrings, "f");
1591
+ __classPrivateFieldSet(this, _KeyringController_keyringsMetadata, validKeyringMetadata, "f");
1487
1592
  }, _KeyringController_checkForDuplicate =
1488
1593
  /**
1489
1594
  * Checks for duplicate keypairs, using the the first account in the given
@@ -1549,6 +1654,7 @@ async function _KeyringController_withRollback(callback) {
1549
1654
  return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_withControllerLock).call(this, async ({ releaseLock }) => {
1550
1655
  const currentSerializedKeyrings = await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getSerializedKeyrings).call(this);
1551
1656
  const currentPassword = __classPrivateFieldGet(this, _KeyringController_password, "f");
1657
+ const currentKeyringsMetadata = __classPrivateFieldGet(this, _KeyringController_keyringsMetadata, "f").slice();
1552
1658
  try {
1553
1659
  return await callback({ releaseLock });
1554
1660
  }
@@ -1556,6 +1662,7 @@ async function _KeyringController_withRollback(callback) {
1556
1662
  // Keyrings and password are restored to their previous state
1557
1663
  await __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_restoreSerializedKeyrings).call(this, currentSerializedKeyrings);
1558
1664
  __classPrivateFieldSet(this, _KeyringController_password, currentPassword, "f");
1665
+ __classPrivateFieldSet(this, _KeyringController_keyringsMetadata, currentKeyringsMetadata, "f");
1559
1666
  throw e;
1560
1667
  }
1561
1668
  });
@@ -1612,5 +1719,13 @@ async function withLock(mutex, callback) {
1612
1719
  releaseLock();
1613
1720
  }
1614
1721
  }
1722
+ /**
1723
+ * Generate a new keyring metadata object.
1724
+ *
1725
+ * @returns Keyring metadata.
1726
+ */
1727
+ function getDefaultKeyringMetadata() {
1728
+ return { id: (0, ulid_1.ulid)(), name: '' };
1729
+ }
1615
1730
  exports.default = KeyringController;
1616
1731
  //# sourceMappingURL=KeyringController.cjs.map