@metamask/accounts-controller 39.1.1 → 40.1.0

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 (76) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/dist/{AccountsController-method-action-types.d.mts → AccountsController-method-action-types.d.ts} +2 -2
  3. package/dist/AccountsController-method-action-types.d.ts.map +1 -0
  4. package/dist/{AccountsController-method-action-types.mjs → AccountsController-method-action-types.js} +1 -1
  5. package/dist/AccountsController-method-action-types.js.map +1 -0
  6. package/dist/{AccountsController.d.mts → AccountsController.d.ts} +11 -11
  7. package/dist/AccountsController.d.ts.map +1 -0
  8. package/dist/AccountsController.js +923 -0
  9. package/dist/AccountsController.js.map +1 -0
  10. package/dist/{index.d.cts → index.d.ts} +5 -5
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +3 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/logger.d.ts +4 -0
  15. package/dist/logger.d.ts.map +1 -0
  16. package/dist/{logger.mjs → logger.js} +2 -2
  17. package/dist/logger.js.map +1 -0
  18. package/dist/{types.d.cts → types.d.ts} +4 -4
  19. package/dist/types.d.ts.map +1 -0
  20. package/dist/{types.mjs → types.js} +1 -1
  21. package/dist/types.js.map +1 -0
  22. package/dist/{typing.d.cts → typing.d.ts} +4 -4
  23. package/dist/typing.d.ts.map +1 -0
  24. package/dist/typing.js +2 -0
  25. package/dist/typing.js.map +1 -0
  26. package/dist/{utils.d.mts → utils.d.ts} +36 -9
  27. package/dist/utils.d.ts.map +1 -0
  28. package/dist/{utils.mjs → utils.js} +52 -12
  29. package/dist/utils.js.map +1 -0
  30. package/package.json +38 -42
  31. package/dist/AccountsController-method-action-types.cjs +0 -7
  32. package/dist/AccountsController-method-action-types.cjs.map +0 -1
  33. package/dist/AccountsController-method-action-types.d.cts +0 -177
  34. package/dist/AccountsController-method-action-types.d.cts.map +0 -1
  35. package/dist/AccountsController-method-action-types.d.mts.map +0 -1
  36. package/dist/AccountsController-method-action-types.mjs.map +0 -1
  37. package/dist/AccountsController.cjs +0 -771
  38. package/dist/AccountsController.cjs.map +0 -1
  39. package/dist/AccountsController.d.cts +0 -312
  40. package/dist/AccountsController.d.cts.map +0 -1
  41. package/dist/AccountsController.d.mts.map +0 -1
  42. package/dist/AccountsController.mjs +0 -767
  43. package/dist/AccountsController.mjs.map +0 -1
  44. package/dist/index.cjs +0 -13
  45. package/dist/index.cjs.map +0 -1
  46. package/dist/index.d.cts.map +0 -1
  47. package/dist/index.d.mts +0 -5
  48. package/dist/index.d.mts.map +0 -1
  49. package/dist/index.mjs +0 -3
  50. package/dist/index.mjs.map +0 -1
  51. package/dist/logger.cjs +0 -8
  52. package/dist/logger.cjs.map +0 -1
  53. package/dist/logger.d.cts +0 -5
  54. package/dist/logger.d.cts.map +0 -1
  55. package/dist/logger.d.mts +0 -5
  56. package/dist/logger.d.mts.map +0 -1
  57. package/dist/logger.mjs.map +0 -1
  58. package/dist/types.cjs +0 -5
  59. package/dist/types.cjs.map +0 -1
  60. package/dist/types.d.cts.map +0 -1
  61. package/dist/types.d.mts +0 -20
  62. package/dist/types.d.mts.map +0 -1
  63. package/dist/types.mjs.map +0 -1
  64. package/dist/typing.cjs +0 -3
  65. package/dist/typing.cjs.map +0 -1
  66. package/dist/typing.d.cts.map +0 -1
  67. package/dist/typing.d.mts +0 -31
  68. package/dist/typing.d.mts.map +0 -1
  69. package/dist/typing.mjs +0 -2
  70. package/dist/typing.mjs.map +0 -1
  71. package/dist/utils.cjs +0 -216
  72. package/dist/utils.cjs.map +0 -1
  73. package/dist/utils.d.cts +0 -117
  74. package/dist/utils.d.cts.map +0 -1
  75. package/dist/utils.d.mts.map +0 -1
  76. package/dist/utils.mjs.map +0 -1
