-
Notifications
You must be signed in to change notification settings - Fork 80
/
saga.ts
708 lines (606 loc) · 23 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
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
import { ContractKit } from '@celo/contractkit'
import { appendPath } from '@celo/utils/lib/string'
import { formatJsonRpcError, formatJsonRpcResult, JsonRpcResult } from '@json-rpc-tools/utils'
import { Core } from '@walletconnect/core'
import '@walletconnect/react-native-compat'
import { SessionTypes } from '@walletconnect/types'
import { buildApprovedNamespaces, getSdkError, parseUri } from '@walletconnect/utils'
import { IWeb3Wallet, Web3Wallet, Web3WalletTypes } from '@walletconnect/web3wallet'
import { EventChannel, eventChannel } from 'redux-saga'
import { showMessage } from 'src/alert/actions'
import { WalletConnectEvents } from 'src/analytics/Events'
import { WalletConnect2Properties } from 'src/analytics/Properties'
import { DappRequestOrigin, WalletConnectPairingOrigin } from 'src/analytics/types'
import ValoraAnalytics from 'src/analytics/ValoraAnalytics'
import { walletConnectEnabledSelector } from 'src/app/selectors'
import { getDappRequestOrigin } from 'src/app/utils'
import { APP_NAME, WEB_LINK } from 'src/brandingConfig'
import { WALLET_CONNECT_PROJECT_ID } from 'src/config'
import { activeDappSelector } from 'src/dapps/selectors'
import { ActiveDapp } from 'src/dapps/types'
import i18n from 'src/i18n'
import { isBottomSheetVisible, navigate, navigateBack } from 'src/navigator/NavigationService'
import { Screens } from 'src/navigator/Screens'
import { ensureError } from 'src/utils/ensureError'
import Logger from 'src/utils/Logger'
import { safely } from 'src/utils/safely'
import {
AcceptRequest,
AcceptSession,
Actions,
clientInitialised,
CloseSession,
DenyRequest,
denyRequest,
DenySession,
initialiseClient,
InitialisePairing,
initialisePairing,
removeExpiredSessions,
sessionCreated,
sessionDeleted,
SessionPayload,
sessionPayload,
sessionProposal,
SessionProposal,
WalletConnectActions,
} from 'src/walletConnect/actions'
import {
getDefaultRequestTrackedProperties,
getDefaultSessionTrackedProperties as getDefaultSessionTrackedPropertiesAnalytics,
} from 'src/walletConnect/analytics'
import { isSupportedAction, SupportedActions, SupportedEvents } from 'src/walletConnect/constants'
import { handleRequest } from 'src/walletConnect/request'
import {
selectHasPendingState,
selectPendingActions,
selectSessions,
} from 'src/walletConnect/selectors'
import { WalletConnectRequestType } from 'src/walletConnect/types'
import { getContractKit } from 'src/web3/contracts'
import networkConfig from 'src/web3/networkConfig'
import { getWalletAddress } from 'src/web3/saga'
import {
call,
delay,
put,
race,
select,
spawn,
take,
takeEvery,
takeLeading,
} from 'typed-redux-saga'
let client: IWeb3Wallet | null = null
export function _setClientForTesting(newClient: IWeb3Wallet | null) {
client = newClient
}
const TAG = 'WalletConnect/saga'
const GET_SESSION_TIMEOUT = 10_000
export function* getDefaultSessionTrackedProperties(
session: Web3WalletTypes.EventArguments['session_proposal'] | SessionTypes.Struct
) {
const activeDapp: ActiveDapp | null = yield* select(activeDappSelector)
return getDefaultSessionTrackedPropertiesAnalytics(session, activeDapp)
}
function* handleInitialiseWalletConnect() {
const walletConnectChannel = yield* call(createWalletConnectChannel)
while (true) {
const message: WalletConnectActions = yield* take(walletConnectChannel)
yield* put(message)
}
}
// Though the WC types say `icons` is string[], we've seen buggy clients with no `icons` property
// so to avoid crashing the code depending on this, we fix it here
// Note: this method mutates the session
function applyIconFixIfNeeded(
session: Web3WalletTypes.EventArguments['session_proposal'] | SessionTypes.Struct
) {
const peer = 'params' in session ? session.params.proposer : session.peer
const { icons } = peer?.metadata || {}
if (peer?.metadata && (!Array.isArray(icons) || typeof icons[0] !== 'string' || !icons[0])) {
peer.metadata.icons = []
}
}
// Export for testing
export const _applyIconFixIfNeeded = applyIconFixIfNeeded
function* createWalletConnectChannel() {
if (!client) {
Logger.debug(TAG + '@createWalletConnectChannel', `init start`)
client = yield* call([Web3Wallet, 'init'], {
core: new Core({
projectId: WALLET_CONNECT_PROJECT_ID,
relayUrl: networkConfig.walletConnectEndpoint,
}),
metadata: {
name: APP_NAME,
description: i18n.t('appDescription'),
url: WEB_LINK,
icons: [appendPath(WEB_LINK, 'favicon.ico')],
redirect: {
native: 'celo://wallet/wc',
universal: 'https://valoraapp.com/wc',
},
},
})
Logger.debug(TAG + '@createWalletConnectChannel', `init end`)
yield* put(clientInitialised())
}
return eventChannel((emit) => {
const onSessionProposal = (session: Web3WalletTypes.EventArguments['session_proposal']) => {
applyIconFixIfNeeded(session)
emit(sessionProposal(session))
}
const onSessionDeleted = (session: Web3WalletTypes.EventArguments['session_delete']) => {
emit(sessionDeleted(session))
}
const onSessionRequest = (request: Web3WalletTypes.EventArguments['session_request']) => {
emit(sessionPayload(request))
}
if (!client) {
return () => {
Logger.debug(TAG + '@createWalletConnectChannel', 'missing client clean up')
}
}
client.on('session_proposal', onSessionProposal)
client.on('session_delete', onSessionDeleted)
client.on('session_request', onSessionRequest)
return async () => {
if (!client) {
Logger.debug(TAG + '@createWalletConnectChannel', 'clean up but missing client')
return
}
Logger.debug(TAG + '@createWalletConnectChannel', 'clean up')
client.off('session_proposal', onSessionProposal)
client.off('session_delete', onSessionDeleted)
client.off('session_request', onSessionRequest)
const connections = client.getActiveSessions()
await Promise.all(
Object.keys(connections).map((topic) =>
client!.disconnectSession({ topic, reason: getSdkError('USER_DISCONNECTED') })
)
)
client = null
}
}) as EventChannel<WalletConnectActions>
}
function* handleInitialisePairing({ uri, origin }: InitialisePairing) {
const activeDapp: ActiveDapp | null = yield* select(activeDappSelector)
try {
ValoraAnalytics.track(WalletConnectEvents.wc_pairing_start, {
dappRequestOrigin: getDappRequestOrigin(activeDapp),
origin,
})
if (!client) {
throw new Error('missing client')
}
Logger.debug(TAG + '@handleInitialisePairing', 'pair start')
yield* call([client, 'pair'], { uri })
Logger.debug(TAG + '@handleInitialisePairing', 'pair end')
} catch (err) {
const error = ensureError(err)
Logger.debug(TAG + '@handleInitialisePairing', error.message)
ValoraAnalytics.track(WalletConnectEvents.wc_pairing_error, {
dappRequestOrigin: getDappRequestOrigin(activeDapp),
error: error.message,
})
}
}
/**
* When handling incoming requests (actions or sessions) we need to handle
* them in order. That means if a request comes in, and we already have a
* pending one, ignore it. Once a request is dealt with we handle the new
* requests accordingly.
*/
function* handleIncomingSessionRequest({ session }: SessionProposal) {
const { pending }: { pending: Web3WalletTypes.EventArguments['session_proposal'][] } =
yield* select(selectSessions)
if (pending.length > 1) {
return
}
yield* call(showSessionRequest, session)
}
function* handleIncomingActionRequest({ request }: SessionPayload) {
const pendingActions: Web3WalletTypes.EventArguments['session_request'][] = yield* select(
selectPendingActions
)
if (pendingActions.length > 1) {
return
}
yield* call(showActionRequest, request)
}
function* showSessionRequest(session: Web3WalletTypes.EventArguments['session_proposal']) {
const activeDapp = yield* select(activeDappSelector)
ValoraAnalytics.track(WalletConnectEvents.wc_pairing_success, {
dappRequestOrigin: activeDapp ? DappRequestOrigin.InAppWebView : DappRequestOrigin.External,
})
const defaultSessionTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
ValoraAnalytics.track(WalletConnectEvents.wc_session_propose, {
...defaultSessionTrackedProperties,
})
const address = yield* call(getWalletAddress)
const { requiredNamespaces } = session.params
// Here we approve all required namespaces, but only for EVM chains.
// This is so we don't break existing dapps which don't specify the Celo chain as required.
// As of writing this, Curve, Toucan and Cred Protocol do that.
// We also add the Celo chain to the list of supported chains if it's not already there.
// The goal is to be more flexible and allow the initial connection to succeed, no matter what (EVM) chain is specified.
// If later the dapp actually requests an action on an unsupported chain, we will show an error.
// See SessionRequest and ActionRequest for more details.
const requiredEip155Chains = requiredNamespaces.eip155?.chains ?? []
const supportedEip155Chains = yield* call(getSupportedChains)
const approvedEip155Chains = [
...supportedEip155Chains,
...requiredEip155Chains.filter((chainId) => !supportedEip155Chains.includes(chainId)),
]
// Here we approve all required methods, but only for EVM chains.
// Again, this is to be more flexible and allow the initial connection to succeed.
// If later an unsupported method is requested, we will show an error.
const requiredEip155Methods = requiredNamespaces.eip155?.methods ?? []
const supportedEip155Methods = Object.values(SupportedActions) as string[]
const approvedEip155Methods = [
...supportedEip155Methods,
...requiredEip155Methods.filter((method) => !supportedEip155Methods.includes(method)),
]
// And similar for events
const requiredEip155Events = requiredNamespaces.eip155?.events ?? []
const supportedEip155Events = Object.values(SupportedEvents) as string[]
const approvedEip155Events = [
...supportedEip155Events,
...requiredEip155Events.filter((event) => !supportedEip155Events.includes(event)),
]
let namespacesToApprove: SessionTypes.Namespaces | null = null
try {
// Important: this still throws if the required namespaces don't overlap with the supported ones
namespacesToApprove = buildApprovedNamespaces({
proposal: session.params,
supportedNamespaces: {
eip155: {
chains: approvedEip155Chains,
methods: approvedEip155Methods,
events: approvedEip155Events,
accounts: approvedEip155Chains.map((chain) => `${chain}:${address}`),
},
},
})
} catch (e) {
// Right now the only way this can happen is if the required chain isn't an EVM chain
// since we've approved all EVM chains/methods/events above.
Logger.warn(TAG + '@showSessionRequest', 'Failed to build approved namespaces', e)
}
navigate(Screens.WalletConnectRequest, {
type: WalletConnectRequestType.Session,
pendingSession: session,
namespacesToApprove,
supportedChains: supportedEip155Chains,
version: 2,
})
}
// Export for testing
export const _showSessionRequest = showSessionRequest
function* getSupportedChains() {
const kit: ContractKit = yield* call(getContractKit)
const chainId = yield* call([kit.connection, 'chainId'])
return [`eip155:${chainId}`]
}
function* showActionRequest(request: Web3WalletTypes.EventArguments['session_request']) {
if (!client) {
throw new Error('missing client')
}
if (!isSupportedAction(request.params.request.method)) {
// Directly deny unsupported requests
yield* put(denyRequest(request, getSdkError('WC_METHOD_UNSUPPORTED')))
return
}
const session: SessionTypes.Struct = yield* call(getSessionFromRequest, request)
const defaultSessionTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
ValoraAnalytics.track(WalletConnectEvents.wc_request_propose, {
...defaultSessionTrackedProperties,
...getDefaultRequestTrackedProperties(request),
})
const activeSessions = yield* call([client, 'getActiveSessions'])
const activeSession = activeSessions[session.topic]
if (!activeSession) {
yield* put(denyRequest(request, getSdkError('UNAUTHORIZED_EVENT')))
return
}
const supportedChains = yield* call(getSupportedChains)
navigate(Screens.WalletConnectRequest, {
type: WalletConnectRequestType.Action,
pendingAction: request,
supportedChains,
version: 2,
})
}
function* acceptSession({ session, approvedNamespaces }: AcceptSession) {
const defaultTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
try {
ValoraAnalytics.track(WalletConnectEvents.wc_session_approve_start, defaultTrackedProperties)
if (!client) {
throw new Error('missing client')
}
const { relays, proposer } = session.params
yield* call([client, 'approveSession'], {
id: session.id,
relayProtocol: relays[0].protocol,
namespaces: approvedNamespaces,
})
ValoraAnalytics.track(WalletConnectEvents.wc_session_approve_success, defaultTrackedProperties)
// the Client does not emit any events when a new session value is
// available, so if no matching session could be found we can wait and try again.
const { timedOut, newSession } = yield* race({
timedOut: delay(GET_SESSION_TIMEOUT),
newSession: call(getSessionFromClient, session),
})
if (!newSession || timedOut) {
throw new Error('No corresponding session could not be found on the client')
}
yield* put(sessionCreated(newSession))
yield* call(showWalletConnectionSuccessMessage, proposer.metadata.name)
} catch (err) {
const e = ensureError(err)
Logger.debug(TAG + '@acceptSession', e.message)
ValoraAnalytics.track(WalletConnectEvents.wc_session_approve_error, {
...defaultTrackedProperties,
error: e.message,
})
}
yield* call(handlePendingStateOrNavigateBack)
}
// Export for testing
export const _acceptSession = acceptSession
function* getSessionFromClient(session: Web3WalletTypes.EventArguments['session_proposal']) {
if (!client) {
// should not happen
throw new Error('missing client')
}
let sessionValue: null | SessionTypes.Struct = null
while (!sessionValue) {
const sessions: Record<string, SessionTypes.Struct> = yield* call([client, 'getActiveSessions'])
Object.values(sessions).forEach((entry) => {
if (entry.pairingTopic === session.params.pairingTopic) {
sessionValue = entry
}
})
if (!sessionValue) {
yield* delay(500)
}
}
applyIconFixIfNeeded(sessionValue)
return sessionValue as SessionTypes.Struct
}
function* denySession({ session, reason }: DenySession) {
const defaultSessionTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
const defaultTrackedProperties = {
...defaultSessionTrackedProperties,
rejectReason: reason.message,
}
try {
ValoraAnalytics.track(WalletConnectEvents.wc_session_reject_start, defaultTrackedProperties)
if (!client) {
throw new Error('missing client')
}
yield* call([client, 'rejectSession'], {
id: session.id,
reason,
})
ValoraAnalytics.track(WalletConnectEvents.wc_session_reject_success, defaultTrackedProperties)
} catch (err) {
const e = ensureError(err)
Logger.debug(TAG + '@denySession', e.message)
ValoraAnalytics.track(WalletConnectEvents.wc_session_reject_error, {
...defaultTrackedProperties,
error: e.message,
})
}
yield* call(handlePendingStateOrNavigateBack)
}
function* getSessionFromRequest(request: Web3WalletTypes.EventArguments['session_request']) {
if (!client) {
// should not happen
throw new Error('missing client')
}
// Active Sessions is an object with keys that are uuids
const activeSessions = yield* call([client, 'getActiveSessions'])
const session = activeSessions[request.topic]
if (!session) {
// This should never happen
throw new Error(`Unable to find WalletConnect session matching topic ${request.topic}`)
}
return session
}
function* handleAcceptRequest({ request }: AcceptRequest) {
const session: SessionTypes.Struct = yield* call(getSessionFromRequest, request)
const defaultSessionTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
const defaultTrackedProperties = {
...defaultSessionTrackedProperties,
...getDefaultRequestTrackedProperties(request),
}
try {
ValoraAnalytics.track(WalletConnectEvents.wc_request_accept_start, defaultTrackedProperties)
if (!client) {
throw new Error('Missing client')
}
const { topic, id, params } = request
const activeSessions = yield* call([client, 'getActiveSessions'])
const activeSession = activeSessions[topic]
if (!activeSession) {
throw new Error(`Missing active session for topic ${topic}`)
}
const result = yield* call(handleRequest, { ...params.request })
const response: JsonRpcResult<string> = formatJsonRpcResult(
id,
(params.request.method = typeof result === 'string' ? result : result.raw)
)
yield* call([client, 'respondSessionRequest'], { topic, response })
ValoraAnalytics.track(WalletConnectEvents.wc_request_accept_success, defaultTrackedProperties)
yield* call(showWalletConnectionSuccessMessage, activeSession.peer.metadata.name)
} catch (err) {
const e = ensureError(err)
Logger.debug(TAG + '@acceptRequest', e.message)
ValoraAnalytics.track(WalletConnectEvents.wc_request_accept_error, {
...defaultTrackedProperties,
error: e.message,
})
}
yield* call(handlePendingStateOrNavigateBack)
}
function* handleDenyRequest({ request, reason }: DenyRequest) {
const session: SessionTypes.Struct = yield* call(getSessionFromRequest, request)
const defaultSessionTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
const defaultTrackedProperties = {
...defaultSessionTrackedProperties,
...getDefaultRequestTrackedProperties(request),
denyReason: reason.message,
}
try {
ValoraAnalytics.track(WalletConnectEvents.wc_request_deny_start, defaultTrackedProperties)
if (!client) {
throw new Error('Missing client')
}
const { topic, id } = request
const response = formatJsonRpcError(id, reason.message)
yield* call([client, 'respondSessionRequest'], { topic, response })
ValoraAnalytics.track(WalletConnectEvents.wc_request_deny_success, defaultTrackedProperties)
} catch (err) {
const e = ensureError(err)
Logger.debug(TAG + '@denyRequest', e.message)
ValoraAnalytics.track(WalletConnectEvents.wc_request_deny_error, {
...defaultTrackedProperties,
error: e.message,
})
}
yield* call(handlePendingStateOrNavigateBack)
}
function* closeSession({ session }: CloseSession) {
const defaultTrackedProperties: WalletConnect2Properties = yield* call(
getDefaultSessionTrackedProperties,
session
)
try {
ValoraAnalytics.track(WalletConnectEvents.wc_session_remove_start, defaultTrackedProperties)
if (!client) {
throw new Error('missing client')
}
yield* call([client, 'disconnectSession'], {
topic: session.topic,
reason: getSdkError('USER_DISCONNECTED'),
})
ValoraAnalytics.track(WalletConnectEvents.wc_session_remove_success, defaultTrackedProperties)
} catch (err) {
const e = ensureError(err)
Logger.debug(TAG + '@closeSession', e.message)
ValoraAnalytics.track(WalletConnectEvents.wc_session_remove_error, {
...defaultTrackedProperties,
error: e.message,
})
}
}
function* handlePendingStateOrNavigateBack() {
const hasPendingState: boolean = yield* select(selectHasPendingState)
if (hasPendingState) {
yield* call(handlePendingState)
} else if (yield* call(isBottomSheetVisible, Screens.WalletConnectRequest)) {
navigateBack()
}
}
function* handlePendingState() {
const {
pending: [pendingSession],
}: { pending: Web3WalletTypes.EventArguments['session_proposal'][] } = yield* select(
selectSessions
)
if (pendingSession) {
yield* call(showSessionRequest, pendingSession)
return
}
const [pendingRequest]: Web3WalletTypes.EventArguments['session_request'][] = yield* select(
selectPendingActions
)
if (pendingRequest) {
yield* call(showActionRequest, pendingRequest)
}
}
function* checkPersistedState() {
yield* put(removeExpiredSessions(Date.now() / 1000))
const hasPendingState = yield* select(selectHasPendingState)
if (hasPendingState) {
yield* put(initialiseClient())
yield* take(Actions.CLIENT_INITIALISED)
yield* call(handlePendingState)
return
}
const { sessions }: { sessions: SessionTypes.Struct[] } = yield* select(selectSessions)
if (sessions.length) {
yield* put(initialiseClient())
}
}
export function* walletConnectSaga() {
yield* takeLeading(Actions.INITIALISE_CLIENT, safely(handleInitialiseWalletConnect))
yield* takeEvery(Actions.INITIALISE_PAIRING, safely(handleInitialisePairing))
yield* takeEvery(Actions.CLOSE_SESSION, safely(closeSession))
yield* takeEvery(Actions.SESSION_PROPOSAL, safely(handleIncomingSessionRequest))
yield* takeEvery(Actions.ACCEPT_SESSION, safely(acceptSession))
yield* takeEvery(Actions.DENY_SESSION, safely(denySession))
yield* takeEvery(Actions.SESSION_PAYLOAD, safely(handleIncomingActionRequest))
yield* takeEvery(Actions.ACCEPT_REQUEST, safely(handleAcceptRequest))
yield* takeEvery(Actions.DENY_REQUEST, safely(handleDenyRequest))
yield* spawn(checkPersistedState)
}
export function* initialiseWalletConnectV2(uri: string, origin: WalletConnectPairingOrigin) {
if (!client) {
yield* put(initialiseClient())
yield* take(Actions.CLIENT_INITIALISED)
}
yield* put(initialisePairing(uri, origin))
}
export function* isWalletConnectEnabled(uri: string) {
const { version } = parseUri(uri)
const { v1, v2 }: { v1: boolean; v2: boolean } = yield* select(walletConnectEnabledSelector)
const versionEnabled: { [version: string]: boolean | undefined } = {
'1': v1,
'2': v2,
}
return versionEnabled[version] ?? false
}
export function* initialiseWalletConnect(uri: string, origin: WalletConnectPairingOrigin) {
const walletConnectEnabled = yield* call(isWalletConnectEnabled, uri)
const { version } = parseUri(uri)
if (!walletConnectEnabled) {
Logger.debug('initialiseWalletConnect', `v${version} is disabled, ignoring`)
return
}
switch (version) {
case 2:
yield* call(initialiseWalletConnectV2, uri, origin)
break
case 1:
default:
throw new Error(`Unsupported WalletConnect version '${version}'`)
}
}
export function* showWalletConnectionSuccessMessage(dappName: string) {
const activeDapp = yield* select(activeDappSelector)
const successMessage = activeDapp
? i18n.t('inAppConnectionSuccess', { dappName })
: i18n.t('connectionSuccess', { dappName })
yield* put(showMessage(successMessage))
}