-
Notifications
You must be signed in to change notification settings - Fork 504
/
sagas.ts
539 lines (498 loc) · 16 KB
/
sagas.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
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
import * as A from './actions'
import * as AT from './actionTypes'
import * as S from './selectors'
import { actions, actionTypes, selectors } from 'data'
import {
call,
cancel,
delay,
fork,
put,
race,
select,
spawn,
take
} from 'redux-saga/effects'
import { compose, equals, lift, prop, sortBy, tail } from 'ramda'
import { ExtractSuccess } from 'core/types'
import { KYC_STATES, USER_ACTIVATION_STATES } from './model'
import { promptForSecondPassword } from 'services/SagaService'
import { Remote } from 'blockchain-wallet-v4/src'
import { UserDataType } from './types'
import moment from 'moment'
export const logLocation = 'modules/profile/sagas'
export const userRequiresRestoreError = 'User restored'
export const authRetryDelay = 5000
export const renewUserDelay = 30000
let renewSessionTask = null
let renewUserTask = null
export default ({ api, coreSagas, networks }) => {
const waitForUserData = function * () {
const userData = yield select(selectors.modules.profile.getUserData)
const apiToken = yield select(selectors.modules.profile.getApiToken)
if (Remote.Success.is(userData)) return
if (Remote.Failure.is(apiToken)) return
yield take(actionTypes.modules.profile.FETCH_USER_DATA_SUCCESS)
}
const isTier2 = function * () {
yield call(waitForUserData)
const userDataR = selectors.modules.profile.getUserData(yield select())
const userData = userDataR.getOrElse({
tiers: { current: 0 }
} as UserDataType)
return userData.tiers && userData.tiers.current >= 2
}
const getCampaignData = function * (campaign) {
if (campaign.name === 'sunriver') {
const xlmAccount = (yield select(
selectors.core.kvStore.xlm.getDefaultAccountId
)).getOrFail()
return {
'x-campaign-address': xlmAccount,
'x-campaign-code': campaign.code,
'x-campaign-email': campaign.email
}
}
if (campaign.name === 'BLOCKSTACK') {
let password = yield call(promptForSecondPassword, ['BLOCKSTACK'])
yield put(actions.core.data.stx.generateAddress(password))
const { payload } = yield take(actionTypes.core.data.stx.SET_ADDRESS)
const { address } = payload
return {
'x-campaign-address': address
}
}
return null
}
const signIn = function * () {
try {
const email = (yield select(selectors.core.settings.getEmail)).getOrFail(
'No email'
)
const guid = yield select(selectors.core.wallet.getGuid)
yield call(coreSagas.kvStore.userCredentials.fetchMetadataUserCredentials)
const userId = (yield select(
selectors.core.kvStore.userCredentials.getUserId
)).getOrElse(null)
const lifetimeToken = (yield select(
selectors.core.kvStore.userCredentials.getLifetimeToken
)).getOrElse(null)
if (!userId || !lifetimeToken) {
return yield put(
A.fetchUserDataSuccess({
state: USER_ACTIVATION_STATES.NONE,
kycState: KYC_STATES.NONE
})
)
}
yield put(A.setApiTokenLoading())
renewSessionTask = yield fork(
renewSession,
userId,
lifetimeToken,
email,
guid,
0
)
} catch (e) {
yield put(actions.logs.logErrorMessage(logLocation, 'signIn', e))
}
}
const renewSession = function * (
userId,
lifetimeToken,
email,
guid,
renewIn = 0
) {
try {
yield delay(renewIn)
yield call(setSession, userId, lifetimeToken, email, guid)
} catch (e) {
yield put(A.setApiTokenFailure(e))
yield spawn(
renewSession,
userId,
lifetimeToken,
email,
guid,
authRetryDelay
)
}
}
const setSession = function * (userId, lifetimeToken, email, guid) {
try {
const { token: apiToken, expiresAt } = yield call(
api.generateSession,
userId,
lifetimeToken,
email,
guid
)
yield put(A.setApiTokenSuccess(apiToken))
yield call(fetchUser)
yield call(renewApiSockets)
const expiresIn = moment(expiresAt)
.subtract(5, 's')
.diff(moment())
yield spawn(renewSession, userId, lifetimeToken, email, guid, expiresIn)
} catch (e) {
if (prop('description', e) === userRequiresRestoreError) {
return yield call(recoverUser)
}
throw e
}
}
const fetchUser = function * () {
try {
const user = yield call(api.getUser)
yield put(A.fetchUserDataSuccess(user))
yield call(fetchTiers)
if (!renewUserTask && user.kycState === KYC_STATES.PENDING)
renewUserTask = yield spawn(renewUser, renewUserDelay)
return user
} catch (e) {
if (prop('description', e) === userRequiresRestoreError) throw e
yield put(A.fetchUserDataFailure(e))
yield put(actions.logs.logErrorMessage(logLocation, 'fetchUser', e))
}
}
const renewUser = function * (renewIn = 0) {
try {
yield delay(renewIn)
const user = yield call(api.getUser)
yield put(A.fetchUserDataSuccess(user))
} catch (e) {
yield put(actions.logs.logErrorMessage(logLocation, 'renewUser', e))
} finally {
yield spawn(renewUser, renewUserDelay)
}
}
const renewApiSockets = function * () {
yield put(actions.middleware.webSocket.rates.stopSocket())
yield put(actions.middleware.webSocket.rates.startSocket())
}
const clearSession = function * () {
if (renewSessionTask) {
// @ts-ignore
yield cancel(renewSessionTask)
renewSessionTask = null
}
if (renewUserTask) {
// @ts-ignore
yield cancel(renewUserTask)
renewUserTask = null
}
yield put(A.setApiTokenNotAsked())
}
const generateRetailToken = function * () {
const guid = yield select(selectors.core.wallet.getGuid)
const sharedKey = yield select(selectors.core.wallet.getSharedKey)
const { token } = yield call(api.generateRetailToken, guid, sharedKey)
return token
}
const generateAuthCredentials = function * () {
const retailToken = yield call(generateRetailToken)
const coinifyId = (yield select(
selectors.core.kvStore.buySell.getCoinifyUser
)).getOrElse(null)
const { userId, token: lifetimeToken } = yield call(
api.createUser,
retailToken,
coinifyId
)
yield put(
actions.core.kvStore.userCredentials.setUserCredentials(
userId,
lifetimeToken
)
)
return { userId, lifetimeToken }
}
const recoverUser = function * () {
const retailToken = yield call(generateRetailToken)
const userId = (yield select(
selectors.core.kvStore.userCredentials.getUserId
)).getOrFail()
const lifetimeToken = (yield select(
selectors.core.kvStore.userCredentials.getLifetimeToken
)).getOrFail()
yield call(api.recoverUser, userId, lifetimeToken, retailToken)
const email = (yield select(selectors.core.settings.getEmail)).getOrFail()
const guid = yield select(selectors.core.wallet.getGuid)
yield call(setSession, userId, lifetimeToken, email, guid)
}
const createUser = function * () {
const token = yield select(S.getApiToken)
if (!Remote.NotAsked.is(token)) return
const userIdR = yield select(
selectors.core.kvStore.userCredentials.getUserId
)
const lifetimeTokenR = yield select(
selectors.core.kvStore.userCredentials.getLifetimeToken
)
const authCredentialsR = lift((userId, lifetimeToken) => ({
userId,
lifetimeToken
}))(userIdR, lifetimeTokenR)
const email = (yield select(selectors.core.settings.getEmail)).getOrFail()
const guid = yield select(selectors.core.wallet.getGuid)
const { userId, lifetimeToken } = yield authCredentialsR
.map(authCredentials => {
const { userId, lifetimeToken } = authCredentials
if (!userId || !lifetimeToken) return call(generateAuthCredentials)
return authCredentials
})
.getOrElse({} as ExtractSuccess<typeof authCredentialsR>)
yield call(setSession, userId, lifetimeToken, email, guid)
}
const updateUser = function * ({ payload }) {
const { data } = payload
const userR = S.getUserData(yield select())
const user = userR.getOrElse({
id: '',
address: undefined,
mobile: '',
mobileVerified: false,
state: 'NONE',
kycState: 'NONE'
} as UserDataType)
/* eslint-disable */
const {
id,
address,
mobile,
mobileVerified,
state,
kycState,
...userData
} = user
/* eslint-enable */
const updatedData = { ...userData, ...data }
if (equals(updatedData, userData)) return user
yield call(api.updateUser, updatedData)
return yield call(fetchUser)
}
const updateUserAddress = function * ({ payload }) {
const { address } = payload
const user = (yield select(S.getUserData)).getOrElse({})
const { address: prevAddress } = user
if (equals(address, prevAddress)) return user
yield call(api.updateUserAddress, address)
return yield call(fetchUser)
}
const syncUserWithWallet = function * () {
const retailToken = yield call(generateRetailToken)
const userData = yield call(api.syncUserWithWallet, retailToken)
yield put(A.fetchUserDataSuccess(userData))
}
const fetchUserCampaigns = function * () {
try {
yield put(A.fetchUserCampaignsLoading())
yield call(waitForUserData)
const userCampaigns = yield call(api.getUserCampaigns)
yield put(A.fetchUserCampaignsSuccess(userCampaigns))
} catch (e) {
yield put(A.fetchUserCampaignsFailure(e))
}
}
const fetchTiers = function * () {
try {
yield put(A.fetchTiersLoading())
const tiersData = yield call(api.fetchTiers)
yield put(
A.fetchTiersSuccess(
compose(
tail,
// @ts-ignore
sortBy(prop('index'))
)(tiersData.tiers)
)
)
} catch (e) {
yield put(A.fetchTiersFailure(e))
}
}
const shareWalletAddressesWithExchange = function * () {
try {
yield put(A.shareWalletAddressesWithExchangeLoading())
const remainingCoins = S.getRemainingCoins(yield select())
const walletAddresses = (yield select(S.getWalletAddresses)).getOrFail(
'no_deposit_addresses'
)
// BTC
const defaultIdx = yield select(
selectors.core.wallet.getDefaultAccountIndex
)
const BTC = selectors.core.common.btc.getNextAvailableReceiveAddress(
networks.btc,
defaultIdx
)
// BCH
const BCH = selectors.core.common.bch.getNextAvailableReceiveAddressFormatted(
networks.btc,
defaultIdx
)
// ETH
const ETH = selectors.core.kvStore.eth.getContext
// XLM
const XLM = selectors.core.kvStore.xlm.getDefaultAccountId
const addressSelectors = { BTC, BCH, ETH, XLM, PAX: ETH, USDT: ETH }
const state = yield select()
const remainingAddresses = remainingCoins.reduce((res, coin) => {
res[coin] = addressSelectors[coin](state).getOrElse(null)
return res
}, walletAddresses)
const data = yield call(
api.shareWalletDepositAddresses,
remainingAddresses
)
yield put(A.shareWalletAddressesWithExchangeSuccess(data))
} catch (e) {
yield put(A.shareWalletAddressesWithExchangeFailure(e))
}
}
const linkFromExchangeAccount = function * ({ payload }) {
try {
const { linkId } = payload
yield put(A.linkFromExchangeAccountLoading())
// ensure email is verified else wait
const isEmailVerified = (yield select(
selectors.core.settings.getEmailVerified
)).getOrElse(true)
if (!isEmailVerified)
yield take(actionTypes.core.settings.SET_EMAIL_VERIFIED)
// get or create user
const isUserStateNone = (yield select(S.isUserStateNone)).getOrElse(false)
if (isUserStateNone) yield call(createUser)
// link Account
const data = yield call(api.linkAccount, linkId)
// share addresses
yield put(A.shareWalletAddressesWithExchange())
yield put(A.linkFromExchangeAccountSuccess(data))
// update user
yield call(fetchUser)
} catch (e) {
yield put(A.linkFromExchangeAccountFailure(e))
}
}
const linkToExchangeAccount = function * ({ payload }) {
try {
const { utmCampaign } = payload
yield put(A.linkToExchangeAccountLoading())
// check if wallet is already linked
const isExchangeAccountLinked = (yield select(
S.isExchangeAccountLinked
)).getOrFail()
if (isExchangeAccountLinked) {
throw new Error('Account has already been linked.')
}
// ensure email address is verified
const isEmailVerified = (yield select(
selectors.core.settings.getEmailVerified
)).getOrFail()
if (!isEmailVerified) {
throw new Error('Email address is not verified.')
}
// check if wallet relink should be attempted
const isRelinkAttempt = (yield select(
S.isExchangeRelinkRequired
)).getOrFail()
if (isRelinkAttempt) {
yield put(A.shareWalletAddressesWithExchange())
return yield put(actions.modals.closeAllModals())
} else {
// get or create nabu user
const isUserStateNone = (yield select(S.isUserStateNone)).getOrFail()
if (isUserStateNone) yield call(createUser)
// get exchange linkId, exchange domain and user email
const domains = (yield select(
selectors.core.walletOptions.getDomains
)).getOrFail()
const exchangeDomain = prop('exchange', domains)
const data = yield call(api.createLinkAccountId)
const exchangeLinkId = prop('linkId', data)
const email = (yield select(
selectors.core.settings.getEmail
)).getOrFail()
const accountDeeplinkUrl = `${exchangeDomain}/trade/link/${exchangeLinkId}?email=${encodeURIComponent(
email
)}&utm_source=web_wallet&utm_medium=referral&utm_campaign=${utmCampaign ||
'wallet_exchange_page'}`
// share addresses
yield put(A.shareWalletAddressesWithExchange())
// simulate wait while allowing user to read modal
yield delay(2000)
// attempt to open url for user
window.open(accountDeeplinkUrl, '_blank', 'noreferrer')
yield put(A.setLinkToExchangeAccountDeepLink(accountDeeplinkUrl))
// poll for account link
yield race({
task: call(pollForAccountLinkSuccess, 0),
cancel: take([
AT.LINK_TO_EXCHANGE_ACCOUNT_FAILURE,
AT.LINK_TO_EXCHANGE_ACCOUNT_SUCCESS,
actionTypes.modals.CLOSE_MODAL
])
})
}
} catch (e) {
yield put(A.linkToExchangeAccountFailure(e.message))
}
}
const pollForAccountLinkSuccess = function * (attemptCount) {
try {
// check every 10 seconds
yield delay(10000)
attemptCount++
// if 5 minutes has passed, cancel poll and mark as timeout
if (equals(30, attemptCount)) {
yield put(
A.linkToExchangeAccountFailure(
'Timeout waiting for account connection status.'
)
)
return
}
yield call(fetchUser)
const isExchangeAccountLinked = (yield select(
S.isExchangeAccountLinked
)).getOrElse(false)
if (isExchangeAccountLinked) {
yield put(A.linkToExchangeAccountSuccess())
} else {
yield call(pollForAccountLinkSuccess, attemptCount)
}
} catch (e) {
yield put(
A.linkToExchangeAccountFailure(
'Unable to check current account status.'
)
)
}
}
return {
clearSession,
createUser,
fetchTiers,
fetchUser,
fetchUserCampaigns,
generateAuthCredentials,
generateRetailToken,
getCampaignData,
isTier2,
linkFromExchangeAccount,
linkToExchangeAccount,
recoverUser,
renewApiSockets,
renewSession,
renewUser,
setSession,
shareWalletAddressesWithExchange,
signIn,
syncUserWithWallet,
updateUser,
updateUserAddress,
waitForUserData
}
}