@metamask-previews/keyring-controller 17.2.0-preview-367cb1da → 17.2.0-preview-cf09c0a

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.
Files changed (44) hide show
  1. package/dist/KeyringController.cjs +1608 -0
  2. package/dist/KeyringController.cjs.map +1 -0
  3. package/dist/{types/KeyringController.d.ts → KeyringController.d.cts} +10 -10
  4. package/dist/KeyringController.d.cts.map +1 -0
  5. package/dist/KeyringController.d.mts +700 -0
  6. package/dist/KeyringController.d.mts.map +1 -0
  7. package/dist/KeyringController.mjs +1585 -20
  8. package/dist/KeyringController.mjs.map +1 -1
  9. package/dist/constants.cjs +39 -0
  10. package/dist/constants.cjs.map +1 -0
  11. package/dist/{types/constants.d.ts → constants.d.cts} +1 -1
  12. package/dist/constants.d.cts.map +1 -0
  13. package/dist/constants.d.mts +35 -0
  14. package/dist/constants.d.mts.map +1 -0
  15. package/dist/constants.mjs +35 -6
  16. package/dist/constants.mjs.map +1 -1
  17. package/dist/index.cjs +18 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +2 -0
  20. package/dist/index.d.cts.map +1 -0
  21. package/dist/index.d.mts +2 -0
  22. package/dist/index.d.mts.map +1 -0
  23. package/dist/index.mjs +1 -19
  24. package/dist/index.mjs.map +1 -1
  25. package/package.json +12 -7
  26. package/dist/KeyringController.js +0 -22
  27. package/dist/KeyringController.js.map +0 -1
  28. package/dist/chunk-F64I344Z.mjs +0 -68
  29. package/dist/chunk-F64I344Z.mjs.map +0 -1
  30. package/dist/chunk-JQRVJ3XK.mjs +0 -1595
  31. package/dist/chunk-JQRVJ3XK.mjs.map +0 -1
  32. package/dist/chunk-NOCGQCUM.js +0 -68
  33. package/dist/chunk-NOCGQCUM.js.map +0 -1
  34. package/dist/chunk-YRSQWNOT.js +0 -1595
  35. package/dist/chunk-YRSQWNOT.js.map +0 -1
  36. package/dist/constants.js +0 -7
  37. package/dist/constants.js.map +0 -1
  38. package/dist/index.js +0 -20
  39. package/dist/index.js.map +0 -1
  40. package/dist/tsconfig.build.tsbuildinfo +0 -1
  41. package/dist/types/KeyringController.d.ts.map +0 -1
  42. package/dist/types/constants.d.ts.map +0 -1
  43. package/dist/types/index.d.ts +0 -2
  44. package/dist/types/index.d.ts.map +0 -1
