Skip to content

Commit

Permalink
fix: wc sessions are being pulled from the same storage, even for dif…
Browse files Browse the repository at this point in the history
…ferent address
  • Loading branch information
TravellerOnTheRun committed Feb 29, 2024
1 parent 01a4449 commit fb3b814
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 29 deletions.
59 changes: 33 additions & 26 deletions src/screens/walletConnect/WalletConnect2Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { IWeb3Wallet } from '@walletconnect/web3wallet'
import { WalletConnectAdapter } from '@rsksmart/rif-wallet-adapters'

import { ChainID } from 'lib/eoaWallet'
import { createPendingTxFromTxResponse } from 'lib/utils'

import {
buildRskAllowedNamespaces,
Expand All @@ -21,7 +22,8 @@ import {
import { useAppDispatch, useAppSelector } from 'store/storeUtils'
import { selectChainId } from 'store/slices/settingsSlice'
import { addPendingTransaction } from 'store/slices/transactionsSlice'
import { createPendingTxFromTxResponse } from 'src/lib/utils'
import { Wallet } from 'shared/wallet'
import { addressToUse } from 'shared/hooks'

const onSessionApprove = async (
web3wallet: Web3Wallet,
Expand Down Expand Up @@ -112,6 +114,7 @@ export const WalletConnect2Provider = ({
children,
wallet,
}: WalletConnect2ProviderProps) => {
const address = wallet ? addressToUse(wallet) : null
const dispatch = useAppDispatch()
const chainId = useAppSelector(selectChainId)
const [sessions, setSessions] = useState<SessionStruct[]>([])
Expand All @@ -125,6 +128,8 @@ export const WalletConnect2Provider = ({
proposal: Web3WalletTypes.SessionProposal,
usersWallet: Web3Wallet,
) => {
console.log('onSessionProposal', proposal)

const hasErrors = getProposalErrorComparedWithRskNamespace(proposal)
if (hasErrors) {
await onSessionReject(usersWallet, proposal, hasErrors)
Expand All @@ -144,15 +149,15 @@ export const WalletConnect2Provider = ({
}

const subscribeToEvents = useCallback(
(usersWallet: Web3Wallet) => {
(usersWallet: Web3Wallet, _wallet: Wallet) => {
usersWallet.on('session_proposal', async proposal =>
onSessionProposal(proposal, usersWallet),
)
usersWallet.on('session_request', async event => {
if (!wallet) {
if (!_wallet) {
return
}
const adapter = new WalletConnectAdapter(wallet)
const adapter = new WalletConnectAdapter(_wallet)
const eth_signTypedDataResolver = adapter
.getResolvers()
.find(
Expand All @@ -163,12 +168,7 @@ export const WalletConnect2Provider = ({
eth_signTypedDataResolver.validate = ({ domain }) => {
// if address = relay address - throw error
const { verifyingContract } = domain
if (
[
wallet.smartWalletAddress.toLowerCase(),
wallet.rifRelaySdk.smartWalletFactory.address.toLowerCase(),
].includes(verifyingContract.toLowerCase())
) {
if ([address].includes(verifyingContract.toLowerCase())) {
throw new Error(
'Error: Unauthorized Contract Address - Signing not permitted. This address is exclusive to the relay contract.',
)
Expand All @@ -194,12 +194,12 @@ export const WalletConnect2Provider = ({
adapter
.handleCall(method, params)
.then(async signedMessage => {
if (method === 'eth_sendTransaction') {
if (method === 'eth_sendTransaction' && address) {
const pendingTx = await createPendingTxFromTxResponse(
signedMessage,
{
chainId,
from: wallet.smartWalletAddress,
from: address,
to: params[0].to,
},
)
Expand Down Expand Up @@ -231,14 +231,14 @@ export const WalletConnect2Provider = ({
)
})
},
[chainId, dispatch, wallet],
[chainId, dispatch, address],
)

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

if (!isWcUriValid(uri)) {
Expand Down Expand Up @@ -279,15 +279,15 @@ export const WalletConnect2Provider = ({
}
}
},
[subscribeToEvents, web3wallet],
[subscribeToEvents, web3wallet, wallet],
)

const onUserApprovedSession = async () => {
if (pendingSession && wallet) {
if (pendingSession && address) {
const newSession = await onSessionApprove(
pendingSession.web3wallet,
pendingSession.proposal,
wallet.smartWalletAddress,
address,
chainId,
)
if (typeof newSession === 'string') {
Expand Down Expand Up @@ -338,20 +338,27 @@ export const WalletConnect2Provider = ({
[web3wallet],
)

const onContextFirstLoad = useCallback(async () => {
console.log('onContextFirstLoad')
const newWeb3Wallet = await createWeb3Wallet()
setWeb3Wallet(newWeb3Wallet)
subscribeToEvents(newWeb3Wallet)
setSessions(Object.values(newWeb3Wallet.getActiveSessions()))
}, [subscribeToEvents])
const onContextFirstLoad = useCallback(
async (_wallet: Wallet) => {
try {
console.log('onContextFirstLoad')
const newWeb3Wallet = await createWeb3Wallet(_wallet.address)
setWeb3Wallet(newWeb3Wallet)
subscribeToEvents(newWeb3Wallet, _wallet)
setSessions(Object.values(newWeb3Wallet.getActiveSessions()))
} catch (err) {
throw new Error(err)
}
},
[subscribeToEvents],
)

/**
* useEffect On first load, fetch previous saved sessions
*/
useEffect(() => {
if (wallet) {
onContextFirstLoad().catch(console.log)
onContextFirstLoad(wallet).catch(console.log)
}
}, [wallet, onContextFirstLoad])

Expand Down
10 changes: 7 additions & 3 deletions src/screens/walletConnect/walletConnect2.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ const WalletConnect2SdkErrorEnum: { [P in WalletConnect2SdkErrorString]: P } = {
type StorageTypeFromCore = InstanceType<typeof Core>['storage']

class MMKVCoreStorage implements StorageTypeFromCore {
storage = new MMKVStorage('WC2')
storage: MMKVStorage

constructor(storageKey: string) {
this.storage = new MMKVStorage(storageKey)
}

getEntries<T = never>(): Promise<[string, T][]> {
const keys = this.storage.getAllKeys()
Expand Down Expand Up @@ -67,11 +71,11 @@ class MMKVCoreStorage implements StorageTypeFromCore {
}
}

export const createWeb3Wallet = async () => {
export const createWeb3Wallet = async (storageKey: string) => {
const projectId = getEnvSetting(SETTINGS.WALLETCONNECT2_PROJECT_ID) // this should change if we need to vary from testnet/mainnet by using getWalletSetting
const core = new Core({
projectId,
storage: new MMKVCoreStorage(),
storage: new MMKVCoreStorage(storageKey),
// logger: 'info', // info on this: https://github.com/pinojs/pino/blob/master/docs/api.md#levels
})

Expand Down

0 comments on commit fb3b814

Please sign in to comment.