-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathaccountPicker.ts
More file actions
1520 lines (1277 loc) · 54.1 KB
/
Copy pathaccountPicker.ts
File metadata and controls
1520 lines (1277 loc) · 54.1 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
/* eslint-disable @typescript-eslint/no-floating-promises */
import { getCreate2Address, keccak256 } from 'ethers'
import EmittableError from '../../classes/EmittableError'
import ExternalSignerError from '../../classes/ExternalSignerError'
import { DEFAULT_ACCOUNT_LABEL } from '../../consts/account'
import { MAX_UINT256 } from '../../consts/deploy'
import {
HD_PATH_TEMPLATE_TYPE,
SMART_ACCOUNT_SIGNER_KEY_DERIVATION_OFFSET
} from '../../consts/derivation'
import { HARDWARE_WALLET_DEVICE_NAMES } from '../../consts/hardwareWallets'
import {
Account,
AccountOnchainState,
AccountOnPage,
AccountWithNetworkMeta,
DerivedAccount,
DerivedAccountWithoutNetworkMeta,
IAccountsController,
ImportStatus,
SelectedAccountForImport
} from '../../interfaces/account'
import { IAccountPickerController } from '../../interfaces/accountPicker'
import { IEventEmitterRegistryController } from '../../interfaces/eventEmitter'
import { Fetch } from '../../interfaces/fetch'
import { KeyIterator } from '../../interfaces/keyIterator'
import {
dedicatedToOneSAPriv,
ExternalKey,
ExternalSignerControllers,
IKeystoreController,
Key,
ReadyToAddKeys
} from '../../interfaces/keystore'
import { INetworksController } from '../../interfaces/network'
import { IProvidersController } from '../../interfaces/provider'
import {
getAccountImportStatus,
getBasicAccount,
getDefaultAccountPreferences,
getEmailAccount,
getSmartAccount,
isDerivedForSmartAccountKeyOnly,
isSmartAccount
} from '../../libs/account/account'
import { getRelayerLinkedAccounts } from '../../libs/accountPicker/accountPicker'
import { getAccountState } from '../../libs/accountState/accountState'
import { getDefaultKeyLabel, getExistingKeyLabel } from '../../libs/keys/keys'
import { relayerCall } from '../../libs/relayerCall/relayerCall'
import EventEmitter from '../eventEmitter/eventEmitter'
export const DEFAULT_PAGE = 1
export const DEFAULT_PAGE_SIZE = 1
const DEFAULT_SHOULD_SEARCH_FOR_LINKED_ACCOUNTS = true
const DEFAULT_SHOULD_GET_ACCOUNTS_USED_ON_NETWORKS = true
const DEFAULT_SHOULD_ADD_NEXT_ACCOUNT_AUTOMATICALLY = true
/**
* Account Picker Controller
* is responsible for listing accounts that can be selected for adding.
* It uses a KeyIterator interface allow iterating all the keys in a specific
* underlying store such as a hardware device or an object holding a seed.
*/
export class AccountPickerController extends EventEmitter implements IAccountPickerController {
#callRelayer: Function
#accounts: IAccountsController
#keystore: IKeystoreController
#networks: INetworksController
#providers: IProvidersController
#externalSignerControllers: ExternalSignerControllers
initParams: {
keyIterator: KeyIterator | null
hdPathTemplate: HD_PATH_TEMPLATE_TYPE
page?: number
pageSize?: number
shouldSearchForLinkedAccounts?: boolean
shouldGetAccountsUsedOnNetworks?: boolean
shouldAddNextAccountAutomatically?: boolean
} | null = null
keyIterator?: KeyIterator | null
hdPathTemplate?: HD_PATH_TEMPLATE_TYPE
isInitialized: boolean = false
shouldSearchForLinkedAccounts = DEFAULT_SHOULD_SEARCH_FOR_LINKED_ACCOUNTS
shouldGetAccountsUsedOnNetworks = DEFAULT_SHOULD_GET_ACCOUNTS_USED_ON_NETWORKS
shouldAddNextAccountAutomatically = DEFAULT_SHOULD_ADD_NEXT_ACCOUNT_AUTOMATICALLY
/* This is only the index of the current page */
page: number = DEFAULT_PAGE
/* The number of accounts to be displayed on a single page */
pageSize: number = DEFAULT_PAGE_SIZE
/* State to indicate the page requested fails to load (and the reason why) */
pageError: null | string = null
selectedAccountsFromCurrentSession: SelectedAccountForImport[] = []
// Accounts which identity is created on the Relayer (if needed), and are ready
// to be added to the user's account list by the Main Controller
readyToAddAccounts: Account[] = []
// Accounts that were selected in a previous session but are now deselected in the current one
readyToRemoveAccounts: Account[] = []
// The keys for the `readyToAddAccounts`, that are ready to be added to the
// user's keystore by the Main Controller
readyToAddKeys: ReadyToAddKeys = { internal: [], external: [] }
// Identity for the smart accounts must be created on the Relayer, this
// represents the status of the operation, needed managing UI state
addAccountsStatus: 'LOADING' | 'SUCCESS' | 'INITIAL' = 'INITIAL'
selectNextAccountStatus: 'LOADING' | 'SUCCESS' | 'INITIAL' = 'INITIAL'
#addedAccountsFromCurrentSession: Account[] = []
accountsLoading: boolean = false
linkedAccountsLoading: boolean = false
linkedAccountsError: string = ''
networksWithAccountStateError: bigint[] = []
#derivedAccounts: DerivedAccount[] = []
#linkedAccounts: { account: AccountWithNetworkMeta; isLinked: boolean }[] = []
#alreadyImportedAccounts: Account[] = []
addAccountsPromise?: Promise<void>
#onAddAccountsSuccessCallback: () => Promise<void>
#onAddAccountsSuccessCallbackPromise?: Promise<void>
#controllerSubscriptions: Function[] = []
// Used in order to expose the ongoing "find linked accounts" task, so other
// code can await it, preventing race conditions.
findAndSetLinkedAccountsPromise?: Promise<void>
/**
* Needed in order to cancel the ongoing findAndSetLinkedAccounts operation
* when reset() is called (usually when the user navigates away/closes the Account Picker).
* This prevents the operation from continuing after the controller state has been
* cleared, avoiding errors in #verifyLinkedAccounts when #derivedAccounts is empty.
*/
#findAndSetLinkedAccountsAbortController?: AbortController
/**
* Incremented on each setPage() call and on reset() to invalidate in-flight
* page loads. Prevents stale async work from leaving accountsLoading stuck.
*/
#setPageGeneration = 0
#shouldDebounceFlags: { [key: string]: boolean } = {}
#addAccountsOnKeystoreReady: {
accounts?: SelectedAccountForImport[]
} | null = null
constructor({
eventEmitterRegistry,
accounts,
keystore,
networks,
providers,
externalSignerControllers,
relayerUrl,
fetch,
onAddAccountsSuccessCallback
}: {
eventEmitterRegistry?: IEventEmitterRegistryController
accounts: IAccountsController
keystore: IKeystoreController
networks: INetworksController
providers: IProvidersController
externalSignerControllers: ExternalSignerControllers
relayerUrl: string
fetch: Fetch
onAddAccountsSuccessCallback: () => Promise<void>
}) {
super(eventEmitterRegistry)
this.#accounts = accounts
this.#keystore = keystore
this.#networks = networks
this.#providers = providers
this.#externalSignerControllers = externalSignerControllers
this.#callRelayer = relayerCall.bind({ url: relayerUrl, fetch })
this.#onAddAccountsSuccessCallback = onAddAccountsSuccessCallback
this.#controllerSubscriptions.push(
this.#accounts.onUpdate(() => {
this.#debounceFunctionCalls(
'update-accounts',
() => {
if (!this.isInitialized) return
if (this.addAccountsStatus !== 'INITIAL') return
this.#updateStateWithTheLatestFromAccounts()
},
20
)
})
)
this.#controllerSubscriptions.push(
this.#keystore.onUpdate(() => {
if (this.#addAccountsOnKeystoreReady && this.#keystore.isReadyToStoreKeys) {
this.addAccounts(this.#addAccountsOnKeystoreReady.accounts)
this.#addAccountsOnKeystoreReady = null
}
})
)
}
get accountsOnPage(): AccountOnPage[] {
const processedAccounts = this.#derivedAccounts
// Remove smart accounts derived programmatically, because since v4.60.0
// unused smart accounts are no longer displayed on page.
.filter((a) => !isSmartAccount(a.account))
// The displayed (visible) accounts on page should not include the derived
// EOA (basic) accounts only used as smart account keys, they should not
// be visible nor importable (or selectable).
.filter((x) => !isDerivedForSmartAccountKeyOnly(x.index))
.flatMap((derivedAccount) => {
const associatedLinkedAccounts = this.#linkedAccounts.filter(
(linkedAcc) =>
!isSmartAccount(derivedAccount.account) &&
linkedAcc.account.associatedKeys.includes(derivedAccount.account.addr)
)
const correspondingSmartAccount = this.#derivedAccounts.find(
(acc) => isSmartAccount(acc.account) && acc.slot === derivedAccount.slot
)
let accountsToReturn: Omit<AccountOnPage, 'importStatus'>[] = []
if (!isSmartAccount(derivedAccount.account)) {
accountsToReturn.push(derivedAccount)
const duplicate = associatedLinkedAccounts.find(
(linkedAcc) => linkedAcc.account.addr === correspondingSmartAccount?.account?.addr
)
// The derived smart account that matches the relayer's linked account
// should not be displayed as linked account. Use this cycle to mark it.
if (duplicate) duplicate.isLinked = false
if (!duplicate && correspondingSmartAccount) {
accountsToReturn.push(correspondingSmartAccount)
}
}
accountsToReturn = accountsToReturn.concat(
associatedLinkedAccounts.map((linkedAcc) => ({
...linkedAcc,
slot: derivedAccount.slot,
index: derivedAccount.index
}))
)
return accountsToReturn
})
const unprocessedLinkedAccounts = this.#linkedAccounts
.filter(
(linkedAcc) =>
!processedAccounts.find(
(processedAcc) => processedAcc?.account.addr === linkedAcc.account.addr
)
)
// Use `flatMap` instead of `map` in order to auto remove missing values.
// The `flatMap` has a built-in mechanism to flatten the array and remove
// null or undefined values (by returning empty array).
.flatMap((linkedAcc) => {
const correspondingDerivedAccount = this.#derivedAccounts.find((derivedAccount) =>
linkedAcc.account.associatedKeys.includes(derivedAccount.account.addr)
)
// The `correspondingDerivedAccount` should always be found, except when
// something is wrong with the data we have stored on the Relayer.
// The this.#verifyLinkedAndDerivedAccounts() method should have
// already emitted an error in that case. Do not emit here, since
// this is a getter method (and emitting here is a no-go).
if (!correspondingDerivedAccount) return []
return [
{
...linkedAcc,
slot: correspondingDerivedAccount.slot,
index: correspondingDerivedAccount.index
}
]
})
const mergedAccounts = [...processedAccounts, ...unprocessedLinkedAccounts].filter(
(a) =>
!isSmartAccount(a.account) ||
(isSmartAccount(a.account) &&
this.#linkedAccounts.find((linkedAcc) => linkedAcc.account.addr === a.account.addr))
)
mergedAccounts.sort((a, b) => {
const prioritizeAccountType = (item: any) => {
if (!isSmartAccount(item.account)) return -1
if (item.isLinked) return 1
return 0
}
return prioritizeAccountType(a) - prioritizeAccountType(b) || a.slot - b.slot
})
const accountsWithStatus = mergedAccounts.map((acc) => ({
...acc,
importStatus: getAccountImportStatus({
account: acc.account,
alreadyImportedAccounts: this.#alreadyImportedAccounts,
keys: this.#keystore.keys,
accountsOnPage: mergedAccounts,
keyIteratorType: this.keyIterator?.type
})
}))
// Since v4.60.0 there should always be 1 unused Smart Account on the page,
// except when all smart accounts are found via linked accounts (therefore, used).
const nextUnusedSmartAcc = this.#derivedAccounts
.filter((acc) => isSmartAccount(acc.account))
.filter((acc) => !accountsWithStatus.map((as) => as.account.addr).includes(acc.account.addr))
.sort((a, b) => a.index - b.index)[0]
if (nextUnusedSmartAcc) {
accountsWithStatus.push({
...nextUnusedSmartAcc,
importStatus: getAccountImportStatus({
account: nextUnusedSmartAcc.account,
alreadyImportedAccounts: this.#alreadyImportedAccounts,
keys: this.#keystore.keys,
accountsOnPage: mergedAccounts,
keyIteratorType: this.keyIterator?.type
})
})
}
return accountsWithStatus
}
get allKeysOnPage() {
const derivedKeys = this.#derivedAccounts.flatMap((a) => a.account.associatedKeys)
const linkedKeys = this.#linkedAccounts.flatMap((a) => a.account.associatedKeys)
return [...new Set([...derivedKeys, ...linkedKeys])]
}
get selectedAccounts(): SelectedAccountForImport[] {
const accountsOnPageWithKeys = this.#alreadyImportedAccounts.filter((a) =>
this.#keystore.keys.some((k) => a.associatedKeys.includes(k.addr))
)
const accountsAddrOnPage = accountsOnPageWithKeys.map((a) => a.addr)
const selectedAccountsFromPrevSession = this.accountsOnPage
.filter(
(a) =>
accountsAddrOnPage.includes(a.account.addr) &&
a.importStatus === ImportStatus.ImportedWithTheSameKeys
)
.map((a) => {
const accountsOnPageWithThisAcc = this.accountsOnPage.filter(
(accOnPage) => accOnPage.account.addr === a.account.addr
)
const accountKeys = this.#getAccountKeys(a.account, accountsOnPageWithThisAcc)
return {
account: a.account,
isLinked: a.isLinked,
accountKeys: accountKeys.map((accKey) => ({
addr: accKey.account.addr,
slot: accKey.slot,
index: accKey.index
}))
} as SelectedAccountForImport
})
const nextSelectedAccount = [
...selectedAccountsFromPrevSession,
...this.selectedAccountsFromCurrentSession
]
const readyToRemoveAccountsAddr = this.readyToRemoveAccounts.map((a) => a.addr)
return nextSelectedAccount.filter((a) => !readyToRemoveAccountsAddr.includes(a.account.addr))
}
get addedAccountsFromCurrentSession() {
return this.#addedAccountsFromCurrentSession
}
set addedAccountsFromCurrentSession(val: Account[]) {
this.#addedAccountsFromCurrentSession = Array.from(
new Map(val.map((account) => [account.addr, account])).values()
)
}
setInitParams(params: {
keyIterator: KeyIterator | null
hdPathTemplate: HD_PATH_TEMPLATE_TYPE
page?: number
pageSize?: number
shouldSearchForLinkedAccounts?: boolean
shouldGetAccountsUsedOnNetworks?: boolean
shouldAddNextAccountAutomatically?: boolean
}) {
this.initParams = params
if (params.pageSize) this.pageSize = params.pageSize
this.emitUpdate()
}
async init() {
if (!this.initParams) {
this.emitError({
level: 'silent',
message: 'AccountPickerController init failed: missing initParams.',
error: new Error('AccountPickerController init failed: missing initParams.')
})
return
}
const {
keyIterator,
hdPathTemplate,
page,
pageSize,
shouldSearchForLinkedAccounts = DEFAULT_SHOULD_SEARCH_FOR_LINKED_ACCOUNTS,
shouldGetAccountsUsedOnNetworks = DEFAULT_SHOULD_GET_ACCOUNTS_USED_ON_NETWORKS,
shouldAddNextAccountAutomatically = DEFAULT_SHOULD_ADD_NEXT_ACCOUNT_AUTOMATICALLY
} = this.initParams
await this.reset(false)
this.keyIterator = keyIterator
if (!this.keyIterator) return this.#throwMissingKeyIterator()
this.page = page || DEFAULT_PAGE
if (pageSize) this.pageSize = pageSize
this.hdPathTemplate = hdPathTemplate
this.isInitialized = true
this.#alreadyImportedAccounts = [...this.#accounts.accounts]
this.shouldSearchForLinkedAccounts = shouldSearchForLinkedAccounts
this.shouldGetAccountsUsedOnNetworks = shouldGetAccountsUsedOnNetworks
if (shouldAddNextAccountAutomatically) {
await this.selectNextAccount()
await this.addAccounts()
} else {
await this.forceEmitUpdate()
}
}
get type() {
return this.keyIterator?.type || this.initParams?.keyIterator?.type
}
get subType() {
return this.keyIterator?.subType || this.initParams?.keyIterator?.subType
}
async reset(resetInitParams: boolean = true) {
await this.addAccountsPromise
// Abort any ongoing findAndSetLinkedAccounts operation
if (this.#findAndSetLinkedAccountsAbortController) {
this.#findAndSetLinkedAccountsAbortController.abort()
this.#findAndSetLinkedAccountsAbortController = undefined
}
this.#setPageGeneration += 1
this.accountsLoading = false
if (resetInitParams) this.initParams = null
this.keyIterator = null
this.selectedAccountsFromCurrentSession = []
this.page = DEFAULT_PAGE
this.pageSize = DEFAULT_PAGE_SIZE
this.hdPathTemplate = undefined
this.shouldSearchForLinkedAccounts = DEFAULT_SHOULD_SEARCH_FOR_LINKED_ACCOUNTS
this.shouldGetAccountsUsedOnNetworks = DEFAULT_SHOULD_GET_ACCOUNTS_USED_ON_NETWORKS
this.pageError = null
this.linkedAccountsLoading = false
this.linkedAccountsError = ''
this.addAccountsStatus = 'INITIAL'
this.#derivedAccounts = []
this.#linkedAccounts = []
this.readyToAddAccounts = []
this.networksWithAccountStateError = []
this.readyToAddKeys = { internal: [], external: [] }
this.isInitialized = false
this.addedAccountsFromCurrentSession = []
this.#addAccountsOnKeystoreReady = null
await this.forceEmitUpdate()
}
destroy() {
super.destroy()
// We must unsubscribe from the controllers and CAN'T call
// their destroy methods. That is because they are also used
// outside of this controller instance.
this.#controllerSubscriptions.forEach((unsubscribe) => unsubscribe())
this.#controllerSubscriptions = []
}
resetAccountsSelection() {
this.selectedAccountsFromCurrentSession = []
this.readyToRemoveAccounts = []
this.emitUpdate()
}
async setHDPathTemplateAndPage({
hdPathTemplate,
page = this.page
}: {
hdPathTemplate: HD_PATH_TEMPLATE_TYPE
page: number
}) {
const arePropsUnchanged = this.hdPathTemplate === hdPathTemplate && page === this.page
if (arePropsUnchanged) return
this.hdPathTemplate = hdPathTemplate
// Reset the currently selected accounts, because for the keys of these
// accounts, as of v4.32.0, we don't store their hd path. When import
// completes, only the latest hd path of the controller is stored.
this.selectedAccountsFromCurrentSession = []
this.#derivedAccounts = []
this.emitUpdate()
await this.setPage({
page,
shouldGetAccountsUsedOnNetworks: DEFAULT_SHOULD_GET_ACCOUNTS_USED_ON_NETWORKS,
shouldSearchForLinkedAccounts: DEFAULT_SHOULD_SEARCH_FOR_LINKED_ACCOUNTS
})
}
#getAccountKeys(account: Account, accountsOnPageWithThisAcc: AccountOnPage[]) {
// should never happen
if (accountsOnPageWithThisAcc.length === 0) {
const message = `accountPicker: account ${account.addr} was not found in the accountsOnPage.`
this.emitError({ message, level: 'silent', error: new Error(message) })
return []
}
// Case 1: The account is a EOA
const isBasicAcc = !isSmartAccount(account)
// The key of the EOA is the EOA itself
if (isBasicAcc) return accountsOnPageWithThisAcc
// Case 2: The account is a Smart account, but not a linked one
const isSmartAccountAndNotLinked =
isSmartAccount(account) &&
accountsOnPageWithThisAcc.length === 1 &&
accountsOnPageWithThisAcc[0]?.isLinked === false
if (isSmartAccountAndNotLinked) {
// The key of the smart account is the EOA on the same slot
// that is explicitly derived for a smart account key only.
const basicAccOnThisSlotDerivedForSmartAccKey = this.#derivedAccounts.find(
(a) =>
a.slot === accountsOnPageWithThisAcc[0]?.slot &&
!isSmartAccount(a.account) &&
isDerivedForSmartAccountKeyOnly(a.index)
)
return basicAccOnThisSlotDerivedForSmartAccKey
? [basicAccOnThisSlotDerivedForSmartAccKey]
: []
}
// Case 3: The account is a smart account (v1 or v2) and a linked one.
// Since it's found as linked, the key(s) must be one or more of the EOAs
// derived, because linked accounts are searched on the EOAs only.
return this.#derivedAccounts
.filter((a) => !isSmartAccount(a.account))
.filter((a) => account.associatedKeys.includes(a.account.addr))
}
selectAccount(_account: Account | AccountWithNetworkMeta) {
if (!this.isInitialized) return this.#throwNotInitialized()
if (!this.keyIterator) return this.#throwMissingKeyIterator()
const account =
'usedOnNetworks' in _account
? // destructure and re-build to remove the `usedOnNetworks` property
(({ usedOnNetworks, ...rest }) => ({ ...rest }))(_account)
: _account
// Needed, because linked accounts could have multiple keys (EOAs),
// and therefore - same linked account could be found on different slots.
const accountsOnPageWithThisAcc = this.accountsOnPage.filter(
(accOnPage) => accOnPage.account.addr === account.addr
)
const accountKeys = this.#getAccountKeys(account, accountsOnPageWithThisAcc)
if (!accountKeys.length)
return this.emitError({
level: 'major',
message: `Selecting ${account.addr} account failed because the details for this account are missing. Please try again or contact support if the problem persists.`,
error: new Error(
`Trying to select ${account.addr} account, but this account was not found in the accountsOnPage or it's keys were not found.`
)
})
const nextSelectedAccount = {
account,
// If the account has more than 1 key, it is for sure linked account,
// since EOAs have only 1 key and smart accounts with more than
// one key present should always be found as linked accounts anyways.
isLinked: accountKeys.length > 1,
accountKeys: accountKeys.map((a) => ({
addr: a.account.addr,
slot: a.slot,
index: a.index
}))
}
const accountExists = this.selectedAccountsFromCurrentSession.some(
(x) => x.account.addr === nextSelectedAccount.account.addr
)
if (!accountExists) this.selectedAccountsFromCurrentSession.push(nextSelectedAccount)
this.readyToRemoveAccounts = this.readyToRemoveAccounts.filter(
(a) => a.addr !== nextSelectedAccount.account.addr
)
this.emitUpdate()
}
deselectAccount(account: Account) {
if (!this.isInitialized) return this.#throwNotInitialized()
if (!this.keyIterator) return this.#throwMissingKeyIterator()
if (!this.selectedAccounts.find((x) => x.account.addr === account.addr)) return
this.selectedAccountsFromCurrentSession = this.selectedAccountsFromCurrentSession.filter(
(a) => a.account.addr !== account.addr
)
const accountInAlreadyAddedAccounts = this.#alreadyImportedAccounts.find(
(a) => a.addr === account.addr
)
if (accountInAlreadyAddedAccounts) {
const accountInReadyToRemoveAccounts = this.readyToRemoveAccounts.find(
(a) => a.addr === account.addr
)
if (!accountInReadyToRemoveAccounts) this.readyToRemoveAccounts.push(account)
}
this.emitUpdate()
}
/**
* For internal keys only! Returns the ready to be added internal (private)
* keys of the currently selected accounts.
*/
retrieveInternalKeysOfSelectedAccounts() {
if (!this.hdPathTemplate) {
this.#throwMissingHdPath()
return []
}
if (!this.keyIterator?.retrieveInternalKeys) {
this.#throwMissingKeyIteratorRetrieveInternalKeysMethod()
return []
}
return this.keyIterator?.retrieveInternalKeys(
this.selectedAccountsFromCurrentSession,
this.hdPathTemplate,
this.#keystore.keys
)
}
/**
* Guard to ensure we only proceed with data that matches the current page load
* request. Similar to #isFindAndSetLinkedAccountsCancelled.
*/
#isSetPageRequestStale(calledForPage: number, calledForGeneration: number): boolean {
return calledForGeneration !== this.#setPageGeneration || calledForPage !== this.page
}
async setPage({
page = this.page,
pageSize,
shouldSearchForLinkedAccounts,
shouldGetAccountsUsedOnNetworks
}: {
page: number
pageSize?: number
shouldSearchForLinkedAccounts?: boolean
shouldGetAccountsUsedOnNetworks?: boolean
}): Promise<void> {
if (!this.isInitialized) return this.#throwNotInitialized()
if (!this.keyIterator) return this.#throwMissingKeyIterator()
if (shouldSearchForLinkedAccounts !== undefined) {
this.shouldSearchForLinkedAccounts = shouldSearchForLinkedAccounts
}
if (shouldGetAccountsUsedOnNetworks !== undefined) {
this.shouldGetAccountsUsedOnNetworks = shouldGetAccountsUsedOnNetworks
}
if (pageSize && pageSize !== this.pageSize) {
this.pageSize = pageSize
this.page = page
} else if (page === this.page && this.#derivedAccounts.length) return
const setPageGeneration = ++this.#setPageGeneration
this.page = page
this.pageError = null
this.#derivedAccounts = []
this.#linkedAccounts = []
this.accountsLoading = true
this.networksWithAccountStateError = []
this.linkedAccountsLoading = false
this.emitUpdate()
if (page <= 0) {
this.pageError = `Unexpected page was requested (page ${page}). Please try again or contact support for help.`
this.page = DEFAULT_PAGE // fallback to the default (initial) page
this.accountsLoading = false
this.emitUpdate()
return
}
try {
const derivedAccounts = await this.#deriveAccounts()
if (this.#isSetPageRequestStale(page, setPageGeneration)) return
this.#derivedAccounts = derivedAccounts
// The used on information is not critical. Allow the user to proceed after
// 1 second. It will get popuplated in the background.
const minWaitTimeout = setTimeout(() => {
if (this.#isSetPageRequestStale(page, setPageGeneration)) return
this.accountsLoading = false
this.emitUpdate()
}, 1000)
const derivedAccountsWithUsedOn = await this.#getAccountsUsedOnNetworks({
accounts: this.#derivedAccounts,
page
})
if (this.#isSetPageRequestStale(page, setPageGeneration)) return
this.#derivedAccounts = derivedAccountsWithUsedOn
clearTimeout(minWaitTimeout)
this.accountsLoading = false
this.emitUpdate()
if (this.keyIterator?.type === 'internal' && this.keyIterator?.subType === 'private-key') {
const accountsOnPageWithoutTheLinked = this.accountsOnPage.filter((acc) => !acc.isLinked)
const usedAccounts = accountsOnPageWithoutTheLinked.filter(
(acc) => acc.account.usedOnNetworks?.length
)
// If at least one account is used - preselect all accounts on the page
// (except the linked ones). Usually there are are two accounts
// (since the private key flow gas `pageSize` of 1)
if (usedAccounts.length) {
accountsOnPageWithoutTheLinked.forEach((acc) => this.selectAccount(acc.account))
}
}
} catch (e: any) {
if (this.#isSetPageRequestStale(page, setPageGeneration)) return
const fallbackMessage = `Failed to retrieve accounts on page ${this.page}. Please try again or contact support for assistance. Error details: ${e?.message}.`
this.accountsLoading = false
this.pageError = e instanceof ExternalSignerError ? e.message : fallbackMessage
this.emitUpdate()
}
if (this.#isSetPageRequestStale(page, setPageGeneration)) return
await this.findAndSetLinkedAccounts()
}
#updateStateWithTheLatestFromAccounts() {
this.#alreadyImportedAccounts = [...this.#accounts.accounts]
this.addedAccountsFromCurrentSession = Array.from(
new Set([
...(this.addedAccountsFromCurrentSession
.map((a) => this.#accounts.accounts.find((acc) => acc.addr === a.addr))
.filter(Boolean) as Account[])
])
)
this.#derivedAccounts = this.#derivedAccounts.map((derivedAcc) => {
const updatedAccount = this.#accounts.accounts.find(
(acc) => acc.addr === derivedAcc.account.addr
)
if (updatedAccount) {
return {
...derivedAcc,
account: { ...derivedAcc.account, ...updatedAccount }
}
}
return derivedAcc
})
const accountsAddr = this.#accounts.accounts.map((a) => a.addr)
this.readyToRemoveAccounts = this.readyToRemoveAccounts.filter((a) =>
accountsAddr.includes(a.addr)
)
this.readyToAddAccounts = this.readyToAddAccounts.filter((a) => !accountsAddr.includes(a.addr))
this.emitUpdate()
}
/**
* Triggers the process of adding accounts via the AccountPicker flow by
* creating identity for the smart accounts (if needed) on the Relayer.
* Then the `onAccountPickerSuccess` listener in the Main Controller gets
* triggered, which uses the `readyToAdd...` properties to further set
* the newly added accounts data (like preferences, keys and others)
*/
async addAccounts(accounts?: SelectedAccountForImport[]) {
this.addAccountsPromise = this.#addAccounts(accounts).finally(() => {
this.addAccountsPromise = undefined
})
await this.addAccountsPromise
}
async #addAccounts(accounts?: SelectedAccountForImport[]) {
if (!this.isInitialized) return this.#throwNotInitialized()
if (!this.keyIterator) return this.#throwMissingKeyIterator()
if (!this.#keystore.isReadyToStoreKeys) {
this.#addAccountsOnKeystoreReady = { accounts }
return
}
this.addAccountsStatus = 'LOADING'
await this.forceEmitUpdate()
this.readyToAddAccounts = [
...(accounts || this.selectedAccountsFromCurrentSession).map((x, i) => {
const alreadyImportedAcc = this.#alreadyImportedAccounts.find(
(a) => a.addr === x.account.addr
)
return {
...x.account,
// Persist the already imported account preferences on purpose, otherwise,
// re-importing the same account via different key type(s) would reset them.
preferences: alreadyImportedAcc
? alreadyImportedAcc.preferences
: getDefaultAccountPreferences(x.account.addr, this.#alreadyImportedAccounts, i)
}
})
]
const readyToAddKeys: ReadyToAddKeys = {
internal: [],
external: []
}
if (this.type === 'internal') {
readyToAddKeys.internal = this.retrieveInternalKeysOfSelectedAccounts()
} else {
// External keys flow
const keyType = this.type as ExternalKey['type']
const deviceIds: { [key in ExternalKey['type']]: string } = {
ledger: this.#externalSignerControllers.ledger?.deviceId || '',
trezor: this.#externalSignerControllers.trezor?.deviceId || '',
lattice: this.#externalSignerControllers?.lattice?.deviceId || '',
qr: this.#externalSignerControllers.qr?.deviceId || ''
}
const deviceModels: { [key in ExternalKey['type']]: string } = {
ledger: this.#externalSignerControllers.ledger?.deviceModel || '',
trezor: this.#externalSignerControllers.trezor?.deviceModel || '',
lattice: this.#externalSignerControllers.lattice?.deviceModel || '',
qr: this.#externalSignerControllers.qr?.deviceModel || ''
}
const masterFingerprint = this.#externalSignerControllers.qr?.masterFingerprint || ''
const hdPathTemplate = this.hdPathTemplate as HD_PATH_TEMPLATE_TYPE
const readyToAddExternalKeys = this.selectedAccountsFromCurrentSession.flatMap(
({ account, accountKeys }) =>
accountKeys.map(({ addr, index }, i) => ({
addr,
type: keyType,
label: `${HARDWARE_WALLET_DEVICE_NAMES[this.type as ExternalKey['type']]} ${
getExistingKeyLabel(this.#keystore.keys, addr, this.type as Key['type']) ||
getDefaultKeyLabel(
this.#keystore.keys.filter((key) => account.associatedKeys.includes(key.addr)),
i
)
}`,
dedicatedToOneSA: isDerivedForSmartAccountKeyOnly(index),
meta: {
deviceId: deviceIds[keyType],
deviceModel: deviceModels[keyType],
// always defined in the case of external keys
hdPathTemplate,
...(keyType === 'qr'
? {
masterFingerprint
}
: {}),
index,
createdAt: new Date().getTime()
}
}))
)
readyToAddKeys.external = readyToAddExternalKeys
}
this.readyToAddKeys = readyToAddKeys
this.addedAccountsFromCurrentSession = [
...this.addedAccountsFromCurrentSession,
...this.readyToAddAccounts
]
this.selectedAccountsFromCurrentSession = []
this.#onAddAccountsSuccessCallbackPromise = this.#onAddAccountsSuccessCallback().finally(() => {
this.#onAddAccountsSuccessCallbackPromise = undefined
})
// Explicitly emit an update here because the front-end needs this state immediately,
// without waiting for the promise below to resolve.
// Previously, this caused a bug in AccountPersonalizeScreen where
// `addedAccountsFromCurrentSession` was still empty while waiting for the Promise.
// As a result, the app redirected to the NextRoute instead of showing the Personalize screen.
await this.forceEmitUpdate()
await this.#onAddAccountsSuccessCallbackPromise
this.addAccountsStatus = 'SUCCESS'
await this.forceEmitUpdate()
this.#updateStateWithTheLatestFromAccounts()
// reset the addAccountsStatus in the next tick to ensure the FE receives the 'SUCCESS' state
this.addAccountsStatus = 'INITIAL'
await this.forceEmitUpdate()
}
async selectNextAccount() {
if (!this.isInitialized) return this.#throwNotInitialized()
if (!this.keyIterator) return this.#throwMissingKeyIterator()
this.selectNextAccountStatus = 'LOADING'
await this.forceEmitUpdate()
let currentPage: number = this.page
let nextAccount: AccountWithNetworkMeta | undefined
const maxPages = 10000 // limit, acts as a safeguard to prevent infinite loops
while (currentPage <= maxPages) {
// TODO: Flag that excludes getting smart account key addresses
// Load the accounts for the current page
await this.setPage({
page: currentPage,
pageSize: this.pageSize,
shouldGetAccountsUsedOnNetworks: false,
shouldSearchForLinkedAccounts: false
})
if (this.pageError) {
throw new EmittableError({
message: this.pageError,
level: 'major',
error: new Error(this.pageError)
})
}
nextAccount = this.accountsOnPage.find(