-
-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathAccountTreeController.ts
More file actions
1665 lines (1474 loc) · 53.2 KB
/
AccountTreeController.ts
File metadata and controls
1665 lines (1474 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AccountWalletType, select } from '@metamask/account-api';
import type {
AccountGroupId,
AccountWalletId,
AccountSelector,
MultichainAccountWalletId,
AccountGroupType,
} from '@metamask/account-api';
import type { MultichainAccountWalletStatus } from '@metamask/account-api';
import type { AccountId } from '@metamask/accounts-controller';
import type { StateMetadata } from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import type { TraceCallback } from '@metamask/controller-utils';
import { isEvmAccountType } from '@metamask/keyring-api';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import { assert } from '@metamask/utils';
import type { BackupAndSyncEmitAnalyticsEventParams } from './backup-and-sync/analytics';
import {
formatAnalyticsEvent,
traceFallback,
} from './backup-and-sync/analytics';
import { BackupAndSyncService } from './backup-and-sync/service';
import type { BackupAndSyncContext } from './backup-and-sync/types';
import type { AccountGroupObject, AccountTypeOrderKey } from './group';
import {
ACCOUNT_TYPE_TO_SORT_ORDER,
isAccountGroupNameUnique,
isAccountGroupNameUniqueFromWallet,
MAX_SORT_ORDER,
} from './group';
import { projectLogger as log } from './logger';
import type { Rule } from './rule';
import { EntropyRule } from './rules/entropy';
import { KeyringRule } from './rules/keyring';
import { SnapRule } from './rules/snap';
import type {
AccountTreeControllerConfig,
AccountTreeControllerInternalBackupAndSyncConfig,
AccountTreeControllerMessenger,
AccountTreeControllerState,
} from './types';
import type { AccountWalletObject, AccountWalletObjectOf } from './wallet';
export const controllerName = 'AccountTreeController';
const MESSENGER_EXPOSED_METHODS = [
'getSelectedAccountGroup',
'setSelectedAccountGroup',
'getAccountsFromSelectedAccountGroup',
'getAccountContext',
'setAccountWalletName',
'setAccountGroupName',
'setAccountGroupPinned',
'setAccountGroupHidden',
'getAccountWalletObject',
'getAccountWalletObjects',
'getAccountGroupObject',
'clearState',
'syncWithUserStorage',
'syncWithUserStorageAtLeastOnce',
] as const;
const accountTreeControllerMetadata: StateMetadata<AccountTreeControllerState> =
{
accountTree: {
includeInStateLogs: true,
persist: false, // We do re-recompute this state everytime.
includeInDebugSnapshot: false,
usedInUi: true,
},
selectedAccountGroup: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
isAccountTreeSyncingInProgress: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
hasAccountTreeSyncingSyncedAtLeastOnce: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
accountGroupsMetadata: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
accountWalletsMetadata: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
};
/**
* Gets default state of the `AccountTreeController`.
*
* @returns The default state of the `AccountTreeController`.
*/
export function getDefaultAccountTreeControllerState(): AccountTreeControllerState {
return {
accountTree: {
wallets: {},
},
selectedAccountGroup: '',
isAccountTreeSyncingInProgress: false,
hasAccountTreeSyncingSyncedAtLeastOnce: false,
accountGroupsMetadata: {},
accountWalletsMetadata: {},
};
}
/**
* Context for an account.
*/
export type AccountContext = {
/**
* Wallet ID associated to that account.
*/
walletId: AccountWalletObject['id'];
/**
* Account group ID associated to that account.
*/
groupId: AccountGroupObject['id'];
/**
* Sort order of the account.
*/
sortOrder: (typeof ACCOUNT_TYPE_TO_SORT_ORDER)[AccountTypeOrderKey];
};
export class AccountTreeController extends BaseController<
typeof controllerName,
AccountTreeControllerState,
AccountTreeControllerMessenger
> {
readonly #accountIdToContext: Map<AccountId, AccountContext>;
readonly #groupIdToWalletId: Map<AccountGroupId, AccountWalletId>;
/**
* Service responsible for all backup and sync operations.
*/
readonly #backupAndSyncService: BackupAndSyncService;
readonly #rules: [EntropyRule, SnapRule, KeyringRule];
readonly #trace: TraceCallback;
readonly #backupAndSyncConfig: AccountTreeControllerInternalBackupAndSyncConfig;
/**
* Callbacks to migrate hidden and pinned account information from the account order controller
*/
readonly #accountOrderCallbacks:
| AccountTreeControllerConfig['accountOrderCallbacks']
| undefined;
#initialized: boolean;
/**
* Constructor for AccountTreeController.
*
* @param options - The controller options.
* @param options.messenger - The messenger object.
* @param options.state - Initial state to set on this controller
* @param options.config - Optional configuration for the controller.
*/
constructor({
messenger,
state,
config,
}: {
messenger: AccountTreeControllerMessenger;
state?: Partial<AccountTreeControllerState>;
config?: AccountTreeControllerConfig;
}) {
super({
messenger,
name: controllerName,
metadata: accountTreeControllerMetadata,
state: {
...getDefaultAccountTreeControllerState(),
...state,
},
});
// This will be set to true upon the first `init` call.
this.#initialized = false;
// Reverse map to allow fast node access from an account ID.
this.#accountIdToContext = new Map();
// Reverse map to allow fast wallet node access from a group ID.
this.#groupIdToWalletId = new Map();
// Rules to apply to construct the wallets tree.
this.#rules = [
// 1. We group by entropy-source
new EntropyRule(this.messenger),
// 2. We group by Snap ID
new SnapRule(this.messenger),
// 3. We group by wallet type (this rule cannot fail and will group all non-matching accounts)
new KeyringRule(this.messenger),
];
// Initialize trace function
this.#trace = config?.trace ?? traceFallback;
// Initialize backup and sync config
this.#backupAndSyncConfig = {
emitAnalyticsEventFn: (event: BackupAndSyncEmitAnalyticsEventParams) => {
return config?.backupAndSync?.onBackupAndSyncEvent?.(
formatAnalyticsEvent(event),
);
},
};
// Used when migrating initial hidden/pinned state for groups (if available).
this.#accountOrderCallbacks = config?.accountOrderCallbacks;
// Initialize the backup and sync service
this.#backupAndSyncService = new BackupAndSyncService(
this.#createBackupAndSyncContext(),
);
this.messenger.subscribe('AccountsController:accountsAdded', (accounts) => {
this.#handleAccountsAdded(accounts);
});
this.messenger.subscribe(
'AccountsController:accountsRemoved',
(accountIds) => {
this.#handleAccountsRemoved(accountIds);
},
);
this.messenger.subscribe(
'AccountsController:selectedAccountChange',
(account) => {
this.#handleSelectedAccountChange(account);
},
);
this.messenger.subscribe(
'UserStorageController:stateChange',
(userStorageControllerState) => {
this.#backupAndSyncService.handleUserStorageStateChange(
userStorageControllerState,
);
},
);
this.messenger.subscribe(
'MultichainAccountService:walletStatusChange',
(walletId, status) => {
this.#handleMultichainAccountWalletStatusChange(walletId, status);
},
);
this.messenger.registerMethodActionHandlers(
this,
MESSENGER_EXPOSED_METHODS,
);
}
/**
* Initialize the controller's state.
*
* It constructs the initial state of the account tree (tree nodes, nodes
* names, metadata, etc..) and will automatically update the controller's
* state with it.
*/
init() {
if (this.#initialized) {
// We prevent re-initilializing the state multiple times. Though, we can use
// `reinit` to re-init everything from scratch.
return;
}
log('Initializing...');
const wallets: AccountTreeControllerState['accountTree']['wallets'] = {};
// Clear mappings for fresh rebuild.
this.#accountIdToContext.clear();
this.#groupIdToWalletId.clear();
// Keep the current selected group to check if it's still part of the tree
// after rebuilding it.
const previousSelectedAccountGroup = this.state.selectedAccountGroup;
// There's no guarantee that accounts would be sorted by their import time
// with `listMultichainAccounts`. We have to sort them here before constructing
// the tree.
//
// Because of the alignment mecanism, some accounts from the same group might not
// have been imported at the same time, but at least of them should have been
// imported at the right time, thus, inserting the group at the proper place too.
//
// Lastly, if one day we allow to have "gaps" in between groups, then this `sort`
// won't be enough and we would have to use group properties instead (like group
// index or maybe introduce a `importTime` at group level).
const accounts = this.#listAccounts().sort(
(a, b) => a.metadata.importTime - b.metadata.importTime,
);
// For now, we always re-compute all wallets, we do not re-use the existing state.
for (const account of accounts) {
this.#insert(wallets, account);
}
// Once we have the account tree, we can apply persisted metadata (names + UI states).
let previousSelectedAccountGroupStillExists = false;
this.update((state) => {
state.accountTree.wallets = wallets;
// Apply group metadata within the state update
for (const wallet of Object.values(state.accountTree.wallets)) {
this.#applyAccountWalletMetadata(state, wallet.id);
// Used for default group default names (so we use human-indexing here).
let nextNaturalNameIndex = 1;
for (const group of Object.values(wallet.groups)) {
this.#applyAccountGroupMetadata(state, wallet.id, group.id, {
// We allow computed name when initializing the tree.
// This will automatically handle account name migration for the very first init of the
// tree. Once groups are created, their name will be persisted, thus, taking precedence
// over the computed names (even if we re-init).
allowComputedName: true,
// FIXME: We should not need this kind of logic if we were not inserting accounts
// 1 by 1. Instead, we should be inserting wallets and groups directly. This would
// allow us to naturally insert a group in the tree AND update its metadata right
// away...
// But here, we have to wait for the entire group to be ready before updating
// its metadata (mainly because we're dealing with single accounts rather than entire
// groups).
// That is why we need this kind of extra parameter.
nextNaturalNameIndex,
});
if (group.id === previousSelectedAccountGroup) {
previousSelectedAccountGroupStillExists = true;
}
nextNaturalNameIndex += 1;
}
}
if (
!previousSelectedAccountGroupStillExists ||
previousSelectedAccountGroup === ''
) {
// No group is selected yet OR group no longer exists, re-sync with the
// AccountsController.
state.selectedAccountGroup = this.#getDefaultSelectedAccountGroup(
state.accountTree.wallets, // Re-use updated wallets with metadata here.
);
}
});
// We always fire the current selected group after init, even if it did not change, to ensure that
// all subscribers are aware of it and can react accordingly (e.g. by fetching accounts from
// the selected group).
log(`Selected (initial) group is: [${this.state.selectedAccountGroup}]`);
this.messenger.publish(
`${controllerName}:selectedAccountGroupChange`,
this.state.selectedAccountGroup,
previousSelectedAccountGroup,
);
log('Initialized!');
this.#initialized = true;
}
/**
* Re-initialize the controller's state.
*
* This is done in one single (atomic) `update` block to avoid having a temporary
* cleared state. Use this when you need to force a full re-init even if already initialized.
*/
reinit() {
log('Re-initializing...');
this.#initialized = false;
this.init();
}
/**
* Rule for entropy-base wallets.
*
* @returns The rule for entropy-based wallets.
*/
#getEntropyRule(): EntropyRule {
return this.#rules[0];
}
/**
* Rule for Snap-base wallets.
*
* @returns The rule for snap-based wallets.
*/
#getSnapRule(): SnapRule {
return this.#rules[1];
}
/**
* Rule for keyring-base wallets.
*
* This rule acts as a fallback and never fails since all accounts
* comes from a keyring anyway.
*
* @returns The fallback rule for every accounts that did not match
* any other rules.
*/
#getKeyringRule(): KeyringRule {
return this.#rules[2];
}
/**
* Applies wallet metadata updates (name) by checking the persistent state
* first, and then fallbacks to default values (based on the wallet's
* type).
*
* @param state Controller state to update for persistence.
* @param walletId The wallet ID to update.
*/
#applyAccountWalletMetadata(
state: AccountTreeControllerState,
walletId: AccountWalletId,
) {
const wallet = state.accountTree.wallets[walletId];
const persistedMetadata = state.accountWalletsMetadata[walletId];
// Apply persisted name if available (including empty strings)
if (persistedMetadata?.name !== undefined) {
wallet.metadata.name = persistedMetadata.name.value;
} else if (!wallet.metadata.name) {
// Generate default name if none exists
if (wallet.type === AccountWalletType.Entropy) {
wallet.metadata.name =
this.#getEntropyRule().getDefaultAccountWalletName(wallet);
} else if (wallet.type === AccountWalletType.Snap) {
wallet.metadata.name =
this.#getSnapRule().getDefaultAccountWalletName(wallet);
} else {
wallet.metadata.name =
this.#getKeyringRule().getDefaultAccountWalletName(wallet);
}
log(`[${wallet.id}] Set default name to: "${wallet.metadata.name}"`);
}
}
/**
* Gets the appropriate rule instance for a given wallet type.
*
* @param wallet - The wallet object to get the rule for.
* @returns The rule instance that handles the wallet's type.
*/
#getRuleForWallet<WalletType extends AccountWalletType>(
wallet: AccountWalletObjectOf<WalletType>,
): Rule<WalletType, AccountGroupType> {
switch (wallet.type) {
case AccountWalletType.Entropy:
return this.#getEntropyRule() as unknown as Rule<
WalletType,
AccountGroupType
>;
case AccountWalletType.Snap:
return this.#getSnapRule() as unknown as Rule<
WalletType,
AccountGroupType
>;
default:
return this.#getKeyringRule() as unknown as Rule<
WalletType,
AccountGroupType
>;
}
}
/**
* Gets the computed name of a group (using its associated accounts).
*
* @param wallet The wallet containing the group.
* @param group The account group to update.
* @returns The computed name for the group or '' if there's no compute named for this group.
*/
#getComputedAccountGroupName(
wallet: AccountWalletObject,
group: AccountGroupObject,
): string {
let proposedName = ''; // Empty means there's no computed name for this group.
for (const id of group.accounts) {
const account = this.messenger.call('AccountsController:getAccount', id);
if (!account?.metadata.name.length) {
continue;
}
// We only pick a new proposed name if we don't have one yet.
if (!proposedName) {
proposedName = account.metadata.name;
}
// But EVM accounts take precedence over any other computed names.
if (isEvmAccountType(account.type)) {
// So we just overwrite the proposed name and stop looping right away.
proposedName = account.metadata.name;
break;
}
}
// If this name already exists for whatever reason, we rename it to resolve this conflict.
if (
proposedName.length &&
!isAccountGroupNameUniqueFromWallet(wallet, group.id, proposedName)
) {
proposedName = this.#resolveNameConflict(wallet, group.id, proposedName);
}
return proposedName;
}
/**
* Gets the default name of a group.
*
* @param state Controller state to update for persistence.
* @param wallet The wallet containing the group.
* @param group The account group to update.
* @param nextNaturalNameIndex The next natural name index for this group.
* @returns The default name for the group.
*/
#getDefaultAccountGroupName(
state: AccountTreeControllerState,
wallet: AccountWalletObject,
group: AccountGroupObject,
nextNaturalNameIndex?: number,
): string {
// Get the appropriate rule for this wallet type
const rule = this.#getRuleForWallet(wallet);
// Get the prefix for groups of this wallet
const namePrefix = rule.getDefaultAccountGroupPrefix(wallet);
// Parse the highest account index being used (similar to accounts-controller)
let highestNameIndex = 0;
for (const { id: otherGroupId } of Object.values(
wallet.groups,
) as AccountGroupObject[]) {
// Skip the current group being processed
if (otherGroupId === group.id) {
continue;
}
// We always get the name from the persisted map, since `init` will clear the
// `state.accountTree.wallets`, thus, given empty `group.metadata.name`.
// NOTE: If the other group has not been named yet, we just use an empty name.
const otherGroupName =
state.accountGroupsMetadata[otherGroupId]?.name?.value ?? '';
// Parse the existing group name to extract the numeric index
const nameMatch = otherGroupName.match(/account\s+(\d+)$/iu);
if (nameMatch) {
const nameIndex = parseInt(nameMatch[1], 10);
if (nameIndex > highestNameIndex) {
highestNameIndex = nameIndex;
}
}
}
// We just use the highest known index no matter the wallet type.
//
// For entropy-based wallets (bip44), if a multichain account group with group index 1
// is inserted before another one with group index 0, then the naming will be:
// - "Account 1" (group index 1)
// - "Account 2" (group index 0)
// This naming makes more sense for the end-user.
//
// For other type of wallets, since those wallets can create arbitrary gaps, we still
// rely on the highest know index to avoid back-filling account with "old names".
let proposedNameIndex = Math.max(
// Use + 1 to use the next available index.
highestNameIndex + 1,
// In case all accounts have been renamed differently than the usual "Account <index>"
// pattern, we want to use the next "natural" index, which is just the number of groups
// in that wallet (e.g. ["Account A", "Another Account"], next natural index would be
// "Account 3" in this case).
nextNaturalNameIndex ?? Object.keys(wallet.groups).length,
);
// Find a unique name by checking for conflicts and incrementing if needed
let proposedNameExists: boolean;
let proposedName = '';
do {
proposedName = `${namePrefix} ${proposedNameIndex}`;
// Check if this name already exists in the wallet (excluding current group)
proposedNameExists = !isAccountGroupNameUniqueFromWallet(
wallet,
group.id,
proposedName,
);
/* istanbul ignore next */
if (proposedNameExists) {
proposedNameIndex += 1; // Try next number
}
} while (proposedNameExists);
return proposedName;
}
/**
* Applies group metadata updates (name, pinned, hidden flags) by checking
* the persistent state first, and then fallbacks to default values (based
* on the wallet's
* type).
*
* @param state Controller state to update for persistence.
* @param walletId The wallet ID containing the group.
* @param groupId The account group ID to update.
* @param namingOptions Options around account group naming.
* @param namingOptions.allowComputedName Allow to use original account names to compute the default name.
* @param namingOptions.nextNaturalNameIndex The next natural name index for this group (only used for default names).
*/
#applyAccountGroupMetadata(
state: AccountTreeControllerState,
walletId: AccountWalletId,
groupId: AccountGroupId,
{
allowComputedName,
nextNaturalNameIndex,
}: {
allowComputedName?: boolean;
nextNaturalNameIndex?: number;
} = {},
) {
const wallet = state.accountTree.wallets[walletId];
const group = wallet.groups[groupId];
const persistedGroupMetadata = state.accountGroupsMetadata[groupId];
// Ensure metadata object exists once at the beginning
state.accountGroupsMetadata[groupId] ??= {};
// Apply persisted name if available (including empty strings)
if (persistedGroupMetadata?.name !== undefined) {
state.accountTree.wallets[walletId].groups[groupId].metadata.name =
persistedGroupMetadata.name.value;
} else if (!group.metadata.name) {
let proposedName = '';
// Computed names are usually only used for existing/old accounts. So this option
// should be used only when we first initialize the tree.
if (allowComputedName) {
proposedName = this.#getComputedAccountGroupName(wallet, group);
}
// If we still don't have a valid name candidate, we fallback to a default name.
if (!proposedName.length) {
proposedName = this.#getDefaultAccountGroupName(
state,
wallet,
group,
nextNaturalNameIndex,
);
}
state.accountTree.wallets[walletId].groups[groupId].metadata.name =
proposedName;
log(`[${group.id}] Set default name to: "${group.metadata.name}"`);
// Persist the generated name to ensure consistency
state.accountGroupsMetadata[groupId].name = {
value: proposedName,
// The `lastUpdatedAt` field is used for backup and sync, when comparing local names
// with backed up names. In this case, the generated name should never take precedence
// over a user-defined name, so we set `lastUpdatedAt` to 0.
lastUpdatedAt: 0,
};
}
// Apply persisted UI states
if (persistedGroupMetadata?.pinned?.value !== undefined) {
group.metadata.pinned = persistedGroupMetadata.pinned.value;
} else {
let isPinned = false;
if (this.#accountOrderCallbacks?.isPinnedAccount) {
isPinned = group.accounts.some((account) =>
this.#accountOrderCallbacks?.isPinnedAccount?.(account),
);
}
state.accountGroupsMetadata[groupId].pinned = {
value: isPinned,
lastUpdatedAt: 0,
};
// If any accounts was previously pinned, then we consider the group to be pinned as well.
group.metadata.pinned = isPinned;
}
if (persistedGroupMetadata?.hidden?.value !== undefined) {
group.metadata.hidden = persistedGroupMetadata.hidden.value;
} else {
let isHidden = false;
if (this.#accountOrderCallbacks?.isHiddenAccount) {
isHidden = group.accounts.some((account) =>
this.#accountOrderCallbacks?.isHiddenAccount?.(account),
);
}
state.accountGroupsMetadata[groupId].hidden = {
value: isHidden,
lastUpdatedAt: 0,
};
// If any accounts was previously hidden, then we consider the group to be hidden as well.
group.metadata.hidden = isHidden;
}
// Apply persisted lastSelected (plain number, not synced).
if (
persistedGroupMetadata?.lastSelected !== undefined &&
persistedGroupMetadata.lastSelected >= 0
) {
group.metadata.lastSelected = persistedGroupMetadata.lastSelected;
} else {
// Automatiacally inject default value.
state.accountGroupsMetadata[groupId].lastSelected = 0;
group.metadata.lastSelected = 0;
}
}
/**
* Gets the account wallet object from its ID.
*
* @param walletId - Account wallet ID.
* @returns The account wallet object if found, undefined otherwise.
*/
getAccountWalletObject(
walletId: AccountWalletId,
): AccountWalletObject | undefined {
const wallet = this.state.accountTree.wallets[walletId];
if (!wallet) {
return undefined;
}
return wallet;
}
/**
* Gets all account wallet objects.
*
* @returns All account wallet objects.
*/
getAccountWalletObjects(): AccountWalletObject[] {
return Object.values(this.state.accountTree.wallets);
}
/**
* Gets all underlying accounts from the currently selected account
* group.
*
* It also support account selector, which allows to filter specific
* accounts given some criterias (account type, address, scopes, etc...).
*
* @param selector - Optional account selector.
* @returns Underlying accounts for the currently selected account (filtered
* by the selector if provided).
*/
getAccountsFromSelectedAccountGroup(
selector?: AccountSelector<InternalAccount>,
) {
const groupId = this.getSelectedAccountGroup();
if (!groupId) {
return [];
}
const group = this.getAccountGroupObject(groupId);
// We should never reach this part, so we cannot cover it either.
/* istanbul ignore next */
if (!group) {
return [];
}
const accounts: InternalAccount[] = [];
for (const id of group.accounts) {
const account = this.messenger.call('AccountsController:getAccount', id);
// For now, we're filtering undefined account, but I believe
// throwing would be more appropriate here.
if (account) {
accounts.push(account);
}
}
return selector ? select(accounts, selector) : accounts;
}
/**
* Gets the account group object from its ID.
*
* @param groupId - Account group ID.
* @returns The account group object if found, undefined otherwise.
*/
getAccountGroupObject(
groupId: AccountGroupId,
): AccountGroupObject | undefined {
const walletId = this.#groupIdToWalletId.get(groupId);
if (!walletId) {
return undefined;
}
const wallet = this.getAccountWalletObject(walletId);
return wallet?.groups[groupId];
}
/**
* Gets the account's context which contains its wallet ID, group ID, and sort order.
*
* @param accountId - Account ID.
* @returns The account context if found, undefined otherwise.
*/
getAccountContext(accountId: AccountId): AccountContext | undefined {
return this.#accountIdToContext.get(accountId);
}
/**
* Handles "AccountsController:accountsAdded" event to insert
* new accounts into the tree in a single state update.
*
* @param accounts - New accounts.
*/
#handleAccountsAdded(accounts: InternalAccount[]): void {
// We wait for the first `init` to be called to actually build up the tree and
// mutate it. We expect the caller to first update the `AccountsController` state
// to force the migration of accounts, and then call `init`.
if (!this.#initialized) {
return;
}
// Filter out accounts already known by the tree to avoid double-insertion.
const newAccounts = accounts.filter(
(account) => !this.#accountIdToContext.has(account.id),
);
if (newAccounts.length === 0) {
return;
}
this.update((state) => {
for (const account of newAccounts) {
this.#insert(state.accountTree.wallets, account);
const context = this.#accountIdToContext.get(account.id);
if (context) {
const { walletId, groupId } = context;
const wallet = state.accountTree.wallets[walletId];
if (wallet) {
this.#applyAccountWalletMetadata(state, walletId);
this.#applyAccountGroupMetadata(state, walletId, groupId);
}
}
}
});
this.messenger.publish(
`${controllerName}:accountTreeChange`,
this.state.accountTree,
);
}
/**
* Handles "AccountsController:accountsRemoved" event to remove
* given accounts from the tree in a single state update.
*
* @param accountIds - Removed account IDs.
*/
#handleAccountsRemoved(accountIds: AccountId[]): void {
// We wait for the first `init` to be called to actually build up the tree and
// mutate it. We expect the caller to first update the `AccountsController` state
// to force the migration of accounts, and then call `init`.
if (!this.#initialized) {
return;
}
const knownAccounts: { id: AccountId; context: AccountContext }[] = [];
for (const id of accountIds) {
const context = this.#accountIdToContext.get(id);
if (context) {
knownAccounts.push({ id, context });
}
}
if (knownAccounts.length === 0) {
return;
}
const previousSelectedAccountGroup = this.state.selectedAccountGroup;
this.update((state) => {
for (const { id: accountId, context } of knownAccounts) {
const { walletId, groupId } = context;
const accounts =
state.accountTree.wallets[walletId]?.groups[groupId]?.accounts;
if (accounts) {
const index = accounts.indexOf(accountId);
if (index !== -1) {
accounts.splice(index, 1);
if (
state.selectedAccountGroup === groupId &&
accounts.length === 0
) {
state.selectedAccountGroup = this.#getDefaultAccountGroupId(
state.accountTree.wallets,
);
}
}
if (accounts.length === 0) {
this.#pruneEmptyGroupAndWallet(state, walletId, groupId);
}
}
}
});
// Clear reverse-mappings after the state update
for (const { id } of knownAccounts) {
this.#accountIdToContext.delete(id);
}
this.messenger.publish(
`${controllerName}:accountTreeChange`,
this.state.accountTree,
);
const newSelectedAccountGroup = this.state.selectedAccountGroup;
if (newSelectedAccountGroup !== previousSelectedAccountGroup) {
this.messenger.publish(
`${controllerName}:selectedAccountGroupChange`,
newSelectedAccountGroup,
previousSelectedAccountGroup,
);
}
}
/**
* Helper method to prune a group if it holds no accounts and additionally
* prune the wallet if it holds no groups. This action should take place
* after a singular account removal.
*
* NOTE: This method should only be used for a group that we know to be empty.
*
* @param state - The AccountTreeController state to prune.
* @param walletId - The wallet ID to prune, the wallet should be the parent of the associated group that holds the removed account.
* @param groupId - The group ID to prune, the group should be the parent of the associated account that was removed.
* @returns The updated state.
*/
#pruneEmptyGroupAndWallet(
state: AccountTreeControllerState,
walletId: AccountWalletId,
groupId: AccountGroupId,
) {
const { wallets } = state.accountTree;
delete wallets[walletId].groups[groupId];
this.#groupIdToWalletId.delete(groupId);
// Clean up metadata for the pruned group
delete state.accountGroupsMetadata[groupId];
if (Object.keys(wallets[walletId].groups).length === 0) {
delete wallets[walletId];
// Clean up metadata for the pruned wallet
delete state.accountWalletsMetadata[walletId];
}
return state;
}
/**
* Insert an account inside an account tree.
*
* We go over multiple rules to try to "match" the account following
* specific criterias. If a rule "matches" an account, then this
* account get added into its proper account wallet and account group.
*
* @param wallets - Account tree.
* @param account - The account to be inserted.
*/