@metamask/accounts-controller 18.2.0 → 18.2.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (59) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/AccountsController.cjs +608 -0
  3. package/dist/AccountsController.cjs.map +1 -0
  4. package/dist/{types/AccountsController.d.ts → AccountsController.d.cts} +8 -8
  5. package/dist/AccountsController.d.cts.map +1 -0
  6. package/dist/AccountsController.d.mts +215 -0
  7. package/dist/AccountsController.d.mts.map +1 -0
  8. package/dist/AccountsController.mjs +604 -9
  9. package/dist/AccountsController.mjs.map +1 -1
  10. package/dist/index.cjs +9 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/{types/index.d.ts → index.d.cts} +4 -4
  13. package/dist/index.d.cts.map +1 -0
  14. package/dist/index.d.mts +4 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +2 -13
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/tests/mocks.cjs +49 -0
  19. package/dist/tests/mocks.cjs.map +1 -0
  20. package/dist/{types/tests/mocks.d.ts → tests/mocks.d.cts} +3 -3
  21. package/dist/tests/mocks.d.cts.map +1 -0
  22. package/dist/tests/mocks.d.mts +17 -0
  23. package/dist/tests/mocks.d.mts.map +1 -0
  24. package/dist/tests/mocks.mjs +41 -60
  25. package/dist/tests/mocks.mjs.map +1 -1
  26. package/dist/utils.cjs +80 -0
  27. package/dist/utils.cjs.map +1 -0
  28. package/dist/{types/utils.d.ts → utils.d.cts} +3 -3
  29. package/dist/utils.d.cts.map +1 -0
  30. package/dist/utils.d.mts +28 -0
  31. package/dist/utils.d.mts.map +1 -0
  32. package/dist/utils.mjs +73 -13
  33. package/dist/utils.mjs.map +1 -1
  34. package/package.json +20 -15
  35. package/dist/AccountsController.js +0 -11
  36. package/dist/AccountsController.js.map +0 -1
  37. package/dist/chunk-2DVFC4VN.js +0 -763
  38. package/dist/chunk-2DVFC4VN.js.map +0 -1
  39. package/dist/chunk-BYPP7G2N.js +0 -56
  40. package/dist/chunk-BYPP7G2N.js.map +0 -1
  41. package/dist/chunk-RIZO66PK.mjs +0 -763
  42. package/dist/chunk-RIZO66PK.mjs.map +0 -1
  43. package/dist/chunk-UJIPPGP6.js +0 -19
  44. package/dist/chunk-UJIPPGP6.js.map +0 -1
  45. package/dist/chunk-Y2QVUNIA.mjs +0 -56
  46. package/dist/chunk-Y2QVUNIA.mjs.map +0 -1
  47. package/dist/chunk-ZNSHBDHA.mjs +0 -19
  48. package/dist/chunk-ZNSHBDHA.mjs.map +0 -1
  49. package/dist/index.js +0 -14
  50. package/dist/index.js.map +0 -1
  51. package/dist/tests/mocks.js +0 -65
  52. package/dist/tests/mocks.js.map +0 -1
  53. package/dist/tsconfig.build.tsbuildinfo +0 -1
  54. package/dist/types/AccountsController.d.ts.map +0 -1
  55. package/dist/types/index.d.ts.map +0 -1
  56. package/dist/types/tests/mocks.d.ts.map +0 -1
  57. package/dist/types/utils.d.ts.map +0 -1
  58. package/dist/utils.js +0 -14
  59. package/dist/utils.js.map +0 -1