@@ -1,1595 +0,0 @@
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 _chunkNOCGQCUMjs = require('./chunk-NOCGQCUM.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
-
25
- var _utils = require('@metamask/utils');
26
- var _asyncmutex = require('async-mutex');
27
- var _ethereumjswallet = require('ethereumjs-wallet'); var _ethereumjswallet2 = _interopRequireDefault(_ethereumjswallet);
28
- var name = "KeyringController";
29
- var KeyringTypes = /* @__PURE__ */ ((KeyringTypes2) => {
30
- KeyringTypes2["simple"] = "Simple Key Pair";
31
- KeyringTypes2["hd"] = "HD Key Tree";
32
- KeyringTypes2["qr"] = "QR Hardware Wallet Device";
33
- KeyringTypes2["trezor"] = "Trezor Hardware";
34
- KeyringTypes2["ledger"] = "Ledger Hardware";
35
- KeyringTypes2["lattice"] = "Lattice Hardware";
36
- KeyringTypes2["snap"] = "Snap Keyring";
37
- return KeyringTypes2;
38
- })(KeyringTypes || {});
39
- var isCustodyKeyring = (keyringType) => {
40
- return keyringType.startsWith("Custody");
41
- };
42
- var AccountImportStrategy = /* @__PURE__ */ ((AccountImportStrategy2) => {
43
- AccountImportStrategy2["privateKey"] = "privateKey";
44
- AccountImportStrategy2["json"] = "json";
45
- return AccountImportStrategy2;
46
- })(AccountImportStrategy || {});
47
- var SignTypedDataVersion = /* @__PURE__ */ ((SignTypedDataVersion2) => {
48
- SignTypedDataVersion2["V1"] = "V1";
49
- SignTypedDataVersion2["V3"] = "V3";
50
- SignTypedDataVersion2["V4"] = "V4";
51
- return SignTypedDataVersion2;
52
- })(SignTypedDataVersion || {});
53
- function keyringBuilderFactory(KeyringConstructor) {
54
- const builder = () => new KeyringConstructor();
55
- builder.type = KeyringConstructor.type;
56
- return builder;
57
- }
58
- var defaultKeyringBuilders = [
59
- keyringBuilderFactory(_ethsimplekeyring2.default),
60
- keyringBuilderFactory(_ethhdkeyring2.default)
61
- ];
62
- var getDefaultKeyringState = () => {
63
- return {
64
- isUnlocked: false,
65
- keyrings: []
66
- };
67
- };
68
- function assertHasUint8ArrayMnemonic(keyring) {
69
- if (!(_utils.hasProperty.call(void 0, keyring, "mnemonic") && keyring.mnemonic instanceof Uint8Array)) {
70
- throw new Error("Can't get mnemonic bytes from keyring");
71
- }
72
- }
73
- function assertIsExportableKeyEncryptor(encryptor) {
74
- if (!("importKey" in encryptor && typeof encryptor.importKey === "function" && "decryptWithKey" in encryptor && typeof encryptor.decryptWithKey === "function" && "encryptWithKey" in encryptor && typeof encryptor.encryptWithKey === "function")) {
75
- throw new Error("KeyringController - The encryptor does not support encryption key export." /* UnsupportedEncryptionKeyExport */);
76
- }
77
- }
78
- function assertIsValidPassword(password) {
79
- if (typeof password !== "string") {
80
- throw new Error("KeyringController - Password must be of type string." /* WrongPasswordType */);
81
- }
82
- if (!password || !password.length) {
83
- throw new Error("KeyringController - Password cannot be empty." /* InvalidEmptyPassword */);
84
- }
85
- }
86
- function isSerializedKeyringsArray(array) {
87
- return typeof array === "object" && Array.isArray(array) && array.every((value) => value.type && _utils.isValidJson.call(void 0, value.data));
88
- }
89
- async function displayForKeyring(keyring) {
90
- const accounts = await keyring.getAccounts();
91
- return {
92
- type: keyring.type,
93
- // Cast to `string[]` here is safe here because `accounts` has no nullish
94
- // values, and `normalize` returns `string` unless given a nullish value
95
- accounts: accounts.map(normalize)
96
- };
97
- }
98
- function isEthAddress(address) {
99
- return (
100
- // NOTE: This function only checks for lowercased strings
101
- _utils.isStrictHexString.call(void 0, address.toLowerCase()) && // This checks for lowercased addresses and checksum addresses too
102
- _utils.isValidHexAddress.call(void 0, address)
103
- );
104
- }
105
- function normalize(address) {
106
- return isEthAddress(address) ? _ethsigutil.normalize.call(void 0, address) : address;
107
- }
108
- var _controllerOperationMutex, _vaultOperationMutex, _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, _getUpdatedKeyrings, getUpdatedKeyrings_fn, _getSerializedKeyrings, getSerializedKeyrings_fn, _restoreSerializedKeyrings, restoreSerializedKeyrings_fn, _unlockKeyrings, unlockKeyrings_fn, _updateVault, updateVault_fn, _getAccountsFromKeyrings, getAccountsFromKeyrings_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, _persistOrRollback, persistOrRollback_fn, _withRollback, withRollback_fn, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn, _withControllerLock, withControllerLock_fn, _withVaultLock, withVaultLock_fn;
109
- var KeyringController = class extends _basecontroller.BaseController {
110
- /**
111
- * Creates a KeyringController instance.
112
- *
113
- * @param options - Initial options used to configure this controller
114
- * @param options.encryptor - An optional object for defining encryption schemes.
115
- * @param options.keyringBuilders - Set a new name for account.
116
- * @param options.cacheEncryptionKey - Whether to cache or not encryption key.
117
- * @param options.messenger - A restricted controller messenger.
118
- * @param options.state - Initial state to set on this controller.
119
- */
120
- constructor(options) {
121
- const {
122
- encryptor = encryptorUtils,
123
- keyringBuilders,
124
- messenger,
125
- state
126
- } = options;
127
- super({
128
- name,
129
- metadata: {
130
- vault: { persist: true, anonymous: false },
131
- isUnlocked: { persist: false, anonymous: true },
132
- keyrings: { persist: false, anonymous: false },
133
- encryptionKey: { persist: false, anonymous: false },
134
- encryptionSalt: { persist: false, anonymous: false }
135
- },
136
- messenger,
137
- state: {
138
- ...getDefaultKeyringState(),
139
- ...state
140
- }
141
- });
142
- /**
143
- * Constructor helper for registering this controller's messaging system
144
- * actions.
145
- */
146
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _registerMessageHandlers);
147
- /**
148
- * Get the keyring builder for the given `type`.
149
- *
150
- * @param type - The type of keyring to get the builder for.
151
- * @returns The keyring builder, or undefined if none exists.
152
- */
153
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _getKeyringBuilderForType);
154
- /**
155
- * Add qr hardware keyring.
156
- *
157
- * @returns The added keyring
158
- * @throws If a QRKeyring builder is not provided
159
- * when initializing the controller
160
- */
161
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _addQRKeyring);
162
- /**
163
- * Subscribe to a QRKeyring state change events and
164
- * forward them through the messaging system.
165
- *
166
- * @param qrKeyring - The QRKeyring instance to subscribe to
167
- */
168
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _subscribeToQRKeyringEvents);
169
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _unsubscribeFromQRKeyringsEvents);
170
- /**
171
- * Create new vault with an initial keyring
172
- *
173
- * Destroys any old encrypted storage,
174
- * creates a new encrypted store with the given password,
175
- * creates a new wallet with 1 account.
176
- *
177
- * @fires KeyringController:unlock
178
- * @param password - The password to encrypt the vault with.
179
- * @param keyring - A object containing the params to instantiate a new keyring.
180
- * @param keyring.type - The keyring type.
181
- * @param keyring.opts - Optional parameters required to instantiate the keyring.
182
- * @returns A promise that resolves to the state.
183
- */
184
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _createNewVaultWithKeyring);
185
- /**
186
- * Get the updated array of each keyring's type and
187
- * accounts list.
188
- *
189
- * @returns A promise resolving to the updated keyrings array.
190
- */
191
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _getUpdatedKeyrings);
192
- /**
193
- * Serialize the current array of keyring instances,
194
- * including unsupported keyrings by default.
195
- *
196
- * @param options - Method options.
197
- * @param options.includeUnsupported - Whether to include unsupported keyrings.
198
- * @returns The serialized keyrings.
199
- */
200
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _getSerializedKeyrings);
201
- /**
202
- * Restore a serialized keyrings array.
203
- *
204
- * @param serializedKeyrings - The serialized keyrings array.
205
- */
206
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _restoreSerializedKeyrings);
207
- /**
208
- * Unlock Keyrings, decrypting the vault and deserializing all
209
- * keyrings contained in it, using a password or an encryption key with salt.
210
- *
211
- * @param password - The keyring controller password.
212
- * @param encryptionKey - An exported key string to unlock keyrings with.
213
- * @param encryptionSalt - The salt used to encrypt the vault.
214
- * @returns A promise resolving to the deserialized keyrings array.
215
- */
216
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _unlockKeyrings);
217
- /**
218
- * Update the vault with the current keyrings.
219
- *
220
- * @returns A promise resolving to `true` if the operation is successful.
221
- */
222
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _updateVault);
223
- /**
224
- * Retrieves all the accounts from keyrings instances
225
- * that are currently in memory.
226
- *
227
- * @returns A promise resolving to an array of accounts.
228
- */
229
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _getAccountsFromKeyrings);
230
- /**
231
- * Create a new keyring, ensuring that the first account is
232
- * also created.
233
- *
234
- * @param type - Keyring type to instantiate.
235
- * @param opts - Optional parameters required to instantiate the keyring.
236
- * @returns A promise that resolves if the operation is successful.
237
- */
238
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _createKeyringWithFirstAccount);
239
- /**
240
- * Instantiate, initialize and return a new keyring of the given `type`,
241
- * using the given `opts`. The keyring is built using the keyring builder
242
- * registered for the given `type`.
243
- *
244
- *
245
- * @param type - The type of keyring to add.
246
- * @param data - The data to restore a previously serialized keyring.
247
- * @returns The new keyring.
248
- * @throws If the keyring includes duplicated accounts.
249
- */
250
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _newKeyring);
251
- /**
252
- * Remove all managed keyrings, destroying all their
253
- * instances in memory.
254
- */
255
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _clearKeyrings);
256
- /**
257
- * Restore a Keyring from a provided serialized payload.
258
- * On success, returns the resulting keyring instance.
259
- *
260
- * @param serialized - The serialized keyring.
261
- * @returns The deserialized keyring or undefined if the keyring type is unsupported.
262
- */
263
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _restoreKeyring);
264
- /**
265
- * Destroy Keyring
266
- *
267
- * Some keyrings support a method called `destroy`, that destroys the
268
- * keyring along with removing all its event listeners and, in some cases,
269
- * clears the keyring bridge iframe from the DOM.
270
- *
271
- * @param keyring - The keyring to destroy.
272
- */
273
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _destroyKeyring);
274
- /**
275
- * Remove empty keyrings.
276
- *
277
- * Loops through the keyrings and removes the ones with empty accounts
278
- * (usually after removing the last / only account) from a keyring.
279
- */
280
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _removeEmptyKeyrings);
281
- /**
282
- * Checks for duplicate keypairs, using the the first account in the given
283
- * array. Rejects if a duplicate is found.
284
- *
285
- * Only supports 'Simple Key Pair'.
286
- *
287
- * @param type - The key pair type to check for.
288
- * @param newAccountArray - Array of new accounts.
289
- * @returns The account, if no duplicate is found.
290
- */
291
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _checkForDuplicate);
292
- /**
293
- * Set the `isUnlocked` to true and notify listeners
294
- * through the messenger.
295
- *
296
- * @fires KeyringController:unlock
297
- */
298
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _setUnlocked);
299
- /**
300
- * Execute the given function after acquiring the controller lock
301
- * and save the keyrings to state after it, or rollback to their
302
- * previous state in case of error.
303
- *
304
- * @param fn - The function to execute.
305
- * @returns The result of the function.
306
- */
307
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
308
- // eslint-disable-next-line @typescript-eslint/naming-convention
309
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _persistOrRollback);
310
- /**
311
- * Execute the given function after acquiring the controller lock
312
- * and rollback keyrings and password states in case of error.
313
- *
314
- * @param fn - The function to execute atomically.
315
- * @returns The result of the function.
316
- */
317
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
318
- // eslint-disable-next-line @typescript-eslint/naming-convention
319
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _withRollback);
320
- /**
321
- * Assert that the controller mutex is locked.
322
- *
323
- * @throws If the controller mutex is not locked.
324
- */
325
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _assertControllerMutexIsLocked);
326
- /**
327
- * Lock the controller mutex before executing the given function,
328
- * and release it after the function is resolved or after an
329
- * error is thrown.
330
- *
331
- * This wrapper ensures that each mutable operation that interacts with the
332
- * controller and that changes its state is executed in a mutually exclusive way,
333
- * preventing unsafe concurrent access that could lead to unpredictable behavior.
334
- *
335
- * @param fn - The function to execute while the controller mutex is locked.
336
- * @returns The result of the function.
337
- */
338
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
339
- // eslint-disable-next-line @typescript-eslint/naming-convention
340
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _withControllerLock);
341
- /**
342
- * Lock the vault mutex before executing the given function,
343
- * and release it after the function is resolved or after an
344
- * error is thrown.
345
- *
346
- * This ensures that each operation that interacts with the vault
347
- * is executed in a mutually exclusive way.
348
- *
349
- * @param fn - The function to execute while the vault mutex is locked.
350
- * @returns The result of the function.
351
- */
352
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
353
- // eslint-disable-next-line @typescript-eslint/naming-convention
354
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _withVaultLock);
355
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _controllerOperationMutex, new (0, _asyncmutex.Mutex)());
356
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _vaultOperationMutex, new (0, _asyncmutex.Mutex)());
357
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _keyringBuilders, void 0);
358
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _keyrings, void 0);
359
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _unsupportedKeyrings, void 0);
360
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _password, void 0);
361
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _encryptor, void 0);
362
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _cacheEncryptionKey, void 0);
363
- _chunkNOCGQCUMjs.__privateAdd.call(void 0, this, _qrKeyringStateListener, void 0);
364
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyringBuilders, keyringBuilders ? keyringBuilders.concat(defaultKeyringBuilders) : defaultKeyringBuilders);
365
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _encryptor, encryptor);
366
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyrings, []);
367
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _unsupportedKeyrings, []);
368
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _cacheEncryptionKey, Boolean(options.cacheEncryptionKey));
369
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
370
- assertIsExportableKeyEncryptor(encryptor);
371
- }
372
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
373
- }
374
- /**
375
- * Adds a new account to the default (first) HD seed phrase keyring.
376
- *
377
- * @param accountCount - Number of accounts before adding a new one, used to
378
- * make the method idempotent.
379
- * @returns Promise resolving to the added account address.
380
- */
381
- async addNewAccount(accountCount) {
382
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
383
- const primaryKeyring = this.getKeyringsByType("HD Key Tree")[0];
384
- if (!primaryKeyring) {
385
- throw new Error("No HD keyring found");
386
- }
387
- const oldAccounts = await primaryKeyring.getAccounts();
388
- if (accountCount && oldAccounts.length !== accountCount) {
389
- if (accountCount > oldAccounts.length) {
390
- throw new Error("Account out of sequence");
391
- }
392
- const existingAccount = oldAccounts[accountCount];
393
- if (!existingAccount) {
394
- throw new Error(`Can't find account at index ${accountCount}`);
395
- }
396
- return existingAccount;
397
- }
398
- const [addedAccountAddress] = await primaryKeyring.addAccounts(1);
399
- await this.verifySeedPhrase();
400
- return addedAccountAddress;
401
- });
402
- }
403
- /**
404
- * Adds a new account to the specified keyring.
405
- *
406
- * @param keyring - Keyring to add the account to.
407
- * @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.
408
- * @returns Promise resolving to the added account address
409
- */
410
- async addNewAccountForKeyring(keyring, accountCount) {
411
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
412
- const oldAccounts = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this);
413
- if (accountCount && oldAccounts.length !== accountCount) {
414
- if (accountCount > oldAccounts.length) {
415
- throw new Error("Account out of sequence");
416
- }
417
- const existingAccount = oldAccounts[accountCount];
418
- _utils.assertIsStrictHexString.call(void 0, existingAccount);
419
- return existingAccount;
420
- }
421
- await keyring.addAccounts(1);
422
- const addedAccountAddress = (await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this)).find(
423
- (selectedAddress) => !oldAccounts.includes(selectedAddress)
424
- );
425
- _utils.assertIsStrictHexString.call(void 0, addedAccountAddress);
426
- return addedAccountAddress;
427
- });
428
- }
429
- /**
430
- * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences.
431
- *
432
- * @returns Promise resolving to the added account address.
433
- */
434
- async addNewAccountWithoutUpdate() {
435
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
436
- const primaryKeyring = this.getKeyringsByType("HD Key Tree")[0];
437
- if (!primaryKeyring) {
438
- throw new Error("No HD keyring found");
439
- }
440
- const [addedAccountAddress] = await primaryKeyring.addAccounts(1);
441
- await this.verifySeedPhrase();
442
- return addedAccountAddress;
443
- });
444
- }
445
- /**
446
- * Effectively the same as creating a new keychain then populating it
447
- * using the given seed phrase.
448
- *
449
- * @param password - Password to unlock keychain.
450
- * @param seed - A BIP39-compliant seed phrase as Uint8Array,
451
- * either as a string or an array of UTF-8 bytes that represent the string.
452
- * @returns Promise resolving when the operation ends successfully.
453
- */
454
- async createNewVaultAndRestore(password, seed) {
455
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
456
- assertIsValidPassword(password);
457
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _createNewVaultWithKeyring, createNewVaultWithKeyring_fn).call(this, password, {
458
- type: "HD Key Tree" /* hd */,
459
- opts: {
460
- mnemonic: seed,
461
- numberOfAccounts: 1
462
- }
463
- });
464
- });
465
- }
466
- /**
467
- * Create a new vault and primary keyring.
468
- *
469
- * This only works if keyrings are empty. If there is a pre-existing unlocked vault, calling this will have no effect.
470
- * If there is a pre-existing locked vault, it will be replaced.
471
- *
472
- * @param password - Password to unlock the new vault.
473
- */
474
- async createNewVaultAndKeychain(password) {
475
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
476
- const accounts = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this);
477
- if (!accounts.length) {
478
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _createNewVaultWithKeyring, createNewVaultWithKeyring_fn).call(this, password, {
479
- type: "HD Key Tree" /* hd */
480
- });
481
- }
482
- });
483
- }
484
- /**
485
- * Adds a new keyring of the given `type`.
486
- *
487
- * @param type - Keyring type name.
488
- * @param opts - Keyring options.
489
- * @throws If a builder for the given `type` does not exist.
490
- * @returns Promise resolving to the added keyring.
491
- */
492
- async addNewKeyring(type, opts) {
493
- if (type === "QR Hardware Wallet Device" /* qr */) {
494
- return this.getOrAddQRKeyring();
495
- }
496
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, type, opts));
497
- }
498
- /**
499
- * Method to verify a given password validity. Throws an
500
- * error if the password is invalid.
501
- *
502
- * @param password - Password of the keyring.
503
- */
504
- async verifyPassword(password) {
505
- if (!this.state.vault) {
506
- throw new Error("KeyringController - Cannot unlock without a previous vault." /* VaultError */);
507
- }
508
- await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).decrypt(password, this.state.vault);
509
- }
510
- /**
511
- * Returns the status of the vault.
512
- *
513
- * @returns Boolean returning true if the vault is unlocked.
514
- */
515
- isUnlocked() {
516
- return this.state.isUnlocked;
517
- }
518
- /**
519
- * Gets the seed phrase of the HD keyring.
520
- *
521
- * @param password - Password of the keyring.
522
- * @returns Promise resolving to the seed phrase.
523
- */
524
- async exportSeedPhrase(password) {
525
- await this.verifyPassword(password);
526
- assertHasUint8ArrayMnemonic(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings)[0]);
527
- return _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings)[0].mnemonic;
528
- }
529
- /**
530
- * Gets the private key from the keyring controlling an address.
531
- *
532
- * @param password - Password of the keyring.
533
- * @param address - Address to export.
534
- * @returns Promise resolving to the private key for an address.
535
- */
536
- async exportAccount(password, address) {
537
- await this.verifyPassword(password);
538
- const keyring = await this.getKeyringForAccount(
539
- address
540
- );
541
- if (!keyring.exportAccount) {
542
- throw new Error("`KeyringController - The keyring for the current address does not support the method exportAccount" /* UnsupportedExportAccount */);
543
- }
544
- return await keyring.exportAccount(normalize(address));
545
- }
546
- /**
547
- * Returns the public addresses of all accounts from every keyring.
548
- *
549
- * @returns A promise resolving to an array of addresses.
550
- */
551
- async getAccounts() {
552
- return this.state.keyrings.reduce(
553
- (accounts, keyring) => accounts.concat(keyring.accounts),
554
- []
555
- );
556
- }
557
- /**
558
- * Get encryption public key.
559
- *
560
- * @param account - An account address.
561
- * @param opts - Additional encryption options.
562
- * @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method
563
- * @returns Promise resolving to encyption public key of the `account` if one exists.
564
- */
565
- async getEncryptionPublicKey(account, opts) {
566
- const address = _ethsigutil.normalize.call(void 0, account);
567
- const keyring = await this.getKeyringForAccount(
568
- account
569
- );
570
- if (!keyring.getEncryptionPublicKey) {
571
- throw new Error("KeyringController - The keyring for the current address does not support the method getEncryptionPublicKey." /* UnsupportedGetEncryptionPublicKey */);
572
- }
573
- return await keyring.getEncryptionPublicKey(address, opts);
574
- }
575
- /**
576
- * Attempts to decrypt the provided message parameters.
577
- *
578
- * @param messageParams - The decryption message parameters.
579
- * @param messageParams.from - The address of the account you want to use to decrypt the message.
580
- * @param messageParams.data - The encrypted data that you want to decrypt.
581
- * @returns The raw decryption result.
582
- */
583
- async decryptMessage(messageParams) {
584
- const address = _ethsigutil.normalize.call(void 0, messageParams.from);
585
- const keyring = await this.getKeyringForAccount(
586
- address
587
- );
588
- if (!keyring.decryptMessage) {
589
- throw new Error("KeyringController - The keyring for the current address does not support the method decryptMessage." /* UnsupportedDecryptMessage */);
590
- }
591
- return keyring.decryptMessage(address, messageParams.data);
592
- }
593
- /**
594
- * Returns the currently initialized keyring that manages
595
- * the specified `address` if one exists.
596
- *
597
- * @deprecated Use of this method is discouraged as actions executed directly on
598
- * keyrings are not being reflected in the KeyringController state and not
599
- * persisted in the vault. Use `withKeyring` instead.
600
- * @param account - An account address.
601
- * @returns Promise resolving to keyring of the `account` if one exists.
602
- */
603
- async getKeyringForAccount(account) {
604
- const address = normalize(account);
605
- const candidates = await Promise.all(
606
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
607
- return Promise.all([keyring, keyring.getAccounts()]);
608
- })
609
- );
610
- const winners = candidates.filter((candidate) => {
611
- const accounts = candidate[1].map(normalize);
612
- return accounts.includes(address);
613
- });
614
- if (winners.length && winners[0]?.length) {
615
- return winners[0][0];
616
- }
617
- let errorInfo = "";
618
- if (!candidates.length) {
619
- errorInfo = "There are no keyrings";
620
- } else if (!winners.length) {
621
- errorInfo = "There are keyrings, but none match the address";
622
- }
623
- throw new Error(
624
- `${"KeyringController - No keyring found" /* NoKeyring */}. Error info: ${errorInfo}`
625
- );
626
- }
627
- /**
628
- * Returns all keyrings of the given type.
629
- *
630
- * @deprecated Use of this method is discouraged as actions executed directly on
631
- * keyrings are not being reflected in the KeyringController state and not
632
- * persisted in the vault. Use `withKeyring` instead.
633
- * @param type - Keyring type name.
634
- * @returns An array of keyrings of the given type.
635
- */
636
- getKeyringsByType(type) {
637
- return _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).filter((keyring) => keyring.type === type);
638
- }
639
- /**
640
- * Persist all serialized keyrings in the vault.
641
- *
642
- * @deprecated This method is being phased out in favor of `withKeyring`.
643
- * @returns Promise resolving with `true` value when the
644
- * operation completes.
645
- */
646
- async persistAllKeyrings() {
647
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => true);
648
- }
649
- /**
650
- * Imports an account with the specified import strategy.
651
- *
652
- * @param strategy - Import strategy name.
653
- * @param args - Array of arguments to pass to the underlying stategy.
654
- * @throws Will throw when passed an unrecognized strategy.
655
- * @returns Promise resolving to the imported account address.
656
- */
657
- async importAccountWithStrategy(strategy, args) {
658
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
659
- let privateKey;
660
- switch (strategy) {
661
- case "privateKey":
662
- const [importedKey] = args;
663
- if (!importedKey) {
664
- throw new Error("Cannot import an empty key.");
665
- }
666
- const prefixed = _utils.add0x.call(void 0, importedKey);
667
- let bufferedPrivateKey;
668
- try {
669
- bufferedPrivateKey = _util.toBuffer.call(void 0, prefixed);
670
- } catch {
671
- throw new Error("Cannot import invalid private key.");
672
- }
673
- if (!_util.isValidPrivate.call(void 0, bufferedPrivateKey) || // ensures that the key is 64 bytes long
674
- _util.getBinarySize.call(void 0, prefixed) !== 64 + "0x".length) {
675
- throw new Error("Cannot import invalid private key.");
676
- }
677
- privateKey = _utils.remove0x.call(void 0, prefixed);
678
- break;
679
- case "json":
680
- let wallet;
681
- const [input, password] = args;
682
- try {
683
- wallet = _ethereumjswallet.thirdparty.fromEtherWallet(input, password);
684
- } catch (e) {
685
- wallet = wallet || await _ethereumjswallet2.default.fromV3(input, password, true);
686
- }
687
- privateKey = _utils.bytesToHex.call(void 0, wallet.getPrivateKey());
688
- break;
689
- default:
690
- throw new Error(`Unexpected import strategy: '${strategy}'`);
691
- }
692
- const newKeyring = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, "Simple Key Pair" /* simple */, [
693
- privateKey
694
- ]);
695
- const accounts = await newKeyring.getAccounts();
696
- return accounts[0];
697
- });
698
- }
699
- /**
700
- * Removes an account from keyring state.
701
- *
702
- * @param address - Address of the account to remove.
703
- * @fires KeyringController:accountRemoved
704
- * @returns Promise resolving when the account is removed.
705
- */
706
- async removeAccount(address) {
707
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
708
- const keyring = await this.getKeyringForAccount(
709
- address
710
- );
711
- if (!keyring.removeAccount) {
712
- throw new Error("`KeyringController - The keyring for the current address does not support the method removeAccount" /* UnsupportedRemoveAccount */);
713
- }
714
- keyring.removeAccount(address);
715
- const accounts = await keyring.getAccounts();
716
- if (accounts.length === 0) {
717
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _removeEmptyKeyrings, removeEmptyKeyrings_fn).call(this);
718
- }
719
- });
720
- this.messagingSystem.publish(`${name}:accountRemoved`, address);
721
- }
722
- /**
723
- * Deallocates all secrets and locks the wallet.
724
- *
725
- * @returns Promise resolving when the operation completes.
726
- */
727
- async setLocked() {
728
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withRollback, withRollback_fn).call(this, async () => {
729
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _unsubscribeFromQRKeyringsEvents, unsubscribeFromQRKeyringsEvents_fn).call(this);
730
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, void 0);
731
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
732
- this.update((state) => {
733
- state.isUnlocked = false;
734
- state.keyrings = [];
735
- delete state.encryptionKey;
736
- delete state.encryptionSalt;
737
- });
738
- this.messagingSystem.publish(`${name}:lock`);
739
- });
740
- }
741
- /**
742
- * Signs message by calling down into a specific keyring.
743
- *
744
- * @param messageParams - PersonalMessageParams object to sign.
745
- * @returns Promise resolving to a signed message string.
746
- */
747
- async signMessage(messageParams) {
748
- if (!messageParams.data) {
749
- throw new Error("Can't sign an empty message");
750
- }
751
- const address = _ethsigutil.normalize.call(void 0, messageParams.from);
752
- const keyring = await this.getKeyringForAccount(
753
- address
754
- );
755
- if (!keyring.signMessage) {
756
- throw new Error("KeyringController - The keyring for the current address does not support the method signMessage." /* UnsupportedSignMessage */);
757
- }
758
- return await keyring.signMessage(address, messageParams.data);
759
- }
760
- /**
761
- * Signs personal message by calling down into a specific keyring.
762
- *
763
- * @param messageParams - PersonalMessageParams object to sign.
764
- * @returns Promise resolving to a signed message string.
765
- */
766
- async signPersonalMessage(messageParams) {
767
- const address = _ethsigutil.normalize.call(void 0, messageParams.from);
768
- const keyring = await this.getKeyringForAccount(
769
- address
770
- );
771
- if (!keyring.signPersonalMessage) {
772
- throw new Error("KeyringController - The keyring for the current address does not support the method signPersonalMessage." /* UnsupportedSignPersonalMessage */);
773
- }
774
- const normalizedData = normalize(messageParams.data);
775
- return await keyring.signPersonalMessage(address, normalizedData);
776
- }
777
- /**
778
- * Signs typed message by calling down into a specific keyring.
779
- *
780
- * @param messageParams - TypedMessageParams object to sign.
781
- * @param version - Compatibility version EIP712.
782
- * @throws Will throw when passed an unrecognized version.
783
- * @returns Promise resolving to a signed message string or an error if any.
784
- */
785
- async signTypedMessage(messageParams, version) {
786
- try {
787
- if (![
788
- "V1" /* V1 */,
789
- "V3" /* V3 */,
790
- "V4" /* V4 */
791
- ].includes(version)) {
792
- throw new Error(`Unexpected signTypedMessage version: '${version}'`);
793
- }
794
- const address = _ethsigutil.normalize.call(void 0, messageParams.from);
795
- const keyring = await this.getKeyringForAccount(
796
- address
797
- );
798
- if (!keyring.signTypedData) {
799
- throw new Error("KeyringController - The keyring for the current address does not support the method signTypedMessage." /* UnsupportedSignTypedMessage */);
800
- }
801
- return await keyring.signTypedData(
802
- address,
803
- version !== "V1" /* V1 */ && typeof messageParams.data === "string" ? JSON.parse(messageParams.data) : messageParams.data,
804
- { version }
805
- );
806
- } catch (error) {
807
- throw new Error(`Keyring Controller signTypedMessage: ${error}`);
808
- }
809
- }
810
- /**
811
- * Signs a transaction by calling down into a specific keyring.
812
- *
813
- * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance.
814
- * @param from - Address to sign from, should be in keychain.
815
- * @param opts - An optional options object.
816
- * @returns Promise resolving to a signed transaction string.
817
- */
818
- async signTransaction(transaction, from, opts) {
819
- const address = _ethsigutil.normalize.call(void 0, from);
820
- const keyring = await this.getKeyringForAccount(
821
- address
822
- );
823
- if (!keyring.signTransaction) {
824
- throw new Error("KeyringController - The keyring for the current address does not support the method signTransaction." /* UnsupportedSignTransaction */);
825
- }
826
- return await keyring.signTransaction(address, transaction, opts);
827
- }
828
- /**
829
- * Convert a base transaction to a base UserOperation.
830
- *
831
- * @param from - Address of the sender.
832
- * @param transactions - Base transactions to include in the UserOperation.
833
- * @param executionContext - The execution context to use for the UserOperation.
834
- * @returns A pseudo-UserOperation that can be used to construct a real.
835
- */
836
- async prepareUserOperation(from, transactions, executionContext) {
837
- const address = _ethsigutil.normalize.call(void 0, from);
838
- const keyring = await this.getKeyringForAccount(
839
- address
840
- );
841
- if (!keyring.prepareUserOperation) {
842
- throw new Error("KeyringController - The keyring for the current address does not support the method prepareUserOperation." /* UnsupportedPrepareUserOperation */);
843
- }
844
- return await keyring.prepareUserOperation(
845
- address,
846
- transactions,
847
- executionContext
848
- );
849
- }
850
- /**
851
- * Patches properties of a UserOperation. Currently, only the
852
- * `paymasterAndData` can be patched.
853
- *
854
- * @param from - Address of the sender.
855
- * @param userOp - UserOperation to patch.
856
- * @param executionContext - The execution context to use for the UserOperation.
857
- * @returns A patch to apply to the UserOperation.
858
- */
859
- async patchUserOperation(from, userOp, executionContext) {
860
- const address = _ethsigutil.normalize.call(void 0, from);
861
- const keyring = await this.getKeyringForAccount(
862
- address
863
- );
864
- if (!keyring.patchUserOperation) {
865
- throw new Error("KeyringController - The keyring for the current address does not support the method patchUserOperation." /* UnsupportedPatchUserOperation */);
866
- }
867
- return await keyring.patchUserOperation(address, userOp, executionContext);
868
- }
869
- /**
870
- * Signs an UserOperation.
871
- *
872
- * @param from - Address of the sender.
873
- * @param userOp - UserOperation to sign.
874
- * @param executionContext - The execution context to use for the UserOperation.
875
- * @returns The signature of the UserOperation.
876
- */
877
- async signUserOperation(from, userOp, executionContext) {
878
- const address = _ethsigutil.normalize.call(void 0, from);
879
- const keyring = await this.getKeyringForAccount(
880
- address
881
- );
882
- if (!keyring.signUserOperation) {
883
- throw new Error("KeyringController - The keyring for the current address does not support the method signUserOperation." /* UnsupportedSignUserOperation */);
884
- }
885
- return await keyring.signUserOperation(address, userOp, executionContext);
886
- }
887
- /**
888
- * Changes the password used to encrypt the vault.
889
- *
890
- * @param password - The new password.
891
- * @returns Promise resolving when the operation completes.
892
- */
893
- changePassword(password) {
894
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
895
- if (!this.state.isUnlocked) {
896
- throw new Error("KeyringController - Cannot persist vault without password and encryption key" /* MissingCredentials */);
897
- }
898
- assertIsValidPassword(password);
899
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, password);
900
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
901
- this.update((state) => {
902
- delete state.encryptionKey;
903
- delete state.encryptionSalt;
904
- });
905
- }
906
- });
907
- }
908
- /**
909
- * Attempts to decrypt the current vault and load its keyrings,
910
- * using the given encryption key and salt.
911
- *
912
- * @param encryptionKey - Key to unlock the keychain.
913
- * @param encryptionSalt - Salt to unlock the keychain.
914
- * @returns Promise resolving when the operation completes.
915
- */
916
- async submitEncryptionKey(encryptionKey, encryptionSalt) {
917
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withRollback, withRollback_fn).call(this, async () => {
918
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyrings, await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _unlockKeyrings, unlockKeyrings_fn).call(this, void 0, encryptionKey, encryptionSalt));
919
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
920
- });
921
- }
922
- /**
923
- * Attempts to decrypt the current vault and load its keyrings,
924
- * using the given password.
925
- *
926
- * @param password - Password to unlock the keychain.
927
- * @returns Promise resolving when the operation completes.
928
- */
929
- async submitPassword(password) {
930
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withRollback, withRollback_fn).call(this, async () => {
931
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyrings, await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _unlockKeyrings, unlockKeyrings_fn).call(this, password));
932
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
933
- });
934
- }
935
- /**
936
- * Verifies the that the seed phrase restores the current keychain's accounts.
937
- *
938
- * @returns Promise resolving to the seed phrase as Uint8Array.
939
- */
940
- async verifySeedPhrase() {
941
- const primaryKeyring = this.getKeyringsByType("HD Key Tree" /* hd */)[0];
942
- if (!primaryKeyring) {
943
- throw new Error("No HD keyring found.");
944
- }
945
- assertHasUint8ArrayMnemonic(primaryKeyring);
946
- const seedWords = primaryKeyring.mnemonic;
947
- const accounts = await primaryKeyring.getAccounts();
948
- if (accounts.length === 0) {
949
- throw new Error("Cannot verify an empty keyring.");
950
- }
951
- const hdKeyringBuilder = _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getKeyringBuilderForType, getKeyringBuilderForType_fn).call(this, "HD Key Tree" /* hd */);
952
- const hdKeyring = hdKeyringBuilder();
953
- await hdKeyring.deserialize({
954
- mnemonic: seedWords,
955
- numberOfAccounts: accounts.length
956
- });
957
- const testAccounts = await hdKeyring.getAccounts();
958
- if (testAccounts.length !== accounts.length) {
959
- throw new Error("Seed phrase imported incorrect number of accounts.");
960
- }
961
- testAccounts.forEach((account, i) => {
962
- if (account.toLowerCase() !== accounts[i].toLowerCase()) {
963
- throw new Error("Seed phrase imported different accounts.");
964
- }
965
- });
966
- return seedWords;
967
- }
968
- async withKeyring(selector, operation, options = {
969
- createIfMissing: false
970
- }) {
971
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
972
- let keyring;
973
- if ("address" in selector) {
974
- keyring = await this.getKeyringForAccount(selector.address);
975
- } else {
976
- keyring = this.getKeyringsByType(selector.type)[selector.index || 0];
977
- if (!keyring && options.createIfMissing) {
978
- keyring = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, selector.type, options.createWithData);
979
- }
980
- }
981
- if (!keyring) {
982
- throw new Error("KeyringController - Keyring not found." /* KeyringNotFound */);
983
- }
984
- const result = await operation(keyring);
985
- if (Object.is(result, keyring)) {
986
- throw new Error("KeyringController - Returning keyring instances is unsafe" /* UnsafeDirectKeyringAccess */);
987
- }
988
- return result;
989
- });
990
- }
991
- // QR Hardware related methods
992
- /**
993
- * Get QR Hardware keyring.
994
- *
995
- * @returns The QR Keyring if defined, otherwise undefined
996
- * @deprecated Use `withKeyring` instead.
997
- */
998
- getQRKeyring() {
999
- return this.getKeyringsByType("QR Hardware Wallet Device" /* qr */)[0];
1000
- }
1001
- /**
1002
- * Get QR hardware keyring. If it doesn't exist, add it.
1003
- *
1004
- * @returns The added keyring
1005
- * @deprecated Use `addNewKeyring` and `withKeyring` instead.
1006
- */
1007
- async getOrAddQRKeyring() {
1008
- return this.getQRKeyring() || await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _addQRKeyring, addQRKeyring_fn).call(this));
1009
- }
1010
- /**
1011
- * Restore QR keyring from serialized data.
1012
- *
1013
- * @param serialized - Serialized data to restore the keyring from.
1014
- * @returns Promise resolving when the operation completes.
1015
- * @deprecated Use `withKeyring` instead.
1016
- */
1017
- // TODO: Replace `any` with type
1018
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1019
- async restoreQRKeyring(serialized) {
1020
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
1021
- const keyring = this.getQRKeyring() || await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _addQRKeyring, addQRKeyring_fn).call(this);
1022
- keyring.deserialize(serialized);
1023
- });
1024
- }
1025
- /**
1026
- * Reset QR keyring state.
1027
- *
1028
- * @returns Promise resolving when the operation completes.
1029
- * @deprecated Use `withKeyring` instead.
1030
- */
1031
- async resetQRKeyringState() {
1032
- (await this.getOrAddQRKeyring()).resetStore();
1033
- }
1034
- /**
1035
- * Get QR keyring state.
1036
- *
1037
- * @returns Promise resolving to the keyring state.
1038
- * @deprecated Use `withKeyring` or subscribe to `"KeyringController:qrKeyringStateChange"`
1039
- * instead.
1040
- */
1041
- async getQRKeyringState() {
1042
- return (await this.getOrAddQRKeyring()).getMemStore();
1043
- }
1044
- /**
1045
- * Submit QR hardware wallet public HDKey.
1046
- *
1047
- * @param cryptoHDKey - The key to submit.
1048
- * @returns Promise resolving when the operation completes.
1049
- * @deprecated Use `withKeyring` instead.
1050
- */
1051
- async submitQRCryptoHDKey(cryptoHDKey) {
1052
- (await this.getOrAddQRKeyring()).submitCryptoHDKey(cryptoHDKey);
1053
- }
1054
- /**
1055
- * Submit QR hardware wallet account.
1056
- *
1057
- * @param cryptoAccount - The account to submit.
1058
- * @returns Promise resolving when the operation completes.
1059
- * @deprecated Use `withKeyring` instead.
1060
- */
1061
- async submitQRCryptoAccount(cryptoAccount) {
1062
- (await this.getOrAddQRKeyring()).submitCryptoAccount(cryptoAccount);
1063
- }
1064
- /**
1065
- * Submit QR hardware wallet signature.
1066
- *
1067
- * @param requestId - The request ID.
1068
- * @param ethSignature - The signature to submit.
1069
- * @returns Promise resolving when the operation completes.
1070
- * @deprecated Use `withKeyring` instead.
1071
- */
1072
- async submitQRSignature(requestId, ethSignature) {
1073
- (await this.getOrAddQRKeyring()).submitSignature(requestId, ethSignature);
1074
- }
1075
- /**
1076
- * Cancel QR sign request.
1077
- *
1078
- * @returns Promise resolving when the operation completes.
1079
- * @deprecated Use `withKeyring` instead.
1080
- */
1081
- async cancelQRSignRequest() {
1082
- (await this.getOrAddQRKeyring()).cancelSignRequest();
1083
- }
1084
- /**
1085
- * Cancels qr keyring sync.
1086
- *
1087
- * @returns Promise resolving when the operation completes.
1088
- * @deprecated Use `withKeyring` instead.
1089
- */
1090
- async cancelQRSynchronization() {
1091
- (await this.getOrAddQRKeyring()).cancelSync();
1092
- }
1093
- /**
1094
- * Connect to QR hardware wallet.
1095
- *
1096
- * @param page - The page to connect to.
1097
- * @returns Promise resolving to the connected accounts.
1098
- * @deprecated Use of this method is discouraged as it creates a dangling promise
1099
- * internal to the `QRKeyring`, which can lead to unpredictable deadlocks. Please use
1100
- * `withKeyring` instead.
1101
- */
1102
- async connectQRHardware(page) {
1103
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
1104
- try {
1105
- const keyring = this.getQRKeyring() || await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _addQRKeyring, addQRKeyring_fn).call(this);
1106
- let accounts;
1107
- switch (page) {
1108
- case -1:
1109
- accounts = await keyring.getPreviousPage();
1110
- break;
1111
- case 1:
1112
- accounts = await keyring.getNextPage();
1113
- break;
1114
- default:
1115
- accounts = await keyring.getFirstPage();
1116
- }
1117
- return accounts.map((account) => {
1118
- return {
1119
- ...account,
1120
- balance: "0x0"
1121
- };
1122
- });
1123
- } catch (e) {
1124
- throw new Error(`Unspecified error when connect QR Hardware, ${e}`);
1125
- }
1126
- });
1127
- }
1128
- /**
1129
- * Unlock a QR hardware wallet account.
1130
- *
1131
- * @param index - The index of the account to unlock.
1132
- * @returns Promise resolving when the operation completes.
1133
- * @deprecated Use `withKeyring` instead.
1134
- */
1135
- async unlockQRHardwareWalletAccount(index) {
1136
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
1137
- const keyring = this.getQRKeyring() || await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _addQRKeyring, addQRKeyring_fn).call(this);
1138
- keyring.setAccountToUnlock(index);
1139
- await keyring.addAccounts(1);
1140
- });
1141
- }
1142
- async getAccountKeyringType(account) {
1143
- const keyring = await this.getKeyringForAccount(
1144
- account
1145
- );
1146
- return keyring.type;
1147
- }
1148
- /**
1149
- * Forget the QR hardware wallet.
1150
- *
1151
- * @returns Promise resolving to the removed accounts and the remaining accounts.
1152
- * @deprecated Use `withKeyring` instead.
1153
- */
1154
- async forgetQRDevice() {
1155
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _persistOrRollback, persistOrRollback_fn).call(this, async () => {
1156
- const keyring = this.getQRKeyring();
1157
- if (!keyring) {
1158
- return { removedAccounts: [], remainingAccounts: [] };
1159
- }
1160
- const allAccounts = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this);
1161
- keyring.forgetDevice();
1162
- const remainingAccounts = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this);
1163
- const removedAccounts = allAccounts.filter(
1164
- (address) => !remainingAccounts.includes(address)
1165
- );
1166
- return { removedAccounts, remainingAccounts };
1167
- });
1168
- }
1169
- };
1170
- _controllerOperationMutex = new WeakMap();
1171
- _vaultOperationMutex = new WeakMap();
1172
- _keyringBuilders = new WeakMap();
1173
- _keyrings = new WeakMap();
1174
- _unsupportedKeyrings = new WeakMap();
1175
- _password = new WeakMap();
1176
- _encryptor = new WeakMap();
1177
- _cacheEncryptionKey = new WeakMap();
1178
- _qrKeyringStateListener = new WeakMap();
1179
- _registerMessageHandlers = new WeakSet();
1180
- registerMessageHandlers_fn = function() {
1181
- this.messagingSystem.registerActionHandler(
1182
- `${name}:signMessage`,
1183
- this.signMessage.bind(this)
1184
- );
1185
- this.messagingSystem.registerActionHandler(
1186
- `${name}:signPersonalMessage`,
1187
- this.signPersonalMessage.bind(this)
1188
- );
1189
- this.messagingSystem.registerActionHandler(
1190
- `${name}:signTypedMessage`,
1191
- this.signTypedMessage.bind(this)
1192
- );
1193
- this.messagingSystem.registerActionHandler(
1194
- `${name}:decryptMessage`,
1195
- this.decryptMessage.bind(this)
1196
- );
1197
- this.messagingSystem.registerActionHandler(
1198
- `${name}:getEncryptionPublicKey`,
1199
- this.getEncryptionPublicKey.bind(this)
1200
- );
1201
- this.messagingSystem.registerActionHandler(
1202
- `${name}:getAccounts`,
1203
- this.getAccounts.bind(this)
1204
- );
1205
- this.messagingSystem.registerActionHandler(
1206
- `${name}:getKeyringsByType`,
1207
- this.getKeyringsByType.bind(this)
1208
- );
1209
- this.messagingSystem.registerActionHandler(
1210
- `${name}:getKeyringForAccount`,
1211
- this.getKeyringForAccount.bind(this)
1212
- );
1213
- this.messagingSystem.registerActionHandler(
1214
- `${name}:persistAllKeyrings`,
1215
- this.persistAllKeyrings.bind(this)
1216
- );
1217
- this.messagingSystem.registerActionHandler(
1218
- `${name}:prepareUserOperation`,
1219
- this.prepareUserOperation.bind(this)
1220
- );
1221
- this.messagingSystem.registerActionHandler(
1222
- `${name}:patchUserOperation`,
1223
- this.patchUserOperation.bind(this)
1224
- );
1225
- this.messagingSystem.registerActionHandler(
1226
- `${name}:signUserOperation`,
1227
- this.signUserOperation.bind(this)
1228
- );
1229
- this.messagingSystem.registerActionHandler(
1230
- `${name}:addNewAccount`,
1231
- this.addNewAccount.bind(this)
1232
- );
1233
- };
1234
- _getKeyringBuilderForType = new WeakSet();
1235
- getKeyringBuilderForType_fn = function(type) {
1236
- return _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyringBuilders).find(
1237
- (keyringBuilder) => keyringBuilder.type === type
1238
- );
1239
- };
1240
- _addQRKeyring = new WeakSet();
1241
- addQRKeyring_fn = async function() {
1242
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1243
- return await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, "QR Hardware Wallet Device" /* qr */);
1244
- };
1245
- _subscribeToQRKeyringEvents = new WeakSet();
1246
- subscribeToQRKeyringEvents_fn = function(qrKeyring) {
1247
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _qrKeyringStateListener, (state) => {
1248
- this.messagingSystem.publish(`${name}:qrKeyringStateChange`, state);
1249
- });
1250
- qrKeyring.getMemStore().subscribe(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _qrKeyringStateListener));
1251
- };
1252
- _unsubscribeFromQRKeyringsEvents = new WeakSet();
1253
- unsubscribeFromQRKeyringsEvents_fn = function() {
1254
- const qrKeyrings = this.getKeyringsByType(
1255
- "QR Hardware Wallet Device" /* qr */
1256
- );
1257
- qrKeyrings.forEach((qrKeyring) => {
1258
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _qrKeyringStateListener)) {
1259
- qrKeyring.getMemStore().unsubscribe(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _qrKeyringStateListener));
1260
- }
1261
- });
1262
- };
1263
- _createNewVaultWithKeyring = new WeakSet();
1264
- createNewVaultWithKeyring_fn = async function(password, keyring) {
1265
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1266
- if (typeof password !== "string") {
1267
- throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1268
- }
1269
- this.update((state) => {
1270
- delete state.encryptionKey;
1271
- delete state.encryptionSalt;
1272
- });
1273
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, password);
1274
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
1275
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _createKeyringWithFirstAccount, createKeyringWithFirstAccount_fn).call(this, keyring.type, keyring.opts);
1276
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _setUnlocked, setUnlocked_fn).call(this);
1277
- };
1278
- _getUpdatedKeyrings = new WeakSet();
1279
- getUpdatedKeyrings_fn = async function() {
1280
- return Promise.all(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).map(displayForKeyring));
1281
- };
1282
- _getSerializedKeyrings = new WeakSet();
1283
- getSerializedKeyrings_fn = async function({ includeUnsupported } = {
1284
- includeUnsupported: true
1285
- }) {
1286
- const serializedKeyrings = await Promise.all(
1287
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
1288
- const [type, data] = await Promise.all([
1289
- keyring.type,
1290
- keyring.serialize()
1291
- ]);
1292
- return { type, data };
1293
- })
1294
- );
1295
- if (includeUnsupported) {
1296
- serializedKeyrings.push(..._chunkNOCGQCUMjs.__privateGet.call(void 0, this, _unsupportedKeyrings));
1297
- }
1298
- return serializedKeyrings;
1299
- };
1300
- _restoreSerializedKeyrings = new WeakSet();
1301
- restoreSerializedKeyrings_fn = async function(serializedKeyrings) {
1302
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _clearKeyrings, clearKeyrings_fn).call(this);
1303
- for (const serializedKeyring of serializedKeyrings) {
1304
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _restoreKeyring, restoreKeyring_fn).call(this, serializedKeyring);
1305
- }
1306
- };
1307
- _unlockKeyrings = new WeakSet();
1308
- unlockKeyrings_fn = async function(password, encryptionKey, encryptionSalt) {
1309
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withVaultLock, withVaultLock_fn).call(this, async ({ releaseLock }) => {
1310
- const encryptedVault = this.state.vault;
1311
- if (!encryptedVault) {
1312
- throw new Error("KeyringController - Cannot unlock without a previous vault." /* VaultError */);
1313
- }
1314
- let vault;
1315
- const updatedState = {};
1316
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
1317
- assertIsExportableKeyEncryptor(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor));
1318
- if (password) {
1319
- const result = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).decryptWithDetail(
1320
- password,
1321
- encryptedVault
1322
- );
1323
- vault = result.vault;
1324
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, password);
1325
- updatedState.encryptionKey = result.exportedKeyString;
1326
- updatedState.encryptionSalt = result.salt;
1327
- } else {
1328
- const parsedEncryptedVault = JSON.parse(encryptedVault);
1329
- if (encryptionSalt !== parsedEncryptedVault.salt) {
1330
- throw new Error("KeyringController - Encryption key and salt provided are expired" /* ExpiredCredentials */);
1331
- }
1332
- if (typeof encryptionKey !== "string") {
1333
- throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1334
- }
1335
- const key = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).importKey(encryptionKey);
1336
- vault = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).decryptWithKey(
1337
- key,
1338
- parsedEncryptedVault
1339
- );
1340
- updatedState.encryptionKey = encryptionKey;
1341
- updatedState.encryptionSalt = encryptionSalt;
1342
- }
1343
- } else {
1344
- if (typeof password !== "string") {
1345
- throw new TypeError("KeyringController - Password must be of type string." /* WrongPasswordType */);
1346
- }
1347
- vault = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).decrypt(password, encryptedVault);
1348
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, password);
1349
- }
1350
- if (!isSerializedKeyringsArray(vault)) {
1351
- throw new Error("KeyringController - The decrypted vault has an unexpected shape." /* VaultDataError */);
1352
- }
1353
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _restoreSerializedKeyrings, restoreSerializedKeyrings_fn).call(this, vault);
1354
- const updatedKeyrings = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getUpdatedKeyrings, getUpdatedKeyrings_fn).call(this);
1355
- this.update((state) => {
1356
- state.keyrings = updatedKeyrings;
1357
- if (updatedState.encryptionKey || updatedState.encryptionSalt) {
1358
- state.encryptionKey = updatedState.encryptionKey;
1359
- state.encryptionSalt = updatedState.encryptionSalt;
1360
- }
1361
- });
1362
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password) && (!_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _cacheEncryptionKey) || !encryptionKey) && _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).isVaultUpdated && !_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).isVaultUpdated(encryptedVault)) {
1363
- releaseLock();
1364
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _updateVault, updateVault_fn).call(this);
1365
- }
1366
- return _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings);
1367
- });
1368
- };
1369
- _updateVault = new WeakSet();
1370
- updateVault_fn = function() {
1371
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withVaultLock, withVaultLock_fn).call(this, async () => {
1372
- const { encryptionKey, encryptionSalt } = this.state;
1373
- if (!_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password) && !encryptionKey) {
1374
- throw new Error("KeyringController - Cannot persist vault without password and encryption key" /* MissingCredentials */);
1375
- }
1376
- const serializedKeyrings = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getSerializedKeyrings, getSerializedKeyrings_fn).call(this);
1377
- if (!serializedKeyrings.some((keyring) => keyring.type === "HD Key Tree" /* hd */)) {
1378
- throw new Error("KeyringController - No HD Keyring found" /* NoHdKeyring */);
1379
- }
1380
- const updatedState = {};
1381
- if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _cacheEncryptionKey)) {
1382
- assertIsExportableKeyEncryptor(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor));
1383
- if (encryptionKey) {
1384
- const key = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).importKey(encryptionKey);
1385
- const vaultJSON = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).encryptWithKey(
1386
- key,
1387
- serializedKeyrings
1388
- );
1389
- vaultJSON.salt = encryptionSalt;
1390
- updatedState.vault = JSON.stringify(vaultJSON);
1391
- } else if (_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password)) {
1392
- const { vault: newVault, exportedKeyString } = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).encryptWithDetail(
1393
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password),
1394
- serializedKeyrings
1395
- );
1396
- updatedState.vault = newVault;
1397
- updatedState.encryptionKey = exportedKeyString;
1398
- }
1399
- } else {
1400
- assertIsValidPassword(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password));
1401
- updatedState.vault = await _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _encryptor).encrypt(
1402
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password),
1403
- serializedKeyrings
1404
- );
1405
- }
1406
- if (!updatedState.vault) {
1407
- throw new Error("KeyringController - Cannot persist vault without vault information" /* MissingVaultData */);
1408
- }
1409
- const updatedKeyrings = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getUpdatedKeyrings, getUpdatedKeyrings_fn).call(this);
1410
- this.update((state) => {
1411
- state.vault = updatedState.vault;
1412
- state.keyrings = updatedKeyrings;
1413
- if (updatedState.encryptionKey) {
1414
- state.encryptionKey = updatedState.encryptionKey;
1415
- state.encryptionSalt = JSON.parse(updatedState.vault).salt;
1416
- }
1417
- });
1418
- return true;
1419
- });
1420
- };
1421
- _getAccountsFromKeyrings = new WeakSet();
1422
- getAccountsFromKeyrings_fn = async function() {
1423
- const keyrings = _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings);
1424
- const keyringArrays = await Promise.all(
1425
- keyrings.map(async (keyring) => keyring.getAccounts())
1426
- );
1427
- const addresses = keyringArrays.reduce((res, arr) => {
1428
- return res.concat(arr);
1429
- }, []);
1430
- return addresses.map(normalize);
1431
- };
1432
- _createKeyringWithFirstAccount = new WeakSet();
1433
- createKeyringWithFirstAccount_fn = async function(type, opts) {
1434
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1435
- const keyring = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, type, opts);
1436
- const [firstAccount] = await keyring.getAccounts();
1437
- if (!firstAccount) {
1438
- throw new Error("KeyringController - First Account not found." /* NoFirstAccount */);
1439
- }
1440
- };
1441
- _newKeyring = new WeakSet();
1442
- newKeyring_fn = async function(type, data) {
1443
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1444
- const keyringBuilder = _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getKeyringBuilderForType, getKeyringBuilderForType_fn).call(this, type);
1445
- if (!keyringBuilder) {
1446
- throw new Error(
1447
- `${"KeyringController - No keyringBuilder found for keyring" /* NoKeyringBuilder */}. Keyring type: ${type}`
1448
- );
1449
- }
1450
- const keyring = keyringBuilder();
1451
- await keyring.deserialize(data);
1452
- if (keyring.init) {
1453
- await keyring.init();
1454
- }
1455
- if (type === "HD Key Tree" /* hd */ && (!_utils.isObject.call(void 0, data) || !data.mnemonic)) {
1456
- if (!keyring.generateRandomMnemonic) {
1457
- throw new Error(
1458
- "KeyringController - The current keyring does not support the method generateRandomMnemonic." /* UnsupportedGenerateRandomMnemonic */
1459
- );
1460
- }
1461
- keyring.generateRandomMnemonic();
1462
- await keyring.addAccounts(1);
1463
- }
1464
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _checkForDuplicate, checkForDuplicate_fn).call(this, type, await keyring.getAccounts());
1465
- if (type === "QR Hardware Wallet Device" /* qr */) {
1466
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _subscribeToQRKeyringEvents, subscribeToQRKeyringEvents_fn).call(this, keyring);
1467
- }
1468
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).push(keyring);
1469
- return keyring;
1470
- };
1471
- _clearKeyrings = new WeakSet();
1472
- clearKeyrings_fn = async function() {
1473
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1474
- for (const keyring of _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings)) {
1475
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _destroyKeyring, destroyKeyring_fn).call(this, keyring);
1476
- }
1477
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyrings, []);
1478
- };
1479
- _restoreKeyring = new WeakSet();
1480
- restoreKeyring_fn = async function(serialized) {
1481
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1482
- try {
1483
- const { type, data } = serialized;
1484
- return await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _newKeyring, newKeyring_fn).call(this, type, data);
1485
- } catch (_) {
1486
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _unsupportedKeyrings).push(serialized);
1487
- return void 0;
1488
- }
1489
- };
1490
- _destroyKeyring = new WeakSet();
1491
- destroyKeyring_fn = async function(keyring) {
1492
- await keyring.destroy?.();
1493
- };
1494
- _removeEmptyKeyrings = new WeakSet();
1495
- removeEmptyKeyrings_fn = async function() {
1496
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1497
- const validKeyrings = [];
1498
- await Promise.all(
1499
- _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _keyrings).map(async (keyring) => {
1500
- const accounts = await keyring.getAccounts();
1501
- if (accounts.length > 0) {
1502
- validKeyrings.push(keyring);
1503
- } else {
1504
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _destroyKeyring, destroyKeyring_fn).call(this, keyring);
1505
- }
1506
- })
1507
- );
1508
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _keyrings, validKeyrings);
1509
- };
1510
- _checkForDuplicate = new WeakSet();
1511
- checkForDuplicate_fn = async function(type, newAccountArray) {
1512
- const accounts = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getAccountsFromKeyrings, getAccountsFromKeyrings_fn).call(this);
1513
- switch (type) {
1514
- case "Simple Key Pair" /* simple */: {
1515
- const isIncluded = Boolean(
1516
- accounts.find(
1517
- (key) => newAccountArray[0] && (key === newAccountArray[0] || key === _utils.remove0x.call(void 0, newAccountArray[0]))
1518
- )
1519
- );
1520
- if (isIncluded) {
1521
- throw new Error("KeyringController - The account you are trying to import is a duplicate" /* DuplicatedAccount */);
1522
- }
1523
- return newAccountArray;
1524
- }
1525
- default: {
1526
- return newAccountArray;
1527
- }
1528
- }
1529
- };
1530
- _setUnlocked = new WeakSet();
1531
- setUnlocked_fn = function() {
1532
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1533
- this.update((state) => {
1534
- state.isUnlocked = true;
1535
- });
1536
- this.messagingSystem.publish(`${name}:unlock`);
1537
- };
1538
- _persistOrRollback = new WeakSet();
1539
- persistOrRollback_fn = async function(fn) {
1540
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withRollback, withRollback_fn).call(this, async ({ releaseLock }) => {
1541
- const callbackResult = await fn({ releaseLock });
1542
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _updateVault, updateVault_fn).call(this);
1543
- return callbackResult;
1544
- });
1545
- };
1546
- _withRollback = new WeakSet();
1547
- withRollback_fn = async function(fn) {
1548
- return _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _withControllerLock, withControllerLock_fn).call(this, async ({ releaseLock }) => {
1549
- const currentSerializedKeyrings = await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _getSerializedKeyrings, getSerializedKeyrings_fn).call(this);
1550
- const currentPassword = _chunkNOCGQCUMjs.__privateGet.call(void 0, this, _password);
1551
- try {
1552
- return await fn({ releaseLock });
1553
- } catch (e) {
1554
- await _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _restoreSerializedKeyrings, restoreSerializedKeyrings_fn).call(this, currentSerializedKeyrings);
1555
- _chunkNOCGQCUMjs.__privateSet.call(void 0, this, _password, currentPassword);
1556
- throw e;
1557
- }
1558
- });
1559
- };
1560
- _assertControllerMutexIsLocked = new WeakSet();
1561
- assertControllerMutexIsLocked_fn = function() {
1562
- if (!_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _controllerOperationMutex).isLocked()) {
1563
- throw new Error("KeyringController - attempt to update vault during a non mutually exclusive operation" /* ControllerLockRequired */);
1564
- }
1565
- };
1566
- _withControllerLock = new WeakSet();
1567
- withControllerLock_fn = async function(fn) {
1568
- return withLock(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _controllerOperationMutex), fn);
1569
- };
1570
- _withVaultLock = new WeakSet();
1571
- withVaultLock_fn = async function(fn) {
1572
- _chunkNOCGQCUMjs.__privateMethod.call(void 0, this, _assertControllerMutexIsLocked, assertControllerMutexIsLocked_fn).call(this);
1573
- return withLock(_chunkNOCGQCUMjs.__privateGet.call(void 0, this, _vaultOperationMutex), fn);
1574
- };
1575
- async function withLock(mutex, fn) {
1576
- const releaseLock = await mutex.acquire();
1577
- try {
1578
- return await fn({ releaseLock });
1579
- } finally {
1580
- releaseLock();
1581
- }
1582
- }
1583
- var KeyringController_default = KeyringController;
1584
-
1585
-
1586
-
1587
-
1588
-
1589
-
1590
-
1591
-
1592
-
1593
-
1594
- 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;
1595
- //# sourceMappingURL=chunk-YRSQWNOT.js.map