@metamask-previews/keyring-controller 13.0.0-preview.e5c396b → 14.0.1-preview-d4ae797

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.
@@ -0,0 +1,1290 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
+
3
+
4
+
5
+
6
+ var _chunkCHLPTPMZjs = require('./chunk-CHLPTPMZ.js');
7
+
8
+ // src/KeyringController.ts
9
+ var _util = require('@ethereumjs/util');
10
+ var _basecontroller = require('@metamask/base-controller');
11
+ var _browserpassworder = require('@metamask/browser-passworder'); var encryptorUtils = _interopRequireWildcard(_browserpassworder);
12
+ var _ethhdkeyring = require('@metamask/eth-hd-keyring'); var _ethhdkeyring2 = _interopRequireDefault(_ethhdkeyring);
13
+ var _ethsigutil = require('@metamask/eth-sig-util');
14
+ var _ethsimplekeyring = require('@metamask/eth-simple-keyring'); var _ethsimplekeyring2 = _interopRequireDefault(_ethsimplekeyring);
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+ var _utils = require('@metamask/utils');
25
+ var _asyncmutex = require('async-mutex');
26
+ var _ethereumjswallet = require('ethereumjs-wallet'); var _ethereumjswallet2 = _interopRequireDefault(_ethereumjswallet);
27
+ var name = "KeyringController";
28
+ var KeyringTypes = /* @__PURE__ */ ((KeyringTypes2) => {
29
+ KeyringTypes2["simple"] = "Simple Key Pair";
30
+ KeyringTypes2["hd"] = "HD Key Tree";
31
+ KeyringTypes2["qr"] = "QR Hardware Wallet Device";
32
+ KeyringTypes2["trezor"] = "Trezor Hardware";
33
+ KeyringTypes2["ledger"] = "Ledger Hardware";
34
+ KeyringTypes2["lattice"] = "Lattice Hardware";
35
+ KeyringTypes2["snap"] = "Snap Keyring";
36
+ return KeyringTypes2;
37
+ })(KeyringTypes || {});
38
+ var isCustodyKeyring = (keyringType) => {
39
+ return keyringType.startsWith("Custody");
40
+ };
41
+ var AccountImportStrategy = /* @__PURE__ */ ((AccountImportStrategy2) => {
42
+ AccountImportStrategy2["privateKey"] = "privateKey";
43
+ AccountImportStrategy2["json"] = "json";
44
+ return AccountImportStrategy2;
45
+ })(AccountImportStrategy || {});
46
+ var SignTypedDataVersion = /* @__PURE__ */ ((SignTypedDataVersion2) => {
47
+ SignTypedDataVersion2["V1"] = "V1";
48
+ SignTypedDataVersion2["V3"] = "V3";
49
+ SignTypedDataVersion2["V4"] = "V4";
50
+ return SignTypedDataVersion2;
51
+ })(SignTypedDataVersion || {});
52
+ function keyringBuilderFactory(KeyringConstructor) {
53
+ const builder = () => new KeyringConstructor();
54
+ builder.type = KeyringConstructor.type;
55
+ return builder;
56
+ }
57
+ var defaultKeyringBuilders = [
58
+ keyringBuilderFactory(_ethsimplekeyring2.default),
59
+ keyringBuilderFactory(_ethhdkeyring2.default)
60
+ ];
61
+ var getDefaultKeyringState = () => {
62
+ return {
63
+ isUnlocked: false,
64
+ keyrings: []
65
+ };
66
+ };
67
+ function assertHasUint8ArrayMnemonic(keyring) {
68
+ if (!(_utils.hasProperty.call(void 0, keyring, "mnemonic") && keyring.mnemonic instanceof Uint8Array)) {
69
+ throw new Error("Can't get mnemonic bytes from keyring");
70
+ }
71
+ }
72
+ function assertIsExportableKeyEncryptor(encryptor) {
73
+ if (!("importKey" in encryptor && typeof encryptor.importKey === "function" && "decryptWithKey" in encryptor && typeof encryptor.decryptWithKey === "function" && "encryptWithKey" in encryptor && typeof encryptor.encryptWithKey === "function")) {
74
+ throw new Error("KeyringController - The encryptor does not support encryption key export." /* UnsupportedEncryptionKeyExport */);
75
+ }
76
+ }
77
+ function isSerializedKeyringsArray(array) {
78
+ return typeof array === "object" && Array.isArray(array) && array.every((value) => value.type && _utils.isValidJson.call(void 0, value.data));
79
+ }
80
+ async function displayForKeyring(keyring) {
81
+ const accounts = await keyring.getAccounts();
82
+ return {
83
+ type: keyring.type,
84
+ // Cast to `Hex[]` here is safe here because `accounts` has no nullish
85
+ // values, and `normalize` returns `Hex` unless given a nullish value
86
+ accounts: accounts.map(_ethsigutil.normalize)
87
+ };
88
+ }
89
+ var _keyringBuilders, _keyrings, _unsupportedKeyrings, _password, _encryptor, _cacheEncryptionKey, _qrKeyringStateListener, _registerMessageHandlers, registerMessageHandlers_fn, _getKeyringBuilderForType, getKeyringBuilderForType_fn, _addQRKeyring, addQRKeyring_fn, _subscribeToQRKeyringEvents, subscribeToQRKeyringEvents_fn, _unsubscribeFromQRKeyringsEvents, unsubscribeFromQRKeyringsEvents_fn, _createNewVaultWithKeyring, createNewVaultWithKeyring_fn, _updateKeyringsInState, updateKeyringsInState_fn, _unlockKeyrings, unlockKeyrings_fn, _createKeyringWithFirstAccount, createKeyringWithFirstAccount_fn, _newKeyring, newKeyring_fn, _clearKeyrings, clearKeyrings_fn, _restoreKeyring, restoreKeyring_fn, _destroyKeyring, destroyKeyring_fn, _removeEmptyKeyrings, removeEmptyKeyrings_fn, _checkForDuplicate, checkForDuplicate_fn, _setUnlocked, setUnlocked_fn, _getMemState, getMemState_fn;
90
+ var KeyringController = class extends _basecontroller.BaseController {
91
+ /**
92
+ * Creates a KeyringController instance.
93
+ *
94
+ * @param options - Initial options used to configure this controller
95
+ * @param options.encryptor - An optional object for defining encryption schemes.
96
+ * @param options.keyringBuilders - Set a new name for account.
97
+ * @param options.cacheEncryptionKey - Whether to cache or not encryption key.
98
+ * @param options.messenger - A restricted controller messenger.
99
+ * @param options.state - Initial state to set on this controller.
100
+ */
101
+ constructor(options) {
102
+ const {
103
+ encryptor = encryptorUtils,
104
+ keyringBuilders,
105
+ messenger,
106
+ state
107
+ } = options;
108
+ super({
109
+ name,
110
+ metadata: {
111
+ vault: { persist: true, anonymous: false },
112
+ isUnlocked: { persist: false, anonymous: true },
113
+ keyrings: { persist: false, anonymous: false },
114
+ encryptionKey: { persist: false, anonymous: false },
115
+ encryptionSalt: { persist: false, anonymous: false }
116
+ },
117
+ messenger,
118
+ state: {
119
+ ...getDefaultKeyringState(),
120
+ ...state
121
+ }
122
+ });
123
+ /**
124
+ * Constructor helper for registering this controller's messaging system
125
+ * actions.
126
+ */
127
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _registerMessageHandlers);
128
+ /**
129
+ * Get the keyring builder for the given `type`.
130
+ *
131
+ * @param type - The type of keyring to get the builder for.
132
+ * @returns The keyring builder, or undefined if none exists.
133
+ */
134
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _getKeyringBuilderForType);
135
+ /**
136
+ * Add qr hardware keyring.
137
+ *
138
+ * @returns The added keyring
139
+ * @throws If a QRKeyring builder is not provided
140
+ * when initializing the controller
141
+ */
142
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _addQRKeyring);
143
+ /**
144
+ * Subscribe to a QRKeyring state change events and
145
+ * forward them through the messaging system.
146
+ *
147
+ * @param qrKeyring - The QRKeyring instance to subscribe to
148
+ */
149
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _subscribeToQRKeyringEvents);
150
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _unsubscribeFromQRKeyringsEvents);
151
+ /**
152
+ * Create new vault with an initial keyring
153
+ *
154
+ * Destroys any old encrypted storage,
155
+ * creates a new encrypted store with the given password,
156
+ * creates a new wallet with 1 account.
157
+ *
158
+ * @fires KeyringController:unlock
159
+ * @param password - The password to encrypt the vault with.
160
+ * @param keyring - A object containing the params to instantiate a new keyring.
161
+ * @param keyring.type - The keyring type.
162
+ * @param keyring.opts - Optional parameters required to instantiate the keyring.
163
+ * @returns A promise that resolves to the state.
164
+ */
165
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _createNewVaultWithKeyring);
166
+ /**
167
+ * Update the controller state with its current keyrings.
168
+ */
169
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _updateKeyringsInState);
170
+ /**
171
+ * Unlock Keyrings, decrypting the vault and deserializing all
172
+ * keyrings contained in it, using a password or an encryption key with salt.
173
+ *
174
+ * @param password - The keyring controller password.
175
+ * @param encryptionKey - An exported key string to unlock keyrings with.
176
+ * @param encryptionSalt - The salt used to encrypt the vault.
177
+ * @returns A promise resolving to the deserialized keyrings array.
178
+ */
179
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _unlockKeyrings);
180
+ /**
181
+ * Create a new keyring, ensuring that the first account is
182
+ * also created.
183
+ *
184
+ * @param type - Keyring type to instantiate.
185
+ * @param opts - Optional parameters required to instantiate the keyring.
186
+ * @returns A promise that resolves if the operation is successful.
187
+ */
188
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _createKeyringWithFirstAccount);
189
+ /**
190
+ * Instantiate, initialize and return a new keyring of the given `type`,
191
+ * using the given `opts`. The keyring is built using the keyring builder
192
+ * registered for the given `type`.
193
+ *
194
+ * @param type - The type of keyring to add.
195
+ * @param data - The data to restore a previously serialized keyring.
196
+ * @returns The new keyring.
197
+ */
198
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _newKeyring);
199
+ /**
200
+ * Remove all managed keyrings, destroying all their
201
+ * instances in memory.
202
+ */
203
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _clearKeyrings);
204
+ /**
205
+ * Restore a Keyring from a provided serialized payload.
206
+ * On success, returns the resulting keyring instance.
207
+ *
208
+ * @param serialized - The serialized keyring.
209
+ * @returns The deserialized keyring or undefined if the keyring type is unsupported.
210
+ */
211
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _restoreKeyring);
212
+ /**
213
+ * Destroy Keyring
214
+ *
215
+ * Some keyrings support a method called `destroy`, that destroys the
216
+ * keyring along with removing all its event listeners and, in some cases,
217
+ * clears the keyring bridge iframe from the DOM.
218
+ *
219
+ * @param keyring - The keyring to destroy.
220
+ */
221
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _destroyKeyring);
222
+ /**
223
+ * Remove empty keyrings.
224
+ *
225
+ * Loops through the keyrings and removes the ones with empty accounts
226
+ * (usually after removing the last / only account) from a keyring.
227
+ */
228
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _removeEmptyKeyrings);
229
+ /**
230
+ * Checks for duplicate keypairs, using the the first account in the given
231
+ * array. Rejects if a duplicate is found.
232
+ *
233
+ * Only supports 'Simple Key Pair'.
234
+ *
235
+ * @param type - The key pair type to check for.
236
+ * @param newAccountArray - Array of new accounts.
237
+ * @returns The account, if no duplicate is found.
238
+ */
239
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _checkForDuplicate);
240
+ /**
241
+ * Set the `isUnlocked` to true and notify listeners
242
+ * through the messenger.
243
+ *
244
+ * @fires KeyringController:unlock
245
+ */
246
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _setUnlocked);
247
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _getMemState);
248
+ this.mutex = new (0, _asyncmutex.Mutex)();
249
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _keyringBuilders, void 0);
250
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _keyrings, void 0);
251
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _unsupportedKeyrings, void 0);
252
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _password, void 0);
253
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _encryptor, void 0);
254
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _cacheEncryptionKey, void 0);
255
+ _chunkCHLPTPMZjs.__privateAdd.call(void 0, this, _qrKeyringStateListener, void 0);
256
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyringBuilders, keyringBuilders ? defaultKeyringBuilders.concat(keyringBuilders) : defaultKeyringBuilders);
257
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _encryptor, encryptor);
258
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyrings, []);
259
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _unsupportedKeyrings, []);
260
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _cacheEncryptionKey, Boolean(options.cacheEncryptionKey));
261
+ if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
262
+ assertIsExportableKeyEncryptor(encryptor);
263
+ }
264
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
265
+ }
266
+ /**
267
+ * Adds a new account to the default (first) HD seed phrase keyring.
268
+ *
269
+ * @param accountCount - Number of accounts before adding a new one, used to
270
+ * make the method idempotent.
271
+ * @returns Promise resolving to keyring current state and added account
272
+ * address.
273
+ */
274
+ async addNewAccount(accountCount) {
275
+ const primaryKeyring = this.getKeyringsByType("HD Key Tree")[0];
276
+ if (!primaryKeyring) {
277
+ throw new Error("No HD keyring found");
278
+ }
279
+ const oldAccounts = await this.getAccounts();
280
+ if (accountCount && oldAccounts.length !== accountCount) {
281
+ if (accountCount > oldAccounts.length) {
282
+ throw new Error("Account out of sequence");
283
+ }
284
+ const primaryKeyringAccounts = await primaryKeyring.getAccounts();
285
+ return {
286
+ keyringState: _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this),
287
+ addedAccountAddress: primaryKeyringAccounts[accountCount]
288
+ };
289
+ }
290
+ const addedAccountAddress = await this.addNewAccountForKeyring(
291
+ primaryKeyring
292
+ );
293
+ await this.verifySeedPhrase();
294
+ return {
295
+ keyringState: _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this),
296
+ addedAccountAddress
297
+ };
298
+ }
299
+ /**
300
+ * Adds a new account to the specified keyring.
301
+ *
302
+ * @param keyring - Keyring to add the account to.
303
+ * @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.
304
+ * @returns Promise resolving to keyring current state and added account
305
+ */
306
+ async addNewAccountForKeyring(keyring, accountCount) {
307
+ const oldAccounts = await this.getAccounts();
308
+ if (accountCount && oldAccounts.length !== accountCount) {
309
+ if (accountCount > oldAccounts.length) {
310
+ throw new Error("Account out of sequence");
311
+ }
312
+ const existingAccount = oldAccounts[accountCount];
313
+ _utils.assertIsStrictHexString.call(void 0, existingAccount);
314
+ return existingAccount;
315
+ }
316
+ await keyring.addAccounts(1);
317
+ await this.persistAllKeyrings();
318
+ const addedAccountAddress = (await this.getAccounts()).find(
319
+ (selectedAddress) => !oldAccounts.includes(selectedAddress)
320
+ );
321
+ _utils.assertIsStrictHexString.call(void 0, addedAccountAddress);
322
+ return addedAccountAddress;
323
+ }
324
+ /**
325
+ * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences.
326
+ *
327
+ * @returns Promise resolving to current state when the account is added.
328
+ */
329
+ async addNewAccountWithoutUpdate() {
330
+ const primaryKeyring = this.getKeyringsByType("HD Key Tree")[0];
331
+ if (!primaryKeyring) {
332
+ throw new Error("No HD keyring found");
333
+ }
334
+ await primaryKeyring.addAccounts(1);
335
+ await this.persistAllKeyrings();
336
+ await this.verifySeedPhrase();
337
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
338
+ }
339
+ /**
340
+ * Effectively the same as creating a new keychain then populating it
341
+ * using the given seed phrase.
342
+ *
343
+ * @param password - Password to unlock keychain.
344
+ * @param seed - A BIP39-compliant seed phrase as Uint8Array,
345
+ * either as a string or an array of UTF-8 bytes that represent the string.
346
+ * @returns Promise resolving to the restored keychain object.
347
+ */
348
+ async createNewVaultAndRestore(password, seed) {
349
+ const releaseLock = await this.mutex.acquire();
350
+ if (!password || !password.length) {
351
+ throw new Error("Invalid password");
352
+ }
353
+ try {
354
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _createNewVaultWithKeyring, createNewVaultWithKeyring_fn).call(this, password, {
355
+ type: "HD Key Tree" /* hd */,
356
+ opts: {
357
+ mnemonic: seed,
358
+ numberOfAccounts: 1
359
+ }
360
+ });
361
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
362
+ } finally {
363
+ releaseLock();
364
+ }
365
+ }
366
+ /**
367
+ * Create a new primary keychain and wipe any previous keychains.
368
+ *
369
+ * @param password - Password to unlock the new vault.
370
+ * @returns Newly-created keychain object.
371
+ */
372
+ async createNewVaultAndKeychain(password) {
373
+ const releaseLock = await this.mutex.acquire();
374
+ try {
375
+ const accounts = await this.getAccounts();
376
+ if (!accounts.length) {
377
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _createNewVaultWithKeyring, createNewVaultWithKeyring_fn).call(this, password, {
378
+ type: "HD Key Tree" /* hd */
379
+ });
380
+ }
381
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
382
+ } finally {
383
+ releaseLock();
384
+ }
385
+ }
386
+ /**
387
+ * Adds a new keyring of the given `type`.
388
+ *
389
+ * @param type - Keyring type name.
390
+ * @param opts - Keyring options.
391
+ * @throws If a builder for the given `type` does not exist.
392
+ * @returns Promise resolving to the added keyring.
393
+ */
394
+ async addNewKeyring(type, opts) {
395
+ if (type === "QR Hardware Wallet Device" /* qr */) {
396
+ return this.getOrAddQRKeyring();
397
+ }
398
+ const keyring = await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, type, opts);
399
+ if (type === "HD Key Tree" /* hd */ && (!_utils.isObject.call(void 0, opts) || !opts.mnemonic)) {
400
+ if (!keyring.generateRandomMnemonic) {
401
+ throw new Error(
402
+ "KeyringController - The current keyring does not support the method generateRandomMnemonic." /* UnsupportedGenerateRandomMnemonic */
403
+ );
404
+ }
405
+ keyring.generateRandomMnemonic();
406
+ await keyring.addAccounts(1);
407
+ }
408
+ const accounts = await keyring.getAccounts();
409
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _checkForDuplicate, checkForDuplicate_fn).call(this, type, accounts);
410
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).push(keyring);
411
+ await this.persistAllKeyrings();
412
+ return keyring;
413
+ }
414
+ /**
415
+ * Method to verify a given password validity. Throws an
416
+ * error if the password is invalid.
417
+ *
418
+ * @param password - Password of the keyring.
419
+ */
420
+ async verifyPassword(password) {
421
+ if (!this.state.vault) {
422
+ throw new Error("KeyringController - Cannot unlock without a previous vault." /* VaultError */);
423
+ }
424
+ await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).decrypt(password, this.state.vault);
425
+ }
426
+ /**
427
+ * Returns the status of the vault.
428
+ *
429
+ * @returns Boolean returning true if the vault is unlocked.
430
+ */
431
+ isUnlocked() {
432
+ return this.state.isUnlocked;
433
+ }
434
+ /**
435
+ * Gets the seed phrase of the HD keyring.
436
+ *
437
+ * @param password - Password of the keyring.
438
+ * @returns Promise resolving to the seed phrase.
439
+ */
440
+ async exportSeedPhrase(password) {
441
+ await this.verifyPassword(password);
442
+ assertHasUint8ArrayMnemonic(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings)[0]);
443
+ return _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings)[0].mnemonic;
444
+ }
445
+ /**
446
+ * Gets the private key from the keyring controlling an address.
447
+ *
448
+ * @param password - Password of the keyring.
449
+ * @param address - Address to export.
450
+ * @returns Promise resolving to the private key for an address.
451
+ */
452
+ async exportAccount(password, address) {
453
+ await this.verifyPassword(password);
454
+ const keyring = await this.getKeyringForAccount(
455
+ address
456
+ );
457
+ if (!keyring.exportAccount) {
458
+ throw new Error("`KeyringController - The keyring for the current address does not support the method exportAccount" /* UnsupportedExportAccount */);
459
+ }
460
+ return await keyring.exportAccount(_ethsigutil.normalize.call(void 0, address));
461
+ }
462
+ /**
463
+ * Returns the public addresses of all accounts for the current keyring.
464
+ *
465
+ * @returns A promise resolving to an array of addresses.
466
+ */
467
+ async getAccounts() {
468
+ const keyrings = _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings);
469
+ const keyringArrays = await Promise.all(
470
+ keyrings.map(async (keyring) => keyring.getAccounts())
471
+ );
472
+ const addresses = keyringArrays.reduce((res, arr) => {
473
+ return res.concat(arr);
474
+ }, []);
475
+ return addresses.map(_ethsigutil.normalize);
476
+ }
477
+ /**
478
+ * Get encryption public key.
479
+ *
480
+ * @param account - An account address.
481
+ * @param opts - Additional encryption options.
482
+ * @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method
483
+ * @returns Promise resolving to encyption public key of the `account` if one exists.
484
+ */
485
+ async getEncryptionPublicKey(account, opts) {
486
+ const normalizedAddress = _ethsigutil.normalize.call(void 0, account);
487
+ const keyring = await this.getKeyringForAccount(
488
+ account
489
+ );
490
+ if (!keyring.getEncryptionPublicKey) {
491
+ throw new Error("KeyringController - The keyring for the current address does not support the method getEncryptionPublicKey." /* UnsupportedGetEncryptionPublicKey */);
492
+ }
493
+ return await keyring.getEncryptionPublicKey(normalizedAddress, opts);
494
+ }
495
+ /**
496
+ * Attempts to decrypt the provided message parameters.
497
+ *
498
+ * @param messageParams - The decryption message parameters.
499
+ * @param messageParams.from - The address of the account you want to use to decrypt the message.
500
+ * @param messageParams.data - The encrypted data that you want to decrypt.
501
+ * @returns The raw decryption result.
502
+ */
503
+ async decryptMessage(messageParams) {
504
+ const address = _ethsigutil.normalize.call(void 0, messageParams.from);
505
+ const keyring = await this.getKeyringForAccount(
506
+ address
507
+ );
508
+ if (!keyring.decryptMessage) {
509
+ throw new Error("KeyringController - The keyring for the current address does not support the method decryptMessage." /* UnsupportedDecryptMessage */);
510
+ }
511
+ return keyring.decryptMessage(address, messageParams.data);
512
+ }
513
+ /**
514
+ * Returns the currently initialized keyring that manages
515
+ * the specified `address` if one exists.
516
+ *
517
+ * @deprecated Use of this method is discouraged as actions executed directly on
518
+ * keyrings are not being reflected in the KeyringController state and not
519
+ * persisted in the vault.
520
+ * @param account - An account address.
521
+ * @returns Promise resolving to keyring of the `account` if one exists.
522
+ */
523
+ async getKeyringForAccount(account) {
524
+ const hexed = _ethsigutil.normalize.call(void 0, account);
525
+ const candidates = await Promise.all(
526
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
527
+ return Promise.all([keyring, keyring.getAccounts()]);
528
+ })
529
+ );
530
+ const winners = candidates.filter((candidate) => {
531
+ const accounts = candidate[1].map(_ethsigutil.normalize);
532
+ return accounts.includes(hexed);
533
+ });
534
+ if (winners.length && winners[0]?.length) {
535
+ return winners[0][0];
536
+ }
537
+ let errorInfo = "";
538
+ if (!_utils.isValidHexAddress.call(void 0, hexed)) {
539
+ errorInfo = "The address passed in is invalid/empty";
540
+ } else if (!candidates.length) {
541
+ errorInfo = "There are no keyrings";
542
+ } else if (!winners.length) {
543
+ errorInfo = "There are keyrings, but none match the address";
544
+ }
545
+ throw new Error(
546
+ `${"KeyringController - No keyring found" /* NoKeyring */}. Error info: ${errorInfo}`
547
+ );
548
+ }
549
+ /**
550
+ * Returns all keyrings of the given type.
551
+ *
552
+ * @deprecated Use of this method is discouraged as actions executed directly on
553
+ * keyrings are not being reflected in the KeyringController state and not
554
+ * persisted in the vault.
555
+ * @param type - Keyring type name.
556
+ * @returns An array of keyrings of the given type.
557
+ */
558
+ getKeyringsByType(type) {
559
+ return _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).filter((keyring) => keyring.type === type);
560
+ }
561
+ /**
562
+ * Persist all serialized keyrings in the vault.
563
+ *
564
+ * @returns Promise resolving with `true` value when the
565
+ * operation completes.
566
+ */
567
+ async persistAllKeyrings() {
568
+ const { encryptionKey, encryptionSalt } = this.state;
569
+ if (!_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password) && !encryptionKey) {
570
+ throw new Error("KeyringController - Cannot persist vault without password and encryption key" /* MissingCredentials */);
571
+ }
572
+ const serializedKeyrings = await Promise.all(
573
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
574
+ const [type, data] = await Promise.all([
575
+ keyring.type,
576
+ keyring.serialize()
577
+ ]);
578
+ return { type, data };
579
+ })
580
+ );
581
+ serializedKeyrings.push(..._chunkCHLPTPMZjs.__privateGet.call(void 0, this, _unsupportedKeyrings));
582
+ let vault;
583
+ let newEncryptionKey;
584
+ if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
585
+ assertIsExportableKeyEncryptor(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor));
586
+ if (encryptionKey) {
587
+ const key = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).importKey(encryptionKey);
588
+ const vaultJSON = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).encryptWithKey(
589
+ key,
590
+ serializedKeyrings
591
+ );
592
+ vaultJSON.salt = encryptionSalt;
593
+ vault = JSON.stringify(vaultJSON);
594
+ } else if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password)) {
595
+ const { vault: newVault, exportedKeyString } = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).encryptWithDetail(
596
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password),
597
+ serializedKeyrings
598
+ );
599
+ vault = newVault;
600
+ newEncryptionKey = exportedKeyString;
601
+ }
602
+ } else {
603
+ if (typeof _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password) !== "string") {
604
+ throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
605
+ }
606
+ vault = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).encrypt(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password), serializedKeyrings);
607
+ }
608
+ if (!vault) {
609
+ throw new Error("KeyringController - Cannot persist vault without vault information" /* MissingVaultData */);
610
+ }
611
+ this.update((state) => {
612
+ state.vault = vault;
613
+ });
614
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _updateKeyringsInState, updateKeyringsInState_fn).call(this);
615
+ if (newEncryptionKey) {
616
+ this.update((state) => {
617
+ state.encryptionKey = newEncryptionKey;
618
+ state.encryptionSalt = JSON.parse(vault).salt;
619
+ });
620
+ }
621
+ return true;
622
+ }
623
+ /**
624
+ * Imports an account with the specified import strategy.
625
+ *
626
+ * @param strategy - Import strategy name.
627
+ * @param args - Array of arguments to pass to the underlying stategy.
628
+ * @throws Will throw when passed an unrecognized strategy.
629
+ * @returns Promise resolving to keyring current state and imported account
630
+ * address.
631
+ */
632
+ async importAccountWithStrategy(strategy, args) {
633
+ let privateKey;
634
+ switch (strategy) {
635
+ case "privateKey":
636
+ const [importedKey] = args;
637
+ if (!importedKey) {
638
+ throw new Error("Cannot import an empty key.");
639
+ }
640
+ const prefixed = _utils.add0x.call(void 0, importedKey);
641
+ let bufferedPrivateKey;
642
+ try {
643
+ bufferedPrivateKey = _util.toBuffer.call(void 0, prefixed);
644
+ } catch {
645
+ throw new Error("Cannot import invalid private key.");
646
+ }
647
+ if (!_util.isValidPrivate.call(void 0, bufferedPrivateKey) || // ensures that the key is 64 bytes long
648
+ _util.getBinarySize.call(void 0, prefixed) !== 64 + "0x".length) {
649
+ throw new Error("Cannot import invalid private key.");
650
+ }
651
+ privateKey = _utils.remove0x.call(void 0, prefixed);
652
+ break;
653
+ case "json":
654
+ let wallet;
655
+ const [input, password] = args;
656
+ try {
657
+ wallet = _ethereumjswallet.thirdparty.fromEtherWallet(input, password);
658
+ } catch (e) {
659
+ wallet = wallet || await _ethereumjswallet2.default.fromV3(input, password, true);
660
+ }
661
+ privateKey = _utils.bytesToHex.call(void 0, wallet.getPrivateKey());
662
+ break;
663
+ default:
664
+ throw new Error(`Unexpected import strategy: '${strategy}'`);
665
+ }
666
+ const newKeyring = await this.addNewKeyring("Simple Key Pair" /* simple */, [
667
+ privateKey
668
+ ]);
669
+ const accounts = await newKeyring.getAccounts();
670
+ return {
671
+ keyringState: _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this),
672
+ importedAccountAddress: accounts[0]
673
+ };
674
+ }
675
+ /**
676
+ * Removes an account from keyring state.
677
+ *
678
+ * @param address - Address of the account to remove.
679
+ * @fires KeyringController:accountRemoved
680
+ * @returns Promise resolving current state when this account removal completes.
681
+ */
682
+ async removeAccount(address) {
683
+ const keyring = await this.getKeyringForAccount(
684
+ address
685
+ );
686
+ if (!keyring.removeAccount) {
687
+ throw new Error("`KeyringController - The keyring for the current address does not support the method removeAccount" /* UnsupportedRemoveAccount */);
688
+ }
689
+ await keyring.removeAccount(address);
690
+ const accounts = await keyring.getAccounts();
691
+ if (accounts.length === 0) {
692
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _removeEmptyKeyrings, removeEmptyKeyrings_fn).call(this);
693
+ }
694
+ await this.persistAllKeyrings();
695
+ this.messagingSystem.publish(`${name}:accountRemoved`, address);
696
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
697
+ }
698
+ /**
699
+ * Deallocates all secrets and locks the wallet.
700
+ *
701
+ * @returns Promise resolving to current state.
702
+ */
703
+ async setLocked() {
704
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _unsubscribeFromQRKeyringsEvents, unsubscribeFromQRKeyringsEvents_fn).call(this);
705
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _password, void 0);
706
+ this.update((state) => {
707
+ state.isUnlocked = false;
708
+ state.keyrings = [];
709
+ });
710
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
711
+ this.messagingSystem.publish(`${name}:lock`);
712
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
713
+ }
714
+ /**
715
+ * Signs message by calling down into a specific keyring.
716
+ *
717
+ * @param messageParams - PersonalMessageParams object to sign.
718
+ * @returns Promise resolving to a signed message string.
719
+ */
720
+ async signMessage(messageParams) {
721
+ if (!messageParams.data) {
722
+ throw new Error("Can't sign an empty message");
723
+ }
724
+ const address = _ethsigutil.normalize.call(void 0, messageParams.from);
725
+ const keyring = await this.getKeyringForAccount(
726
+ address
727
+ );
728
+ if (!keyring.signMessage) {
729
+ throw new Error("KeyringController - The keyring for the current address does not support the method signMessage." /* UnsupportedSignMessage */);
730
+ }
731
+ return await keyring.signMessage(address, messageParams.data);
732
+ }
733
+ /**
734
+ * Signs personal message by calling down into a specific keyring.
735
+ *
736
+ * @param messageParams - PersonalMessageParams object to sign.
737
+ * @returns Promise resolving to a signed message string.
738
+ */
739
+ async signPersonalMessage(messageParams) {
740
+ const address = _ethsigutil.normalize.call(void 0, messageParams.from);
741
+ const keyring = await this.getKeyringForAccount(
742
+ address
743
+ );
744
+ if (!keyring.signPersonalMessage) {
745
+ throw new Error("KeyringController - The keyring for the current address does not support the method signPersonalMessage." /* UnsupportedSignPersonalMessage */);
746
+ }
747
+ const normalizedData = _ethsigutil.normalize.call(void 0, messageParams.data);
748
+ return await keyring.signPersonalMessage(address, normalizedData);
749
+ }
750
+ /**
751
+ * Signs typed message by calling down into a specific keyring.
752
+ *
753
+ * @param messageParams - TypedMessageParams object to sign.
754
+ * @param version - Compatibility version EIP712.
755
+ * @throws Will throw when passed an unrecognized version.
756
+ * @returns Promise resolving to a signed message string or an error if any.
757
+ */
758
+ async signTypedMessage(messageParams, version) {
759
+ try {
760
+ if (![
761
+ "V1" /* V1 */,
762
+ "V3" /* V3 */,
763
+ "V4" /* V4 */
764
+ ].includes(version)) {
765
+ throw new Error(`Unexpected signTypedMessage version: '${version}'`);
766
+ }
767
+ const address = _ethsigutil.normalize.call(void 0, messageParams.from);
768
+ const keyring = await this.getKeyringForAccount(
769
+ address
770
+ );
771
+ if (!keyring.signTypedData) {
772
+ throw new Error("KeyringController - The keyring for the current address does not support the method signTypedMessage." /* UnsupportedSignTypedMessage */);
773
+ }
774
+ return await keyring.signTypedData(
775
+ address,
776
+ version !== "V1" /* V1 */ && typeof messageParams.data === "string" ? JSON.parse(messageParams.data) : messageParams.data,
777
+ { version }
778
+ );
779
+ } catch (error) {
780
+ throw new Error(`Keyring Controller signTypedMessage: ${error}`);
781
+ }
782
+ }
783
+ /**
784
+ * Signs a transaction by calling down into a specific keyring.
785
+ *
786
+ * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance.
787
+ * @param from - Address to sign from, should be in keychain.
788
+ * @param opts - An optional options object.
789
+ * @returns Promise resolving to a signed transaction string.
790
+ */
791
+ async signTransaction(transaction, from, opts) {
792
+ const address = _ethsigutil.normalize.call(void 0, from);
793
+ const keyring = await this.getKeyringForAccount(
794
+ address
795
+ );
796
+ if (!keyring.signTransaction) {
797
+ throw new Error("KeyringController - The keyring for the current address does not support the method signTransaction." /* UnsupportedSignTransaction */);
798
+ }
799
+ return await keyring.signTransaction(address, transaction, opts);
800
+ }
801
+ /**
802
+ * Convert a base transaction to a base UserOperation.
803
+ *
804
+ * @param from - Address of the sender.
805
+ * @param transactions - Base transactions to include in the UserOperation.
806
+ * @returns A pseudo-UserOperation that can be used to construct a real.
807
+ */
808
+ async prepareUserOperation(from, transactions) {
809
+ const address = _ethsigutil.normalize.call(void 0, from);
810
+ const keyring = await this.getKeyringForAccount(
811
+ address
812
+ );
813
+ if (!keyring.prepareUserOperation) {
814
+ throw new Error("KeyringController - The keyring for the current address does not support the method prepareUserOperation." /* UnsupportedPrepareUserOperation */);
815
+ }
816
+ return await keyring.prepareUserOperation(address, transactions);
817
+ }
818
+ /**
819
+ * Patches properties of a UserOperation. Currently, only the
820
+ * `paymasterAndData` can be patched.
821
+ *
822
+ * @param from - Address of the sender.
823
+ * @param userOp - UserOperation to patch.
824
+ * @returns A patch to apply to the UserOperation.
825
+ */
826
+ async patchUserOperation(from, userOp) {
827
+ const address = _ethsigutil.normalize.call(void 0, from);
828
+ const keyring = await this.getKeyringForAccount(
829
+ address
830
+ );
831
+ if (!keyring.patchUserOperation) {
832
+ throw new Error("KeyringController - The keyring for the current address does not support the method patchUserOperation." /* UnsupportedPatchUserOperation */);
833
+ }
834
+ return await keyring.patchUserOperation(address, userOp);
835
+ }
836
+ /**
837
+ * Signs an UserOperation.
838
+ *
839
+ * @param from - Address of the sender.
840
+ * @param userOp - UserOperation to sign.
841
+ * @returns The signature of the UserOperation.
842
+ */
843
+ async signUserOperation(from, userOp) {
844
+ const address = _ethsigutil.normalize.call(void 0, from);
845
+ const keyring = await this.getKeyringForAccount(
846
+ address
847
+ );
848
+ if (!keyring.signUserOperation) {
849
+ throw new Error("KeyringController - The keyring for the current address does not support the method signUserOperation." /* UnsupportedSignUserOperation */);
850
+ }
851
+ return await keyring.signUserOperation(address, userOp);
852
+ }
853
+ /**
854
+ * Attempts to decrypt the current vault and load its keyrings,
855
+ * using the given encryption key and salt.
856
+ *
857
+ * @param encryptionKey - Key to unlock the keychain.
858
+ * @param encryptionSalt - Salt to unlock the keychain.
859
+ * @returns Promise resolving to the current state.
860
+ */
861
+ async submitEncryptionKey(encryptionKey, encryptionSalt) {
862
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyrings, await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _unlockKeyrings, unlockKeyrings_fn).call(this, void 0, encryptionKey, encryptionSalt));
863
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
864
+ const qrKeyring = this.getQRKeyring();
865
+ if (qrKeyring) {
866
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _subscribeToQRKeyringEvents, subscribeToQRKeyringEvents_fn).call(this, qrKeyring);
867
+ }
868
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
869
+ }
870
+ /**
871
+ * Attempts to decrypt the current vault and load its keyrings,
872
+ * using the given password.
873
+ *
874
+ * @param password - Password to unlock the keychain.
875
+ * @returns Promise resolving to the current state.
876
+ */
877
+ async submitPassword(password) {
878
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyrings, await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _unlockKeyrings, unlockKeyrings_fn).call(this, password));
879
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
880
+ const qrKeyring = this.getQRKeyring();
881
+ if (qrKeyring) {
882
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _subscribeToQRKeyringEvents, subscribeToQRKeyringEvents_fn).call(this, qrKeyring);
883
+ }
884
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
885
+ }
886
+ /**
887
+ * Verifies the that the seed phrase restores the current keychain's accounts.
888
+ *
889
+ * @returns Promise resolving to the seed phrase as Uint8Array.
890
+ */
891
+ async verifySeedPhrase() {
892
+ const primaryKeyring = this.getKeyringsByType("HD Key Tree" /* hd */)[0];
893
+ if (!primaryKeyring) {
894
+ throw new Error("No HD keyring found.");
895
+ }
896
+ assertHasUint8ArrayMnemonic(primaryKeyring);
897
+ const seedWords = primaryKeyring.mnemonic;
898
+ const accounts = await primaryKeyring.getAccounts();
899
+ if (accounts.length === 0) {
900
+ throw new Error("Cannot verify an empty keyring.");
901
+ }
902
+ const hdKeyringBuilder = _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getKeyringBuilderForType, getKeyringBuilderForType_fn).call(this, "HD Key Tree" /* hd */);
903
+ const hdKeyring = hdKeyringBuilder();
904
+ await hdKeyring.deserialize({
905
+ mnemonic: seedWords,
906
+ numberOfAccounts: accounts.length
907
+ });
908
+ const testAccounts = await hdKeyring.getAccounts();
909
+ if (testAccounts.length !== accounts.length) {
910
+ throw new Error("Seed phrase imported incorrect number of accounts.");
911
+ }
912
+ testAccounts.forEach((account, i) => {
913
+ if (account.toLowerCase() !== accounts[i].toLowerCase()) {
914
+ throw new Error("Seed phrase imported different accounts.");
915
+ }
916
+ });
917
+ return seedWords;
918
+ }
919
+ // QR Hardware related methods
920
+ /**
921
+ * Get QR Hardware keyring.
922
+ *
923
+ * @returns The QR Keyring if defined, otherwise undefined
924
+ */
925
+ getQRKeyring() {
926
+ return this.getKeyringsByType("QR Hardware Wallet Device" /* qr */)[0];
927
+ }
928
+ /**
929
+ * Get QR hardware keyring. If it doesn't exist, add it.
930
+ *
931
+ * @returns The added keyring
932
+ */
933
+ async getOrAddQRKeyring() {
934
+ return this.getQRKeyring() || await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _addQRKeyring, addQRKeyring_fn).call(this);
935
+ }
936
+ // TODO: Replace `any` with type
937
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
938
+ async restoreQRKeyring(serialized) {
939
+ (await this.getOrAddQRKeyring()).deserialize(serialized);
940
+ await this.persistAllKeyrings();
941
+ }
942
+ async resetQRKeyringState() {
943
+ (await this.getOrAddQRKeyring()).resetStore();
944
+ }
945
+ async getQRKeyringState() {
946
+ return (await this.getOrAddQRKeyring()).getMemStore();
947
+ }
948
+ async submitQRCryptoHDKey(cryptoHDKey) {
949
+ (await this.getOrAddQRKeyring()).submitCryptoHDKey(cryptoHDKey);
950
+ }
951
+ async submitQRCryptoAccount(cryptoAccount) {
952
+ (await this.getOrAddQRKeyring()).submitCryptoAccount(cryptoAccount);
953
+ }
954
+ async submitQRSignature(requestId, ethSignature) {
955
+ (await this.getOrAddQRKeyring()).submitSignature(requestId, ethSignature);
956
+ }
957
+ async cancelQRSignRequest() {
958
+ (await this.getOrAddQRKeyring()).cancelSignRequest();
959
+ }
960
+ /**
961
+ * Cancels qr keyring sync.
962
+ */
963
+ async cancelQRSynchronization() {
964
+ (await this.getOrAddQRKeyring()).cancelSync();
965
+ }
966
+ async connectQRHardware(page) {
967
+ try {
968
+ const keyring = await this.getOrAddQRKeyring();
969
+ let accounts;
970
+ switch (page) {
971
+ case -1:
972
+ accounts = await keyring.getPreviousPage();
973
+ break;
974
+ case 1:
975
+ accounts = await keyring.getNextPage();
976
+ break;
977
+ default:
978
+ accounts = await keyring.getFirstPage();
979
+ }
980
+ return accounts.map((account) => {
981
+ return {
982
+ ...account,
983
+ balance: "0x0"
984
+ };
985
+ });
986
+ } catch (e) {
987
+ throw new Error(`Unspecified error when connect QR Hardware, ${e}`);
988
+ }
989
+ }
990
+ async unlockQRHardwareWalletAccount(index) {
991
+ const keyring = await this.getOrAddQRKeyring();
992
+ keyring.setAccountToUnlock(index);
993
+ await this.addNewAccountForKeyring(keyring);
994
+ await this.persistAllKeyrings();
995
+ }
996
+ async getAccountKeyringType(account) {
997
+ const keyring = await this.getKeyringForAccount(
998
+ account
999
+ );
1000
+ return keyring.type;
1001
+ }
1002
+ async forgetQRDevice() {
1003
+ const keyring = await this.getOrAddQRKeyring();
1004
+ const allAccounts = await this.getAccounts();
1005
+ keyring.forgetDevice();
1006
+ const remainingAccounts = await this.getAccounts();
1007
+ const removedAccounts = allAccounts.filter(
1008
+ (address) => !remainingAccounts.includes(address)
1009
+ );
1010
+ await this.persistAllKeyrings();
1011
+ return { removedAccounts, remainingAccounts };
1012
+ }
1013
+ };
1014
+ _keyringBuilders = new WeakMap();
1015
+ _keyrings = new WeakMap();
1016
+ _unsupportedKeyrings = new WeakMap();
1017
+ _password = new WeakMap();
1018
+ _encryptor = new WeakMap();
1019
+ _cacheEncryptionKey = new WeakMap();
1020
+ _qrKeyringStateListener = new WeakMap();
1021
+ _registerMessageHandlers = new WeakSet();
1022
+ registerMessageHandlers_fn = function() {
1023
+ this.messagingSystem.registerActionHandler(
1024
+ `${name}:signMessage`,
1025
+ this.signMessage.bind(this)
1026
+ );
1027
+ this.messagingSystem.registerActionHandler(
1028
+ `${name}:signPersonalMessage`,
1029
+ this.signPersonalMessage.bind(this)
1030
+ );
1031
+ this.messagingSystem.registerActionHandler(
1032
+ `${name}:signTypedMessage`,
1033
+ this.signTypedMessage.bind(this)
1034
+ );
1035
+ this.messagingSystem.registerActionHandler(
1036
+ `${name}:decryptMessage`,
1037
+ this.decryptMessage.bind(this)
1038
+ );
1039
+ this.messagingSystem.registerActionHandler(
1040
+ `${name}:getEncryptionPublicKey`,
1041
+ this.getEncryptionPublicKey.bind(this)
1042
+ );
1043
+ this.messagingSystem.registerActionHandler(
1044
+ `${name}:getAccounts`,
1045
+ this.getAccounts.bind(this)
1046
+ );
1047
+ this.messagingSystem.registerActionHandler(
1048
+ `${name}:getKeyringsByType`,
1049
+ this.getKeyringsByType.bind(this)
1050
+ );
1051
+ this.messagingSystem.registerActionHandler(
1052
+ `${name}:getKeyringForAccount`,
1053
+ this.getKeyringForAccount.bind(this)
1054
+ );
1055
+ this.messagingSystem.registerActionHandler(
1056
+ `${name}:persistAllKeyrings`,
1057
+ this.persistAllKeyrings.bind(this)
1058
+ );
1059
+ this.messagingSystem.registerActionHandler(
1060
+ `${name}:prepareUserOperation`,
1061
+ this.prepareUserOperation.bind(this)
1062
+ );
1063
+ this.messagingSystem.registerActionHandler(
1064
+ `${name}:patchUserOperation`,
1065
+ this.patchUserOperation.bind(this)
1066
+ );
1067
+ this.messagingSystem.registerActionHandler(
1068
+ `${name}:signUserOperation`,
1069
+ this.signUserOperation.bind(this)
1070
+ );
1071
+ };
1072
+ _getKeyringBuilderForType = new WeakSet();
1073
+ getKeyringBuilderForType_fn = function(type) {
1074
+ return _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyringBuilders).find(
1075
+ (keyringBuilder) => keyringBuilder.type === type
1076
+ );
1077
+ };
1078
+ _addQRKeyring = new WeakSet();
1079
+ addQRKeyring_fn = async function() {
1080
+ const qrKeyring = await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, "QR Hardware Wallet Device" /* qr */, {
1081
+ accounts: []
1082
+ });
1083
+ const accounts = await qrKeyring.getAccounts();
1084
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _checkForDuplicate, checkForDuplicate_fn).call(this, "QR Hardware Wallet Device" /* qr */, accounts);
1085
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).push(qrKeyring);
1086
+ await this.persistAllKeyrings();
1087
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _subscribeToQRKeyringEvents, subscribeToQRKeyringEvents_fn).call(this, qrKeyring);
1088
+ return qrKeyring;
1089
+ };
1090
+ _subscribeToQRKeyringEvents = new WeakSet();
1091
+ subscribeToQRKeyringEvents_fn = function(qrKeyring) {
1092
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _qrKeyringStateListener, (state) => {
1093
+ this.messagingSystem.publish(`${name}:qrKeyringStateChange`, state);
1094
+ });
1095
+ qrKeyring.getMemStore().subscribe(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _qrKeyringStateListener));
1096
+ };
1097
+ _unsubscribeFromQRKeyringsEvents = new WeakSet();
1098
+ unsubscribeFromQRKeyringsEvents_fn = function() {
1099
+ const qrKeyrings = this.getKeyringsByType(
1100
+ "QR Hardware Wallet Device" /* qr */
1101
+ );
1102
+ qrKeyrings.forEach((qrKeyring) => {
1103
+ if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _qrKeyringStateListener)) {
1104
+ qrKeyring.getMemStore().unsubscribe(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _qrKeyringStateListener));
1105
+ }
1106
+ });
1107
+ };
1108
+ _createNewVaultWithKeyring = new WeakSet();
1109
+ createNewVaultWithKeyring_fn = async function(password, keyring) {
1110
+ if (typeof password !== "string") {
1111
+ throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1112
+ }
1113
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _password, password);
1114
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
1115
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _createKeyringWithFirstAccount, createKeyringWithFirstAccount_fn).call(this, keyring.type, keyring.opts);
1116
+ _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
1117
+ return _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getMemState, getMemState_fn).call(this);
1118
+ };
1119
+ _updateKeyringsInState = new WeakSet();
1120
+ updateKeyringsInState_fn = async function() {
1121
+ const keyrings = await Promise.all(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).map(displayForKeyring));
1122
+ this.update((state) => {
1123
+ state.keyrings = keyrings;
1124
+ });
1125
+ };
1126
+ _unlockKeyrings = new WeakSet();
1127
+ unlockKeyrings_fn = async function(password, encryptionKey, encryptionSalt) {
1128
+ const encryptedVault = this.state.vault;
1129
+ if (!encryptedVault) {
1130
+ throw new Error("KeyringController - Cannot unlock without a previous vault." /* VaultError */);
1131
+ }
1132
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
1133
+ let vault;
1134
+ if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
1135
+ assertIsExportableKeyEncryptor(_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor));
1136
+ if (password) {
1137
+ const result = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).decryptWithDetail(
1138
+ password,
1139
+ encryptedVault
1140
+ );
1141
+ vault = result.vault;
1142
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _password, password);
1143
+ this.update((state) => {
1144
+ state.encryptionKey = result.exportedKeyString;
1145
+ state.encryptionSalt = result.salt;
1146
+ });
1147
+ } else {
1148
+ const parsedEncryptedVault = JSON.parse(encryptedVault);
1149
+ if (encryptionSalt !== parsedEncryptedVault.salt) {
1150
+ throw new Error("KeyringController - Encryption key and salt provided are expired" /* ExpiredCredentials */);
1151
+ }
1152
+ if (typeof encryptionKey !== "string") {
1153
+ throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1154
+ }
1155
+ const key = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).importKey(encryptionKey);
1156
+ vault = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).decryptWithKey(key, parsedEncryptedVault);
1157
+ this.update((state) => {
1158
+ state.encryptionKey = encryptionKey;
1159
+ state.encryptionSalt = encryptionSalt;
1160
+ });
1161
+ }
1162
+ } else {
1163
+ if (typeof password !== "string") {
1164
+ throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1165
+ }
1166
+ vault = await _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).decrypt(password, encryptedVault);
1167
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _password, password);
1168
+ }
1169
+ if (!isSerializedKeyringsArray(vault)) {
1170
+ throw new Error("KeyringController - The decrypted vault has an unexpected shape." /* VaultDataError */);
1171
+ }
1172
+ await Promise.all(vault.map(_chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _restoreKeyring, restoreKeyring_fn).bind(this)));
1173
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _updateKeyringsInState, updateKeyringsInState_fn).call(this);
1174
+ if (_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _password) && (!_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _cacheEncryptionKey) || !encryptionKey) && _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).isVaultUpdated && !_chunkCHLPTPMZjs.__privateGet.call(void 0, this, _encryptor).isVaultUpdated(encryptedVault)) {
1175
+ await this.persistAllKeyrings();
1176
+ }
1177
+ return _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings);
1178
+ };
1179
+ _createKeyringWithFirstAccount = new WeakSet();
1180
+ createKeyringWithFirstAccount_fn = async function(type, opts) {
1181
+ const keyring = await this.addNewKeyring(type, opts);
1182
+ const [firstAccount] = await keyring.getAccounts();
1183
+ if (!firstAccount) {
1184
+ throw new Error("KeyringController - First Account not found." /* NoFirstAccount */);
1185
+ }
1186
+ };
1187
+ _newKeyring = new WeakSet();
1188
+ newKeyring_fn = async function(type, data) {
1189
+ const keyringBuilder = _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _getKeyringBuilderForType, getKeyringBuilderForType_fn).call(this, type);
1190
+ if (!keyringBuilder) {
1191
+ throw new Error(
1192
+ `${"KeyringController - No keyringBuilder found for keyring" /* NoKeyringBuilder */}. Keyring type: ${type}`
1193
+ );
1194
+ }
1195
+ const keyring = keyringBuilder();
1196
+ await keyring.deserialize(data);
1197
+ if (keyring.init) {
1198
+ await keyring.init();
1199
+ }
1200
+ return keyring;
1201
+ };
1202
+ _clearKeyrings = new WeakSet();
1203
+ clearKeyrings_fn = async function() {
1204
+ for (const keyring of _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings)) {
1205
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _destroyKeyring, destroyKeyring_fn).call(this, keyring);
1206
+ }
1207
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyrings, []);
1208
+ this.update((state) => {
1209
+ state.keyrings = [];
1210
+ });
1211
+ };
1212
+ _restoreKeyring = new WeakSet();
1213
+ restoreKeyring_fn = async function(serialized) {
1214
+ try {
1215
+ const { type, data } = serialized;
1216
+ const keyring = await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, type, data);
1217
+ await keyring.getAccounts();
1218
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).push(keyring);
1219
+ return keyring;
1220
+ } catch (_) {
1221
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _unsupportedKeyrings).push(serialized);
1222
+ return void 0;
1223
+ }
1224
+ };
1225
+ _destroyKeyring = new WeakSet();
1226
+ destroyKeyring_fn = async function(keyring) {
1227
+ await keyring.destroy?.();
1228
+ };
1229
+ _removeEmptyKeyrings = new WeakSet();
1230
+ removeEmptyKeyrings_fn = async function() {
1231
+ const validKeyrings = [];
1232
+ await Promise.all(
1233
+ _chunkCHLPTPMZjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
1234
+ const accounts = await keyring.getAccounts();
1235
+ if (accounts.length > 0) {
1236
+ validKeyrings.push(keyring);
1237
+ } else {
1238
+ await _chunkCHLPTPMZjs.__privateMethod.call(void 0, this, _destroyKeyring, destroyKeyring_fn).call(this, keyring);
1239
+ }
1240
+ })
1241
+ );
1242
+ _chunkCHLPTPMZjs.__privateSet.call(void 0, this, _keyrings, validKeyrings);
1243
+ };
1244
+ _checkForDuplicate = new WeakSet();
1245
+ checkForDuplicate_fn = async function(type, newAccountArray) {
1246
+ const accounts = await this.getAccounts();
1247
+ switch (type) {
1248
+ case "Simple Key Pair" /* simple */: {
1249
+ const isIncluded = Boolean(
1250
+ accounts.find(
1251
+ (key) => newAccountArray[0] && (key === newAccountArray[0] || key === _utils.remove0x.call(void 0, newAccountArray[0]))
1252
+ )
1253
+ );
1254
+ if (isIncluded) {
1255
+ throw new Error("KeyringController - The account you are trying to import is a duplicate" /* DuplicatedAccount */);
1256
+ }
1257
+ return newAccountArray;
1258
+ }
1259
+ default: {
1260
+ return newAccountArray;
1261
+ }
1262
+ }
1263
+ };
1264
+ _setUnlocked = new WeakSet();
1265
+ setUnlocked_fn = function() {
1266
+ this.update((state) => {
1267
+ state.isUnlocked = true;
1268
+ });
1269
+ this.messagingSystem.publish(`${name}:unlock`);
1270
+ };
1271
+ _getMemState = new WeakSet();
1272
+ getMemState_fn = function() {
1273
+ return {
1274
+ isUnlocked: this.state.isUnlocked,
1275
+ keyrings: this.state.keyrings
1276
+ };
1277
+ };
1278
+ var KeyringController_default = KeyringController;
1279
+
1280
+
1281
+
1282
+
1283
+
1284
+
1285
+
1286
+
1287
+
1288
+
1289
+ exports.KeyringTypes = KeyringTypes; exports.isCustodyKeyring = isCustodyKeyring; exports.AccountImportStrategy = AccountImportStrategy; exports.SignTypedDataVersion = SignTypedDataVersion; exports.keyringBuilderFactory = keyringBuilderFactory; exports.getDefaultKeyringState = getDefaultKeyringState; exports.KeyringController = KeyringController; exports.KeyringController_default = KeyringController_default;
1290
+ //# sourceMappingURL=chunk-BVSGYW4D.js.map