-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathDeepLinkingActions.tsx
More file actions
462 lines (418 loc) · 14.4 KB
/
Copy pathDeepLinkingActions.tsx
File metadata and controls
462 lines (418 loc) · 14.4 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
import type { EdgeParsedUri, EdgeTokenId } from 'edge-core-js'
import * as React from 'react'
import { Linking } from 'react-native'
import { sprintf } from 'sprintf-js'
import { ButtonsModal } from '../components/modals/ButtonsModal'
import { ConfirmContinueModal } from '../components/modals/ConfirmContinueModal'
import { FundAccountModal } from '../components/modals/FundAccountModal'
import { pickWallet } from '../components/modals/WalletListModal'
import {
Airship,
showError,
showToast,
showToastSpinner
} from '../components/services/AirshipInstance'
import { guiPlugins } from '../constants/plugins/GuiPlugins'
import { SPECIAL_CURRENCY_INFO } from '../constants/WalletAndCurrencyConstants'
import { lstrings } from '../locales/strings'
import {
executePlugin,
fiatProviderDeeplinkHandler
} from '../plugins/gui/fiatPlugin'
import { rampDeeplinkManager } from '../plugins/ramps/rampDeeplinkHandler'
import { config } from '../theme/appConfig'
import type { DeepLink } from '../types/DeepLinkTypes'
import type { Dispatch, RootState, ThunkAction } from '../types/reduxTypes'
import type { NavigationBase } from '../types/routerTypes'
import type { EdgeAsset } from '../types/types'
import { logEvent } from '../util/tracking'
import { base58ToUuid, isEmail } from '../util/utils'
import { activatePromotion } from './AccountReferralActions'
import { checkAndShowLightBackupModal } from './BackupModalActions'
import { logoutRequest } from './LoginActions'
import { launchPaymentProto } from './PaymentProtoActions'
import { doRequestAddress, handleWalletUris } from './ScanActions'
// These are the asset types that we'll manually check for when deep linking with a
// URI for the format edge://pay/bitcoin/[privateKey]
// Such assets will allow the user to auto create a wallet if they don't have one
const CREATE_WALLET_ASSETS: Record<string, EdgeAsset> = {
bitcoin: { pluginId: 'bitcoin', tokenId: null },
bitcoincash: { pluginId: 'bitcoincash', tokenId: null },
litecoin: { pluginId: 'litecoin', tokenId: null },
dogecoin: { pluginId: 'dogecoin', tokenId: null },
dash: { pluginId: 'dash', tokenId: null }
}
/**
* The app has just received some of link,
* so try to follow it if possible, or save it for later if not.
*/
export function launchDeepLink(
navigation: NavigationBase,
link: DeepLink
): ThunkAction<Promise<void>> {
return async (dispatch, getState) => {
const state = getState()
await handleLink(navigation, dispatch, state, link)
}
}
/**
* Launches a link if it app is able to do so.
* @returns true if the link is handled,
* or false if the app is in the wrong state to handle this link.
*/
async function handleLink(
navigation: NavigationBase,
dispatch: Dispatch,
state: RootState,
link: DeepLink
): Promise<void> {
const { account, context, disklet } = state.core
const { defaultIsoFiat } = state.ui.settings
const { currencyWallets } = account
const deviceId = base58ToUuid(context.clientId)
switch (link.type) {
case 'edgeLogin':
navigation.push('edgeLogin', {
lobbyId: link.lobbyId
})
break
case 'passwordRecovery':
await dispatch(
logoutRequest(navigation, {
passwordRecoveryKey: link.passwordRecoveryKey
})
)
break
case 'plugin': {
const { pluginId, path, query } = link
const plugin = guiPlugins[pluginId]
if (plugin?.pluginId == null || plugin?.pluginId === 'custom') {
showError(`No plugin named "${pluginId}" exists`)
break
}
// Check the disabled status:
if (
state.ui.exchangeInfo.buy.disablePlugins[pluginId] === true ||
state.ui.exchangeInfo.sell.disablePlugins[pluginId] === true
) {
showError(`Plugin "${pluginId}" is disabled`)
break
}
navigation.push('pluginView', {
plugin,
deepPath: path,
deepQuery: query
})
break
}
case 'fiatPlugin': {
const {
direction = 'buy',
paymentType = 'credit',
pluginId,
providerId
} = link
const plugin = guiPlugins[pluginId]
if (plugin?.nativePlugin == null) {
showError(new Error(`No fiat plugin named "${pluginId}" exists`))
break
}
// Check the disabled status:
const disableProviders =
state.ui.exchangeInfo[direction].disablePlugins[pluginId] ?? {}
if (disableProviders === true) {
showError(`Plugin "${pluginId}" is disabled`)
break
}
await executePlugin({
account,
defaultIsoFiat,
deviceId,
disablePlugins: disableProviders,
disklet,
guiPlugin: plugin,
direction,
regionCode: { countryCode: state.ui.settings.countryCode },
paymentType,
providerId,
navigation,
onLogEvent: (event, values) => {
dispatch(logEvent(event, values))
},
dispatch
})
break
}
// NOTE: We MUST keep 'fiatProvider' case around indefinitely for backwards compatibility
// because some buy/sell providers manage the callback URL state (e.g. Simplex).
// This means we can never really change the callback URL for those providers without
// breaking the older versions of the app which do not have the ramp plugins.
// Only until those providers become deprecated or accept parameterized callback URLs,
// can we remove this deeplink handling.
case 'fiatProvider': {
// Handle with ramp deeplink manager first for backward compatibility
// of some fiat providers (e.g. Simplex) because we cannot upgrade those
// providers to use the new `/ramp/` deeplink format..
const result = rampDeeplinkManager.handleDeeplink({
...link,
type: 'ramp'
})
if (result.success) {
break
}
// Handle with legacy fiat plugin handler
fiatProviderDeeplinkHandler(link)
break
}
case 'promotion':
await dispatch(activatePromotion(link.installerId ?? ''))
break
case 'affiliate':
await dispatch(activatePromotion(link.installerId))
await handleLink(navigation, dispatch, state, link.link)
break
case 'requestAddress':
await doRequestAddress(navigation, state.core.account, dispatch, link)
break
case 'swap':
navigation.navigate('swapTab', { screen: 'swapCreate' })
break
case 'azteco': {
const result = await pickWallet({
account,
assets: [{ pluginId: 'bitcoin', tokenId: null }],
navigation,
showCreateWallet: true
})
if (result?.type !== 'wallet') break
const wallet = account.currencyWallets[result.walletId]
if (wallet == null) break
if (checkAndShowLightBackupModal(account, navigation)) break
const address = await wallet.getReceiveAddress({ tokenId: null })
const response = await fetch(`${link.uri}${address.publicAddress}`)
if (response.ok) {
showToast(lstrings.azteco_success)
} else if (response.status === 400) {
showError(lstrings.azteco_invalid_code)
} else {
showError(lstrings.azteco_service_unavailable)
}
navigation.navigate('home')
break
}
case 'walletConnect':
navigation.push('wcConnections', {
uri: link.uri
})
break
case 'paymentProto':
await launchPaymentProto(navigation, account, link.uri, {
hideScamWarning: false
})
break
case 'price-change': {
const { pluginId, body } = link
const currencyCode =
account.currencyConfig[pluginId].currencyInfo.currencyCode
let result
if (config.disableSwaps === true) {
result = await Airship.show<'buy' | 'sell' | undefined>(bridge => (
<ButtonsModal
bridge={bridge}
title={lstrings.price_change_notification}
message={`${body} ${sprintf(
lstrings.price_change_buy_sell_trade,
currencyCode
)}`}
buttons={{
buy: { label: lstrings.title_buy, type: 'secondary' },
sell: { label: lstrings.title_sell }
}}
/>
))
} else {
result = await Airship.show<'buy' | 'sell' | 'exchange' | undefined>(
bridge => (
<ButtonsModal
bridge={bridge}
title={lstrings.price_change_notification}
message={`${body} ${sprintf(
lstrings.price_change_buy_sell_trade,
currencyCode
)}`}
buttons={{
buy: { label: lstrings.title_buy, type: 'secondary' },
sell: { label: lstrings.title_sell },
exchange: { label: lstrings.buy_crypto_modal_exchange }
}}
/>
)
)
}
if (result === 'buy') {
navigation.navigate('buyTab', { screen: 'pluginListBuy', params: {} })
} else if (result === 'sell') {
navigation.navigate('sellTab', { screen: 'pluginListSell', params: {} })
} else if (result === 'exchange') {
navigation.navigate('swapTab', { screen: 'swapCreate' })
}
break
}
case 'marketing': {
// The user opened the app from a marketing push. Report it so the
// campaign's open rate can be tracked. The send UI lives in the internal
// tools project; the campaignId rides in the push notification payload.
dispatch(
logEvent('Marketing_Notification_Opened', {
campaignId: link.campaignId
})
)
// Optional navigation: delegate to the shared handler, mirroring the
// affiliate link. Unsupported targets fall through its existing guards.
if (link.link != null) {
await handleLink(navigation, dispatch, state, link.link)
}
break
}
case 'other': {
const matchingWalletIdsAndUris: Array<{
walletId: string
parsedUri: EdgeParsedUri
tokenId: EdgeTokenId
}> = []
const assets: EdgeAsset[] = []
const parseWallets = async (): Promise<void> => {
// Try to parse with all wallets
for (const wallet of Object.values(currencyWallets)) {
const { pluginId } = wallet.currencyInfo
// Ignore disabled wallets:
const { keysOnlyMode = false } = SPECIAL_CURRENCY_INFO[pluginId] ?? {}
if (keysOnlyMode) continue
const parsedUri = await wallet
.parseUri(link.uri)
.catch((_: unknown) => undefined)
if (parsedUri != null) {
const { tokenId = null } = parsedUri
matchingWalletIdsAndUris.push({
walletId: wallet.id,
parsedUri,
tokenId
})
assets.push({ pluginId, tokenId })
}
}
}
const promise = parseWallets()
await showToastSpinner(lstrings.scan_parsing_link, promise)
// Check if this is an email for Tron USDT and show warning for potential
// PIX send
if (
isEmail(link.uri) &&
assets.find(
asset =>
asset.pluginId === 'tron' &&
asset.tokenId === 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'
) != null
) {
const approved = await Airship.show<boolean>(bridge => (
<ConfirmContinueModal
bridge={bridge}
title={lstrings.warning_sending_pix_to_email_title}
body={lstrings.warning_sending_pix_to_email_body}
warning
isSkippable
/>
))
if (!approved) {
return
}
}
// Check if the uri matches one of the wallet types that we could create. In such a case, link.uri
// would be of the format 'dogecoin:QUE1U9n3kMYR...'
const [linkCurrency] = link.uri.split(':')
const createWalletAsset = CREATE_WALLET_ASSETS[linkCurrency]
if (matchingWalletIdsAndUris.length === 0 && createWalletAsset == null) {
showToast(lstrings.alert_deep_link_no_wallet_for_uri)
break
}
if (matchingWalletIdsAndUris.length === 1) {
const { walletId, parsedUri } = matchingWalletIdsAndUris[0]
await dispatch(
handleWalletUris(navigation, currencyWallets[walletId], parsedUri)
)
break
}
if (createWalletAsset != null) {
assets.push(createWalletAsset)
}
const result = await pickWallet({
account,
assets,
navigation,
showCreateWallet: true
})
if (result?.type !== 'wallet') break
const wallet = account.currencyWallets[result.walletId]
if (wallet == null) break
// Re-parse the uri with the final chosen wallet
// just in case this was a URI for a wallet we didn't have:
const finalParsedUri = await wallet.parseUri(link.uri)
await dispatch(handleWalletUris(navigation, wallet, finalParsedUri))
break
}
case 'scene': {
try {
navigation.navigate(link.sceneName as any, link.query as any)
} catch (e) {
showError(
`Deep link failed. Unable to navigate to: '${link.sceneName}'`
)
}
break
}
case 'modal': {
switch (link.modalName) {
case 'fundAccount':
await Airship.show(bridge => (
<FundAccountModal bridge={bridge} navigation={navigation} />
))
break
default:
showError(`Unknown modal: '${link.modalName}'`)
}
break
}
case 'ramp': {
const result = rampDeeplinkManager.handleDeeplink(link)
if (!result.success) {
showError(result.error)
}
break
}
case 'rewards': {
const { pluginId, tokenId } = link
// Choose wallet:
const walletListResult = await pickWallet({
account,
assets: [{ pluginId, tokenId }],
navigation,
showCreateWallet: true
})
if (walletListResult?.type !== 'wallet') break
const { walletId } = walletListResult
const wallet = account.currencyWallets[walletId]
const { publicAddress } = (await wallet.getAddresses({ tokenId }))[0]
const { currencyCode } =
tokenId == null
? account.currencyConfig[pluginId].currencyInfo
: account.currencyConfig[pluginId].allTokens[tokenId]
// Encode data:
const data = btoa(`edgerewards|${publicAddress}|${currencyCode}`)
// Open URL:
await Linking.openURL(`https://edge.app/rewards/?data=${data}`)
break
}
default:
break
}
}