@@ -0,0 +1,923 @@
1
+ import { BaseController } from '@metamask/base-controller';
2
+ import { SnapKeyring } from '@metamask/eth-snap-keyring';
3
+ import { EthAccountType, EthMethod, EthScope, isEvmAccountType, KeyringAccountEntropyTypeOption, } from '@metamask/keyring-api';
4
+ import { KeyringType } from '@metamask/keyring-api/v2';
5
+ import { KeyringV1Adapter } from '@metamask/keyring-sdk/v2';
6
+ import { isScopeEqualToAny } from '@metamask/keyring-utils';
7
+ import { isCaipChainId } from '@metamask/utils';
8
+ import { cloneDeep } from 'lodash-es';
9
+ import { projectLogger as log } from './logger.js';
10
+ import { constructAccountIdByAddress, getEvmDerivationPathForIndex, getEvmGroupIndexFromAddressIndex, getUUIDFromAddressOfNormalAccount, isHdKeyringType, isHdSnapKeyringAccount, isSkippedKeyringType, isSnapKeyringType, isSnapKeyringV2Type, isWatchOnlyKeyringType, keyringTypeToName, } from './utils.js';
11
+ const controllerName = 'AccountsController';
12
+ const MESSENGER_EXPOSED_METHODS = [
13
+ 'setSelectedAccount',
14
+ 'setAccountName',
15
+ 'setAccountNameAndSelectAccount',
16
+ 'listAccounts',
17
+ 'listMultichainAccounts',
18
+ 'updateAccounts',
19
+ 'getSelectedAccount',
20
+ 'getSelectedMultichainAccount',
21
+ 'getAccountByAddress',
22
+ 'getAccount',
23
+ 'getAccounts',
24
+ 'updateAccountMetadata',
25
+ 'loadBackup',
26
+ 'clearState',
27
+ ];
28
+ const accountsControllerMetadata = {
29
+ internalAccounts: {
30
+ includeInStateLogs: true,
31
+ persist: true,
32
+ includeInDebugSnapshot: false,
33
+ usedInUi: true,
34
+ },
35
+ accountIdByAddress: {
36
+ includeInStateLogs: false,
37
+ persist: false,
38
+ includeInDebugSnapshot: false,
39
+ usedInUi: true,
40
+ },
41
+ };
42
+ /**
43
+ * Returns the default state for the AccountsController.
44
+ *
45
+ * @deprecated This function is deprecated and will be removed in a future version.
46
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
47
+ * @returns The default AccountsController state.
48
+ */
49
+ export function getDefaultAccountsControllerState() {
50
+ return {
51
+ internalAccounts: {
52
+ accounts: {},
53
+ selectedAccount: '',
54
+ },
55
+ accountIdByAddress: {},
56
+ };
57
+ }
58
+ /**
59
+ * @deprecated This constant is deprecated and will be removed in a future version.
60
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
61
+ */
62
+ export const EMPTY_ACCOUNT = {
63
+ id: '',
64
+ address: '',
65
+ options: {},
66
+ methods: [],
67
+ type: EthAccountType.Eoa,
68
+ scopes: [EthScope.Eoa],
69
+ metadata: {
70
+ name: '',
71
+ keyring: {
72
+ type: '',
73
+ },
74
+ importTime: 0,
75
+ },
76
+ };
77
+ /**
78
+ * Controller that manages internal accounts.
79
+ * The accounts controller is responsible for creating and managing internal accounts.
80
+ * It also provides convenience methods for accessing and updating the internal accounts.
81
+ * The accounts controller also listens for keyring state changes and updates the internal accounts accordingly.
82
+ * The accounts controller also listens for snap state changes and updates the internal accounts accordingly.
83
+ *
84
+ * @deprecated This class is deprecated and will be removed in a future version.
85
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
86
+ */
87
+ export class AccountsController extends BaseController {
88
+ /**
89
+ * Constructor for AccountsController.
90
+ *
91
+ * @param options - The controller options.
92
+ * @param options.messenger - The messenger object.
93
+ * @param options.state - Initial state to set on this controller
94
+ */
95
+ constructor({ messenger, state, }) {
96
+ const accountIdByAddress = constructAccountIdByAddress(state?.internalAccounts?.accounts ?? {});
97
+ super({
98
+ messenger,
99
+ name: controllerName,
100
+ metadata: accountsControllerMetadata,
101
+ state: {
102
+ ...getDefaultAccountsControllerState(),
103
+ ...state,
104
+ accountIdByAddress,
105
+ },
106
+ });
107
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
108
+ this.#subscribeToMessageEvents();
109
+ }
110
+ /**
111
+ * Returns the internal account object for the given account ID, if it exists.
112
+ *
113
+ * @deprecated This method is deprecated and will be removed in a future version.
114
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
115
+ * @param accountId - The ID of the account to retrieve.
116
+ * @returns The internal account object, or undefined if the account does not exist.
117
+ */
118
+ getAccount(accountId) {
119
+ return this.state.internalAccounts.accounts[accountId];
120
+ }
121
+ /**
122
+ * Returns the internal account objects for the given account IDs, if they exist.
123
+ *
124
+ * @deprecated This method is deprecated and will be removed in a future version.
125
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
126
+ * @param accountIds - The IDs of the accounts to retrieve.
127
+ * @returns The internal account objects, or undefined if the account(s) do not exist.
128
+ */
129
+ getAccounts(accountIds) {
130
+ return accountIds.map((accountId) => this.getAccount(accountId));
131
+ }
132
+ /**
133
+ * Returns an array of all evm internal accounts.
134
+ *
135
+ * @deprecated This method is deprecated and will be removed in a future version.
136
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
137
+ * @returns An array of InternalAccount objects.
138
+ */
139
+ listAccounts() {
140
+ const accounts = Object.values(this.state.internalAccounts.accounts);
141
+ return accounts.filter((account) => isEvmAccountType(account.type));
142
+ }
143
+ /**
144
+ * Returns an array of all internal accounts.
145
+ *
146
+ * @deprecated This method is deprecated and will be removed in a future version.
147
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
148
+ * @param chainId - The chain ID.
149
+ * @returns An array of InternalAccount objects.
150
+ */
151
+ listMultichainAccounts(chainId) {
152
+ const accounts = Object.values(this.state.internalAccounts.accounts);
153
+ if (!chainId) {
154
+ return accounts;
155
+ }
156
+ if (!isCaipChainId(chainId)) {
157
+ throw new Error(`Invalid CAIP-2 chain ID: ${String(chainId)}`);
158
+ }
159
+ return accounts.filter((account) => isScopeEqualToAny(chainId, account.scopes));
160
+ }
161
+ /**
162
+ * Returns the internal account object for the given account ID.
163
+ *
164
+ * @deprecated This method is deprecated and will be removed in a future version.
165
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
166
+ * @param accountId - The ID of the account to retrieve.
167
+ * @returns The internal account object.
168
+ * @throws An error if the account ID is not found.
169
+ */
170
+ #getAccountExpect(accountId) {
171
+ const account = this.getAccount(accountId);
172
+ if (account === undefined) {
173
+ throw new Error(`Account Id "${accountId}" not found`);
174
+ }
175
+ return account;
176
+ }
177
+ /**
178
+ * Returns the last selected EVM account.
179
+ *
180
+ * @deprecated This method is deprecated and will be removed in a future version.
181
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
182
+ * @returns The selected internal account.
183
+ */
184
+ getSelectedAccount() {
185
+ const { internalAccounts: { selectedAccount }, } = this.state;
186
+ // Edge case where the extension is setup but the srp is not yet created
187
+ // certain ui elements will query the selected address before any accounts are created.
188
+ if (!selectedAccount) {
189
+ return EMPTY_ACCOUNT;
190
+ }
191
+ const account = this.#getAccountExpect(selectedAccount);
192
+ if (isEvmAccountType(account.type)) {
193
+ return account;
194
+ }
195
+ const accounts = this.listAccounts();
196
+ if (!accounts.length) {
197
+ // ! Should never reach this.
198
+ throw new Error('No EVM accounts');
199
+ }
200
+ // This will never be undefined because we have already checked if accounts.length is > 0
201
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
202
+ return this.#getLastSelectedAccount(accounts);
203
+ }
204
+ /**
205
+ * __WARNING The return value may be undefined if there isn't an account for that chain id.__
206
+ *
207
+ * Retrieves the last selected account by chain ID.
208
+ *
209
+ * @deprecated This method is deprecated and will be removed in a future version.
210
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
211
+ * @param chainId - The chain ID to filter the accounts.
212
+ * @returns The last selected account compatible with the specified chain ID or undefined.
213
+ */
214
+ getSelectedMultichainAccount(chainId) {
215
+ const { internalAccounts: { selectedAccount }, } = this.state;
216
+ // Edge case where the extension is setup but the srp is not yet created
217
+ // certain ui elements will query the selected address before any accounts are created.
218
+ if (!selectedAccount) {
219
+ return EMPTY_ACCOUNT;
220
+ }
221
+ if (!chainId) {
222
+ return this.#getAccountExpect(selectedAccount);
223
+ }
224
+ const accounts = this.listMultichainAccounts(chainId);
225
+ return this.#getLastSelectedAccount(accounts);
226
+ }
227
+ /**
228
+ * Returns the account with the specified address.
229
+ * ! This method will only return the first account that matches the address
230
+ *
231
+ * @deprecated This method is deprecated and will be removed in a future version.
232
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
233
+ * @param address - The address of the account to retrieve.
234
+ * @returns The account with the specified address, or undefined if not found.
235
+ */
236
+ getAccountByAddress(address) {
237
+ // We need to have a fallback as a cache miss might be attributed to a checksummed address being passed.
238
+ let accountId = this.state.accountIdByAddress[address];
239
+ if (!accountId) {
240
+ // FIXME: We should not need lower-cased addresses, but some consumers might
241
+ // still be using non-normalized addresses. For now we keep it
242
+ // for convenience, but we will need to remove this fallback
243
+ // at some point.
244
+ // NOTE: We should only hit that branch for EVM accounts only.
245
+ const lowercasedAddress = address.toLowerCase();
246
+ accountId = this.state.accountIdByAddress[lowercasedAddress];
247
+ if (accountId) {
248
+ log(`Cache missed for account ID: ${accountId}, received address: "${address}", matched address: "${lowercasedAddress}"`);
249
+ }
250
+ }
251
+ return accountId ? this.getAccount(accountId) : undefined;
252
+ }
253
+ /**
254
+ * Sets the selected account by its ID.
255
+ *
256
+ * @deprecated This method is deprecated and will be removed in a future version.
257
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
258
+ * @param accountId - The ID of the account to be selected.
259
+ */
260
+ setSelectedAccount(accountId) {
261
+ const account = this.#getAccountExpect(accountId);
262
+ if (this.state.internalAccounts.selectedAccount === account.id) {
263
+ return;
264
+ }
265
+ this.#update((state) => {
266
+ const { internalAccounts } = state;
267
+ internalAccounts.accounts[account.id].metadata.lastSelected = Date.now();
268
+ internalAccounts.selectedAccount = account.id;
269
+ });
270
+ }
271
+ /**
272
+ * Sets the name of the account with the given ID.
273
+ *
274
+ * @deprecated This method is deprecated and will be removed in a future version.
275
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
276
+ * @param accountId - The ID of the account to set the name for.
277
+ * @param accountName - The new name for the account.
278
+ * @throws An error if an account with the same name already exists.
279
+ */
280
+ setAccountName(accountId, accountName) {
281
+ // This will check for name uniqueness and fire the `accountRenamed` event
282
+ // if the account has been renamed.
283
+ this.updateAccountMetadata(accountId, {
284
+ name: accountName,
285
+ nameLastUpdatedAt: Date.now(),
286
+ });
287
+ }
288
+ /**
289
+ * Sets the name of the account with the given ID and select it.
290
+ *
291
+ * @deprecated This method is deprecated and will be removed in a future version.
292
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
293
+ * @param accountId - The ID of the account to set the name for and select.
294
+ * @param accountName - The new name for the account.
295
+ * @throws An error if an account with the same name already exists.
296
+ */
297
+ setAccountNameAndSelectAccount(accountId, accountName) {
298
+ const account = this.#getAccountExpect(accountId);
299
+ this.#assertAccountCanBeRenamed(account, accountName);
300
+ const internalAccount = {
301
+ ...account,
302
+ metadata: {
303
+ ...account.metadata,
304
+ name: accountName,
305
+ nameLastUpdatedAt: Date.now(),
306
+ lastSelected: this.#getLastSelectedIndex(),
307
+ },
308
+ };
309
+ this.#update((state) => {
310
+ state.internalAccounts.accounts[account.id] = internalAccount;
311
+ state.internalAccounts.selectedAccount = account.id;
312
+ });
313
+ this.messenger.publish('AccountsController:accountRenamed', internalAccount);
314
+ }
315
+ #assertAccountCanBeRenamed(account, accountName) {
316
+ if (this.listMultichainAccounts().find((internalAccount) => internalAccount.metadata.name === accountName &&
317
+ internalAccount.id !== account.id)) {
318
+ throw new Error('Account name already exists');
319
+ }
320
+ }
321
+ /**
322
+ * Updates the metadata of the account with the given ID.
323
+ *
324
+ * @deprecated This method is deprecated and will be removed in a future version.
325
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
326
+ * @param accountId - The ID of the account for which the metadata will be updated.
327
+ * @param metadata - The new metadata for the account.
328
+ */
329
+ updateAccountMetadata(accountId, metadata) {
330
+ const account = this.#getAccountExpect(accountId);
331
+ if (metadata.name) {
332
+ this.#assertAccountCanBeRenamed(account, metadata.name);
333
+ }
334
+ const internalAccount = {
335
+ ...account,
336
+ metadata: { ...account.metadata, ...metadata },
337
+ };
338
+ this.#update((state) => {
339
+ state.internalAccounts.accounts[accountId] = internalAccount;
340
+ });
341
+ if (metadata.name) {
342
+ this.messenger.publish('AccountsController:accountRenamed', internalAccount);
343
+ }
344
+ }
345
+ /**
346
+ * Updates the internal accounts list by retrieving normal and snap accounts,
347
+ * removing duplicates, and updating the metadata of each account.
348
+ *
349
+ * @deprecated This method is deprecated and will be removed in a future version.
350
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
351
+ * @returns A Promise that resolves when the accounts have been updated.
352
+ */
353
+ async updateAccounts() {
354
+ log('Synchronizing accounts with keyrings...');
355
+ const keyringAccountIndexes = new Map();
356
+ const existingInternalAccounts = this.state.internalAccounts.accounts;
357
+ const internalAccounts = {};
358
+ const { keyrings } = this.messenger.call('KeyringController:getState');
359
+ for (const keyring of keyrings) {
360
+ const { type } = keyring;
361
+ // Skipped accounts (Money or MPC Money) are not treated as real accounts, they are owned by their
362
+ // respective controllers, so we need to filter them out here.
363
+ if (isSkippedKeyringType(type)) {
364
+ continue;
365
+ }
366
+ const keyringTypeName = keyringTypeToName(keyring.type);
367
+ for (const address of keyring.accounts) {
368
+ const internalAccount = this.#getInternalAccountFromAddressAndType(address, keyring);
369
+ // This should never really happen, but if for some reason we're not
370
+ // able to get the Snap keyring reference, this would return an
371
+ // undefined account.
372
+ // So we just skip it, even though, this should not really happen.
373
+ if (!internalAccount) {
374
+ continue;
375
+ }
376
+ // Get current index for this keyring (we use human indexing, so start at 1).
377
+ const keyringAccountIndex = keyringAccountIndexes.get(keyringTypeName) ?? 1;
378
+ const existingAccount = existingInternalAccounts[internalAccount.id];
379
+ internalAccounts[internalAccount.id] = {
380
+ ...internalAccount,
381
+ metadata: {
382
+ ...internalAccount.metadata,
383
+ // Re-use existing metadata if any.
384
+ name: existingAccount?.metadata.name ??
385
+ `${keyringTypeName} ${keyringAccountIndex}`,
386
+ importTime: existingAccount?.metadata.importTime ?? Date.now(),
387
+ lastSelected: existingAccount?.metadata.lastSelected ?? 0,
388
+ },
389
+ };
390
+ // Increment the account index for this keyring.
391
+ keyringAccountIndexes.set(keyringTypeName, keyringAccountIndex + 1);
392
+ }
393
+ }
394
+ this.#update((state) => {
395
+ state.internalAccounts.accounts = internalAccounts;
396
+ state.accountIdByAddress = constructAccountIdByAddress(internalAccounts);
397
+ });
398
+ log('Accounts synchronized!');
399
+ }
400
+ /**
401
+ * Loads the backup state of the accounts controller.
402
+ *
403
+ * @deprecated This method is deprecated and will be removed in a future version.
404
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
405
+ * @param backup - The backup state to load.
406
+ */
407
+ loadBackup(backup) {
408
+ if (backup.internalAccounts) {
409
+ const accountIdByAddress = constructAccountIdByAddress(backup.internalAccounts.accounts);
410
+ this.update((currentState) => {
411
+ currentState.internalAccounts = backup.internalAccounts;
412
+ currentState.accountIdByAddress = accountIdByAddress;
413
+ });
414
+ }
415
+ }
416
+ /**
417
+ * Clears the controller state and resets to default values.
418
+ *
419
+ * @deprecated This method is deprecated and will be removed in a future version.
420
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
421
+ */
422
+ clearState() {
423
+ const removedIds = Object.keys(this.state.internalAccounts.accounts);
424
+ this.update(() => {
425
+ return getDefaultAccountsControllerState();
426
+ });
427
+ for (const id of removedIds) {
428
+ this.messenger.publish('AccountsController:accountRemoved', id);
429
+ }
430
+ if (removedIds.length > 0) {
431
+ this.messenger.publish('AccountsController:accountsRemoved', removedIds);
432
+ }
433
+ }
434
+ /**
435
+ * Gets an internal account representation for a non-Snap account.
436
+ *
437
+ * @param address - The address of the account.
438
+ * @param keyring - The keyring object of the account.
439
+ * @returns The generated internal account.
440
+ */
441
+ #getInternalAccountForNonSnapAccount(address, keyring) {
442
+ const id = getUUIDFromAddressOfNormalAccount(address);
443
+ // We might have an account for this ID already, so we'll just re-use
444
+ // the same metadata
445
+ const account = this.getAccount(id);
446
+ const metadata = {
447
+ name: account?.metadata.name ?? '',
448
+ ...(account?.metadata.nameLastUpdatedAt
449
+ ? {
450
+ nameLastUpdatedAt: account?.metadata.nameLastUpdatedAt,
451
+ }
452
+ : {}),
453
+ importTime: account?.metadata.importTime ?? Date.now(),
454
+ lastSelected: account?.metadata.lastSelected ?? 0,
455
+ keyring: {
456
+ type: keyring.type,
457
+ },
458
+ };
459
+ let options = {};
460
+ if (isHdKeyringType(keyring.type)) {
461
+ // We need to find the account index from its HD keyring.
462
+ const groupIndex = getEvmGroupIndexFromAddressIndex(keyring, address);
463
+ // If for some reason, we cannot find this address, then the caller made a mistake
464
+ // and it did not use the proper keyring object. For now, we do not fail and just
465
+ // consider this account as "simple account".
466
+ if (groupIndex !== undefined) {
467
+ // NOTE: We are not using the `hdPath` from the associated keyring here and
468
+ // getting the keyring instance here feels a bit overkill.
469
+ // This will be naturally fixed once every keyring start using `KeyringAccount` and implement the keyring API.
470
+ const derivationPath = getEvmDerivationPathForIndex(groupIndex);
471
+ // Those are "legacy options" and they were used before `KeyringAccount` added
472
+ // support for type options. We keep those temporarily until we update everything
473
+ // to use the new typed options.
474
+ const legacyOptions = {
475
+ entropySource: keyring.metadata.id,
476
+ derivationPath,
477
+ groupIndex,
478
+ };
479
+ // New typed entropy options. This is required for multichain accounts.
480
+ const entropyOptions = {
481
+ entropy: {
482
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
483
+ id: keyring.metadata.id,
484
+ derivationPath,
485
+ groupIndex,
486
+ },
487
+ };
488
+ options = {
489
+ ...legacyOptions,
490
+ ...entropyOptions,
491
+ };
492
+ }
493
+ }
494
+ return {
495
+ id,
496
+ address,
497
+ options,
498
+ methods: [
499
+ EthMethod.PersonalSign,
500
+ EthMethod.Sign,
501
+ EthMethod.SignTransaction,
502
+ EthMethod.SignTypedDataV1,
503
+ EthMethod.SignTypedDataV3,
504
+ EthMethod.SignTypedDataV4,
505
+ ],
506
+ scopes: [EthScope.Eoa],
507
+ type: EthAccountType.Eoa,
508
+ metadata,
509
+ };
510
+ }
511
+ /**
512
+ * Get Snap keyring from the keyring controller.
513
+ *
514
+ * @returns The Snap keyring if available.
515
+ */
516
+ #getSnapKeyring() {
517
+ const [snapKeyring] = this.messenger.call('KeyringController:getKeyringsByType', SnapKeyring.type);
518
+ // Snap keyring is not available until the first account is created in the keyring
519
+ // controller, so this might be undefined.
520
+ return snapKeyring;
521
+ }
522
+ /**
523
+ * Get an account from a Snap keyring v1.
524
+ *
525
+ * @param address - The address of the account to retrieve.
526
+ * @returns The Snap account if available.
527
+ */
528
+ #getAccountFromSnapKeyringV1(address) {
529
+ const snapKeyring = this.#getSnapKeyring();
530
+ // We need the Snap keyring to retrieve the account from its address.
531
+ if (!snapKeyring) {
532
+ return undefined;
533
+ }
534
+ const account = snapKeyring.getAccountByAddress(address);
535
+ // This might be undefined if the Snap deleted the account before
536
+ // reaching that point.
537
+ if (!account) {
538
+ return undefined;
539
+ }
540
+ // We force the copy of the keyring's account, to avoid sharing its
541
+ // nested objects (`options`, `methods`, `scopes`) with the keyring,
542
+ // which controller state updates could mutate or freeze (e.g. through
543
+ // Immer's auto-freeze).
544
+ return cloneDeep(account);
545
+ }
546
+ /**
547
+ * Get an account from a v2 keyring, by iterating over all the keyrings of
548
+ * the given type and looking up the account by address.
549
+ *
550
+ * NOTE: `:getKeyringsByType` will only return v1 instances, that's why we need to use their v1
551
+ * adapter + `unwrap` method to get the reference to their v2 instance.
552
+ *
553
+ * @param keyringType - The type of the keyrings to look into.
554
+ * @param address - The address of the account to retrieve.
555
+ * @param createAccount - Callback to create the final internal account, given the account
556
+ * retrieved from the keyring and the keyring itself.
557
+ * @returns The account if available.
558
+ * @template KeyringV2WithLookup - The concrete type of the v2 keyring.
559
+ */
560
+ #getAccountFromV2Keyrings(keyringType, address, createAccount) {
561
+ const keyrings = this.messenger.call('KeyringController:getKeyringsByType', keyringType);
562
+ for (const keyring of keyrings) {
563
+ if (keyring instanceof KeyringV1Adapter) {
564
+ // NOTE: We are already filtering by `keyringType`, so we are sure that those adapters
565
+ // are wrapping a keyring of that type.
566
+ const adapter = keyring;
567
+ const keyringV2 = adapter.unwrap();
568
+ // We use the synchronous method here since this method is used during `:stateChange` that are
569
+ // use synchronous handlers.
570
+ const account = keyringV2.lookupByAddress(address);
571
+ if (account) {
572
+ return createAccount(account, keyringV2);
573
+ }
574
+ }
575
+ }
576
+ return undefined;
577
+ }
578
+ /**
579
+ * Get an account from a Snap keyring v2.
580
+ *
581
+ * @param address - The address of the account to retrieve.
582
+ * @returns The Snap account if available.
583
+ */
584
+ #getAccountFromSnapKeyringV2(address) {
585
+ // Snap keyring v2 are "per-Snaps" (and can be accessed using their v1 adapter), so we need to
586
+ // iterate over all of them to find the account.
587
+ return this.#getAccountFromV2Keyrings(KeyringType.Snap, address, (account, keyringV2) =>
588
+ // We force the copy of the keyring's account, to avoid sharing its
589
+ // nested objects (`options`, `methods`, `scopes`) with the keyring,
590
+ // which controller state updates could mutate or freeze (e.g. through
591
+ // Immer's auto-freeze).
592
+ cloneDeep({
593
+ ...account,
594
+ // We still have to use internal account for now, so we inject some metadata.
595
+ metadata: {
596
+ name: '',
597
+ importTime: Date.now(),
598
+ lastSelected: 0,
599
+ keyring: {
600
+ type: KeyringType.Snap,
601
+ },
602
+ snap: {
603
+ id: keyringV2.snapId,
604
+ },
605
+ },
606
+ }));
607
+ }
608
+ /**
609
+ * Get an account from a watch-only keyring.
610
+ *
611
+ * @param address - The address of the account to retrieve.
612
+ * @returns The watch-only account if available.
613
+ */
614
+ #getAccountFromWatchOnlyKeyring(address) {
615
+ // There is usually only one watch-only keyring, but we iterate over all of
616
+ // them to find the account, in case more than one was added.
617
+ // The watch-only account is read from the keyring itself, keeping its ID
618
+ // and its (empty) list of methods, so we don't re-create an EVM account
619
+ // without signing methods.
620
+ return this.#getAccountFromV2Keyrings(KeyringType.WatchOnly, address, (account) =>
621
+ // We force the copy of the keyring's account, to avoid sharing its
622
+ // nested objects (`options`, `methods`, `scopes`) with the keyring,
623
+ // which controller state updates could mutate or freeze (e.g. through
624
+ // Immer's auto-freeze).
625
+ cloneDeep({
626
+ ...account,
627
+ // We still have to use internal account for now, so we inject some metadata.
628
+ metadata: {
629
+ name: '',
630
+ importTime: Date.now(),
631
+ lastSelected: 0,
632
+ keyring: {
633
+ type: KeyringType.WatchOnly,
634
+ },
635
+ },
636
+ }));
637
+ }
638
+ /**
639
+ * Re-publish an account event.
640
+ *
641
+ * @param event - The event type. This is a unique identifier for this event.
642
+ * @param payload - The event payload. The type of the parameters for each event handler must
643
+ * match the type of this payload.
644
+ * @template EventType - A Snap keyring event type.
645
+ */
646
+ #handleOnSnapKeyringAccountEvent(event, ...payload) {
647
+ this.messenger.publish(event, ...payload);
648
+ }
649
+ /**
650
+ * Handles changes in the keyring state, specifically when new accounts are added or removed.
651
+ *
652
+ * @param keyringState - The new state of the keyring controller.
653
+ * @param keyringState.isUnlocked - True if the keyrings are unlocked, false otherwise.
654
+ * @param keyringState.keyrings - List of all keyrings.
655
+ */
656
+ #handleOnKeyringStateChange({ isUnlocked, keyrings, }) {
657
+ // TODO: Change when accountAdded event is added to the keyring controller.
658
+ // We check for keyrings length to be greater than 0 because the extension client may try execute
659
+ // submit password twice and clear the keyring state.
660
+ // https://github.com/MetaMask/KeyringController/blob/2d73a4deed8d013913f6ef0c9f5c0bb7c614f7d3/src/KeyringController.ts#L910
661
+ if (!isUnlocked || keyrings.length === 0) {
662
+ return;
663
+ }
664
+ log('Synchronizing accounts with keyrings (through :stateChange)...');
665
+ // State patches.
666
+ const patch = {
667
+ previous: {},
668
+ added: [],
669
+ updated: [],
670
+ removed: [],
671
+ };
672
+ // Create a map (with lower-cased addresses) of all existing accounts.
673
+ for (const account of this.listMultichainAccounts()) {
674
+ const address = account.address.toLowerCase();
675
+ patch.previous[address] = account;
676
+ }
677
+ // Go over all keyring changes and create patches out of it.
678
+ const addresses = new Set();
679
+ for (const keyring of keyrings) {
680
+ // Skipped accounts (Money or MPC Money) are not treated as real accounts, they are owned by their
681
+ // respective controllers, so we need to filter them out here.
682
+ if (isSkippedKeyringType(keyring.type)) {
683
+ continue;
684
+ }
685
+ for (const accountAddress of keyring.accounts) {
686
+ // Lower-case address to use it in the `previous` map.
687
+ const address = accountAddress.toLowerCase();
688
+ const account = patch.previous[address];
689
+ if (account) {
690
+ // If the account exists before, this might be an update.
691
+ patch.updated.push(account);
692
+ }
693
+ else {
694
+ // Otherwise, that's a new account.
695
+ patch.added.push({
696
+ address,
697
+ keyring,
698
+ });
699
+ }
700
+ // Keep track of those address to check for removed accounts later.
701
+ addresses.add(address);
702
+ }
703
+ }
704
+ // We might have accounts associated with removed keyrings, so we iterate
705
+ // over all previous known accounts and check against the keyring addresses.
706
+ for (const [address, account] of Object.entries(patch.previous)) {
707
+ // If a previous address is not part of the new addesses, then it got removed.
708
+ if (!addresses.has(address)) {
709
+ patch.removed.push(account);
710
+ }
711
+ }
712
+ // Diff that we will use to publish events afterward.
713
+ const diff = {
714
+ removed: [],
715
+ added: [],
716
+ };
717
+ this.#update((state) => {
718
+ const { internalAccounts, accountIdByAddress } = state;
719
+ for (const account of patch.removed) {
720
+ delete internalAccounts.accounts[account.id];
721
+ delete accountIdByAddress[account.address];
722
+ diff.removed.push(account.id);
723
+ }
724
+ for (const added of patch.added) {
725
+ const account = this.#getInternalAccountFromAddressAndType(added.address, added.keyring);
726
+ if (account) {
727
+ const accounts = Object.values(internalAccounts.accounts);
728
+ // If it's the first account, we need to select it.
729
+ const lastSelected = accounts.length === 0 ? this.#getLastSelectedIndex() : 0;
730
+ internalAccounts.accounts[account.id] = {
731
+ ...account,
732
+ metadata: {
733
+ ...account.metadata,
734
+ importTime: Date.now(),
735
+ lastSelected,
736
+ },
737
+ };
738
+ accountIdByAddress[account.address] = account.id;
739
+ diff.added.push(internalAccounts.accounts[account.id]);
740
+ }
741
+ }
742
+ },
743
+ // Will get executed after the update, but before re-selecting an account in case
744
+ // the current one is not valid anymore.
745
+ () => {
746
+ // Now publish events
747
+ for (const id of diff.removed) {
748
+ this.messenger.publish('AccountsController:accountRemoved', id);
749
+ }
750
+ if (diff.removed.length > 0) {
751
+ this.messenger.publish('AccountsController:accountsRemoved', diff.removed);
752
+ }
753
+ for (const account of diff.added) {
754
+ this.messenger.publish('AccountsController:accountAdded', account);
755
+ }
756
+ if (diff.added.length > 0) {
757
+ this.messenger.publish('AccountsController:accountsAdded', diff.added);
758
+ }
759
+ });
760
+ log('Accounts synchronized (through :stateChange)!');
761
+ // NOTE: Since we also track "updated" accounts with our patches, we could fire a new event
762
+ // like `accountUpdated` (we would still need to check if anything really changed on the account).
763
+ }
764
+ /**
765
+ * Update the state and fixup the currently selected account.
766
+ *
767
+ * @param callback - Callback for updating state, passed a draft state object.
768
+ * @param beforeAutoSelectAccount - Callback to be executed before auto-selecting an account
769
+ * if the current one is no longer available.
770
+ */
771
+ #update(callback, beforeAutoSelectAccount) {
772
+ // The currently selected account might get deleted during the update, so keep track
773
+ // of it before doing any change.
774
+ const previouslySelectedAccount = this.state.internalAccounts.selectedAccount;
775
+ this.update((state) => {
776
+ callback(state);
777
+ // If the account no longer exists (or none is selected), we need to re-select another one.
778
+ const { internalAccounts } = state;
779
+ if (!internalAccounts.accounts[previouslySelectedAccount]) {
780
+ const accounts = Object.values(internalAccounts.accounts);
781
+ // Get the lastly selected account (according to the current accounts).
782
+ const lastSelectedAccount = this.#getLastSelectedAccount(accounts);
783
+ if (lastSelectedAccount) {
784
+ internalAccounts.selectedAccount = lastSelectedAccount.id;
785
+ internalAccounts.accounts[lastSelectedAccount.id].metadata.lastSelected = this.#getLastSelectedIndex();
786
+ }
787
+ else {
788
+ // It will be undefined if there are no accounts.
789
+ internalAccounts.selectedAccount = '';
790
+ }
791
+ }
792
+ });
793
+ // We might want to do some pre-work before selecting a new account.
794
+ beforeAutoSelectAccount?.();
795
+ // Now, we compare the newly selected account, and we send event if different.
796
+ const { selectedAccount } = this.state.internalAccounts;
797
+ if (selectedAccount && selectedAccount !== previouslySelectedAccount) {
798
+ const account = this.getSelectedMultichainAccount();
799
+ // The account should always be defined at this point, since we have already checked for
800
+ // `selectedAccount` to be non-empty.
801
+ if (account) {
802
+ if (isEvmAccountType(account.type)) {
803
+ this.messenger.publish('AccountsController:selectedEvmAccountChange', account);
804
+ }
805
+ this.messenger.publish('AccountsController:selectedAccountChange', account);
806
+ }
807
+ }
808
+ }
809
+ /**
810
+ * Returns the last selected account from the given array of accounts.
811
+ *
812
+ * @param accounts - An array of InternalAccount objects.
813
+ * @returns The InternalAccount object that was last selected, or undefined if the array is empty.
814
+ */
815
+ #getLastSelectedAccount(accounts) {
816
+ const [accountToSelect] = accounts.sort((accountA, accountB) => {
817
+ // sort by lastSelected descending
818
+ return ((accountB.metadata.lastSelected ?? 0) -
819
+ (accountA.metadata.lastSelected ?? 0));
820
+ });
821
+ return accountToSelect;
822
+ }
823
+ /**
824
+ * Retrieves the index value for `metadata.lastSelected`.
825
+ *
826
+ * @returns The index value.
827
+ */
828
+ #getLastSelectedIndex() {
829
+ // NOTE: For now we use the current date, since we know this value
830
+ // will always be higher than any already selected account index.
831
+ return Date.now();
832
+ }
833
+ /**
834
+ * Get an internal account given an address and a keyring type.
835
+ *
836
+ * If the account is not a Snap Keyring account, generates an internal account for it and adds it to the controller.
837
+ * If the account is a Snap Keyring account, retrieves the account from the keyring and adds it to the controller.
838
+ *
839
+ * @param address - The address of the new account.
840
+ * @param keyring - The keyring object of that new account.
841
+ * @returns The newly generated/retrieved internal account.
842
+ */
843
+ #getInternalAccountFromAddressAndType(address, keyring) {
844
+ const isSnapKeyringV1 = isSnapKeyringType(keyring.type);
845
+ const isSnapKeyringV2 = isSnapKeyringV2Type(keyring.type);
846
+ if (isSnapKeyringV1 || isSnapKeyringV2) {
847
+ const account = isSnapKeyringV1
848
+ ? this.#getAccountFromSnapKeyringV1(address)
849
+ : this.#getAccountFromSnapKeyringV2(address);
850
+ if (account) {
851
+ // MIGRATION: To avoid any existing Snap account migration, we are
852
+ // just "adding" the new typed options that we need for multichain
853
+ // accounts. Ultimately, we would need a real Snap account migrations
854
+ // (being handled by each Snaps).
855
+ // NOTE: The account returned by the helpers above is a detached copy,
856
+ // so it is safe to mutate here.
857
+ if (isHdSnapKeyringAccount(account)) {
858
+ const options = {
859
+ ...account.options,
860
+ entropy: {
861
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
862
+ id: account.options.entropySource,
863
+ groupIndex: account.options.index,
864
+ derivationPath: account.options.derivationPath,
865
+ },
866
+ };
867
+ // Inject the new typed options to the internal account copy.
868
+ account.options = options;
869
+ }
870
+ }
871
+ return account;
872
+ }
873
+ // Watch-only accounts are read from the watch-only keyring itself (like
874
+ // Snap v2 accounts), so we don't re-create an EVM account without signing
875
+ // methods for them.
876
+ if (isWatchOnlyKeyringType(keyring.type)) {
877
+ return this.#getAccountFromWatchOnlyKeyring(address);
878
+ }
879
+ return this.#getInternalAccountForNonSnapAccount(address, keyring);
880
+ }
881
+ /**
882
+ * Handles the change in multichain network by updating the selected account.
883
+ *
884
+ * @param id - The EVM client ID or non-EVM chain ID that changed.
885
+ */
886
+ #handleOnMultichainNetworkDidChange(id) {
887
+ let accountId;
888
+ // We only support non-EVM Caip chain IDs at the moment. Ex Solana and Bitcoin
889
+ // MultichainNetworkController will handle throwing an error if the Caip chain ID is not supported
890
+ if (isCaipChainId(id)) {
891
+ // Update selected account to non evm account
892
+ const lastSelectedNonEvmAccount = this.getSelectedMultichainAccount(id);
893
+ // @ts-expect-error - This should never be undefined, otherwise it's a bug that should be handled
894
+ accountId = lastSelectedNonEvmAccount.id;
895
+ }
896
+ else {
897
+ // Update selected account to evm account
898
+ const lastSelectedEvmAccount = this.getSelectedAccount();
899
+ accountId = lastSelectedEvmAccount.id;
900
+ }
901
+ if (this.state.internalAccounts.selectedAccount === accountId) {
902
+ return;
903
+ }
904
+ this.update((currentState) => {
905
+ currentState.internalAccounts.accounts[accountId].metadata.lastSelected =
906
+ Date.now();
907
+ currentState.internalAccounts.selectedAccount = accountId;
908
+ });
909
+ // DO NOT publish AccountsController:setSelectedAccount to prevent circular listener loops
910
+ }
911
+ /**
912
+ * Subscribes to message events.
913
+ */
914
+ #subscribeToMessageEvents() {
915
+ this.messenger.subscribe('KeyringController:stateChange', (keyringState) => this.#handleOnKeyringStateChange(keyringState));
916
+ this.messenger.subscribe('SnapAccountService:accountAssetListUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountAssetListUpdated', snapAccountEvent));
917
+ this.messenger.subscribe('SnapAccountService:accountBalancesUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountBalancesUpdated', snapAccountEvent));
918
+ this.messenger.subscribe('SnapAccountService:accountTransactionsUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountTransactionsUpdated', snapAccountEvent));
919
+ // Handle account change when multichain network is changed
920
+ this.messenger.subscribe('MultichainNetworkController:networkDidChange', (id) => this.#handleOnMultichainNetworkDidChange(id));
921
+ }
922
+ }
923
+ //# sourceMappingURL=AccountsController.js.map