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