diff --git a/advanced/wallets/reown-web-wallet/src/hooks/useAppKitProviderEventsManager.ts b/advanced/wallets/reown-web-wallet/src/hooks/useAppKitProviderEventsManager.ts index 78b850afb..3fd578516 100644 --- a/advanced/wallets/reown-web-wallet/src/hooks/useAppKitProviderEventsManager.ts +++ b/advanced/wallets/reown-web-wallet/src/hooks/useAppKitProviderEventsManager.ts @@ -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('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('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]) } \ No newline at end of file diff --git a/advanced/wallets/reown-web-wallet/src/hooks/useWalletConnectEventsManager.ts b/advanced/wallets/reown-web-wallet/src/hooks/useWalletConnectEventsManager.ts index 78d0b1335..4bde97196 100644 --- a/advanced/wallets/reown-web-wallet/src/hooks/useWalletConnectEventsManager.ts +++ b/advanced/wallets/reown-web-wallet/src/hooks/useWalletConnectEventsManager.ts @@ -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('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 @@ -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({ @@ -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 @@ -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]) } diff --git a/advanced/wallets/reown-web-wallet/src/pages/_app.tsx b/advanced/wallets/reown-web-wallet/src/pages/_app.tsx index e8d8c0575..e01310271 100644 --- a/advanced/wallets/reown-web-wallet/src/pages/_app.tsx +++ b/advanced/wallets/reown-web-wallet/src/pages/_app.tsx @@ -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() diff --git a/advanced/wallets/reown-web-wallet/src/pages/request.tsx b/advanced/wallets/reown-web-wallet/src/pages/request.tsx index ebf6ada4e..0bbe607d0 100644 --- a/advanced/wallets/reown-web-wallet/src/pages/request.tsx +++ b/advanced/wallets/reown-web-wallet/src/pages/request.tsx @@ -1,10 +1,71 @@ +import PageHeader from "@/components/PageHeader"; +import { walletKit } from "@/utils/WalletConnectUtil"; +import { formatJsonRpcResult } from "@json-rpc-tools/utils"; import { W3mFrameProvider } from "@reown/appkit-wallet"; -import { useAppKitProvider } from "@reown/appkit/react"; +import { useAppKitAccount, useAppKitProvider } from "@reown/appkit/react"; import { useRouter } from "next/router"; +import { useEffect } from "react"; +import { rejectEIP155Request } from '@/utils/EIP155RequestHandlerUtil' +import ModalStore from '@/store/ModalStore' export default function RequestPage() { - const { walletProvider } = useAppKitProvider('eip155') - const {query} = useRouter() + const { walletProvider } = useAppKitProvider('eip155') + const { address, isConnected, caipAddress, status } = useAppKitAccount() - return
RequestPage
+ const router = useRouter() + + useEffect(() => { + if (!isConnected || !walletProvider || !walletKit) { + return + } + + (async () => { + const pendingRequests = walletKit.getPendingSessionRequests() + console.log('pendingRequests', pendingRequests) + + if (pendingRequests.length !== 0) { + const { chainId: activeEthChainId } = await walletProvider.getChainId() + const activeChainId = `eip155:${activeEthChainId}` + + pendingRequests.forEach(async request => { + try { + const requestedChainId = request.params.chainId + if (requestedChainId !== activeChainId) { + ModalStore.open('LoadingModal', {loadingMessage: 'Switching network...'}) + await walletProvider.switchNetwork(requestedChainId) + ModalStore.close() + } + + const response = await walletProvider.request(request.params.request as any) + console.log('response', response) + await walletKit.respondSessionRequest({ + topic: request.topic, + response: formatJsonRpcResult(request.id, response) + }) + } catch (e) { + console.error('error', e) + const response = rejectEIP155Request(request) + await walletKit.respondSessionRequest({ + topic: request.topic, + response + }) + } + }) + + const redirect = router.query.redirect as string + if (redirect) { + window.location.assign(redirect) + } + + } + })() + + }, [walletProvider, walletKit]) + + + return ( + <> + + + ) } \ No newline at end of file diff --git a/advanced/wallets/reown-web-wallet/src/pages/walletconnect.tsx b/advanced/wallets/reown-web-wallet/src/pages/walletconnect.tsx index 628cdb642..f06113127 100644 --- a/advanced/wallets/reown-web-wallet/src/pages/walletconnect.tsx +++ b/advanced/wallets/reown-web-wallet/src/pages/walletconnect.tsx @@ -30,9 +30,7 @@ export default function WalletConnectPage(params: { deepLink?: string }) { try { setLoading(true) walletKit.core.pairing.events.on('pairing_expire', pairingExpiredListener) - console.log('pair', uri) await walletKit.pair({ uri }) - console.log('paired') } catch (error) { console.log('error', error) styledToast((error as Error).message, 'error') @@ -46,7 +44,8 @@ export default function WalletConnectPage(params: { deepLink?: string }) { useEffect(() => { if (deepLink) { console.log('wc page -- deepLink', deepLink) - onConnect(deepLink) + + // onConnect(deepLink) } }, [deepLink]) diff --git a/advanced/wallets/reown-web-wallet/src/pages/wc.tsx b/advanced/wallets/reown-web-wallet/src/pages/wc.tsx index 5d51e13a4..b2cdc4690 100644 --- a/advanced/wallets/reown-web-wallet/src/pages/wc.tsx +++ b/advanced/wallets/reown-web-wallet/src/pages/wc.tsx @@ -32,15 +32,15 @@ export default function DeepLinkPairingPage() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [state.view]) - useEffect(() => { - if (requestId) { - ModalStore.open('LoadingModal', { loadingMessage }) - } - - if (uri) { - ModalStore.open('LoadingModal', { loadingMessage }) - } - }, [uri, requestId, loadingMessage]) + // useEffect(() => { + // if (requestId) { + // ModalStore.open('LoadingModal', { loadingMessage }) + // } + + // if (uri) { + // ModalStore.open('LoadingModal', { loadingMessage }) + // } + // }, [uri, requestId, loadingMessage]) if (!uri && !requestId) { return ( diff --git a/advanced/wallets/reown-web-wallet/src/utils/WalletConnectUtil.ts b/advanced/wallets/reown-web-wallet/src/utils/WalletConnectUtil.ts index 5fad5bddd..5273d2b46 100644 --- a/advanced/wallets/reown-web-wallet/src/utils/WalletConnectUtil.ts +++ b/advanced/wallets/reown-web-wallet/src/utils/WalletConnectUtil.ts @@ -6,7 +6,7 @@ export async function createWalletKit(relayerRegionURL: string) { const core = new Core({ projectId: process.env.NEXT_PUBLIC_PROJECT_ID, relayUrl: relayerRegionURL ?? process.env.NEXT_PUBLIC_RELAY_URL, - logger: 'debug', + // logger: 'debug', customStoragePrefix: 'reown-walletkit' }) walletKit = await WalletKit.init({ diff --git a/advanced/wallets/reown-web-wallet/src/views/AppKitConnectionModal.tsx b/advanced/wallets/reown-web-wallet/src/views/AppKitConnectionModal.tsx index f732e8b31..b412d8aab 100644 --- a/advanced/wallets/reown-web-wallet/src/views/AppKitConnectionModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/AppKitConnectionModal.tsx @@ -1,27 +1,24 @@ import ModalStore from "@/store/ModalStore" -import { useAppKit, useAppKitAccount } from "@reown/appkit/react" +import { useAppKit, useAppKitAccount, useAppKitState } from "@reown/appkit/react" import { useEffect } from "react" import LoadingModal from "./LoadingModal" import RequestModalContainer from "@/components/RequestModalContainer" import { Row, Col, Loading, Divider, Text } from "@nextui-org/react" +import { useSnapshot } from "valtio" export default function AppKitConnectionModal() { + const { open } = useAppKitState() const { isConnected, status } = useAppKitAccount() - const appkit= useAppKit() - // for now just open appkit modal if not connected - useEffect(() => { - console.log('appkit connection modal', status) - if (!isConnected && status !== undefined && status !== 'reconnecting' && status !== 'connecting') { - console.log('opening appkit') - ModalStore.close() - appkit.open() - } + const { view } = useSnapshot(ModalStore.state) - if (isConnected) { - ModalStore.close() - } - }, [isConnected, status]) + // for now just open appkit modal if not connected + // useEffect(() => { + // console.log('appkit connection modal', status) + // if (!isConnected && status !== undefined && status !== 'reconnecting' && status !== 'connecting') { + // appkit.open() + // } + // }, [isConnected, status]) return ( diff --git a/advanced/wallets/reown-web-wallet/src/views/AuthRequestModal.tsx b/advanced/wallets/reown-web-wallet/src/views/AuthRequestModal.tsx index 0ecb56beb..2e65822a0 100644 --- a/advanced/wallets/reown-web-wallet/src/views/AuthRequestModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/AuthRequestModal.tsx @@ -25,64 +25,65 @@ export default function AuthRequestModal() { // Get required request data const { params } = request - const message = walletKit.formatMessage(params.cacaoPayload, iss) + // const message = walletKit.formatMessage(params.cacaoPayload, iss) - // Handle approve action (logic varies based on request method) - const onApprove = useCallback(async () => { - if (request) { - setIsLoadingApprove(true) - const signature = await walletProvider?.request({ - method: 'personal_sign', - params: [message, address] - }) - await walletKit.respondAuthRequest( - { - id: request.id, - signature: { - s: signature, - t: 'eip191' - } - }, - iss - ) - setIsLoadingApprove(false) - ModalStore.close() - } - }, [request, address, message, iss, walletProvider]) + // // Handle approve action (logic varies based on request method) + // const onApprove = useCallback(async () => { + // if (request) { + // setIsLoadingApprove(true) + // const signature = await walletProvider?.request({ + // method: 'personal_sign', + // params: [message, address] + // }) + // await walletKit.respondAuthRequest( + // { + // id: request.id, + // signature: { + // s: signature, + // t: 'eip191' + // } + // }, + // iss + // ) + // setIsLoadingApprove(false) + // ModalStore.close() + // } + // }, [request, address, message, iss, walletProvider]) - // Handle reject action - const onReject = useCallback(async () => { - if (request) { - setIsLoadingReject(true) - await walletKit.respondAuthRequest( - { - id: request.id, - error: getSdkError('USER_REJECTED') - }, - iss - ) - setIsLoadingReject(false) - ModalStore.close() - } - }, [request, iss]) + // // Handle reject action + // const onReject = useCallback(async () => { + // if (request) { + // setIsLoadingReject(true) + // await walletKit.respondAuthRequest( + // { + // id: request.id, + // error: getSdkError('USER_REJECTED') + // }, + // iss + // ) + // setIsLoadingReject(false) + // ModalStore.close() + // } + // }, [request, iss]) return ( - - - - Message - - {message} - - - - +
disabled
+ // + // + // + // Message + // + // {message} + // + // + // + // ) } diff --git a/advanced/wallets/reown-web-wallet/src/views/SessionAuthenticateModal.tsx b/advanced/wallets/reown-web-wallet/src/views/SessionAuthenticateModal.tsx index 115dd27a8..5089d4b24 100644 --- a/advanced/wallets/reown-web-wallet/src/views/SessionAuthenticateModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/SessionAuthenticateModal.tsx @@ -83,31 +83,31 @@ export default function SessionAuthenticateModal() { // Handle approve action (logic varies based on request method) const onApprove = useCallback(async () => { - if (messages.length) { - const signedAuths = [] - for (const message of messages) { - const signature = await walletProvider?.request({ - method: 'personal_sign', - params: [message.message, address] - }) - const signedCacao = buildAuthObject( - message.authPayload, - { - t: 'eip191', - s: signature - }, - message.iss - ) - signedAuths.push(signedCacao) - } + // if (messages.length) { + // const signedAuths = [] + // for (const message of messages) { + // const signature = await walletProvider?.request({ + // method: 'personal_sign', + // params: [message.message, address] + // }) + // const signedCacao = buildAuthObject( + // message.authPayload, + // { + // t: 'eip191', + // s: signature + // }, + // message.iss + // ) + // signedAuths.push(signedCacao) + // } - await walletKit.engine.signClient.approveSessionAuthenticate({ - id: messages[0].id, - auths: signedAuths - }) - SettingsStore.setSessions(Object.values(walletKit.getActiveSessions())) - ModalStore.close() - } + // await walletKit.engine.signClient.approveSessionAuthenticate({ + // id: messages[0].id, + // auths: signedAuths + // }) + // SettingsStore.setSessions(Object.values(walletKit.getActiveSessions())) + // ModalStore.close() + // } }, [address, messages]) // Handle reject action diff --git a/advanced/wallets/reown-web-wallet/src/views/SessionProposalModal.tsx b/advanced/wallets/reown-web-wallet/src/views/SessionProposalModal.tsx index b54c7dd9c..3aba588ec 100644 --- a/advanced/wallets/reown-web-wallet/src/views/SessionProposalModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/SessionProposalModal.tsx @@ -18,6 +18,7 @@ import { EIP5792_METHODS } from '@/data/EIP5792Data' import { ChainController, useAppKitAccount, useAppKitProvider, useAppKitState } from '@reown/appkit/react' import { W3mFrameProvider } from '@reown/appkit-wallet' import LoadingModal from './LoadingModal' +import { useRouter } from 'next/router' const StyledText = styled(Text, { fontWeight: 400 @@ -36,9 +37,10 @@ export default function SessionProposalModal() { const { address, caipAddress } = useAppKitAccount() const { walletProvider } = useAppKitProvider('eip155') - const [supportedNamespaces, setSupportedNamespaces] = useState(null); - const [smartAccounts, setSmartAccounts] = useState([]); - const [activeChainId, setActiveChainId] = useState(''); + const [supportedNamespaces, setSupportedNamespaces] = useState(null) + const [smartAccounts, setSmartAccounts] = useState([]) + const [activeChainId, setActiveChainId] = useState('') + const [email, setEmail] = useState('') useEffect(() => { if (!walletProvider) @@ -47,23 +49,37 @@ export default function SessionProposalModal() { const fetchSupportedNamespaces = async () => { console.log('fetchSupportedNamespaces', walletProvider) - const user = await walletProvider.getUser({}); + const user = await walletProvider.getUser({}) - var saAddress = user.accounts?.find(account => account.type === 'smartAccount')?.address; - var eoaAddress = user.accounts?.find(account => account.type === 'eoa')?.address; + const saAddress = user.accounts?.find(account => account.type === 'smartAccount')?.address + const eoaAddress = user.accounts?.find(account => account.type === 'eoa')?.address - const activeChainId = `eip155:${user.chainId}`; + const activeChainId = `eip155:${user.chainId}` // eip155 const eip155Chains = Object.keys(EIP155_CHAINS) - const eip155Methods = Object.values(EIP155_SIGNING_METHODS); + const eip155Methods = Object.values(EIP155_SIGNING_METHODS) // eip5792 - const eip5792Chains = Object.keys(EIP155_CHAINS); - const eip5792Methods = Object.values(EIP5792_METHODS); + const eip5792Chains = Object.keys(EIP155_CHAINS) + const eip5792Methods = Object.values(EIP5792_METHODS) const smartAccounts = eip155Chains.map(chain => `${chain}:${saAddress}`) - const allAccounts = smartAccounts.concat(eip155Chains.map(chain => `${chain}:${eoaAddress}`)); + const eoaAccounts = eip155Chains.map(chain => `${chain}:${eoaAddress}`) + + let allAccounts = [...smartAccounts, ...eoaAccounts]; + + // Move preferred account type for active chain to the front + const preferredAccountType = user.preferredAccountType + const preferredAccountAddress = preferredAccountType === 'smartAccount' ? saAddress : eoaAddress + const preferredAccountForActiveChain = `${activeChainId}:${preferredAccountAddress}` + + allAccounts = [ + preferredAccountForActiveChain, + ...allAccounts.filter(account => account !== preferredAccountForActiveChain) + ]; + + console.log('allAccounts', allAccounts) const result = { eip155: { @@ -75,6 +91,7 @@ export default function SessionProposalModal() { }; setActiveChainId(activeChainId); + setEmail(user.email || '') setSmartAccounts(smartAccounts); setSupportedNamespaces(result); }; @@ -154,19 +171,36 @@ export default function SessionProposalModal() { const onApprove = useCallback(async () => { if (proposal && namespaces) { setIsLoadingApprove(true) - console.log('onApprove. proposal id', proposal.id) - console.log('onApprove. proposal params', proposal.params) try { - await new Promise(resolve => setTimeout(resolve, 1000)) - - await walletKit.approveSession({ + const session = await walletKit.approveSession({ id: proposal.id, namespaces, sessionProperties: { "smartAccounts": JSON.stringify(smartAccounts), + "email": email, } }) SettingsStore.setSessions(Object.values(walletKit.getActiveSessions())) + + await new Promise(resolve => setTimeout(resolve, 1000)) + + const chainChanged = { + topic: session.topic, + event: { + name: 'chainChanged', + data: `0x${parseInt(activeChainId.split(':')[1]).toString(16)}` + }, + chainId: activeChainId + } + + console.log('chainChanged', chainChanged) + await walletKit.emitSessionEvent(chainChanged) + + const nativeRedirect = session.peer.metadata.redirect?.native + if (nativeRedirect) { + // Try to open the native app using the URL schema + window.location.assign(nativeRedirect) + } } catch (e) { setIsLoadingApprove(false) styledToast((e as Error).message, 'error') diff --git a/advanced/wallets/reown-web-wallet/src/views/SessionSendTransactionModal.tsx b/advanced/wallets/reown-web-wallet/src/views/SessionSendTransactionModal.tsx index 6e0b8455f..f712e623e 100644 --- a/advanced/wallets/reown-web-wallet/src/views/SessionSendTransactionModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/SessionSendTransactionModal.tsx @@ -10,11 +10,12 @@ import { styledToast } from '@/utils/HelperUtil' import { walletKit } from '@/utils/WalletConnectUtil' import RequestModal from './RequestModal' import { useAppKitProvider } from '@reown/appkit/react' +import { W3mFrameProvider } from '@reown/appkit-wallet' export default function SessionSendTransactionModal() { const [isLoadingApprove, setIsLoadingApprove] = useState(false) const [isLoadingReject, setIsLoadingReject] = useState(false) - const { walletProvider } = useAppKitProvider('eip155') + const { walletProvider } = useAppKitProvider('eip155') // Get request and wallet data from store const requestEvent = ModalStore.state.data?.requestEvent diff --git a/advanced/wallets/reown-web-wallet/src/views/SessionSignModal.tsx b/advanced/wallets/reown-web-wallet/src/views/SessionSignModal.tsx index d0de606c2..e2c0f800b 100644 --- a/advanced/wallets/reown-web-wallet/src/views/SessionSignModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/SessionSignModal.tsx @@ -9,13 +9,15 @@ import { getSignParamsMessage, styledToast } from '@/utils/HelperUtil' import { walletKit } from '@/utils/WalletConnectUtil' import RequestModal from './RequestModal' import { useAppKitProvider } from '@reown/appkit/react' +import { W3mFrameProvider } from '@reown/appkit-wallet' + export default function SessionSignModal() { // Get request and wallet data from store const requestEvent = ModalStore.state.data?.requestEvent const requestSession = ModalStore.state.data?.requestSession const [isLoadingApprove, setIsLoadingApprove] = useState(false) const [isLoadingReject, setIsLoadingReject] = useState(false) - const { walletProvider } = useAppKitProvider('eip155') + const { walletProvider } = useAppKitProvider('eip155') // Ensure request and wallet are defined if (!requestEvent || !requestSession) { diff --git a/advanced/wallets/reown-web-wallet/src/views/SessionSignTypedDataModal.tsx b/advanced/wallets/reown-web-wallet/src/views/SessionSignTypedDataModal.tsx index 12b368f99..ff6eafc06 100644 --- a/advanced/wallets/reown-web-wallet/src/views/SessionSignTypedDataModal.tsx +++ b/advanced/wallets/reown-web-wallet/src/views/SessionSignTypedDataModal.tsx @@ -12,6 +12,7 @@ import RequestModal from './RequestModal' import { useCallback, useState } from 'react' import PermissionDetailsCard from '@/components/PermissionDetailsCard' import { useAppKitProvider } from '@reown/appkit/react' +import { W3mFrameProvider } from '@reown/appkit-wallet' export default function SessionSignTypedDataModal() { // Get request and wallet data from store @@ -19,7 +20,8 @@ export default function SessionSignTypedDataModal() { const requestSession = ModalStore.state.data?.requestSession const [isLoadingApprove, setIsLoadingApprove] = useState(false) const [isLoadingReject, setIsLoadingReject] = useState(false) - const { walletProvider } = useAppKitProvider('eip155') + const { walletProvider } = useAppKitProvider('eip155') + // Ensure request and wallet are defined if (!requestEvent || !requestSession) {