Skip to content
This repository has been archived by the owner on Mar 11, 2024. It is now read-only.

Walletconnect: auto connect #794

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
67 changes: 54 additions & 13 deletions src/contexts/walletconnect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
import { node } from '@alephium/web3'
import SignClient from '@walletconnect/sign-client'
import { EngineTypes, SignClientTypes } from '@walletconnect/types'
import { getSdkError } from '@walletconnect/utils'
import { getChainsFromNamespaces, getSdkError } from '@walletconnect/utils'
import { partition } from 'lodash'
import { usePostHog } from 'posthog-js/react'
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
Expand Down Expand Up @@ -67,13 +67,13 @@ export interface WalletConnectContextProps {
dappTxData?: DappTxData
onSessionRequestError: (event: RequestEvent, error: ReturnType<typeof getSdkError>) => Promise<void>
onSessionRequestSuccess: (event: RequestEvent, result: node.SignResult) => Promise<void>
onSessionDelete: () => void
connectToWalletConnect: (uri: string) => void
requiredChainInfo?: ChainInfo
wcSessionState: WalletConnectSessionState
sessionTopic?: string
onProposalApprove: (topic: string) => void
connectedDAppMetadata?: ProposalEvent['params']['proposer']['metadata']
tryRestoreLastSession: (client: SignClient) => Promise<void>
}

const initialContext: WalletConnectContextProps = {
Expand All @@ -86,9 +86,9 @@ const initialContext: WalletConnectContextProps = {
requiredChainInfo: undefined,
wcSessionState: 'uninitialized',
sessionTopic: undefined,
onSessionDelete: () => null,
onProposalApprove: () => null,
connectedDAppMetadata: undefined
connectedDAppMetadata: undefined,
tryRestoreLastSession: (client: SignClient) => Promise.resolve()
}

const WalletConnectContext = createContext<WalletConnectContextProps>(initialContext)
Expand All @@ -115,6 +115,32 @@ export const WalletConnectContextProvider: FC = ({ children }) => {
const [sessionTopic, setSessionTopic] = useState(initialContext.sessionTopic)
const [connectedDAppMetadata, setConnectedDappMetadata] = useState(initialContext.connectedDAppMetadata)

const resetSession = useCallback(() => {
setRequiredChainInfo(undefined)
setProposalEvent(undefined)
setWcSessionState('uninitialized')
setSessionTopic(undefined)
}, [])

const tryRestoreLastSession = useCallback(
async (client: SignClient) => {
if (!client.session.length) return resetSession()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to myself: When checking for active sessions, we should probably first cross-reference them with the active pairings. See: https://github.com/alephium/mobile-wallet/blob/master/src/utils/walletConnect.ts#L50-L58

const lastKeyIndex = client.session.keys.length - 1
const session = client.session.get(client.session.keys[lastKeyIndex])
const chains = getChainsFromNamespaces(session.namespaces, [PROVIDER_NAMESPACE])
if (!chains.length) {
await client.disconnect({ topic: session.topic, reason: getSdkError('USER_DISCONNECTED') })
return resetSession()
}
const chainInfo = parseChain(chains[0])
setRequiredChainInfo(chainInfo)
setConnectedDappMetadata(session.peer.metadata)
setSessionTopic(session.topic)
setWcSessionState('initialized')
},
[resetSession]
)

const initializeWalletConnectClient = useCallback(async () => {
try {
const client = await SignClient.init({
Expand All @@ -128,12 +154,13 @@ export const WalletConnectContextProvider: FC = ({ children }) => {
}
})

await tryRestoreLastSession(client)
setWalletConnectClient(client)
} catch (e) {
posthog.capture('Error', { message: 'Could not initialize WalletConnect client' })
console.error('Could not initialize WalletConnect client', e)
}
}, [posthog])
}, [posthog, tryRestoreLastSession])

