@metamask-previews/keyring-controller 7.1.0-preview.d32a7cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,763 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
35
+ if (kind === "m") throw new TypeError("Private method is not writable");
36
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
37
+ 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");
38
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
39
+ };
40
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
41
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
42
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
43
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
44
+ };
45
+ var _KeyringController_instances, _KeyringController_keyring, _KeyringController_addQRKeyring, _KeyringController_fullUpdate, _KeyringController_handleLock, _KeyringController_handleUnlock, _KeyringController_getMemState;
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.KeyringController = exports.SignTypedDataVersion = exports.AccountImportStrategy = exports.KeyringTypes = void 0;
48
+ const base_controller_1 = require("@metamask/base-controller");
49
+ const eth_keyring_controller_1 = require("@metamask/eth-keyring-controller");
50
+ const utils_1 = require("@metamask/utils");
51
+ const async_mutex_1 = require("async-mutex");
52
+ const ethereumjs_util_1 = require("ethereumjs-util");
53
+ const ethereumjs_wallet_1 = __importStar(require("ethereumjs-wallet"));
54
+ const name = 'KeyringController';
55
+ /**
56
+ * Available keyring types
57
+ */
58
+ var KeyringTypes;
59
+ (function (KeyringTypes) {
60
+ KeyringTypes["simple"] = "Simple Key Pair";
61
+ KeyringTypes["hd"] = "HD Key Tree";
62
+ KeyringTypes["qr"] = "QR Hardware Wallet Device";
63
+ })(KeyringTypes = exports.KeyringTypes || (exports.KeyringTypes = {}));
64
+ /**
65
+ * A strategy for importing an account
66
+ */
67
+ var AccountImportStrategy;
68
+ (function (AccountImportStrategy) {
69
+ AccountImportStrategy["privateKey"] = "privateKey";
70
+ AccountImportStrategy["json"] = "json";
71
+ })(AccountImportStrategy = exports.AccountImportStrategy || (exports.AccountImportStrategy = {}));
72
+ /**
73
+ * The `signTypedMessage` version
74
+ *
75
+ * @see https://docs.metamask.io/guide/signing-data.html
76
+ */
77
+ var SignTypedDataVersion;
78
+ (function (SignTypedDataVersion) {
79
+ SignTypedDataVersion["V1"] = "V1";
80
+ SignTypedDataVersion["V3"] = "V3";
81
+ SignTypedDataVersion["V4"] = "V4";
82
+ })(SignTypedDataVersion = exports.SignTypedDataVersion || (exports.SignTypedDataVersion = {}));
83
+ const defaultState = {
84
+ isUnlocked: false,
85
+ keyrings: [],
86
+ };
87
+ /**
88
+ * Assert that the given keyring has an exportable
89
+ * mnemonic.
90
+ *
91
+ * @param keyring - The keyring to check
92
+ * @throws When the keyring does not have a mnemonic
93
+ */
94
+ function assertHasUint8ArrayMnemonic(keyring) {
95
+ if (!((0, utils_1.hasProperty)(keyring, 'mnemonic') && keyring.mnemonic instanceof Uint8Array)) {
96
+ throw new Error("Can't get mnemonic bytes from keyring");
97
+ }
98
+ }
99
+ /**
100
+ * Controller responsible for establishing and managing user identity.
101
+ *
102
+ * This class is a wrapper around the `eth-keyring-controller` package. The
103
+ * `eth-keyring-controller` manages the "vault", which is an encrypted store of private keys, and
104
+ * it manages the wallet "lock" state. This wrapper class has convenience methods for interacting
105
+ * with the internal keyring controller and handling certain complex operations that involve the
106
+ * keyrings.
107
+ */
108
+ class KeyringController extends base_controller_1.BaseControllerV2 {
109
+ /**
110
+ * Creates a KeyringController instance.
111
+ *
112
+ * @param opts - Initial options used to configure this controller
113
+ * @param opts.removeIdentity - Remove the identity with the given address.
114
+ * @param opts.syncIdentities - Sync identities with the given list of addresses.
115
+ * @param opts.updateIdentities - Generate an identity for each address given that doesn't already have an identity.
116
+ * @param opts.setSelectedAddress - Set the selected address.
117
+ * @param opts.setAccountLabel - Set a new name for account.
118
+ * @param opts.encryptor - An optional object for defining encryption schemes.
119
+ * @param opts.keyringBuilders - Set a new name for account.
120
+ * @param opts.cacheEncryptionKey - Whether to cache or not encryption key.
121
+ * @param opts.messenger - A restricted controller messenger.
122
+ * @param opts.state - Initial state to set on this controller.
123
+ */
124
+ constructor({ removeIdentity, syncIdentities, updateIdentities, setSelectedAddress, setAccountLabel, encryptor, keyringBuilders, cacheEncryptionKey = false, messenger, state, }) {
125
+ super({
126
+ name,
127
+ metadata: {
128
+ vault: { persist: true, anonymous: false },
129
+ isUnlocked: { persist: false, anonymous: true },
130
+ keyrings: { persist: false, anonymous: false },
131
+ encryptionKey: { persist: false, anonymous: false },
132
+ encryptionSalt: { persist: false, anonymous: false },
133
+ },
134
+ messenger,
135
+ state: Object.assign(Object.assign({}, defaultState), state),
136
+ });
137
+ _KeyringController_instances.add(this);
138
+ this.mutex = new async_mutex_1.Mutex();
139
+ _KeyringController_keyring.set(this, void 0);
140
+ __classPrivateFieldSet(this, _KeyringController_keyring, new eth_keyring_controller_1.KeyringController({
141
+ initState: state,
142
+ encryptor,
143
+ keyringBuilders,
144
+ cacheEncryptionKey,
145
+ }), "f");
146
+ __classPrivateFieldGet(this, _KeyringController_keyring, "f").memStore.subscribe(__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_fullUpdate).bind(this));
147
+ __classPrivateFieldGet(this, _KeyringController_keyring, "f").store.subscribe(__classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_fullUpdate).bind(this));
148
+ __classPrivateFieldGet(this, _KeyringController_keyring, "f").on('lock', __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_handleLock).bind(this));
149
+ __classPrivateFieldGet(this, _KeyringController_keyring, "f").on('unlock', __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_handleUnlock).bind(this));
150
+ this.removeIdentity = removeIdentity;
151
+ this.syncIdentities = syncIdentities;
152
+ this.updateIdentities = updateIdentities;
153
+ this.setSelectedAddress = setSelectedAddress;
154
+ this.setAccountLabel = setAccountLabel;
155
+ }
156
+ /**
157
+ * Adds a new account to the default (first) HD seed phrase keyring.
158
+ *
159
+ * @param accountCount - Number of accounts before adding a new one, used to
160
+ * make the method idempotent.
161
+ * @returns Promise resolving to keyring current state and added account
162
+ * address.
163
+ */
164
+ addNewAccount(accountCount) {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType('HD Key Tree')[0];
167
+ /* istanbul ignore if */
168
+ if (!primaryKeyring) {
169
+ throw new Error('No HD keyring found');
170
+ }
171
+ const oldAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
172
+ if (accountCount && oldAccounts.length !== accountCount) {
173
+ if (accountCount > oldAccounts.length) {
174
+ throw new Error('Account out of sequence');
175
+ }
176
+ // we return the account already existing at index `accountCount`
177
+ const primaryKeyringAccounts = yield primaryKeyring.getAccounts();
178
+ return {
179
+ keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
180
+ addedAccountAddress: primaryKeyringAccounts[accountCount],
181
+ };
182
+ }
183
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(primaryKeyring);
184
+ const newAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
185
+ yield this.verifySeedPhrase();
186
+ this.updateIdentities(newAccounts);
187
+ const addedAccountAddress = newAccounts.find((selectedAddress) => !oldAccounts.includes(selectedAddress));
188
+ (0, utils_1.assertIsStrictHexString)(addedAccountAddress);
189
+ return {
190
+ keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
191
+ addedAccountAddress,
192
+ };
193
+ });
194
+ }
195
+ /**
196
+ * Adds a new account to the specified keyring.
197
+ *
198
+ * @param keyring - Keyring to add the account to.
199
+ * @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.
200
+ * @returns Promise resolving to keyring current state and added account
201
+ */
202
+ addNewAccountForKeyring(keyring, accountCount) {
203
+ return __awaiter(this, void 0, void 0, function* () {
204
+ const oldAccounts = yield keyring.getAccounts();
205
+ if (accountCount && oldAccounts.length !== accountCount) {
206
+ if (accountCount > oldAccounts.length) {
207
+ throw new Error('Account out of sequence');
208
+ }
209
+ return oldAccounts[accountCount];
210
+ }
211
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(keyring);
212
+ const addedAccountAddress = (yield keyring.getAccounts()).find((selectedAddress) => !oldAccounts.includes(selectedAddress));
213
+ (0, utils_1.assertIsStrictHexString)(addedAccountAddress);
214
+ this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
215
+ return addedAccountAddress;
216
+ });
217
+ }
218
+ /**
219
+ * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences.
220
+ *
221
+ * @returns Promise resolving to current state when the account is added.
222
+ */
223
+ addNewAccountWithoutUpdate() {
224
+ return __awaiter(this, void 0, void 0, function* () {
225
+ const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType('HD Key Tree')[0];
226
+ /* istanbul ignore if */
227
+ if (!primaryKeyring) {
228
+ throw new Error('No HD keyring found');
229
+ }
230
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(primaryKeyring);
231
+ yield this.verifySeedPhrase();
232
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
233
+ });
234
+ }
235
+ /**
236
+ * Effectively the same as creating a new keychain then populating it
237
+ * using the given seed phrase.
238
+ *
239
+ * @param password - Password to unlock keychain.
240
+ * @param seed - A BIP39-compliant seed phrase as Uint8Array,
241
+ * either as a string or an array of UTF-8 bytes that represent the string.
242
+ * @returns Promise resolving to the restored keychain object.
243
+ */
244
+ createNewVaultAndRestore(password, seed) {
245
+ return __awaiter(this, void 0, void 0, function* () {
246
+ const releaseLock = yield this.mutex.acquire();
247
+ if (!password || !password.length) {
248
+ throw new Error('Invalid password');
249
+ }
250
+ try {
251
+ this.updateIdentities([]);
252
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").createNewVaultAndRestore(password, seed);
253
+ this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
254
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
255
+ }
256
+ finally {
257
+ releaseLock();
258
+ }
259
+ });
260
+ }
261
+ /**
262
+ * Create a new primary keychain and wipe any previous keychains.
263
+ *
264
+ * @param password - Password to unlock the new vault.
265
+ * @returns Newly-created keychain object.
266
+ */
267
+ createNewVaultAndKeychain(password) {
268
+ return __awaiter(this, void 0, void 0, function* () {
269
+ const releaseLock = yield this.mutex.acquire();
270
+ try {
271
+ const accounts = yield this.getAccounts();
272
+ if (!accounts.length) {
273
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").createNewVaultAndKeychain(password);
274
+ this.updateIdentities(yield this.getAccounts());
275
+ }
276
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
277
+ }
278
+ finally {
279
+ releaseLock();
280
+ }
281
+ });
282
+ }
283
+ /**
284
+ * Adds a new keyring of the given `type`.
285
+ *
286
+ * @param type - Keyring type name.
287
+ * @param opts - Keyring options.
288
+ * @throws If a builder for the given `type` does not exist.
289
+ * @returns Promise resolving to the added keyring.
290
+ */
291
+ addNewKeyring(type, opts) {
292
+ return __awaiter(this, void 0, void 0, function* () {
293
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(type, opts);
294
+ });
295
+ }
296
+ /**
297
+ * Method to verify a given password validity. Throws an
298
+ * error if the password is invalid.
299
+ *
300
+ * @param password - Password of the keyring.
301
+ */
302
+ verifyPassword(password) {
303
+ return __awaiter(this, void 0, void 0, function* () {
304
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").verifyPassword(password);
305
+ });
306
+ }
307
+ /**
308
+ * Returns the status of the vault.
309
+ *
310
+ * @returns Boolean returning true if the vault is unlocked.
311
+ */
312
+ isUnlocked() {
313
+ return this.state.isUnlocked;
314
+ }
315
+ /**
316
+ * Gets the seed phrase of the HD keyring.
317
+ *
318
+ * @param password - Password of the keyring.
319
+ * @returns Promise resolving to the seed phrase.
320
+ */
321
+ exportSeedPhrase(password) {
322
+ return __awaiter(this, void 0, void 0, function* () {
323
+ yield this.verifyPassword(password);
324
+ assertHasUint8ArrayMnemonic(__classPrivateFieldGet(this, _KeyringController_keyring, "f").keyrings[0]);
325
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").keyrings[0].mnemonic;
326
+ });
327
+ }
328
+ /**
329
+ * Gets the private key from the keyring controlling an address.
330
+ *
331
+ * @param password - Password of the keyring.
332
+ * @param address - Address to export.
333
+ * @returns Promise resolving to the private key for an address.
334
+ */
335
+ exportAccount(password, address) {
336
+ return __awaiter(this, void 0, void 0, function* () {
337
+ yield this.verifyPassword(password);
338
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").exportAccount(address);
339
+ });
340
+ }
341
+ /**
342
+ * Returns the public addresses of all accounts for the current keyring.
343
+ *
344
+ * @returns A promise resolving to an array of addresses.
345
+ */
346
+ getAccounts() {
347
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
348
+ }
349
+ /**
350
+ * Get encryption public key.
351
+ *
352
+ * @param account - An account address.
353
+ * @param opts - Additional encryption options.
354
+ * @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method
355
+ * @returns Promise resolving to encyption public key of the `account` if one exists.
356
+ */
357
+ getEncryptionPublicKey(account, opts) {
358
+ return __awaiter(this, void 0, void 0, function* () {
359
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getEncryptionPublicKey(account, opts);
360
+ });
361
+ }
362
+ /**
363
+ * Returns the currently initialized keyring that manages
364
+ * the specified `address` if one exists.
365
+ *
366
+ * @deprecated Use of this method is discouraged as actions executed directly on
367
+ * keyrings are not being reflected in the KeyringController state and not
368
+ * persisted in the vault.
369
+ * @param account - An account address.
370
+ * @returns Promise resolving to keyring of the `account` if one exists.
371
+ */
372
+ getKeyringForAccount(account) {
373
+ return __awaiter(this, void 0, void 0, function* () {
374
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringForAccount(account);
375
+ });
376
+ }
377
+ /**
378
+ * Returns all keyrings of the given type.
379
+ *
380
+ * @deprecated Use of this method is discouraged as actions executed directly on
381
+ * keyrings are not being reflected in the KeyringController state and not
382
+ * persisted in the vault.
383
+ * @param type - Keyring type name.
384
+ * @returns An array of keyrings of the given type.
385
+ */
386
+ getKeyringsByType(type) {
387
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(type);
388
+ }
389
+ /**
390
+ * Persist all serialized keyrings in the vault.
391
+ *
392
+ * @returns Promise resolving with `true` value when the
393
+ * operation completes.
394
+ */
395
+ persistAllKeyrings() {
396
+ return __awaiter(this, void 0, void 0, function* () {
397
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
398
+ });
399
+ }
400
+ /**
401
+ * Imports an account with the specified import strategy.
402
+ *
403
+ * @param strategy - Import strategy name.
404
+ * @param args - Array of arguments to pass to the underlying stategy.
405
+ * @throws Will throw when passed an unrecognized strategy.
406
+ * @returns Promise resolving to keyring current state and imported account
407
+ * address.
408
+ */
409
+ importAccountWithStrategy(strategy, args) {
410
+ return __awaiter(this, void 0, void 0, function* () {
411
+ let privateKey;
412
+ switch (strategy) {
413
+ case 'privateKey':
414
+ const [importedKey] = args;
415
+ if (!importedKey) {
416
+ throw new Error('Cannot import an empty key.');
417
+ }
418
+ const prefixed = (0, ethereumjs_util_1.addHexPrefix)(importedKey);
419
+ let bufferedPrivateKey;
420
+ try {
421
+ bufferedPrivateKey = (0, ethereumjs_util_1.toBuffer)(prefixed);
422
+ }
423
+ catch (_a) {
424
+ throw new Error('Cannot import invalid private key.');
425
+ }
426
+ /* istanbul ignore if */
427
+ if (!(0, ethereumjs_util_1.isValidPrivate)(bufferedPrivateKey) ||
428
+ // ensures that the key is 64 bytes long
429
+ (0, ethereumjs_util_1.getBinarySize)(prefixed) !== 64 + '0x'.length) {
430
+ throw new Error('Cannot import invalid private key.');
431
+ }
432
+ privateKey = (0, ethereumjs_util_1.stripHexPrefix)(prefixed);
433
+ break;
434
+ case 'json':
435
+ let wallet;
436
+ const [input, password] = args;
437
+ try {
438
+ wallet = ethereumjs_wallet_1.thirdparty.fromEtherWallet(input, password);
439
+ }
440
+ catch (e) {
441
+ wallet = wallet || (yield ethereumjs_wallet_1.default.fromV3(input, password, true));
442
+ }
443
+ privateKey = (0, ethereumjs_util_1.bufferToHex)(wallet.getPrivateKey());
444
+ break;
445
+ default:
446
+ throw new Error(`Unexpected import strategy: '${strategy}'`);
447
+ }
448
+ const newKeyring = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(KeyringTypes.simple, [
449
+ privateKey,
450
+ ]);
451
+ const accounts = yield newKeyring.getAccounts();
452
+ const allAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
453
+ this.updateIdentities(allAccounts);
454
+ return {
455
+ keyringState: __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this),
456
+ importedAccountAddress: accounts[0],
457
+ };
458
+ });
459
+ }
460
+ /**
461
+ * Removes an account from keyring state.
462
+ *
463
+ * @param address - Address of the account to remove.
464
+ * @fires KeyringController:accountRemoved
465
+ * @returns Promise resolving current state when this account removal completes.
466
+ */
467
+ removeAccount(address) {
468
+ return __awaiter(this, void 0, void 0, function* () {
469
+ this.removeIdentity(address);
470
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").removeAccount(address);
471
+ this.messagingSystem.publish(`${name}:accountRemoved`, address);
472
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
473
+ });
474
+ }
475
+ /**
476
+ * Deallocates all secrets and locks the wallet.
477
+ *
478
+ * @returns Promise resolving to current state.
479
+ */
480
+ setLocked() {
481
+ return __awaiter(this, void 0, void 0, function* () {
482
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").setLocked();
483
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
484
+ });
485
+ }
486
+ /**
487
+ * Signs message by calling down into a specific keyring.
488
+ *
489
+ * @param messageParams - PersonalMessageParams object to sign.
490
+ * @returns Promise resolving to a signed message string.
491
+ */
492
+ signMessage(messageParams) {
493
+ if (!messageParams.data) {
494
+ throw new Error("Can't sign an empty message");
495
+ }
496
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signMessage(messageParams);
497
+ }
498
+ /**
499
+ * Signs personal message by calling down into a specific keyring.
500
+ *
501
+ * @param messageParams - PersonalMessageParams object to sign.
502
+ * @returns Promise resolving to a signed message string.
503
+ */
504
+ signPersonalMessage(messageParams) {
505
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signPersonalMessage(messageParams);
506
+ }
507
+ /**
508
+ * Signs typed message by calling down into a specific keyring.
509
+ *
510
+ * @param messageParams - TypedMessageParams object to sign.
511
+ * @param version - Compatibility version EIP712.
512
+ * @throws Will throw when passed an unrecognized version.
513
+ * @returns Promise resolving to a signed message string or an error if any.
514
+ */
515
+ signTypedMessage(messageParams, version) {
516
+ return __awaiter(this, void 0, void 0, function* () {
517
+ try {
518
+ if (![
519
+ SignTypedDataVersion.V1,
520
+ SignTypedDataVersion.V3,
521
+ SignTypedDataVersion.V4,
522
+ ].includes(version)) {
523
+ throw new Error(`Unexpected signTypedMessage version: '${version}'`);
524
+ }
525
+ return yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").signTypedMessage({
526
+ from: messageParams.from,
527
+ data: version !== SignTypedDataVersion.V1 &&
528
+ typeof messageParams.data === 'string'
529
+ ? JSON.parse(messageParams.data)
530
+ : messageParams.data,
531
+ }, { version });
532
+ }
533
+ catch (error) {
534
+ throw new Error(`Keyring Controller signTypedMessage: ${error}`);
535
+ }
536
+ });
537
+ }
538
+ /**
539
+ * Signs a transaction by calling down into a specific keyring.
540
+ *
541
+ * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance.
542
+ * @param from - Address to sign from, should be in keychain.
543
+ * @returns Promise resolving to a signed transaction string.
544
+ */
545
+ signTransaction(transaction, from) {
546
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").signTransaction(transaction, from);
547
+ }
548
+ /**
549
+ * Attempts to decrypt the current vault and load its keyrings,
550
+ * using the given encryption key and salt.
551
+ *
552
+ * @param encryptionKey - Key to unlock the keychain.
553
+ * @param encryptionSalt - Salt to unlock the keychain.
554
+ * @returns Promise resolving to the current state.
555
+ */
556
+ submitEncryptionKey(encryptionKey, encryptionSalt) {
557
+ return __awaiter(this, void 0, void 0, function* () {
558
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").submitEncryptionKey(encryptionKey, encryptionSalt);
559
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
560
+ });
561
+ }
562
+ /**
563
+ * Attempts to decrypt the current vault and load its keyrings,
564
+ * using the given password.
565
+ *
566
+ * @param password - Password to unlock the keychain.
567
+ * @returns Promise resolving to the current state.
568
+ */
569
+ submitPassword(password) {
570
+ return __awaiter(this, void 0, void 0, function* () {
571
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").submitPassword(password);
572
+ const accounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
573
+ yield this.syncIdentities(accounts);
574
+ return __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_getMemState).call(this);
575
+ });
576
+ }
577
+ /**
578
+ * Verifies the that the seed phrase restores the current keychain's accounts.
579
+ *
580
+ * @returns Promise resolving to the seed phrase as Uint8Array.
581
+ */
582
+ verifySeedPhrase() {
583
+ return __awaiter(this, void 0, void 0, function* () {
584
+ const primaryKeyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(KeyringTypes.hd)[0];
585
+ /* istanbul ignore if */
586
+ if (!primaryKeyring) {
587
+ throw new Error('No HD keyring found.');
588
+ }
589
+ assertHasUint8ArrayMnemonic(primaryKeyring);
590
+ const seedWords = primaryKeyring.mnemonic;
591
+ const accounts = yield primaryKeyring.getAccounts();
592
+ /* istanbul ignore if */
593
+ if (accounts.length === 0) {
594
+ throw new Error('Cannot verify an empty keyring.');
595
+ }
596
+ // The HD Keyring Builder is a default keyring builder
597
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
598
+ const hdKeyringBuilder = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringBuilderForType(KeyringTypes.hd);
599
+ const hdKeyring = hdKeyringBuilder();
600
+ // @ts-expect-error @metamask/eth-hd-keyring correctly handles
601
+ // Uint8Array seed phrases in the `deserialize` method.
602
+ hdKeyring.deserialize({
603
+ mnemonic: seedWords,
604
+ numberOfAccounts: accounts.length,
605
+ });
606
+ const testAccounts = yield hdKeyring.getAccounts();
607
+ /* istanbul ignore if */
608
+ if (testAccounts.length !== accounts.length) {
609
+ throw new Error('Seed phrase imported incorrect number of accounts.');
610
+ }
611
+ testAccounts.forEach((account, i) => {
612
+ /* istanbul ignore if */
613
+ if (account.toLowerCase() !== accounts[i].toLowerCase()) {
614
+ throw new Error('Seed phrase imported different accounts.');
615
+ }
616
+ });
617
+ return seedWords;
618
+ });
619
+ }
620
+ // QR Hardware related methods
621
+ /**
622
+ * Get qr hardware keyring.
623
+ *
624
+ * @returns The added keyring
625
+ */
626
+ getOrAddQRKeyring() {
627
+ return __awaiter(this, void 0, void 0, function* () {
628
+ const keyring = __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringsByType(KeyringTypes.qr)[0] || (yield __classPrivateFieldGet(this, _KeyringController_instances, "m", _KeyringController_addQRKeyring).call(this));
629
+ return keyring;
630
+ });
631
+ }
632
+ restoreQRKeyring(serialized) {
633
+ return __awaiter(this, void 0, void 0, function* () {
634
+ (yield this.getOrAddQRKeyring()).deserialize(serialized);
635
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
636
+ this.updateIdentities(yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
637
+ });
638
+ }
639
+ resetQRKeyringState() {
640
+ return __awaiter(this, void 0, void 0, function* () {
641
+ (yield this.getOrAddQRKeyring()).resetStore();
642
+ });
643
+ }
644
+ getQRKeyringState() {
645
+ return __awaiter(this, void 0, void 0, function* () {
646
+ return (yield this.getOrAddQRKeyring()).getMemStore();
647
+ });
648
+ }
649
+ submitQRCryptoHDKey(cryptoHDKey) {
650
+ return __awaiter(this, void 0, void 0, function* () {
651
+ (yield this.getOrAddQRKeyring()).submitCryptoHDKey(cryptoHDKey);
652
+ });
653
+ }
654
+ submitQRCryptoAccount(cryptoAccount) {
655
+ return __awaiter(this, void 0, void 0, function* () {
656
+ (yield this.getOrAddQRKeyring()).submitCryptoAccount(cryptoAccount);
657
+ });
658
+ }
659
+ submitQRSignature(requestId, ethSignature) {
660
+ return __awaiter(this, void 0, void 0, function* () {
661
+ (yield this.getOrAddQRKeyring()).submitSignature(requestId, ethSignature);
662
+ });
663
+ }
664
+ cancelQRSignRequest() {
665
+ return __awaiter(this, void 0, void 0, function* () {
666
+ (yield this.getOrAddQRKeyring()).cancelSignRequest();
667
+ });
668
+ }
669
+ /**
670
+ * Cancels qr keyring sync.
671
+ */
672
+ cancelQRSynchronization() {
673
+ return __awaiter(this, void 0, void 0, function* () {
674
+ // eslint-disable-next-line n/no-sync
675
+ (yield this.getOrAddQRKeyring()).cancelSync();
676
+ });
677
+ }
678
+ connectQRHardware(page) {
679
+ return __awaiter(this, void 0, void 0, function* () {
680
+ try {
681
+ const keyring = yield this.getOrAddQRKeyring();
682
+ let accounts;
683
+ switch (page) {
684
+ case -1:
685
+ accounts = yield keyring.getPreviousPage();
686
+ break;
687
+ case 1:
688
+ accounts = yield keyring.getNextPage();
689
+ break;
690
+ default:
691
+ accounts = yield keyring.getFirstPage();
692
+ }
693
+ return accounts.map((account) => {
694
+ return Object.assign(Object.assign({}, account), { balance: '0x0' });
695
+ });
696
+ }
697
+ catch (e) {
698
+ // TODO: Add test case for when keyring throws
699
+ /* istanbul ignore next */
700
+ throw new Error(`Unspecified error when connect QR Hardware, ${e}`);
701
+ }
702
+ });
703
+ }
704
+ unlockQRHardwareWalletAccount(index) {
705
+ return __awaiter(this, void 0, void 0, function* () {
706
+ const keyring = yield this.getOrAddQRKeyring();
707
+ keyring.setAccountToUnlock(index);
708
+ const oldAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
709
+ // QRKeyring is not yet compatible with Keyring from
710
+ // @metamask/utils, but we can use the `addNewAccount` method
711
+ // as it internally calls `addAccounts` from on the keyring instance,
712
+ // which is supported by QRKeyring API.
713
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewAccount(keyring);
714
+ const newAccounts = yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts();
715
+ this.updateIdentities(newAccounts);
716
+ newAccounts.forEach((address) => {
717
+ if (!oldAccounts.includes(address)) {
718
+ if (this.setAccountLabel) {
719
+ this.setAccountLabel(address, `${keyring.getName()} ${index}`);
720
+ }
721
+ this.setSelectedAddress(address);
722
+ }
723
+ });
724
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
725
+ });
726
+ }
727
+ getAccountKeyringType(account) {
728
+ return __awaiter(this, void 0, void 0, function* () {
729
+ return (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getKeyringForAccount(account)).type;
730
+ });
731
+ }
732
+ forgetQRDevice() {
733
+ return __awaiter(this, void 0, void 0, function* () {
734
+ const keyring = yield this.getOrAddQRKeyring();
735
+ keyring.forgetDevice();
736
+ const accounts = (yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").getAccounts());
737
+ accounts.forEach((account) => {
738
+ this.setSelectedAddress(account);
739
+ });
740
+ yield __classPrivateFieldGet(this, _KeyringController_keyring, "f").persistAllKeyrings();
741
+ });
742
+ }
743
+ }
744
+ exports.KeyringController = KeyringController;
745
+ _KeyringController_keyring = new WeakMap(), _KeyringController_instances = new WeakSet(), _KeyringController_addQRKeyring = function _KeyringController_addQRKeyring() {
746
+ return __awaiter(this, void 0, void 0, function* () {
747
+ // QRKeyring is not yet compatible with Keyring type from @metamask/utils
748
+ return __classPrivateFieldGet(this, _KeyringController_keyring, "f").addNewKeyring(KeyringTypes.qr);
749
+ });
750
+ }, _KeyringController_fullUpdate = function _KeyringController_fullUpdate() {
751
+ this.update(() => (Object.assign(Object.assign({}, __classPrivateFieldGet(this, _KeyringController_keyring, "f").store.getState()), __classPrivateFieldGet(this, _KeyringController_keyring, "f").memStore.getState())));
752
+ }, _KeyringController_handleLock = function _KeyringController_handleLock() {
753
+ this.messagingSystem.publish(`${name}:lock`);
754
+ }, _KeyringController_handleUnlock = function _KeyringController_handleUnlock() {
755
+ this.messagingSystem.publish(`${name}:unlock`);
756
+ }, _KeyringController_getMemState = function _KeyringController_getMemState() {
757
+ return {
758
+ isUnlocked: this.state.isUnlocked,
759
+ keyrings: this.state.keyrings,
760
+ };
761
+ };
762
+ exports.default = KeyringController;
763
+ //# sourceMappingURL=KeyringController.js.map