@metamask/accounts-controller 39.1.1 → 40.0.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 +17 -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 +855 -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} +11 -9
  27. package/dist/utils.d.ts.map +1 -0
  28. package/dist/{utils.mjs → utils.js} +7 -7
  29. package/dist/utils.js.map +1 -0
  30. package/package.json +19 -23
  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,855 @@
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, isMoneyKeyringType, isSnapKeyringType, isSnapKeyringV2Type, 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
+ // Money accounts are not treated as real accounts, they are owned by the `MoneyAccountController`, so
361
+ // we need to filter them out here.
362
+ if (isMoneyKeyringType(keyring.type)) {
363
+ continue;
364
+ }
365
+ const keyringTypeName = keyringTypeToName(keyring.type);
366
+ for (const address of keyring.accounts) {
367
+ const internalAccount = this.#getInternalAccountFromAddressAndType(address, keyring);
368
+ // This should never really happen, but if for some reason we're not
369
+ // able to get the Snap keyring reference, this would return an
370
+ // undefined account.
371
+ // So we just skip it, even though, this should not really happen.
372
+ if (!internalAccount) {
373
+ continue;
374
+ }
375
+ // Get current index for this keyring (we use human indexing, so start at 1).
376
+ const keyringAccountIndex = keyringAccountIndexes.get(keyringTypeName) ?? 1;
377
+ const existingAccount = existingInternalAccounts[internalAccount.id];
378
+ internalAccounts[internalAccount.id] = {
379
+ ...internalAccount,
380
+ metadata: {
381
+ ...internalAccount.metadata,
382
+ // Re-use existing metadata if any.
383
+ name: existingAccount?.metadata.name ??
384
+ `${keyringTypeName} ${keyringAccountIndex}`,
385
+ importTime: existingAccount?.metadata.importTime ?? Date.now(),
386
+ lastSelected: existingAccount?.metadata.lastSelected ?? 0,
387
+ },
388
+ };
389
+ // Increment the account index for this keyring.
390
+ keyringAccountIndexes.set(keyringTypeName, keyringAccountIndex + 1);
391
+ }
392
+ }
393
+ this.#update((state) => {
394
+ state.internalAccounts.accounts = internalAccounts;
395
+ state.accountIdByAddress = constructAccountIdByAddress(internalAccounts);
396
+ });
397
+ log('Accounts synchronized!');
398
+ }
399
+ /**
400
+ * Loads the backup state of the accounts controller.
401
+ *
402
+ * @deprecated This method is deprecated and will be removed in a future version.
403
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
404
+ * @param backup - The backup state to load.
405
+ */
406
+ loadBackup(backup) {
407
+ if (backup.internalAccounts) {
408
+ const accountIdByAddress = constructAccountIdByAddress(backup.internalAccounts.accounts);
409
+ this.update((currentState) => {
410
+ currentState.internalAccounts = backup.internalAccounts;
411
+ currentState.accountIdByAddress = accountIdByAddress;
412
+ });
413
+ }
414
+ }
415
+ /**
416
+ * Clears the controller state and resets to default values.
417
+ *
418
+ * @deprecated This method is deprecated and will be removed in a future version.
419
+ * Use `AccountTreeController`, `MultichainAccountService`, or the Keyring API v2 instead.
420
+ */
421
+ clearState() {
422
+ this.update(() => {
423
+ return getDefaultAccountsControllerState();
424
+ });
425
+ }
426
+ /**
427
+ * Gets an internal account representation for a non-Snap account.
428
+ *
429
+ * @param address - The address of the account.
430
+ * @param keyring - The keyring object of the account.
431
+ * @returns The generated internal account.
432
+ */
433
+ #getInternalAccountForNonSnapAccount(address, keyring) {
434
+ const id = getUUIDFromAddressOfNormalAccount(address);
435
+ // We might have an account for this ID already, so we'll just re-use
436
+ // the same metadata
437
+ const account = this.getAccount(id);
438
+ const metadata = {
439
+ name: account?.metadata.name ?? '',
440
+ ...(account?.metadata.nameLastUpdatedAt
441
+ ? {
442
+ nameLastUpdatedAt: account?.metadata.nameLastUpdatedAt,
443
+ }
444
+ : {}),
445
+ importTime: account?.metadata.importTime ?? Date.now(),
446
+ lastSelected: account?.metadata.lastSelected ?? 0,
447
+ keyring: {
448
+ type: keyring.type,
449
+ },
450
+ };
451
+ let options = {};
452
+ if (isHdKeyringType(keyring.type)) {
453
+ // We need to find the account index from its HD keyring.
454
+ const groupIndex = getEvmGroupIndexFromAddressIndex(keyring, address);
455
+ // If for some reason, we cannot find this address, then the caller made a mistake
456
+ // and it did not use the proper keyring object. For now, we do not fail and just
457
+ // consider this account as "simple account".
458
+ if (groupIndex !== undefined) {
459
+ // NOTE: We are not using the `hdPath` from the associated keyring here and
460
+ // getting the keyring instance here feels a bit overkill.
461
+ // This will be naturally fixed once every keyring start using `KeyringAccount` and implement the keyring API.
462
+ const derivationPath = getEvmDerivationPathForIndex(groupIndex);
463
+ // Those are "legacy options" and they were used before `KeyringAccount` added
464
+ // support for type options. We keep those temporarily until we update everything
465
+ // to use the new typed options.
466
+ const legacyOptions = {
467
+ entropySource: keyring.metadata.id,
468
+ derivationPath,
469
+ groupIndex,
470
+ };
471
+ // New typed entropy options. This is required for multichain accounts.
472
+ const entropyOptions = {
473
+ entropy: {
474
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
475
+ id: keyring.metadata.id,
476
+ derivationPath,
477
+ groupIndex,
478
+ },
479
+ };
480
+ options = {
481
+ ...legacyOptions,
482
+ ...entropyOptions,
483
+ };
484
+ }
485
+ }
486
+ return {
487
+ id,
488
+ address,
489
+ options,
490
+ methods: [
491
+ EthMethod.PersonalSign,
492
+ EthMethod.Sign,
493
+ EthMethod.SignTransaction,
494
+ EthMethod.SignTypedDataV1,
495
+ EthMethod.SignTypedDataV3,
496
+ EthMethod.SignTypedDataV4,
497
+ ],
498
+ scopes: [EthScope.Eoa],
499
+ type: EthAccountType.Eoa,
500
+ metadata,
501
+ };
502
+ }
503
+ /**
504
+ * Get Snap keyring from the keyring controller.
505
+ *
506
+ * @returns The Snap keyring if available.
507
+ */
508
+ #getSnapKeyring() {
509
+ const [snapKeyring] = this.messenger.call('KeyringController:getKeyringsByType', SnapKeyring.type);
510
+ // Snap keyring is not available until the first account is created in the keyring
511
+ // controller, so this might be undefined.
512
+ return snapKeyring;
513
+ }
514
+ /**
515
+ * Get an account from a Snap keyring v1.
516
+ *
517
+ * @param address - The address of the account to retrieve.
518
+ * @returns The Snap account if available.
519
+ */
520
+ #getAccountFromSnapKeyringV1(address) {
521
+ const snapKeyring = this.#getSnapKeyring();
522
+ // We need the Snap keyring to retrieve the account from its address.
523
+ if (!snapKeyring) {
524
+ return undefined;
525
+ }
526
+ // This might be undefined if the Snap deleted the account before
527
+ // reaching that point.
528
+ return snapKeyring.getAccountByAddress(address);
529
+ }
530
+ /**
531
+ * Get an account from a Snap keyring v2.
532
+ *
533
+ * @param address - The address of the account to retrieve.
534
+ * @returns The Snap account if available.
535
+ */
536
+ #getAccountFromSnapKeyringV2(address) {
537
+ const keyrings = this.messenger.call('KeyringController:getKeyringsByType', KeyringType.Snap);
538
+ // Snap keyring v2 are "per-Snaps" (and can be accessed using their v1 adapter), so we need to
539
+ // iterate over all of them to find the account.
540
+ // NOTE: `:getKeyringsByType` will only return v1 instances, that's why we need to use their v1
541
+ // adapter + `unwrap` method to get the reference to their v2 instance.
542
+ for (const keyring of keyrings) {
543
+ if (keyring instanceof KeyringV1Adapter) {
544
+ // NOTE: We already filtering by `KeyringType.Snap`, so we are sure that those adapters
545
+ // are wrapping a Snap keyring v2.
546
+ const adapter = keyring;
547
+ const keyringV2 = adapter.unwrap();
548
+ // We use the synchronous method here since this method is used during `:stateChange` that are
549
+ // use synchronous handlers.
550
+ const account = keyringV2.lookupByAddress(address);
551
+ if (account) {
552
+ return {
553
+ ...account,
554
+ // We still have to use internal account for now, so we inject some metadata.
555
+ metadata: {
556
+ name: '',
557
+ importTime: Date.now(),
558
+ lastSelected: 0,
559
+ keyring: {
560
+ type: KeyringType.Snap,
561
+ },
562
+ snap: {
563
+ id: keyringV2.snapId,
564
+ },
565
+ },
566
+ };
567
+ }
568
+ }
569
+ }
570
+ return undefined;
571
+ }
572
+ /**
573
+ * Re-publish an account event.
574
+ *
575
+ * @param event - The event type. This is a unique identifier for this event.
576
+ * @param payload - The event payload. The type of the parameters for each event handler must
577
+ * match the type of this payload.
578
+ * @template EventType - A Snap keyring event type.
579
+ */
580
+ #handleOnSnapKeyringAccountEvent(event, ...payload) {
581
+ this.messenger.publish(event, ...payload);
582
+ }
583
+ /**
584
+ * Handles changes in the keyring state, specifically when new accounts are added or removed.
585
+ *
586
+ * @param keyringState - The new state of the keyring controller.
587
+ * @param keyringState.isUnlocked - True if the keyrings are unlocked, false otherwise.
588
+ * @param keyringState.keyrings - List of all keyrings.
589
+ */
590
+ #handleOnKeyringStateChange({ isUnlocked, keyrings, }) {
591
+ // TODO: Change when accountAdded event is added to the keyring controller.
592
+ // We check for keyrings length to be greater than 0 because the extension client may try execute
593
+ // submit password twice and clear the keyring state.
594
+ // https://github.com/MetaMask/KeyringController/blob/2d73a4deed8d013913f6ef0c9f5c0bb7c614f7d3/src/KeyringController.ts#L910
595
+ if (!isUnlocked || keyrings.length === 0) {
596
+ return;
597
+ }
598
+ log('Synchronizing accounts with keyrings (through :stateChange)...');
599
+ // State patches.
600
+ const patch = {
601
+ previous: {},
602
+ added: [],
603
+ updated: [],
604
+ removed: [],
605
+ };
606
+ // Create a map (with lower-cased addresses) of all existing accounts.
607
+ for (const account of this.listMultichainAccounts()) {
608
+ const address = account.address.toLowerCase();
609
+ patch.previous[address] = account;
610
+ }
611
+ // Go over all keyring changes and create patches out of it.
612
+ const addresses = new Set();
613
+ for (const keyring of keyrings) {
614
+ // Money accounts are not treated as real accounts, they are owned by the `MoneyAccountController`, so
615
+ // we need to filter them out here.
616
+ if (isMoneyKeyringType(keyring.type)) {
617
+ continue;
618
+ }
619
+ for (const accountAddress of keyring.accounts) {
620
+ // Lower-case address to use it in the `previous` map.
621
+ const address = accountAddress.toLowerCase();
622
+ const account = patch.previous[address];
623
+ if (account) {
624
+ // If the account exists before, this might be an update.
625
+ patch.updated.push(account);
626
+ }
627
+ else {
628
+ // Otherwise, that's a new account.
629
+ patch.added.push({
630
+ address,
631
+ keyring,
632
+ });
633
+ }
634
+ // Keep track of those address to check for removed accounts later.
635
+ addresses.add(address);
636
+ }
637
+ }
638
+ // We might have accounts associated with removed keyrings, so we iterate
639
+ // over all previous known accounts and check against the keyring addresses.
640
+ for (const [address, account] of Object.entries(patch.previous)) {
641
+ // If a previous address is not part of the new addesses, then it got removed.
642
+ if (!addresses.has(address)) {
643
+ patch.removed.push(account);
644
+ }
645
+ }
646
+ // Diff that we will use to publish events afterward.
647
+ const diff = {
648
+ removed: [],
649
+ added: [],
650
+ };
651
+ this.#update((state) => {
652
+ const { internalAccounts, accountIdByAddress } = state;
653
+ for (const account of patch.removed) {
654
+ delete internalAccounts.accounts[account.id];
655
+ delete accountIdByAddress[account.address];
656
+ diff.removed.push(account.id);
657
+ }
658
+ for (const added of patch.added) {
659
+ const account = this.#getInternalAccountFromAddressAndType(added.address, added.keyring);
660
+ if (account) {
661
+ const accounts = Object.values(internalAccounts.accounts);
662
+ // If it's the first account, we need to select it.
663
+ const lastSelected = accounts.length === 0 ? this.#getLastSelectedIndex() : 0;
664
+ internalAccounts.accounts[account.id] = {
665
+ ...account,
666
+ metadata: {
667
+ ...account.metadata,
668
+ importTime: Date.now(),
669
+ lastSelected,
670
+ },
671
+ };
672
+ accountIdByAddress[account.address] = account.id;
673
+ diff.added.push(internalAccounts.accounts[account.id]);
674
+ }
675
+ }
676
+ },
677
+ // Will get executed after the update, but before re-selecting an account in case
678
+ // the current one is not valid anymore.
679
+ () => {
680
+ // Now publish events
681
+ for (const id of diff.removed) {
682
+ this.messenger.publish('AccountsController:accountRemoved', id);
683
+ }
684
+ if (diff.removed.length > 0) {
685
+ this.messenger.publish('AccountsController:accountsRemoved', diff.removed);
686
+ }
687
+ for (const account of diff.added) {
688
+ this.messenger.publish('AccountsController:accountAdded', account);
689
+ }
690
+ if (diff.added.length > 0) {
691
+ this.messenger.publish('AccountsController:accountsAdded', diff.added);
692
+ }
693
+ });
694
+ log('Accounts synchronized (through :stateChange)!');
695
+ // NOTE: Since we also track "updated" accounts with our patches, we could fire a new event
696
+ // like `accountUpdated` (we would still need to check if anything really changed on the account).
697
+ }
698
+ /**
699
+ * Update the state and fixup the currently selected account.
700
+ *
701
+ * @param callback - Callback for updating state, passed a draft state object.
702
+ * @param beforeAutoSelectAccount - Callback to be executed before auto-selecting an account
703
+ * if the current one is no longer available.
704
+ */
705
+ #update(callback, beforeAutoSelectAccount) {
706
+ // The currently selected account might get deleted during the update, so keep track
707
+ // of it before doing any change.
708
+ const previouslySelectedAccount = this.state.internalAccounts.selectedAccount;
709
+ this.update((state) => {
710
+ callback(state);
711
+ // If the account no longer exists (or none is selected), we need to re-select another one.
712
+ const { internalAccounts } = state;
713
+ if (!internalAccounts.accounts[previouslySelectedAccount]) {
714
+ const accounts = Object.values(internalAccounts.accounts);
715
+ // Get the lastly selected account (according to the current accounts).
716
+ const lastSelectedAccount = this.#getLastSelectedAccount(accounts);
717
+ if (lastSelectedAccount) {
718
+ internalAccounts.selectedAccount = lastSelectedAccount.id;
719
+ internalAccounts.accounts[lastSelectedAccount.id].metadata.lastSelected = this.#getLastSelectedIndex();
720
+ }
721
+ else {
722
+ // It will be undefined if there are no accounts.
723
+ internalAccounts.selectedAccount = '';
724
+ }
725
+ }
726
+ });
727
+ // We might want to do some pre-work before selecting a new account.
728
+ beforeAutoSelectAccount?.();
729
+ // Now, we compare the newly selected account, and we send event if different.
730
+ const { selectedAccount } = this.state.internalAccounts;
731
+ if (selectedAccount && selectedAccount !== previouslySelectedAccount) {
732
+ const account = this.getSelectedMultichainAccount();
733
+ // The account should always be defined at this point, since we have already checked for
734
+ // `selectedAccount` to be non-empty.
735
+ if (account) {
736
+ if (isEvmAccountType(account.type)) {
737
+ this.messenger.publish('AccountsController:selectedEvmAccountChange', account);
738
+ }
739
+ this.messenger.publish('AccountsController:selectedAccountChange', account);
740
+ }
741
+ }
742
+ }
743
+ /**
744
+ * Returns the last selected account from the given array of accounts.
745
+ *
746
+ * @param accounts - An array of InternalAccount objects.
747
+ * @returns The InternalAccount object that was last selected, or undefined if the array is empty.
748
+ */
749
+ #getLastSelectedAccount(accounts) {
750
+ const [accountToSelect] = accounts.sort((accountA, accountB) => {
751
+ // sort by lastSelected descending
752
+ return ((accountB.metadata.lastSelected ?? 0) -
753
+ (accountA.metadata.lastSelected ?? 0));
754
+ });
755
+ return accountToSelect;
756
+ }
757
+ /**
758
+ * Retrieves the index value for `metadata.lastSelected`.
759
+ *
760
+ * @returns The index value.
761
+ */
762
+ #getLastSelectedIndex() {
763
+ // NOTE: For now we use the current date, since we know this value
764
+ // will always be higher than any already selected account index.
765
+ return Date.now();
766
+ }
767
+ /**
768
+ * Get an internal account given an address and a keyring type.
769
+ *
770
+ * If the account is not a Snap Keyring account, generates an internal account for it and adds it to the controller.
771
+ * If the account is a Snap Keyring account, retrieves the account from the keyring and adds it to the controller.
772
+ *
773
+ * @param address - The address of the new account.
774
+ * @param keyring - The keyring object of that new account.
775
+ * @returns The newly generated/retrieved internal account.
776
+ */
777
+ #getInternalAccountFromAddressAndType(address, keyring) {
778
+ const isSnapKeyringV1 = isSnapKeyringType(keyring.type);
779
+ const isSnapKeyringV2 = isSnapKeyringV2Type(keyring.type);
780
+ if (isSnapKeyringV1 || isSnapKeyringV2) {
781
+ let account;
782
+ if (isSnapKeyringV1) {
783
+ account = this.#getAccountFromSnapKeyringV1(address);
784
+ }
785
+ else {
786
+ account = this.#getAccountFromSnapKeyringV2(address);
787
+ }
788
+ if (account) {
789
+ // We force the copy here, to avoid mutating the reference returned by the Snap keyring.
790
+ account = cloneDeep(account);
791
+ // MIGRATION: To avoid any existing Snap account migration, we are
792
+ // just "adding" the new typed options that we need for multichain
793
+ // accounts. Ultimately, we would need a real Snap account migrations
794
+ // (being handled by each Snaps).
795
+ if (isHdSnapKeyringAccount(account)) {
796
+ const options = {
797
+ ...account.options,
798
+ entropy: {
799
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
800
+ id: account.options.entropySource,
801
+ groupIndex: account.options.index,
802
+ derivationPath: account.options.derivationPath,
803
+ },
804
+ };
805
+ // Inject the new typed options to the internal account copy.
806
+ account.options = options;
807
+ }
808
+ }
809
+ return account;
810
+ }
811
+ return this.#getInternalAccountForNonSnapAccount(address, keyring);
812
+ }
813
+ /**
814
+ * Handles the change in multichain network by updating the selected account.
815
+ *
816
+ * @param id - The EVM client ID or non-EVM chain ID that changed.
817
+ */
818
+ #handleOnMultichainNetworkDidChange(id) {
819
+ let accountId;
820
+ // We only support non-EVM Caip chain IDs at the moment. Ex Solana and Bitcoin
821
+ // MultichainNetworkController will handle throwing an error if the Caip chain ID is not supported
822
+ if (isCaipChainId(id)) {
823
+ // Update selected account to non evm account
824
+ const lastSelectedNonEvmAccount = this.getSelectedMultichainAccount(id);
825
+ // @ts-expect-error - This should never be undefined, otherwise it's a bug that should be handled
826
+ accountId = lastSelectedNonEvmAccount.id;
827
+ }
828
+ else {
829
+ // Update selected account to evm account
830
+ const lastSelectedEvmAccount = this.getSelectedAccount();
831
+ accountId = lastSelectedEvmAccount.id;
832
+ }
833
+ if (this.state.internalAccounts.selectedAccount === accountId) {
834
+ return;
835
+ }
836
+ this.update((currentState) => {
837
+ currentState.internalAccounts.accounts[accountId].metadata.lastSelected =
838
+ Date.now();
839
+ currentState.internalAccounts.selectedAccount = accountId;
840
+ });
841
+ // DO NOT publish AccountsController:setSelectedAccount to prevent circular listener loops
842
+ }
843
+ /**
844
+ * Subscribes to message events.
845
+ */
846
+ #subscribeToMessageEvents() {
847
+ this.messenger.subscribe('KeyringController:stateChange', (keyringState) => this.#handleOnKeyringStateChange(keyringState));
848
+ this.messenger.subscribe('SnapAccountService:accountAssetListUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountAssetListUpdated', snapAccountEvent));
849
+ this.messenger.subscribe('SnapAccountService:accountBalancesUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountBalancesUpdated', snapAccountEvent));
850
+ this.messenger.subscribe('SnapAccountService:accountTransactionsUpdated', (snapAccountEvent) => this.#handleOnSnapKeyringAccountEvent('AccountsController:accountTransactionsUpdated', snapAccountEvent));
851
+ // Handle account change when multichain network is changed
852
+ this.messenger.subscribe('MultichainNetworkController:networkDidChange', (id) => this.#handleOnMultichainNetworkDidChange(id));
853
+ }
854
+ }
855
+ //# sourceMappingURL=AccountsController.js.map