Skip to content

Commit

Permalink
US-2032 RIF Wallet - WalletConnect sessions are not being deleted (#848)
Browse files Browse the repository at this point in the history
* fix: got rid of WC error when disconnecting session

* refactor: change _web3wallet to usersWallet
  • Loading branch information
TravellerOnTheRun authored Jan 10, 2024
1 parent 4780e56 commit 65ad5e2
Showing 1 changed file with 82 additions and 69 deletions.
151 changes: 82 additions & 69 deletions src/screens/walletConnect/WalletConnect2Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,21 +112,22 @@ export const WalletConnect2Provider = ({
children,
wallet,
}: WalletConnect2ProviderProps) => {
const dispatch = useAppDispatch()
const chainId = useAppSelector(selectChainId)
const [sessions, setSessions] = useState<SessionStruct[]>([])
const [pendingSession, setPendingSession] = useState<
PendingSession | undefined
>(undefined)
const [error, setError] = useState<WalletConnect2ContextArguments['error']>()
const dispatch = useAppDispatch()
const [web3wallet, setWeb3Wallet] = useState<Web3Wallet | null>(null)

const onSessionProposal = async (
proposal: Web3WalletTypes.SessionProposal,
web3wallet: Web3Wallet,
usersWallet: Web3Wallet,
) => {
const hasErrors = getProposalErrorComparedWithRskNamespace(proposal)
if (hasErrors) {
await onSessionReject(web3wallet, proposal, hasErrors)
await onSessionReject(usersWallet, proposal, hasErrors)
setError({
title: 'dapps_session_rejected',
message: 'dapps_requirements_not_met',
Expand All @@ -136,18 +137,18 @@ export const WalletConnect2Provider = ({
// So that when the user confirms/rejects the session (done in WalletConnectScreen)
// then it'll use this session accordingly
setPendingSession({
web3wallet,
web3wallet: usersWallet,
proposal,
})
}
}

const subscribeToEvents = useCallback(
(web3wallet: Web3Wallet) => {
web3wallet.on('session_proposal', async proposal =>
onSessionProposal(proposal, web3wallet),
(usersWallet: Web3Wallet) => {
usersWallet.on('session_proposal', async proposal =>
onSessionProposal(proposal, usersWallet),
)
web3wallet.on('session_request', async event => {
usersWallet.on('session_request', async event => {
if (!wallet) {
return
}
Expand Down Expand Up @@ -206,7 +207,7 @@ export const WalletConnect2Provider = ({
dispatch(addPendingTransaction(pendingTx))
}
}
web3wallet.respondSessionRequest({
usersWallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
Expand All @@ -215,7 +216,7 @@ export const WalletConnect2Provider = ({
})
})
.catch(_ => {
web3wallet.respondSessionRequest({
usersWallet.respondSessionRequest({
...rpcResponse,
response: {
...rpcResponse.response,
Expand All @@ -224,7 +225,7 @@ export const WalletConnect2Provider = ({
})
})
})
web3wallet.on('session_delete', async event => {
usersWallet.on('session_delete', async event => {
setSessions(prevSessions =>
prevSessions.filter(prevSession => prevSession.topic !== event.topic),
)
Expand All @@ -233,49 +234,53 @@ export const WalletConnect2Provider = ({
[chainId, dispatch, wallet],
)

const onCreateNewSession = async (uri: string) => {
try {
const web3wallet = await createWeb3Wallet()
subscribeToEvents(web3wallet)
// Refer to https://docs.walletconnect.com/2.0/reactnative/web3wallet/wallet-usage#session-requests
const onCreateNewSession = useCallback(
async (uri: string) => {
if (web3wallet) {
try {
subscribeToEvents(web3wallet)
// Refer to https://docs.walletconnect.com/2.0/reactnative/web3wallet/wallet-usage#session-requests

if (!isWcUriValid(uri)) {
setError({
title: 'dapps_uri_not_valid_title',
message: 'dapps_uri_not_valid_message',
})
} else {
await web3wallet.core.pairing.pair({ uri })
}
} catch (e) {
// This will handle: "Pairing already exists:"
if (e instanceof Error || typeof e === 'string') {
if (e.toString().includes('already exists')) {
setError({
title: 'dapps_error_pairing_title',
message: 'dapps_error_pairing_message',
})
// NOTE: Left this logic here in case we need it in the future
// User tried to use an OLD QR - try to connect
// const proposals = web3wallet.getPendingSessionProposals()
// If there are pending proposals, use the last one to connect
// if (Array.isArray(proposals) && proposals.length > 0) {
// const lastProposal = proposals.pop()//
// onSessionProposal(
// {
// ...lastProposal,
// params: { requiredNamespaces: lastProposal.requiredNamespaces },
// },
// web3wallet,
// )
// } else {
// // else disconnect the current pairing
// web3wallet.core.pairing.disconnect(parseUri(uri))
// }
if (!isWcUriValid(uri)) {
setError({
title: 'dapps_uri_not_valid_title',
message: 'dapps_uri_not_valid_message',
})
} else {
await web3wallet.core.pairing.pair({ uri })
}
} catch (e) {
// This will handle: "Pairing already exists:"
if (e instanceof Error || typeof e === 'string') {
if (e.toString().includes('already exists')) {
setError({
title: 'dapps_error_pairing_title',
message: 'dapps_error_pairing_message',
})
// NOTE: Left this logic here in case we need it in the future
// User tried to use an OLD QR - try to connect
// const proposals = web3wallet.getPendingSessionProposals()
// If there are pending proposals, use the last one to connect
// if (Array.isArray(proposals) && proposals.length > 0) {
// const lastProposal = proposals.pop()//
// onSessionProposal(
// {
// ...lastProposal,
// params: { requiredNamespaces: lastProposal.requiredNamespaces },
// },
// web3wallet,
// )
// } else {
// // else disconnect the current pairing
// web3wallet.core.pairing.disconnect(parseUri(uri))
// }
}
}
}
}
}
}
},
[subscribeToEvents, web3wallet],
)

const onUserApprovedSession = async () => {
if (pendingSession && wallet) {
Expand All @@ -302,26 +307,34 @@ export const WalletConnect2Provider = ({
}
}

const onDisconnectSession = async (session: SessionStruct) => {
try {
const web3wallet = await createWeb3Wallet()
await web3wallet.disconnectSession({
topic: session.topic,
reason: getSdkError('USER_DISCONNECTED'),
})
setSessions(prevSessions =>
prevSessions.filter(prevSession => prevSession.topic !== session.topic),
)
} catch (err) {
// @TODO handle error disconnecting
console.log('WC2.0 error disconnect', err)
}
}
const onDisconnectSession = useCallback(
async (session: SessionStruct) => {
if (web3wallet) {
try {
await web3wallet.disconnectSession({
topic: session.topic,
reason: getSdkError('USER_DISCONNECTED'),
})
setSessions(prevSessions =>
prevSessions.filter(
prevSession => prevSession.topic !== session.topic,
),
)
} catch (err) {
// @TODO handle error disconnecting
console.log('WC2.0 error disconnect', err)
}
}
},
[web3wallet],
)

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

/**
Expand Down

0 comments on commit 65ad5e2

Please sign in to comment.