-
Notifications
You must be signed in to change notification settings - Fork 103
/
login.ts
175 lines (163 loc) · 7.21 KB
/
login.ts
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
import { initializeRegisteredProposals, registerProposalsFromNodes } from '@contexts/governance/actions'
import { cleanupOnboarding } from '@contexts/onboarding/actions'
import { createNewAccount, setSelectedAccount } from '@core/account/actions'
import { DEFAULT_SYNC_OPTIONS } from '@core/account/constants'
import { IAccount } from '@core/account/interfaces'
import { Platform } from '@core/app/classes'
import { AppContext } from '@core/app/enums'
import { handleError } from '@core/error/handlers'
import { pollLedgerNanoStatus } from '@core/ledger/actions'
import { pollMarketPrices } from '@core/market/actions'
import { getAndUpdateNodeInfo, pollNetworkStatus } from '@core/network/actions'
import { loadNftsForActiveProfile } from '@core/nfts/actions'
import { initialiseProfileManager } from '@core/profile-manager/actions'
import {
getAccounts,
isStrongholdUnlocked,
recoverAccounts,
setStrongholdPasswordClearInterval,
startBackgroundSync,
} from '@core/profile-manager/api'
import { RecoverAccountsPayload } from '@core/profile-manager/interfaces'
import { profileManager } from '@core/profile-manager/stores'
import { buildProfileManagerOptionsFromProfileData } from '@core/profile-manager/utils'
import { routerManager } from '@core/router/stores'
import { sleep } from '@core/utils/os'
import { generateAndStoreActivitiesForAllAccounts, refreshAccountAssetsForActiveProfile } from '@core/wallet/actions'
import { get } from 'svelte/store'
import {
CHECK_PREVIOUS_MANAGER_IS_DESTROYED_INTERVAL,
CHECK_PREVIOUS_MANAGER_IS_DESTROYED_MAX_COUNT,
DEFAULT_ACCOUNT_RECOVERY_CONFIGURATION,
STRONGHOLD_PASSWORD_CLEAR_INTERVAL,
} from '../../constants'
import { ProfileType } from '../../enums'
import { ILoginOptions } from '../../interfaces'
import {
activeAccounts,
activeProfile,
incrementLoginProgress,
isDestroyingManager,
resetLoginProgress,
setTimeStrongholdLastUnlocked,
updateActiveProfile,
updateProfile,
} from '../../stores'
import { isLedgerProfile } from '../../utils'
import { loadAccounts } from './loadAccounts'
import { logout } from './logout'
import { subscribeToWalletApiEventsForActiveProfile } from './subscribeToWalletApiEventsForActiveProfile'
export async function login(loginOptions?: ILoginOptions): Promise<void> {
const loginRouter = get(routerManager).getRouterForAppContext(AppContext.Login)
try {
const _activeProfile = get(activeProfile)
const { loggedIn, lastActiveAt, id, isStrongholdLocked, type, lastUsedAccountIndex } = _activeProfile
if (id) {
// Step 1: create profile manager if its doesn't exist
incrementLoginProgress()
await waitForPreviousManagerToBeDestroyed()
if (!get(profileManager)) {
const profileManagerOptions = await buildProfileManagerOptionsFromProfileData(_activeProfile)
const { storagePath, coinType, clientOptions, secretManager } = profileManagerOptions
// Make sure the profile has the latest client options that we are using
updateActiveProfile({ clientOptions })
const manager = initialiseProfileManager(storagePath, coinType, clientOptions, secretManager, id)
profileManager.set(manager)
}
// Step 2: get node info to check we have a synced node
incrementLoginProgress()
await getAndUpdateNodeInfo(true)
void pollNetworkStatus()
// Step 3: load and build all the profile data
incrementLoginProgress()
let accounts: IAccount[]
if (loginOptions?.isFromOnboardingFlow && loginOptions?.shouldRecoverAccounts) {
const { initialAccountRange, addressGapLimit } = DEFAULT_ACCOUNT_RECOVERY_CONFIGURATION[type]
const recoverAccountsPayload: RecoverAccountsPayload = {
accountStartIndex: 0,
accountGapLimit: initialAccountRange,
addressGapLimit,
syncOptions: DEFAULT_SYNC_OPTIONS,
}
accounts = await recoverAccounts(recoverAccountsPayload)
} else {
accounts = await getAccounts()
}
/**
* NOTE: In the case no accounts with funds were recovered, we must
* create one for the new profile.
*/
if (accounts?.length === 0) {
await createNewAccount()
}
// Step 4: load accounts
incrementLoginProgress()
await loadAccounts()
// Step 5: load assets
incrementLoginProgress()
await refreshAccountAssetsForActiveProfile(
_activeProfile.forceAssetRefresh,
_activeProfile.forceAssetRefresh
)
updateProfile(_activeProfile.id, { forceAssetRefresh: false })
await loadNftsForActiveProfile()
// Step 6: generate and store activities for all accounts
incrementLoginProgress()
await generateAndStoreActivitiesForAllAccounts()
if (type === ProfileType.Software) {
// Step 7: set initial stronghold status
incrementLoginProgress()
const strongholdUnlocked = await isStrongholdUnlocked()
isStrongholdLocked.set(!strongholdUnlocked)
setStrongholdPasswordClearInterval(STRONGHOLD_PASSWORD_CLEAR_INTERVAL)
if (strongholdUnlocked) {
setTimeStrongholdLastUnlocked()
}
} else {
incrementLoginProgress(2)
}
// Step 8: start background sync
incrementLoginProgress()
subscribeToWalletApiEventsForActiveProfile()
await startBackgroundSync({ syncIncomingTransactions: true })
// Step 9: finish login
incrementLoginProgress()
if (isLedgerProfile(type)) {
pollLedgerNanoStatus()
}
setSelectedAccount(lastUsedAccountIndex ?? get(activeAccounts)?.[0]?.index ?? null)
lastActiveAt.set(new Date())
loggedIn.set(true)
setTimeout(() => {
if (!loginOptions?.avoidNextRoute) {
loginRouter?.next()
}
resetLoginProgress()
}, 500)
void pollMarketPrices()
if (Platform.isFeatureFlagEnabled('governance')) {
void initializeRegisteredProposals()
void registerProposalsFromNodes(get(activeAccounts))
}
void cleanupOnboarding()
} else {
throw Error('No active profile error')
}
} catch (err) {
handleError(err)
if (!loginOptions?.isFromOnboardingFlow) {
logout(false)
}
loginRouter?.previous()
resetLoginProgress()
}
}
async function waitForPreviousManagerToBeDestroyed(): Promise<void> {
for (let count = 0; count < CHECK_PREVIOUS_MANAGER_IS_DESTROYED_MAX_COUNT; count++) {
if (!get(isDestroyingManager)) {
return Promise.resolve()
}
await sleep(CHECK_PREVIOUS_MANAGER_IS_DESTROYED_INTERVAL)
}
return Promise.reject()
}