Skip to content

Commit

Permalink
update web wallet poc
Browse files Browse the repository at this point in the history
  • Loading branch information
skibitsky committed Dec 20, 2024
1 parent 8b37ee1 commit c789675
Show file tree
Hide file tree
Showing 14 changed files with 342 additions and 313 deletions.
Original file line number Diff line number Diff line change
@@ -1,111 +1,94 @@
import { W3mFrameProvider } from "@reown/appkit-wallet"
import { Provider, useAppKitAccount, useAppKitProvider } from '@reown/appkit/react'
import { Provider, useAppKit, useAppKitAccount, useAppKitProvider, useAppKitState } from '@reown/appkit/react'

import { useCallback, useEffect } from "react"
import { walletKit } from '@/utils/WalletConnectUtil'
import ModalStore from "@/store/ModalStore"
import { useRouter } from "next/router"

export default function useAppKitProviderEventsManager() {
const { walletProvider } = useAppKitProvider<W3mFrameProvider>('eip155')
const { address, isConnected, caipAddress, status } = useAppKitAccount()

const onConnect = useCallback(async () => {
console.log('onConnect')



await new Promise(resolve => setTimeout(resolve, 1000))

let pendingSessionProposals = Object.values(await walletKit.getPendingSessionProposals())
let pendingSessionRequests = await walletKit.getPendingSessionRequests()

console.log('pendingSessionProposals', pendingSessionProposals)
console.log('pendingSessionRequests', pendingSessionRequests)

// get pending session proposals from local storage
const pendingSessionProposal = localStorage.getItem('pendingSessionProposal')
console.log('pendingSessionProposal', pendingSessionProposal)



if (pendingSessionProposal) {
const proposal = JSON.parse(pendingSessionProposal)

console.log('opening session proposal modal', proposal)
ModalStore.open('SessionProposalModal', { proposal })
} else {
const latestProposal = pendingSessionProposals[pendingSessionProposals.length - 1]
ModalStore.open('SessionProposalModal', {
proposal: {
id: latestProposal.id,
params: latestProposal,
verifyContext: {
verified: {
isScam: false,
origin: '',
validation: 'VALID',
verifyUrl: ''
}
}
}
})
const router = useRouter()
const { open } = useAppKitState()
const { walletProvider } = useAppKitProvider<W3mFrameProvider>('eip155')
const { address, isConnected, caipAddress, status } = useAppKitAccount()
const appkit= useAppKit()

useEffect(() => {
if (open) {
console.log('closing modal because open is true')
ModalStore.close()
}
}, [open])


const onConnect = useCallback(async () => {
console.log('onConnect')

const uri = router.query.uri as string

if (uri) {
console.log('pairing with uri', uri)
try {
await walletKit.pair({ uri })
} catch (error) {
console.error('pairing error', error)
}
}
}, [walletKit])

const handleSetPreferredAccount = async (account: any) => {
console.log('onSetPreferredAccount', account.address)

const {chainId} = await walletProvider.getChainId();

const caip10Address = `eip155:${chainId}:${account.address}`

const sessions = Object.values(walletKit.getActiveSessions())
console.log('sessions', sessions)

sessions.forEach(async session => {
const currentAccounts = session.namespaces.eip155.accounts;
const updatedAccounts = [
caip10Address,
...currentAccounts.filter(acc => acc !== caip10Address)
];

console.log('accounts', currentAccounts, updatedAccounts)

await walletKit.updateSession({
topic: session.topic,
namespaces: {
...session.namespaces,
eip155: {
...session.namespaces.eip155,
accounts: updatedAccounts
}
}
})
})
}


// await new Promise(resolve => setTimeout(resolve, 5000))

// pendingSessionProposals = Object.values(await walletKit.getPendingSessionProposals())
// pendingSessionRequests = await walletKit.getPendingSessionRequests()

// console.log('pendingSessionProposals 2', pendingSessionProposals)
// console.log('pendingSessionRequests 2', pendingSessionRequests)

// if (pendingSessionProposals.length > 0) {
// const latestProposal = pendingSessionProposals[pendingSessionProposals.length - 1]
// console.log('latestProposal', latestProposal)

// // this is a hack to get the proposal to the modal
// // walletkit doesn't include the verifyContext in the pendinng proposal object
// // a better workaround is to manually store verifyContext in the local storage when session_proposal event is received
// ModalStore.open('SessionProposalModal', {
// proposal: {
// id: latestProposal.id,
// params: latestProposal,
// verifyContext: {
// verified: {
// isScam: false,
// origin: '',
// validation: 'VALID',
// verifyUrl: ''
// }
// }
// }
// })
// } else if (pendingSessionRequests.length > 0) {
// const latestRequest = pendingSessionRequests[pendingSessionRequests.length - 1]

// try {
// console.log('resolving request', latestRequest)
// const response = await walletProvider.request(latestRequest as any)
// } catch (e) {
// console.error('error', e)
// }
// }

}, [walletProvider])


useEffect(() => {
console.log('appkit hook', isConnected, walletProvider)
if (!isConnected || !walletProvider) {
return
}
useEffect(() => {
if (status === 'reconnecting' || status === 'connecting' || status === undefined) {
ModalStore.open('AppKitConnectionModal', undefined)
return
}

if (status === 'disconnected') {
appkit.open()
return
}

if (isConnected) {
onConnect()
}
if (walletProvider) {
ModalStore.close()
appkit.close()

onConnect()
// walletProvider.onConnect(onConnect)

walletProvider.onConnect(onConnect)
walletProvider.onSetPreferredAccount(handleSetPreferredAccount)
}

}, [isConnected, walletProvider])
}, [isConnected, walletProvider, status])
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,73 +12,21 @@ import type { W3mFrameProvider, W3mFrameTypes } from '@reown/appkit-wallet';


export default function useWalletConnectEventsManager(initialized: boolean) {
const { address, isConnected, caipAddress, status } = useAppKitAccount()
const { walletProvider } = useAppKitProvider<W3mFrameProvider>('eip155')

useEffect(() => {
if (!walletProvider) return

console.log('walletProvider', walletProvider)

walletProvider.onSetPreferredAccount(async (account) => {
console.log('onSetPreferredAccount', account.address)

const {chainId} = await walletProvider.getChainId();
const chainIdString = chainId.toString()
console

const sessions = walletKit.getActiveSessions()
console.log('sessions', sessions)

Object.values(sessions).forEach(async session => {
await walletKit.updateSession({
topic: session.topic,
namespaces: {
...session.namespaces,
eip155: {
...session.namespaces.eip155,
accounts: [`eip155:1:${account.address}`]
}
}
})
})
})

}, [walletProvider])


/******************************************************************************
* 1. Open session proposal modal for confirmation / rejection
*****************************************************************************/
const onSessionProposal = useCallback(
async (proposal: SignClientTypes.EventArguments['session_proposal']) => {
console.log('session_proposal', proposal)


if (!isConnected || !walletProvider) {


await new Promise(resolve => setTimeout(resolve, 1000))

// save proposal in local storage
// localStorage.setItem('pendingSessionProposal', JSON.stringify(proposal))
let pendingSessionProposals = Object.values(await walletKit.getPendingSessionProposals())

console.log('pendingSessionProposals before appkit', pendingSessionProposals)



console.log('onSessionProposal - opening connection modal', isConnected, walletProvider)
ModalStore.open('AppKitConnectionModal', undefined)
return;
}
console.log('useWalletConnectEventsManager: session_proposal', proposal)

// set the verify context so it can be displayed in the projectInfoCard
SettingsStore.setCurrentRequestVerifyContext(proposal.verifyContext)
console.log('Session Proposal - Opening modal', proposal)
ModalStore.open('SessionProposalModal', { proposal })
},
[walletKit, walletProvider]
[walletKit]
)
/******************************************************************************
* 2. Open Auth modal for confirmation / rejection
Expand All @@ -93,34 +41,33 @@ export default function useWalletConnectEventsManager(initialized: boolean) {
*****************************************************************************/
const onSessionRequest = useCallback(
async (requestEvent: SignClientTypes.EventArguments['session_request']) => {
console.log('onSessionRequest', requestEvent)
const { topic, params, verifyContext, id } = requestEvent
const { request } = params
const { request, chainId: requestChainId } = params
const requestSession = walletKit.engine.signClient.session.get(topic)

if (!walletProvider) {
console.log('AppKit wallet provider is not ready. Rejecting request.')
return;
}

// set the verify context so it can be displayed in the projectInfoCard
SettingsStore.setCurrentRequestVerifyContext(verifyContext)
console.log('requestEvent', requestEvent, walletProvider)

if (!walletProvider)
return;
// if (!walletProvider) {
// console.log('AppKit wallet provider is not ready. Rejecting request.')
// const response = {
// id,
// jsonrpc: '2.0',
// error: {
// code: 5000,
// message: 'User rejected. AppKit wallet provider is not ready.'
// }
// }
// await walletKit.respondSessionRequest({
// topic,
// response
// })
// console.log('rejected')
// return
// }
const { chainId: activeEthChainId } = await walletProvider.getChainId()

const activeChainId = `eip155:${activeEthChainId}`

if (requestChainId !== activeChainId) {
ModalStore.open('LoadingModal', {loadingMessage: 'Switching network...'})
await walletProvider.switchNetwork(requestChainId)
ModalStore.close()
}

try {
console.log('resolving request', requestEvent)
// request.params.chainId = requestChainId.split(':')[1]
console.log('resolving request', request)
const response = await walletProvider.request(request as any)
console.log('response', response)
await walletKit.respondSessionRequest({
Expand Down Expand Up @@ -152,13 +99,11 @@ export default function useWalletConnectEventsManager(initialized: boolean) {
useEffect(() => {
if (initialized && walletKit) {

window['walletkit'] = walletKit


//window['walletKit'] = walletKit
console.log('setting up walletconnect event listeners')
//sign
walletKit.on('session_proposal', onSessionProposal)
walletKit.on('session_request', onSessionRequest)
walletKit.on('session_request', () => console.log('session_request!'))
// auth
// walletKit.on('session_authenticate', onAuthRequest)
// TODOs
Expand All @@ -171,5 +116,5 @@ export default function useWalletConnectEventsManager(initialized: boolean) {
// load sessions on init
SettingsStore.setSessions(Object.values(walletKit.getActiveSessions()))
}
}, [initialized, onAuthRequest, onSessionProposal, onSessionRequest, onSessionAuthenticate])
}, [initialized, walletKit, onAuthRequest, onSessionProposal, onSessionRequest, onSessionAuthenticate])
}
18 changes: 11 additions & 7 deletions advanced/wallets/reown-web-wallet/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,35 @@ import '../../public/main.css'
import { styledToast } from '@/utils/HelperUtil'
import { createAppKit } from '@reown/appkit/react'
import { EthersAdapter } from '@reown/appkit-adapter-ethers'
import { EIP155_CHAINS } from '@/data/EIP155Data'
import { mainnet, polygon, arbitrum, base, optimism} from '@reown/appkit/networks'
import { mainnet, polygon, optimism, avalanche} from '@reown/appkit/networks'
import useAppKitProviderEventsManager from '@/hooks/useAppKitProviderEventsManager'


const ethersAdapter = new EthersAdapter()

const metadata = {
name: 'Reown Web Wallet',
description: 'Reown Web Wallet',
url: 'https://web-wallet.reown.com',
url: 'reown-web-wallet.vercel.app',
icons: ['https://avatars.githubusercontent.com/u/37784886'],
redirect: {
native: typeof window !== 'undefined' ? window.location.origin : undefined
}
}

const modal = createAppKit({
adapters: [ethersAdapter],
networks: [mainnet, polygon, arbitrum, base, optimism],
networks: [mainnet, polygon, optimism, avalanche],
defaultNetwork: mainnet,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID as string,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID as string,
features: {
analytics: true
analytics: true,
emailShowWallets: false,
},
allWallets: 'HIDE',
metadata
})


export default function App({ Component, pageProps }: AppProps) {
// Step 1 - Initialize wallets and wallet connect client
const initialized = useInitialization()
Expand Down
Loading

0 comments on commit c789675

Please sign in to comment.