-
Notifications
You must be signed in to change notification settings - Fork 80
/
saga.ts
572 lines (521 loc) · 20.5 KB
/
saga.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
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
import { compressedPubKey } from '@celo/cryptographic-utils'
import getPhoneHash from '@celo/phone-utils/lib/getPhoneHash'
import { hexToBuffer } from '@celo/utils/lib/address'
import locales from 'locales'
import { AppState, Platform } from 'react-native'
import DeviceInfo from 'react-native-device-info'
import InAppReview from 'react-native-in-app-review'
import * as Keychain from 'react-native-keychain'
import { findBestLanguageTag } from 'react-native-localize'
import { eventChannel } from 'redux-saga'
import { e164NumberSelector } from 'src/account/selectors'
import { AppEvents, InviteEvents } from 'src/analytics/Events'
import ValoraAnalytics from 'src/analytics/ValoraAnalytics'
import { HooksEnablePreviewOrigin } from 'src/analytics/types'
import {
Actions,
OpenDeepLink,
OpenUrlAction,
SetAppState,
androidMobileServicesAvailabilityChecked,
appLock,
inAppReviewRequested,
inviteLinkConsumed,
minAppVersionDetermined,
openDeepLink,
phoneNumberVerificationMigrated,
setAppState,
setSupportedBiometryType,
updateRemoteConfigValues,
} from 'src/app/actions'
import {
getLastTimeBackgrounded,
getRequirePinOnAppOpen,
googleMobileServicesAvailableSelector,
huaweiMobileServicesAvailableSelector,
inAppReviewLastInteractionTimestampSelector,
inviterAddressSelector,
sentryNetworkErrorsSelector,
shouldRunVerificationMigrationSelector,
} from 'src/app/selectors'
import { CeloNewsConfig } from 'src/celoNews/types'
import { DEFAULT_APP_LANGUAGE, FETCH_TIMEOUT_DURATION, isE2EEnv } from 'src/config'
import { claimRewardsSuccess } from 'src/consumerIncentives/slice'
import { SuperchargeTokenConfigByToken } from 'src/consumerIncentives/types'
import { FiatExchangeFlow } from 'src/fiatExchanges/utils'
import { FiatAccountSchemaCountryOverrides } from 'src/fiatconnect/types'
import { appVersionDeprecationChannel, fetchRemoteConfigValues } from 'src/firebase/firebase'
import { initI18n } from 'src/i18n'
import {
allowOtaTranslationsSelector,
currentLanguageSelector,
otaTranslationsAppVersionSelector,
} from 'src/i18n/selectors'
import { E164NumberToSaltType } from 'src/identity/reducer'
import { e164NumberToSaltSelector } from 'src/identity/selectors'
import { jumpstartClaim } from 'src/jumpstart/saga'
import { navigate, navigateHome } from 'src/navigator/NavigationService'
import { Screens } from 'src/navigator/Screens'
import { StackParamList } from 'src/navigator/types'
import { retrieveSignedMessage } from 'src/pincode/authentication'
import { handleEnableHooksPreviewDeepLink } from 'src/positions/saga'
import { allowHooksPreviewSelector } from 'src/positions/selectors'
import { Actions as SendActions } from 'src/send/actions'
import { handlePaymentDeeplink } from 'src/send/utils'
import { initializeSentry } from 'src/sentry/Sentry'
import { SentryTransactionHub } from 'src/sentry/SentryTransactionHub'
import { SentryTransaction } from 'src/sentry/SentryTransactions'
import { getFeatureGate, patchUpdateStatsigUser, setupOverridesFromLaunchArgs } from 'src/statsig'
import { StatsigFeatureGates } from 'src/statsig/types'
import { swapSuccess } from 'src/swap/slice'
import { NetworkId } from 'src/transactions/types'
import Logger from 'src/utils/Logger'
import { ensureError } from 'src/utils/ensureError'
import { isDeepLink, navigateToURI } from 'src/utils/linking'
import { safely } from 'src/utils/safely'
import { ONE_DAY_IN_MILLIS } from 'src/utils/time'
import { isWalletConnectEnabled } from 'src/walletConnect/saga'
import {
handleWalletConnectDeepLink,
isWalletConnectDeepLink,
} from 'src/walletConnect/walletConnect'
import networkConfig from 'src/web3/networkConfig'
import {
dataEncryptionKeySelector,
mtwAddressSelector,
walletAddressSelector,
} from 'src/web3/selectors'
import {
all,
call,
cancelled,
delay,
put,
race,
select,
spawn,
take,
takeEvery,
takeLatest,
} from 'typed-redux-saga'
import { parse } from 'url'
const TAG = 'app/saga'
// There are cases, when user will put the app into `background` state,
// but we do not want to lock it immeditely. Here are some examples:
// case 1: User switches to SMS app to copy verification text
// case 2: User gets a permission request dialog
// (which will put an app into `background` state until dialog disappears).
const DO_NOT_LOCK_PERIOD = 30000 // 30 sec
// REVIEW_INTERVAL is the time between app review prompts
const REVIEW_INTERVAL = ONE_DAY_IN_MILLIS * 120 // 120 days
// Work that's done before other sagas are initalized
// Be mindful to not put long blocking tasks here
export function* appInit() {
SentryTransactionHub.startTransaction(SentryTransaction.app_init_saga)
const allowOtaTranslations = yield* select(allowOtaTranslationsSelector)
const otaTranslationsAppVersion = yield* select(otaTranslationsAppVersionSelector)
const language = yield* select(currentLanguageSelector)
const bestLanguage = findBestLanguageTag(Object.keys(locales))?.languageTag
yield* all([
call(initializeSentry),
call([ValoraAnalytics, 'init']),
call(
initI18n,
language || bestLanguage || DEFAULT_APP_LANGUAGE,
allowOtaTranslations,
otaTranslationsAppVersion
),
])
// This step is important if the user is offline and unable to fetch remote
// config values, we can use the persisted value instead of an empty one
const sentryNetworkErrors = yield* select(sentryNetworkErrorsSelector)
Logger.setNetworkErrors(sentryNetworkErrors)
const supportedBiometryType = yield* call(Keychain.getSupportedBiometryType)
yield* put(setSupportedBiometryType(supportedBiometryType))
// setup statsig overrides for E2E tests
if (isE2EEnv) {
setupOverridesFromLaunchArgs()
}
SentryTransactionHub.finishTransaction(SentryTransaction.app_init_saga)
}
export function* appVersionSaga() {
const appVersionChannel = yield* call(appVersionDeprecationChannel)
if (!appVersionChannel) {
return
}
try {
while (true) {
const minRequiredVersion = yield* take(appVersionChannel)
Logger.info(TAG, `Required min version: ${minRequiredVersion}`)
// Note: The NavigatorWrapper will read this value from the store and
// show the UpdateScreen if necessary.
yield* put(minAppVersionDetermined(minRequiredVersion))
}
} catch (error) {
Logger.error(`${TAG}@appVersionSaga`, 'Failed to watch app version', error)
} finally {
if (yield* cancelled()) {
appVersionChannel.close()
}
}
}
// Check the availability of Google Mobile Services and Huawei Mobile Services, an alternative to
// that ships with Huawei phones which do not have GMS. Log and report the result to analytics.
// Note: On iOS, this will be a no-op.
export function* checkAndroidMobileServicesSaga() {
if (Platform.OS !== 'android') {
return
}
// Check to see if Google Mobile Services (i.e. Google Play Services) are available on this device.
let googleIsAvailable: boolean | undefined
try {
googleIsAvailable = yield* call([DeviceInfo, DeviceInfo.hasGms])
Logger.info(TAG, 'Result of check for Google Mobile Services', googleIsAvailable)
} catch (e) {
Logger.error(TAG, 'Error in check for Google Mobile Services', e)
}
// Check to see if Huawei Mobile Services are available on this device.
let huaweiIsAvailable: boolean | undefined
try {
huaweiIsAvailable = yield* call([DeviceInfo, DeviceInfo.hasHms])
Logger.info(TAG, `Result of check for Huawei Mobile Services`, huaweiIsAvailable)
} catch (e) {
Logger.error(TAG, `Error in check for Huawei Mobile Services`, e)
}
// Check if the availability status has changed. If so, log an analytics events.
// When this is first run, the status in the state tree will be undefined, ensuring this event is
// fired at least once for each client.
const updated =
googleIsAvailable !== (yield* select(googleMobileServicesAvailableSelector)) ||
huaweiIsAvailable !== (yield* select(huaweiMobileServicesAvailableSelector))
if (updated) {
ValoraAnalytics.track(AppEvents.android_mobile_services_checked, {
googleIsAvailable,
huaweiIsAvailable,
})
}
yield* put(androidMobileServicesAvailabilityChecked(googleIsAvailable, huaweiIsAvailable))
}
export interface RemoteConfigValues {
celoEducationUri: string | null
dappListApiUrl: string | null
inviteRewardsVersion: string
walletConnectV2Enabled: boolean
logPhoneNumberTypeEnabled: boolean
superchargeApy: number
superchargeTokenConfigByToken: SuperchargeTokenConfigByToken
pincodeUseExpandedBlocklist: boolean
allowOtaTranslations: boolean
sentryTracesSampleRate: number
sentryNetworkErrors: string[]
maxNumRecentDapps: number
dappsWebViewEnabled: boolean
fiatConnectCashInEnabled: boolean
fiatConnectCashOutEnabled: boolean
fiatAccountSchemaCountryOverrides: FiatAccountSchemaCountryOverrides
coinbasePayEnabled: boolean
showSwapMenuInDrawerMenu: boolean
maxSwapSlippagePercentage: number
networkTimeoutSeconds: number
celoNews: CeloNewsConfig
priceImpactWarningThreshold: number
superchargeRewardContractAddress: string
}
export function* appRemoteFeatureFlagSaga() {
// Refresh feature flags on process start
// and every hour afterwards when the app becomes active.
// If the app keep getting killed and restarted we
// will load the flags more often, but that should be pretty rare.
// if that ever becomes a problem we can save it somewhere persistent.
let lastLoadTime = 0
let isAppActive = true
while (true) {
const isRefreshTime = Date.now() - lastLoadTime > 60 * 60 * 1000
if (isAppActive && isRefreshTime) {
const { configValues } = yield* race({
configValues: call(fetchRemoteConfigValues),
timeout: delay(FETCH_TIMEOUT_DURATION),
})
if (configValues) {
Logger.setNetworkErrors(configValues.sentryNetworkErrors)
yield* put(updateRemoteConfigValues(configValues))
lastLoadTime = Date.now()
}
}
const action = (yield* take(Actions.SET_APP_STATE)) as SetAppState
isAppActive = action.state === 'active'
}
}
function parseValue(value: string) {
if (['true', 'false'].indexOf(value) >= 0) {
return value === 'true'
}
const number = parseFloat(value)
if (!isNaN(number)) {
return number
}
return value
}
// Parses the query string into an object. Only works with built-in strings, booleans and numbers.
function convertQueryToScreenParams(query: string) {
const decodedParams = new URLSearchParams(decodeURIComponent(query))
const params: { [key: string]: any } = {}
decodedParams.forEach((value, key) => {
params[key] = parseValue(value)
})
return params
}
export function* handleDeepLink(action: OpenDeepLink) {
const { deepLink } = action
const { isSecureOrigin } = action
Logger.debug(TAG, 'Handling deep link', deepLink)
const walletAddress = yield* select(walletAddressSelector)
if (!walletAddress) {
Logger.error(TAG, 'No wallet address found in store. This should never happen.')
return
}
if (isWalletConnectDeepLink(deepLink)) {
yield* call(handleWalletConnectDeepLink, deepLink)
return
}
const rawParams = parse(deepLink)
if (rawParams.path) {
const pathParts = rawParams.path.split('/')
const pathStartsWith = pathParts[1].split('?')[0]
// Only log detailed paramters (fullPath and query) for allowed paths. This is a security precaution so we
// don't accidentally log sensitive information on new deeplinks. 'jumpstart' is specifically excluded
const pathStartsWithAllowList = [
'pay',
'cashIn',
'bidali',
'cash-in-success',
'cash-in-failure',
'openScreen',
'share',
'hooks',
]
ValoraAnalytics.track(AppEvents.handle_deeplink, {
pathStartsWith: pathParts[1].split('?')[0],
fullPath: pathStartsWithAllowList.includes(pathStartsWith) ? rawParams.pathname : null,
query: pathStartsWithAllowList.includes(pathStartsWith) ? rawParams.query : null,
})
if (rawParams.path.startsWith('/pay')) {
yield* call(handlePaymentDeeplink, deepLink)
} else if (rawParams.path === '/cashIn') {
navigate(Screens.FiatExchangeCurrencyBottomSheet, { flow: FiatExchangeFlow.CashIn })
} else if (rawParams.pathname === '/bidali') {
navigate(Screens.BidaliScreen, { currency: undefined })
} else if (rawParams.path.startsWith('/cash-in-success')) {
// Some providers append transaction information to the redirect links so can't check for strict equality
const cicoSuccessParam = (rawParams.pathname?.match(/cash-in-success\/(.+)/) || [])[1]
navigate(Screens.CashInSuccess, { provider: cicoSuccessParam.split('/')[0] })
// Some providers append transaction information to the redirect links so can't check for strict equality
} else if (rawParams.path.startsWith('/cash-in-failure')) {
navigateHome()
} else if (isSecureOrigin && rawParams.pathname === '/openScreen' && rawParams.query) {
// The isSecureOrigin is important. We don't want it to be possible to fire this deep link from outside
// of our own notifications for security reasons.
const params = convertQueryToScreenParams(rawParams.query)
navigate(params.screen as keyof StackParamList, params)
} else if (pathParts.length === 3 && pathParts[1] === 'share') {
const inviterAddress = pathParts[2]
yield* put(inviteLinkConsumed(inviterAddress))
ValoraAnalytics.track(InviteEvents.opened_via_invite_url, {
inviterAddress,
})
} else if (pathParts.length === 4 && pathParts[1] === 'jumpstart') {
const privateKey = pathParts[2]
const networkId = pathParts[3] as NetworkId
yield* call(jumpstartClaim, privateKey, networkId, walletAddress)
} else if (
(yield* select(allowHooksPreviewSelector)) &&
rawParams.pathname === '/hooks/enablePreview'
) {
yield* call(handleEnableHooksPreviewDeepLink, deepLink, HooksEnablePreviewOrigin.Deeplink)
}
}
}
export function* watchDeepLinks() {
yield* takeLatest(Actions.OPEN_DEEP_LINK, safely(handleDeepLink))
}
export function* handleOpenUrl(action: OpenUrlAction) {
const { url, openExternal, isSecureOrigin } = action
const walletConnectEnabled: boolean = yield* call(isWalletConnectEnabled, url)
Logger.debug(TAG, 'Handling url', url)
if (isDeepLink(url) || (walletConnectEnabled && isWalletConnectDeepLink(url))) {
// Handle celo links directly, this avoids showing the "Open with App" sheet on Android
yield* call(handleDeepLink, openDeepLink(url, isSecureOrigin))
} else if (/^https?:\/\//i.test(url) === true && !openExternal) {
// We display http or https links using our in app browser, unless openExternal is forced
navigate(Screens.WebViewScreen, { uri: url })
} else {
// Fallback
yield* call(navigateToURI, url)
}
}
export function* watchOpenUrl() {
yield* takeEvery(Actions.OPEN_URL, safely(handleOpenUrl))
}
function createAppStateChannel() {
return eventChannel((emit: any) => {
const appStateListener = AppState.addEventListener('change', emit)
return () => {
appStateListener.remove()
}
})
}
function* watchAppState() {
Logger.debug(`${TAG}@monitorAppState`, 'Starting monitor app state saga')
const appStateChannel = yield* call(createAppStateChannel)
while (true) {
try {
const newState = (yield* take(appStateChannel)) as string
Logger.debug(`${TAG}@monitorAppState`, `App changed state: ${newState}`)
yield* put(setAppState(newState))
} catch (err) {
const error = ensureError(err)
ValoraAnalytics.track(AppEvents.app_state_error, { error: error.message })
Logger.error(`${TAG}@monitorAppState`, `App state Error`, error)
} finally {
if (yield* cancelled()) {
appStateChannel.close()
}
}
}
}
export function* handleSetAppState(action: SetAppState) {
const requirePinOnAppOpen = yield* select(getRequirePinOnAppOpen)
const lastTimeBackgrounded = yield* select(getLastTimeBackgrounded)
const isPassedDoNotLockPeriod = Date.now() - lastTimeBackgrounded > DO_NOT_LOCK_PERIOD
const isAppActive = action.state === 'active'
if (requirePinOnAppOpen && isPassedDoNotLockPeriod && isAppActive) {
yield* put(appLock())
}
if (isAppActive) {
// Force a statsig refresh by updating the user object
yield* call(patchUpdateStatsigUser)
}
}
export function* runCentralPhoneVerificationMigration() {
const shouldRunVerificationMigration = yield* select(shouldRunVerificationMigrationSelector)
if (!shouldRunVerificationMigration) {
return
}
const privateDataEncryptionKey = yield* select(dataEncryptionKeySelector)
if (!privateDataEncryptionKey) {
Logger.warn(
`${TAG}@runCentralPhoneVerificationMigration`,
'No data encryption key was found in the store. This should never happen.'
)
return
}
const address = yield* select(walletAddressSelector)
const mtwAddress = yield* select(mtwAddressSelector)
const phoneNumber = yield* select(e164NumberSelector)
const publicDataEncryptionKey = compressedPubKey(hexToBuffer(privateDataEncryptionKey))
try {
const signedMessage = yield* call(retrieveSignedMessage)
if (!signedMessage) {
Logger.warn(
`${TAG}@runCentralPhoneVerificationMigration`,
'No signed message was found for this user. Skipping CPV migration.'
)
return
}
if (!phoneNumber) {
Logger.warn(
`${TAG}@runCentralPhoneVerificationMigration`,
'No phone number was found for this user. Skipping CPV migration.'
)
return
}
const saltCache: E164NumberToSaltType = yield* select(e164NumberToSaltSelector)
const cachedSalt = saltCache[phoneNumber]
if (!cachedSalt) {
Logger.warn(
`${TAG}@runCentralPhoneVerificationMigration`,
'No salt was cached for phone number. Skipping CPV migration.'
)
return
}
Logger.debug(
`${TAG}@runCentralPhoneVerificationMigration`,
'Starting to run central phone verification migration'
)
const phoneHash = yield* call(getPhoneHash, phoneNumber, cachedSalt)
const inviterAddress = yield* select(inviterAddressSelector)
const response = yield* call(fetch, networkConfig.migratePhoneVerificationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
authorization: `Valora ${address}:${signedMessage}`,
},
body: JSON.stringify({
clientPlatform: Platform.OS,
clientVersion: DeviceInfo.getVersion(),
publicDataEncryptionKey,
phoneNumber,
pepper: cachedSalt,
phoneHash,
mtwAddress: mtwAddress ?? undefined,
inviterAddress: inviterAddress ?? undefined,
}),
})
if (response.status === 200) {
yield* put(phoneNumberVerificationMigrated())
Logger.debug(
`${TAG}@runCentralPhoneVerificationMigration`,
'Central phone verification migration completed successfully'
)
} else {
throw new Error(yield* call([response, 'text']))
}
} catch (error) {
Logger.warn(
`${TAG}@runCentralPhoneVerificationMigration`,
'Could not complete central phone verification migration',
error
)
}
}
export function* requestInAppReview() {
const walletAddress = yield* select(walletAddressSelector)
// Quick return if no wallet address or the device does not support in app review
if (
!walletAddress ||
!InAppReview.isAvailable() ||
!getFeatureGate(StatsigFeatureGates.APP_REVIEW)
)
return
const lastInteractionTimestamp = yield* select(inAppReviewLastInteractionTimestampSelector)
const now = Date.now()
// If the last interaction was less than a quarter year ago or null
if (!lastInteractionTimestamp || now - lastInteractionTimestamp >= REVIEW_INTERVAL) {
try {
// If we call InAppReview.RequestInAppReview and there wasn't an error
// Update the last interaction timestamp and send analytics
yield* call(InAppReview.RequestInAppReview)
yield* put(inAppReviewRequested(now))
ValoraAnalytics.track(AppEvents.in_app_review_impression)
} catch (err) {
const error = ensureError(err)
Logger.error(TAG, `Error while calling InAppReview.RequestInAppReview`, error)
ValoraAnalytics.track(AppEvents.in_app_review_error, { error: error.message })
}
}
}
export function* watchAppReview() {
// Triggers on successful payment, swap, or rewards claim
yield* takeLatest(
[SendActions.SEND_PAYMENT_SUCCESS, swapSuccess, claimRewardsSuccess],
safely(requestInAppReview)
)
}
export function* appSaga() {
yield* spawn(watchDeepLinks)
yield* spawn(watchOpenUrl)
yield* spawn(watchAppState)
yield* spawn(runCentralPhoneVerificationMigration)
yield* takeLatest(Actions.SET_APP_STATE, safely(handleSetAppState))
yield* spawn(watchAppReview)
}