useEffect(() => {
if (!walletConnectClient) initializeWalletConnectClient()
Expand Down Expand Up @@ -338,12 +365,14 @@ export const WalletConnectContextProvider: FC = ({ children }) => {
[dispatch, t, walletConnectClient]
)

const onSessionDelete = useCallback(() => {
setRequiredChainInfo(undefined)
setProposalEvent(undefined)
setWcSessionState('uninitialized')
setSessionTopic(undefined)
}, [])
const onSessionDelete = useCallback(
(params: { topic: string }) => {
if (params.topic === sessionTopic) {
resetSession()
}
},
[sessionTopic, resetSession]
)

const onProposalApprove = (topic: string) => {
setSessionTopic(topic)
Expand Down Expand Up @@ -385,6 +414,18 @@ export const WalletConnectContextProvider: FC = ({ children }) => {
}
}, [connectToWalletConnect, onSessionDelete, onSessionProposal, onSessionRequest, walletConnectClient])

useEffect(() => {
if (wcSessionState !== 'initialized' || !walletConnectClient || !sessionTopic) return

if (walletConnectClient.session.length > 0) {
walletConnectClient.session.getAll().forEach((session) => {
if (session.topic !== sessionTopic) {
walletConnectClient.disconnect({ topic: session.topic, reason: getSdkError('USER_DISCONNECTED') })
}
})
}
}, [wcSessionState, walletConnectClient, sessionTopic])

return (
<WalletConnectContext.Provider
value={{
Expand All @@ -397,10 +438,10 @@ export const WalletConnectContextProvider: FC = ({ children }) => {
connectToWalletConnect,
requiredChainInfo,
wcSessionState,
onSessionDelete,
sessionTopic,
onProposalApprove,
connectedDAppMetadata
connectedDAppMetadata,
tryRestoreLastSession
}}
>
{children}
Expand Down
12 changes: 6 additions & 6 deletions src/modals/WalletConnectModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const WalletConnectModal = ({ onClose }: WalletConnectModalProps) => {
proposalEvent,
sessionTopic,
onProposalApprove,
onSessionDelete,
tryRestoreLastSession,
connectedDAppMetadata
} = useWalletConnectContext()
const addresses = useAppSelector(selectAllAddresses)
Expand All @@ -90,7 +90,7 @@ const WalletConnectModal = ({ onClose }: WalletConnectModalProps) => {

const handleApprove = async () => {
if (!walletConnectClient || !signerAddress) return
if (proposalEvent === undefined) return onSessionDelete()
if (proposalEvent === undefined) return await tryRestoreLastSession(walletConnectClient)

const { id, requiredNamespaces, relays } = proposalEvent.params
const requiredNamespace = requiredNamespaces[PROVIDER_NAMESPACE]
Expand Down Expand Up @@ -158,10 +158,10 @@ const WalletConnectModal = ({ onClose }: WalletConnectModalProps) => {

const handleReject = async () => {
if (!walletConnectClient) return
if (proposalEvent === undefined) return onSessionDelete()
if (proposalEvent === undefined) return await tryRestoreLastSession(walletConnectClient)

await walletConnectClient.reject({ id: proposalEvent.id, reason: getSdkError('USER_REJECTED') })
onSessionDelete()
await tryRestoreLastSession(walletConnectClient)
onClose()

posthog.capture('Rejected WalletConnect connection by clicking "Reject"')
Expand All @@ -174,14 +174,14 @@ const WalletConnectModal = ({ onClose }: WalletConnectModalProps) => {

await walletConnectClient.disconnect({ topic: sessionTopic, reason: getSdkError('USER_DISCONNECTED') })
onClose()
onSessionDelete()
await tryRestoreLastSession(walletConnectClient)

posthog.capture('Clicked WalletConnect disconnect button')
}

const rejectConnectionAndCloseModal = async () => {
if (walletConnectClient && proposalEvent) {
onSessionDelete()
await tryRestoreLastSession(walletConnectClient)
await walletConnectClient.reject({ id: proposalEvent.id, reason: getSdkError('USER_REJECTED') })
}

Expand Down