Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

US-1933: Fix wallet only receives requests from the dapp after opening the dapps screen. #743

Merged
merged 1 commit into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 30 additions & 16 deletions src/core/Core.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useCallback, useEffect } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { StatusBar, View } from 'react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import {
createNavigationContainerRef,
NavigationContainer,
} from '@react-navigation/native'
import { RIFWallet } from '@rsksmart/rif-wallet-core'

import {
RootNavigationComponent,
Expand All @@ -21,6 +22,7 @@ import {
unlockApp,
} from 'store/slices/settingsSlice'
import { sharedStyles } from 'shared/constants'
import { WalletConnect2Provider } from 'src/screens/walletConnect/WalletConnect2Context'

import { useStateSubscription } from './hooks/useStateSubscription'
import { Cover } from './components/Cover'
Expand All @@ -31,13 +33,12 @@ export const navigationContainerRef =

export const Core = () => {
const dispatch = useAppDispatch()

const settings = useAppSelector(selectWholeSettingsState)
const requests = useAppSelector(selectRequests)
const topColor = useAppSelector(selectTopColor)
const isOffline = useIsOffline()

const { unlocked, active } = useStateSubscription()
const [wallet, setWallet] = useState<RIFWallet | null>(null)

const unlockAppFn = useCallback(async () => {
try {
Expand All @@ -51,25 +52,38 @@ export const Core = () => {
unlockAppFn()
}, [unlockAppFn])

/**
* Obs: calling selectWalletState will throw an error since the wallet is not yet ready.
* So we need to retrieve the wallet from the settings state.
*/
useEffect(() => {
const { wallets, walletsIsDeployed, selectedWallet } = settings
if (wallets && walletsIsDeployed) {
setWallet(wallets[selectedWallet])
}
}, [settings, wallet])

return (
<SafeAreaProvider>
<View style={sharedStyles.flex}>
<StatusBar backgroundColor={topColor} />
{!active && <Cover />}
<NavigationContainer ref={navigationContainerRef}>
{settings.loading && !unlocked ? (
<LoadingScreen />
) : (
<>
<RootNavigationComponent />
{requests.length !== 0 && (
<RequestHandler
request={requests[0]}
closeRequest={() => dispatch(closeRequest())}
/>
)}
</>
)}
<WalletConnect2Provider wallet={wallet}>
{settings.loading && !unlocked ? (
<LoadingScreen />
) : (
<>
<RootNavigationComponent />
{requests.length !== 0 && (
<RequestHandler
request={requests[0]}
closeRequest={() => dispatch(closeRequest())}
/>
)}
</>
)}
</WalletConnect2Provider>
</NavigationContainer>
</View>
</SafeAreaProvider>
Expand Down
121 changes: 66 additions & 55 deletions src/screens/walletConnect/WalletConnect2Context.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { createContext, ReactElement, useEffect, useState } from 'react'
import {
createContext,
ReactElement,
useCallback,
useEffect,
useState,
} from 'react'
import { getSdkError, parseUri } from '@walletconnect/utils'
import Web3Wallet, { Web3WalletTypes } from '@walletconnect/web3wallet'
import { IWeb3Wallet } from '@walletconnect/web3wallet'
Expand Down Expand Up @@ -95,7 +101,7 @@ export const WalletConnect2Context =

interface WalletConnect2ProviderProps {
children: ReactElement
wallet: RIFWallet
wallet: RIFWallet | null
}

export const WalletConnect2Provider = ({
Expand Down Expand Up @@ -130,58 +136,61 @@ export const WalletConnect2Provider = ({
}
}

const subscribeToEvents = (web3wallet: Web3Wallet) => {
web3wallet.on('session_proposal', async proposal =>
onSessionProposal(proposal, web3wallet),
)
web3wallet.on('session_request', async event => {
if (!wallet) {
return
}
const adapter = new WalletConnectAdapter(wallet)
const {
params: {
request: { method, params },
},
id,
topic,
} = event

const rpcResponse = {
topic,
response: {
const subscribeToEvents = useCallback(
(web3wallet: Web3Wallet) => {
web3wallet.on('session_proposal', async proposal =>
onSessionProposal(proposal, web3wallet),
)
web3wallet.on('session_request', async event => {
if (!wallet) {
return
}
const adapter = new WalletConnectAdapter(wallet)
const {
params: {
request: { method, params },
},
id,
jsonrpc: '2.0',
},
}
topic,
} = event

const rpcResponse = {
topic,
response: {
id,
jsonrpc: '2.0',
},
}

adapter
.handleCall(method, params)
.then(signedMessage => {
web3wallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
result: signedMessage,
},
adapter
.handleCall(method, params)
.then(signedMessage => {
web3wallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
result: signedMessage,
},
})
})
})
.catch(_ => {
web3wallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
error: getSdkError('USER_REJECTED'),
},
.catch(_ => {
web3wallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
error: getSdkError('USER_REJECTED'),
},
})
})
})
})
web3wallet.on('session_delete', async event => {
setSessions(prevSessions =>
prevSessions.filter(prevSession => prevSession.topic !== event.topic),
)
})
}
})
web3wallet.on('session_delete', async event => {
setSessions(prevSessions =>
prevSessions.filter(prevSession => prevSession.topic !== event.topic),
)
})
},
[wallet],
)

const onCreateNewSession = async (uri: string) => {
try {
Expand Down Expand Up @@ -267,18 +276,20 @@ export const WalletConnect2Provider = ({
}
}

const onContextFirstLoad = async () => {
const onContextFirstLoad = useCallback(async () => {
const web3wallet = await createWeb3Wallet()
subscribeToEvents(web3wallet)
setSessions(Object.values(web3wallet.getActiveSessions()))
}
}, [subscribeToEvents])

/**
* useEffect On first load, fetch previous saved sessions
*/
useEffect(() => {
onContextFirstLoad().catch(console.log)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
if (wallet) {
onContextFirstLoad().catch(console.log)
}
}, [onContextFirstLoad, wallet])
return (
<WalletConnect2Context.Provider
value={{
Expand Down