@@ -1,763 +0,0 @@
1
- import {
2
- getUUIDFromAddressOfNormalAccount,
3
- isNormalKeyringType,
4
- keyringTypeToName
5
- } from "./chunk-Y2QVUNIA.mjs";
6
- import {
7
- __privateAdd,
8
- __privateMethod
9
- } from "./chunk-ZNSHBDHA.mjs";
10
-
11
- // src/AccountsController.ts
12
- import { BaseController } from "@metamask/base-controller";
13
- import { SnapKeyring } from "@metamask/eth-snap-keyring";
14
- import {
15
- EthAccountType,
16
- EthMethod,
17
- isEvmAccountType
18
- } from "@metamask/keyring-api";
19
- import { KeyringTypes } from "@metamask/keyring-controller";
20
- import {
21
- isCaipChainId,
22
- parseCaipChainId
23
- } from "@metamask/utils";
24
- var controllerName = "AccountsController";
25
- var accountsControllerMetadata = {
26
- internalAccounts: {
27
- persist: true,
28
- anonymous: false
29
- }
30
- };
31
- var defaultState = {
32
- internalAccounts: {
33
- accounts: {},
34
- selectedAccount: ""
35
- }
36
- };
37
- var EMPTY_ACCOUNT = {
38
- id: "",
39
- address: "",
40
- options: {},
41
- methods: [],
42
- type: EthAccountType.Eoa,
43
- metadata: {
44
- name: "",
45
- keyring: {
46
- type: ""
47
- },
48
- importTime: 0
49
- }
50
- };
51
- var _generateInternalAccountForNonSnapAccount, generateInternalAccountForNonSnapAccount_fn, _listSnapAccounts, listSnapAccounts_fn, _listNormalAccounts, listNormalAccounts_fn, _handleOnKeyringStateChange, handleOnKeyringStateChange_fn, _handleOnSnapStateChange, handleOnSnapStateChange_fn, _getAccountsByKeyringType, getAccountsByKeyringType_fn, _getLastSelectedAccount, getLastSelectedAccount_fn, _isAccountCompatibleWithChain, isAccountCompatibleWithChain_fn, _getLastSelectedIndex, getLastSelectedIndex_fn, _handleNewAccountAdded, handleNewAccountAdded_fn, _publishAccountChangeEvent, publishAccountChangeEvent_fn, _handleAccountRemoved, handleAccountRemoved_fn, _populateExistingMetadata, populateExistingMetadata_fn, _registerMessageHandlers, registerMessageHandlers_fn;
52
- var AccountsController = class extends BaseController {
53
- /**
54
- * Constructor for AccountsController.
55
- *
56
- * @param options - The controller options.
57
- * @param options.messenger - The messenger object.
58
- * @param options.state - Initial state to set on this controller
59
- */
60
- constructor({
61
- messenger,
62
- state
63
- }) {
64
- super({
65
- messenger,
66
- name: controllerName,
67
- metadata: accountsControllerMetadata,
68
- state: {
69
- ...defaultState,
70
- ...state
71
- }
72
- });
73
- /**
74
- * Generates an internal account for a non-Snap account.
75
- * @param address - The address of the account.
76
- * @param type - The type of the account.
77
- * @returns The generated internal account.
78
- */
79
- __privateAdd(this, _generateInternalAccountForNonSnapAccount);
80
- /**
81
- * Returns a list of internal accounts created using the SnapKeyring.
82
- *
83
- * @returns A promise that resolves to an array of InternalAccount objects.
84
- */
85
- __privateAdd(this, _listSnapAccounts);
86
- /**
87
- * Returns a list of normal accounts.
88
- * Note: listNormalAccounts is a temporary method until the keyrings all implement the InternalAccount interface.
89
- * Once all keyrings implement the InternalAccount interface, this method can be removed and getAccounts can be used instead.
90
- *
91
- * @returns A Promise that resolves to an array of InternalAccount objects.
92
- */
93
- __privateAdd(this, _listNormalAccounts);
94
- /**
95
- * Handles changes in the keyring state, specifically when new accounts are added or removed.
96
- *
97
- * @param keyringState - The new state of the keyring controller.
98
- */
99
- __privateAdd(this, _handleOnKeyringStateChange);
100
- /**
101
- * Handles the change in SnapControllerState by updating the metadata of accounts that have a snap enabled.
102
- *
103
- * @param snapState - The new SnapControllerState.
104
- */
105
- __privateAdd(this, _handleOnSnapStateChange);
106
- /**
107
- * Returns the list of accounts for a given keyring type.
108
- * @param keyringType - The type of keyring.
109
- * @param accounts - Accounts to filter by keyring type.
110
- * @returns The list of accounts associcated with this keyring type.
111
- */
112
- __privateAdd(this, _getAccountsByKeyringType);
113
- /**
114
- * Returns the last selected account from the given array of accounts.
115
- *
116
- * @param accounts - An array of InternalAccount objects.
117
- * @returns The InternalAccount object that was last selected, or undefined if the array is empty.
118
- */
119
- __privateAdd(this, _getLastSelectedAccount);
120
- /**
121
- * Checks if an account is compatible with a given chain namespace.
122
- * @private
123
- * @param account - The account to check compatibility for.
124
- * @param chainId - The CAIP2 to check compatibility with.
125
- * @returns Returns true if the account is compatible with the chain namespace, otherwise false.
126
- */
127
- __privateAdd(this, _isAccountCompatibleWithChain);
128
- /**
129
- * Retrieves the index value for `metadata.lastSelected`.
130
- *
131
- * @returns The index value.
132
- */
133
- __privateAdd(this, _getLastSelectedIndex);
134
- /**
135
- * Handles the addition of a new account to the controller.
136
- * If the account is not a Snap Keyring account, generates an internal account for it and adds it to the controller.
137
- * If the account is a Snap Keyring account, retrieves the account from the keyring and adds it to the controller.
138
- * @param accountsState - AccountsController accounts state that is to be mutated.
139
- * @param account - The address and keyring type object of the new account.
140
- * @returns The updated AccountsController accounts state.
141
- */
142
- __privateAdd(this, _handleNewAccountAdded);
143
- __privateAdd(this, _publishAccountChangeEvent);
144
- /**
145
- * Handles the removal of an account from the internal accounts list.
146
- * @param accountsState - AccountsController accounts state that is to be mutated.
147
- * @param accountId - The ID of the account to be removed.
148
- * @returns The updated AccountsController state.
149
- */
150
- __privateAdd(this, _handleAccountRemoved);
151
- /**
152
- * Retrieves the value of a specific metadata key for an existing account.
153
- * @param accountId - The ID of the account.
154
- * @param metadataKey - The key of the metadata to retrieve.
155
- * @param account - The account object to retrieve the metadata key from.
156
- * @returns The value of the specified metadata key, or undefined if the account or metadata key does not exist.
157
- */
158
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
159
- // eslint-disable-next-line @typescript-eslint/naming-convention
160
- __privateAdd(this, _populateExistingMetadata);
161
- /**
162
- * Registers message handlers for the AccountsController.
163
- * @private
164
- */
165
- __privateAdd(this, _registerMessageHandlers);
166
- this.messagingSystem.subscribe(
167
- "SnapController:stateChange",
168
- (snapStateState) => __privateMethod(this, _handleOnSnapStateChange, handleOnSnapStateChange_fn).call(this, snapStateState)
169
- );
170
- this.messagingSystem.subscribe(
171
- "KeyringController:stateChange",
172
- (keyringState) => __privateMethod(this, _handleOnKeyringStateChange, handleOnKeyringStateChange_fn).call(this, keyringState)
173
- );
174
- __privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
175
- }
176
- /**
177
- * Returns the internal account object for the given account ID, if it exists.
178
- *
179
- * @param accountId - The ID of the account to retrieve.
180
- * @returns The internal account object, or undefined if the account does not exist.
181
- */
182
- getAccount(accountId) {
183
- return this.state.internalAccounts.accounts[accountId];
184
- }
185
- /**
186
- * Returns an array of all evm internal accounts.
187
- *
188
- * @returns An array of InternalAccount objects.
189
- */
190
- listAccounts() {
191
- const accounts = Object.values(this.state.internalAccounts.accounts);
192
- return accounts.filter((account) => isEvmAccountType(account.type));
193
- }
194
- /**
195
- * Returns an array of all internal accounts.
196
- *
197
- * @param chainId - The chain ID.
198
- * @returns An array of InternalAccount objects.
199
- */
200
- listMultichainAccounts(chainId) {
201
- const accounts = Object.values(this.state.internalAccounts.accounts);
202
- if (!chainId) {
203
- return accounts;
204
- }
205
- if (!isCaipChainId(chainId)) {
206
- throw new Error(`Invalid CAIP-2 chain ID: ${String(chainId)}`);
207
- }
208
- return accounts.filter(
209
- (account) => __privateMethod(this, _isAccountCompatibleWithChain, isAccountCompatibleWithChain_fn).call(this, account, chainId)
210
- );
211
- }
212
- /**
213
- * Returns the internal account object for the given account ID.
214
- *
215
- * @param accountId - The ID of the account to retrieve.
216
- * @returns The internal account object.
217
- * @throws An error if the account ID is not found.
218
- */
219
- getAccountExpect(accountId) {
220
- const account = this.getAccount(accountId);
221
- if (account === void 0) {
222
- throw new Error(`Account Id "${accountId}" not found`);
223
- }
224
- return account;
225
- }
226
- /**
227
- * Returns the last selected EVM account.
228
- *
229
- * @returns The selected internal account.
230
- */
231
- getSelectedAccount() {
232
- if (this.state.internalAccounts.selectedAccount === "") {
233
- return EMPTY_ACCOUNT;
234
- }
235
- const selectedAccount = this.getAccountExpect(
236
- this.state.internalAccounts.selectedAccount
237
- );
238
- if (isEvmAccountType(selectedAccount.type)) {
239
- return selectedAccount;
240
- }
241
- const accounts = this.listAccounts();
242
- if (!accounts.length) {
243
- throw new Error("No EVM accounts");
244
- }
245
- return __privateMethod(this, _getLastSelectedAccount, getLastSelectedAccount_fn).call(this, accounts);
246
- }
247
- /**
248
- * __WARNING The return value may be undefined if there isn't an account for that chain id.__
249
- *
250
- * Retrieves the last selected account by chain ID.
251
- *
252
- * @param chainId - The chain ID to filter the accounts.
253
- * @returns The last selected account compatible with the specified chain ID or undefined.
254
- */
255
- getSelectedMultichainAccount(chainId) {
256
- if (this.state.internalAccounts.selectedAccount === "") {
257
- return EMPTY_ACCOUNT;
258
- }
259
- if (!chainId) {
260
- return this.getAccountExpect(this.state.internalAccounts.selectedAccount);
261
- }
262
- if (!isCaipChainId(chainId)) {
263
- throw new Error(`Invalid CAIP-2 chain ID: ${chainId}`);
264
- }
265
- const accounts = Object.values(this.state.internalAccounts.accounts).filter(
266
- (account) => __privateMethod(this, _isAccountCompatibleWithChain, isAccountCompatibleWithChain_fn).call(this, account, chainId)
267
- );
268
- return __privateMethod(this, _getLastSelectedAccount, getLastSelectedAccount_fn).call(this, accounts);
269
- }
270
- /**
271
- * Returns the account with the specified address.
272
- * ! This method will only return the first account that matches the address
273
- * @param address - The address of the account to retrieve.
274
- * @returns The account with the specified address, or undefined if not found.
275
- */
276
- getAccountByAddress(address) {
277
- return this.listMultichainAccounts().find(
278
- (account) => account.address.toLowerCase() === address.toLowerCase()
279
- );
280
- }
281
- /**
282
- * Sets the selected account by its ID.
283
- *
284
- * @param accountId - The ID of the account to be selected.
285
- */
286
- setSelectedAccount(accountId) {
287
- const account = this.getAccountExpect(accountId);
288
- this.update((currentState) => {
289
- currentState.internalAccounts.accounts[account.id].metadata.lastSelected = Date.now();
290
- currentState.internalAccounts.selectedAccount = account.id;
291
- });
292
- __privateMethod(this, _publishAccountChangeEvent, publishAccountChangeEvent_fn).call(this, account);
293
- }
294
- /**
295
- * Sets the name of the account with the given ID.
296
- *
297
- * @param accountId - The ID of the account to set the name for.
298
- * @param accountName - The new name for the account.
299
- * @throws An error if an account with the same name already exists.
300
- */
301
- setAccountName(accountId, accountName) {
302
- this.updateAccountMetadata(accountId, {
303
- name: accountName,
304
- nameLastUpdatedAt: Date.now()
305
- });
306
- }
307
- /**
308
- * Updates the metadata of the account with the given ID.
309
- *
310
- * @param accountId - The ID of the account for which the metadata will be updated.
311
- * @param metadata - The new metadata for the account.
312
- */
313
- updateAccountMetadata(accountId, metadata) {
314
- const account = this.getAccountExpect(accountId);
315
- if (metadata.name && this.listMultichainAccounts().find(
316
- (internalAccount) => internalAccount.metadata.name === metadata.name && internalAccount.id !== accountId
317
- )) {
318
- throw new Error("Account name already exists");
319
- }
320
- this.update((currentState) => {
321
- const internalAccount = {
322
- ...account,
323
- metadata: { ...account.metadata, ...metadata }
324
- };
325
- currentState.internalAccounts.accounts[accountId] = internalAccount;
326
- if (metadata.name) {
327
- this.messagingSystem.publish(
328
- "AccountsController:accountRenamed",
329
- internalAccount
330
- );
331
- }
332
- });
333
- }
334
- /**
335
- * Updates the internal accounts list by retrieving normal and snap accounts,
336
- * removing duplicates, and updating the metadata of each account.
337
- *
338
- * @returns A Promise that resolves when the accounts have been updated.
339
- */
340
- async updateAccounts() {
341
- const snapAccounts = await __privateMethod(this, _listSnapAccounts, listSnapAccounts_fn).call(this);
342
- const normalAccounts = await __privateMethod(this, _listNormalAccounts, listNormalAccounts_fn).call(this);
343
- const keyringTypes = /* @__PURE__ */ new Map();
344
- const previousAccounts = this.state.internalAccounts.accounts;
345
- const accounts = [
346
- ...normalAccounts,
347
- ...snapAccounts
348
- ].reduce((internalAccountMap, internalAccount) => {
349
- const keyringTypeName = keyringTypeToName(
350
- internalAccount.metadata.keyring.type
351
- );
352
- const keyringAccountIndex = keyringTypes.get(keyringTypeName) ?? 0;
353
- if (keyringAccountIndex) {
354
- keyringTypes.set(keyringTypeName, keyringAccountIndex + 1);
355
- } else {
356
- keyringTypes.set(keyringTypeName, 1);
357
- }
358
- const existingAccount = previousAccounts[internalAccount.id];
359
- internalAccountMap[internalAccount.id] = {
360
- ...internalAccount,
361
- metadata: {
362
- ...internalAccount.metadata,
363
- name: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, existingAccount?.id, "name") ?? `${keyringTypeName} ${keyringAccountIndex + 1}`,
364
- importTime: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, existingAccount?.id, "importTime") ?? Date.now(),
365
- lastSelected: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, existingAccount?.id, "lastSelected") ?? 0
366
- }
367
- };
368
- return internalAccountMap;
369
- }, {});
370
- this.update((currentState) => {
371
- currentState.internalAccounts.accounts = accounts;
372
- if (!currentState.internalAccounts.accounts[currentState.internalAccounts.selectedAccount]) {
373
- const lastSelectedAccount = __privateMethod(this, _getLastSelectedAccount, getLastSelectedAccount_fn).call(this, Object.values(accounts));
374
- if (lastSelectedAccount) {
375
- currentState.internalAccounts.selectedAccount = lastSelectedAccount.id;
376
- currentState.internalAccounts.accounts[lastSelectedAccount.id].metadata.lastSelected = __privateMethod(this, _getLastSelectedIndex, getLastSelectedIndex_fn).call(this);
377
- __privateMethod(this, _publishAccountChangeEvent, publishAccountChangeEvent_fn).call(this, lastSelectedAccount);
378
- } else {
379
- currentState.internalAccounts.selectedAccount = "";
380
- }
381
- }
382
- });
383
- }
384
- /**
385
- * Loads the backup state of the accounts controller.
386
- *
387
- * @param backup - The backup state to load.
388
- */
389
- loadBackup(backup) {
390
- if (backup.internalAccounts) {
391
- this.update((currentState) => {
392
- currentState.internalAccounts = backup.internalAccounts;
393
- });
394
- }
395
- }
396
- /**
397
- * Returns the next account number for a given keyring type.
398
- * @param keyringType - The type of keyring.
399
- * @param accounts - Existing accounts to check for the next available account number.
400
- * @returns An object containing the account prefix and index to use.
401
- */
402
- getNextAvailableAccountName(keyringType = KeyringTypes.hd, accounts) {
403
- const keyringName = keyringTypeToName(keyringType);
404
- const keyringAccounts = __privateMethod(this, _getAccountsByKeyringType, getAccountsByKeyringType_fn).call(this, keyringType, accounts);
405
- const lastDefaultIndexUsedForKeyringType = keyringAccounts.reduce(
406
- (maxInternalAccountIndex, internalAccount) => {
407
- const match = new RegExp(`${keyringName} ([0-9]+)$`, "u").exec(
408
- internalAccount.metadata.name
409
- );
410
- if (match) {
411
- const internalAccountIndex = parseInt(match[1], 10);
412
- return Math.max(maxInternalAccountIndex, internalAccountIndex);
413
- }
414
- return maxInternalAccountIndex;
415
- },
416
- 0
417
- );
418
- const index = Math.max(
419
- keyringAccounts.length + 1,
420
- // ESLint is confused; this is a number.
421
- // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
422
- lastDefaultIndexUsedForKeyringType + 1
423
- );
424
- return `${keyringName} ${index}`;
425
- }
426
- };
427
- _generateInternalAccountForNonSnapAccount = new WeakSet();
428
- generateInternalAccountForNonSnapAccount_fn = function(address, type) {
429
- return {
430
- id: getUUIDFromAddressOfNormalAccount(address),
431
- address,
432
- options: {},
433
- methods: [
434
- EthMethod.PersonalSign,
435
- EthMethod.Sign,
436
- EthMethod.SignTransaction,
437
- EthMethod.SignTypedDataV1,
438
- EthMethod.SignTypedDataV3,
439
- EthMethod.SignTypedDataV4
440
- ],
441
- type: EthAccountType.Eoa,
442
- metadata: {
443
- name: "",
444
- importTime: Date.now(),
445
- keyring: {
446
- type
447
- }
448
- }
449
- };
450
- };
451
- _listSnapAccounts = new WeakSet();
452
- listSnapAccounts_fn = async function() {
453
- const [snapKeyring] = this.messagingSystem.call(
454
- "KeyringController:getKeyringsByType",
455
- SnapKeyring.type
456
- );
457
- if (!snapKeyring) {
458
- return [];
459
- }
460
- const snapAccounts = snapKeyring.listAccounts();
461
- return snapAccounts;
462
- };
463
- _listNormalAccounts = new WeakSet();
464
- listNormalAccounts_fn = async function() {
465
- const addresses = await this.messagingSystem.call(
466
- "KeyringController:getAccounts"
467
- );
468
- const internalAccounts = [];
469
- for (const address of addresses) {
470
- const keyring = await this.messagingSystem.call(
471
- "KeyringController:getKeyringForAccount",
472
- address
473
- );
474
- const keyringType = keyring.type;
475
- if (!isNormalKeyringType(keyringType)) {
476
- continue;
477
- }
478
- const id = getUUIDFromAddressOfNormalAccount(address);
479
- const nameLastUpdatedAt = __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, id, "nameLastUpdatedAt");
480
- internalAccounts.push({
481
- id,
482
- address,
483
- options: {},
484
- methods: [
485
- EthMethod.PersonalSign,
486
- EthMethod.Sign,
487
- EthMethod.SignTransaction,
488
- EthMethod.SignTypedDataV1,
489
- EthMethod.SignTypedDataV3,
490
- EthMethod.SignTypedDataV4
491
- ],
492
- type: EthAccountType.Eoa,
493
- metadata: {
494
- name: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, id, "name") ?? "",
495
- ...nameLastUpdatedAt && { nameLastUpdatedAt },
496
- importTime: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, id, "importTime") ?? Date.now(),
497
- lastSelected: __privateMethod(this, _populateExistingMetadata, populateExistingMetadata_fn).call(this, id, "lastSelected") ?? 0,
498
- keyring: {
499
- type: keyring.type
500
- }
501
- }
502
- });
503
- }
504
- return internalAccounts;
505
- };
506
- _handleOnKeyringStateChange = new WeakSet();
507
- handleOnKeyringStateChange_fn = function(keyringState) {
508
- if (keyringState.isUnlocked && keyringState.keyrings.length > 0) {
509
- const updatedNormalKeyringAddresses = [];
510
- const updatedSnapKeyringAddresses = [];
511
- for (const keyring of keyringState.keyrings) {
512
- if (keyring.type === KeyringTypes.snap) {
513
- updatedSnapKeyringAddresses.push(
514
- ...keyring.accounts.map((address) => {
515
- return {
516
- address,
517
- type: keyring.type
518
- };
519
- })
520
- );
521
- } else {
522
- updatedNormalKeyringAddresses.push(
523
- ...keyring.accounts.map((address) => {
524
- return {
525
- address,
526
- type: keyring.type
527
- };
528
- })
529
- );
530
- }
531
- }
532
- const { previousNormalInternalAccounts, previousSnapInternalAccounts } = this.listMultichainAccounts().reduce(
533
- (accumulator, account) => {
534
- if (account.metadata.keyring.type === KeyringTypes.snap) {
535
- accumulator.previousSnapInternalAccounts.push(account);
536
- } else {
537
- accumulator.previousNormalInternalAccounts.push(account);
538
- }
539
- return accumulator;
540
- },
541
- {
542
- previousNormalInternalAccounts: [],
543
- previousSnapInternalAccounts: []
544
- }
545
- );
546
- const addedAccounts = [];
547
- const deletedAccounts = [];
548
- for (const account of updatedNormalKeyringAddresses) {
549
- if (!this.state.internalAccounts.accounts[getUUIDFromAddressOfNormalAccount(account.address)]) {
550
- addedAccounts.push(account);
551
- }
552
- }
553
- for (const account of updatedSnapKeyringAddresses) {
554
- if (!previousSnapInternalAccounts.find(
555
- (internalAccount) => internalAccount.address.toLowerCase() === account.address.toLowerCase()
556
- )) {
557
- addedAccounts.push(account);
558
- }
559
- }
560
- for (const account of previousNormalInternalAccounts) {
561
- if (!updatedNormalKeyringAddresses.find(
562
- ({ address }) => address.toLowerCase() === account.address.toLowerCase()
563
- )) {
564
- deletedAccounts.push(account);
565
- }
566
- }
567
- for (const account of previousSnapInternalAccounts) {
568
- if (!updatedSnapKeyringAddresses.find(
569
- ({ address }) => address.toLowerCase() === account.address.toLowerCase()
570
- )) {
571
- deletedAccounts.push(account);
572
- }
573
- }
574
- this.update((currentState) => {
575
- if (deletedAccounts.length > 0) {
576
- for (const account of deletedAccounts) {
577
- currentState.internalAccounts.accounts = __privateMethod(this, _handleAccountRemoved, handleAccountRemoved_fn).call(this, currentState.internalAccounts.accounts, account.id);
578
- }
579
- }
580
- if (addedAccounts.length > 0) {
581
- for (const account of addedAccounts) {
582
- currentState.internalAccounts.accounts = __privateMethod(this, _handleNewAccountAdded, handleNewAccountAdded_fn).call(this, currentState.internalAccounts.accounts, account);
583
- }
584
- }
585
- const existingAccounts = Object.values(
586
- currentState.internalAccounts.accounts
587
- );
588
- if (!currentState.internalAccounts.accounts[this.state.internalAccounts.selectedAccount]) {
589
- const lastSelectedAccount = __privateMethod(this, _getLastSelectedAccount, getLastSelectedAccount_fn).call(this, existingAccounts);
590
- if (lastSelectedAccount) {
591
- currentState.internalAccounts.selectedAccount = lastSelectedAccount.id;
592
- currentState.internalAccounts.accounts[lastSelectedAccount.id].metadata.lastSelected = __privateMethod(this, _getLastSelectedIndex, getLastSelectedIndex_fn).call(this);
593
- __privateMethod(this, _publishAccountChangeEvent, publishAccountChangeEvent_fn).call(this, lastSelectedAccount);
594
- } else {
595
- currentState.internalAccounts.selectedAccount = "";
596
- }
597
- }
598
- });
599
- }
600
- };
601
- _handleOnSnapStateChange = new WeakSet();
602
- handleOnSnapStateChange_fn = function(snapState) {
603
- const { snaps } = snapState;
604
- const accounts = this.listMultichainAccounts().filter(
605
- (account) => account.metadata.snap
606
- );
607
- this.update((currentState) => {
608
- accounts.forEach((account) => {
609
- const currentAccount = currentState.internalAccounts.accounts[account.id];
610
- if (currentAccount.metadata.snap) {
611
- const snapId = currentAccount.metadata.snap.id;
612
- const storedSnap = snaps[snapId];
613
- if (storedSnap) {
614
- currentAccount.metadata.snap.enabled = storedSnap.enabled && !storedSnap.blocked;
615
- }
616
- }
617
- });
618
- });
619
- };
620
- _getAccountsByKeyringType = new WeakSet();
621
- getAccountsByKeyringType_fn = function(keyringType, accounts) {
622
- return (accounts ?? this.listMultichainAccounts()).filter(
623
- (internalAccount) => {
624
- if (keyringType === KeyringTypes.hd || keyringType === KeyringTypes.simple) {
625
- return internalAccount.metadata.keyring.type === KeyringTypes.hd || internalAccount.metadata.keyring.type === KeyringTypes.simple;
626
- }
627
- return internalAccount.metadata.keyring.type === keyringType;
628
- }
629
- );
630
- };
631
- _getLastSelectedAccount = new WeakSet();
632
- getLastSelectedAccount_fn = function(accounts) {
633
- const [accountToSelect] = accounts.sort((accountA, accountB) => {
634
- return (accountB.metadata.lastSelected ?? 0) - (accountA.metadata.lastSelected ?? 0);
635
- });
636
- return accountToSelect;
637
- };
638
- _isAccountCompatibleWithChain = new WeakSet();
639
- isAccountCompatibleWithChain_fn = function(account, chainId) {
640
- return account.type.startsWith(parseCaipChainId(chainId).namespace);
641
- };
642
- _getLastSelectedIndex = new WeakSet();
643
- getLastSelectedIndex_fn = function() {
644
- return Date.now();
645
- };
646
- _handleNewAccountAdded = new WeakSet();
647
- handleNewAccountAdded_fn = function(accountsState, account) {
648
- let newAccount;
649
- if (account.type !== KeyringTypes.snap) {
650
- newAccount = __privateMethod(this, _generateInternalAccountForNonSnapAccount, generateInternalAccountForNonSnapAccount_fn).call(this, account.address, account.type);
651
- } else {
652
- const [snapKeyring] = this.messagingSystem.call(
653
- "KeyringController:getKeyringsByType",
654
- SnapKeyring.type
655
- );
656
- newAccount = snapKeyring.getAccountByAddress(
657
- account.address
658
- );
659
- if (!newAccount) {
660
- return accountsState;
661
- }
662
- }
663
- const isFirstAccount = Object.keys(accountsState).length === 0;
664
- const accountName = this.getNextAvailableAccountName(
665
- newAccount.metadata.keyring.type,
666
- Object.values(accountsState)
667
- );
668
- const newAccountWithUpdatedMetadata = {
669
- ...newAccount,
670
- metadata: {
671
- ...newAccount.metadata,
672
- name: accountName,
673
- importTime: Date.now(),
674
- lastSelected: isFirstAccount ? __privateMethod(this, _getLastSelectedIndex, getLastSelectedIndex_fn).call(this) : 0
675
- }
676
- };
677
- accountsState[newAccount.id] = newAccountWithUpdatedMetadata;
678
- this.messagingSystem.publish(
679
- "AccountsController:accountAdded",
680
- newAccountWithUpdatedMetadata
681
- );
682
- return accountsState;
683
- };
684
- _publishAccountChangeEvent = new WeakSet();
685
- publishAccountChangeEvent_fn = function(account) {
686
- if (isEvmAccountType(account.type)) {
687
- this.messagingSystem.publish(
688
- "AccountsController:selectedEvmAccountChange",
689
- account
690
- );
691
- }
692
- this.messagingSystem.publish(
693
- "AccountsController:selectedAccountChange",
694
- account
695
- );
696
- };
697
- _handleAccountRemoved = new WeakSet();
698
- handleAccountRemoved_fn = function(accountsState, accountId) {
699
- delete accountsState[accountId];
700
- this.messagingSystem.publish(
701
- "AccountsController:accountRemoved",
702
- accountId
703
- );
704
- return accountsState;
705
- };
706
- _populateExistingMetadata = new WeakSet();
707
- populateExistingMetadata_fn = function(accountId, metadataKey, account) {
708
- const internalAccount = account ?? this.getAccount(accountId);
709
- return internalAccount ? internalAccount.metadata[metadataKey] : void 0;
710
- };
711
- _registerMessageHandlers = new WeakSet();
712
- registerMessageHandlers_fn = function() {
713
- this.messagingSystem.registerActionHandler(
714
- `${controllerName}:setSelectedAccount`,
715
- this.setSelectedAccount.bind(this)
716
- );
717
- this.messagingSystem.registerActionHandler(
718
- `${controllerName}:listAccounts`,
719
- this.listAccounts.bind(this)
720
- );
721
- this.messagingSystem.registerActionHandler(
722
- `${controllerName}:listMultichainAccounts`,
723
- this.listMultichainAccounts.bind(this)
724
- );
725
- this.messagingSystem.registerActionHandler(
726
- `${controllerName}:setAccountName`,
727
- this.setAccountName.bind(this)
728
- );
729
- this.messagingSystem.registerActionHandler(
730
- `${controllerName}:updateAccounts`,
731
- this.updateAccounts.bind(this)
732
- );
733
- this.messagingSystem.registerActionHandler(
734
- `${controllerName}:getSelectedAccount`,
735
- this.getSelectedAccount.bind(this)
736
- );
737
- this.messagingSystem.registerActionHandler(
738
- `${controllerName}:getSelectedMultichainAccount`,
739
- this.getSelectedMultichainAccount.bind(this)
740
- );
741
- this.messagingSystem.registerActionHandler(
742
- `${controllerName}:getAccountByAddress`,
743
- this.getAccountByAddress.bind(this)
744
- );
745
- this.messagingSystem.registerActionHandler(
746
- `${controllerName}:getNextAvailableAccountName`,
747
- this.getNextAvailableAccountName.bind(this)
748
- );
749
- this.messagingSystem.registerActionHandler(
750
- `AccountsController:getAccount`,
751
- this.getAccount.bind(this)
752
- );
753
- this.messagingSystem.registerActionHandler(
754
- `AccountsController:updateAccountMetadata`,
755
- this.updateAccountMetadata.bind(this)
756
- );
757
- };
758
-
759
- export {
760
- EMPTY_ACCOUNT,
761
- AccountsController
762
- };
763
- //# sourceMappingURL=chunk-RIZO66PK.mjs.map