From 3a98910dcf2787465ba7457aa221597f65e3da31 Mon Sep 17 00:00:00 2001 From: Damian Date: Wed, 1 Dec 2021 16:31:47 -0300 Subject: [PATCH] Add AlertDialog for wrong network message and fix chainChanged callback --- .../components/WrongNetworkAlertDialog.jsx | 90 ++++++++++++++ packages/react-app/helpers/Web3Context.js | 112 +++++------------- packages/react-app/pages/_app.js | 4 +- 3 files changed, 123 insertions(+), 83 deletions(-) create mode 100644 packages/react-app/components/WrongNetworkAlertDialog.jsx diff --git a/packages/react-app/components/WrongNetworkAlertDialog.jsx b/packages/react-app/components/WrongNetworkAlertDialog.jsx new file mode 100644 index 0000000..1f26da1 --- /dev/null +++ b/packages/react-app/components/WrongNetworkAlertDialog.jsx @@ -0,0 +1,90 @@ +import React, { useContext, useEffect, useState } from "react"; +import { + Button, + AlertDialog, + AlertDialogBody, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogContent, + AlertDialogOverlay, +} from "@chakra-ui/react"; + +import { Web3Context } from "../helpers/Web3Context"; + +function WrongNetworkAlertDialog() { + const [isAlertOpen, setIsAlertOpen] = useState(false); + const context = useContext(Web3Context); + const cancelRef = React.useRef(); + + useEffect(() => { + if (context) { + setIsAlertOpen(!context.rightNetwork); + } + }, [context && context.rightNetwork]); + + const onNetworkSwitch = async () => { + const data = [ + { + chainId: "0x" + context.targetNetwork.chainId.toString(16), + chainName: context.targetNetwork.name, + nativeCurrency: context.targetNetwork.nativeCurrency, + rpcUrls: [context.targetNetwork.rpcUrl], + blockExplorerUrls: [context.targetNetwork.blockExplorer], + }, + ]; + try { + await ethereum.request({ + method: "wallet_switchEthereumChain", + params: [{ chainId: data[0].chainId }], + }); + setIsAlertOpen(false); + } catch (switchError) { + // This error code indicates that the chain has not been added to MetaMask. + if (switchError.code === 4902) { + try { + await ethereum.request({ + method: "wallet_addEthereumChain", + params: data, + }); + setIsAlertOpen(false); + } catch (addError) { + console.log(addError); + } + } + // handle other "switch" errors + } + }; + + return ( + + + + + Switch network + + + + To use this app you must switch to the {context.targetNetwork.name} network. + + + + + + + + + + ); +} + +export default WrongNetworkAlertDialog; diff --git a/packages/react-app/helpers/Web3Context.js b/packages/react-app/helpers/Web3Context.js index 32b556c..97be51d 100644 --- a/packages/react-app/helpers/Web3Context.js +++ b/packages/react-app/helpers/Web3Context.js @@ -284,61 +284,6 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N /> ); - } else { - networkDisplay = ( -
- - You have {networkSelected && networkSelected.name} selected and you need to be on{" "} - -
- } - type="error" - closable={false} - /> - - ); } } else { networkDisplay = ( @@ -354,36 +299,39 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N const signer = provider.getSigner(); const account = await signer.getAddress(); setInjectedProvider(provider); - const mySelf = await SelfID.authenticate({ - authProvider: new EthereumAuthProvider(provider.provider, account), - ceramic: CERAMIC_TESTNET, - connectNetwork: CERAMIC_TESTNET, - model: modelAliases, - }); - console.log("curr self", mySelf.id); - setSelf(mySelf); - const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/nonce/${account}`); - const signature = await provider.provider.request({ - method: "personal_sign", - params: [data.message, account], - }); - const verifyResponse = await axios.post( - `${process.env.NEXT_PUBLIC_API_URL}/verify/${account}`, - { - signature, - }, - { - withCredentials: true, - }, - ); - if (verifyResponse.status !== 200) { - throw new Error("Unauthorized"); + if (rightNetwork) { + const mySelf = await SelfID.authenticate({ + authProvider: new EthereumAuthProvider(provider.provider, account), + ceramic: CERAMIC_TESTNET, + connectNetwork: CERAMIC_TESTNET, + model: modelAliases, + }); + console.log("curr self", mySelf.id); + setSelf(mySelf); + + const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/nonce/${account}`); + const signature = await provider.provider.request({ + method: "personal_sign", + params: [data.message, account], + }); + const verifyResponse = await axios.post( + `${process.env.NEXT_PUBLIC_API_URL}/verify/${account}`, + { + signature, + }, + { + withCredentials: true, + }, + ); + if (verifyResponse.status !== 200) { + throw new Error("Unauthorized"); + } } connection.on("chainChanged", chainId => { console.log(`chain changed to ${chainId}! updating providers`); - setInjectedProvider(provider); + setInjectedProvider(new ethers.providers.Web3Provider(connection)); }); connection.on("accountsChanged", newAccounts => { @@ -404,13 +352,13 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N connection.on("disconnect", (code, reason) => { logoutOfWeb3Modal(); }); - }, [setInjectedProvider]); + }, [setInjectedProvider, rightNetwork]); useEffect(() => { if (web3Modal && web3Modal.cachedProvider) { loadWeb3Modal(); } - }, [web3Modal]); + }, [loadWeb3Modal]); let faucetHint = ""; const faucetAvailable = localProvider && localProvider.connection && targetNetwork.name.indexOf("local") !== -1; diff --git a/packages/react-app/pages/_app.js b/packages/react-app/pages/_app.js index 8ae1a52..6c67aaf 100644 --- a/packages/react-app/pages/_app.js +++ b/packages/react-app/pages/_app.js @@ -3,10 +3,11 @@ import "antd/dist/antd.css"; import Head from "next/head"; import Link from "next/link"; import { ChakraProvider } from "@chakra-ui/react"; -import React, { useEffect, useRef, useState } from "react"; +import React, { useContext, useEffect, useRef, useState } from "react"; import { ThemeSwitcherProvider } from "react-css-theme-switcher"; import { Header } from "../components"; import DevUI from "../components/DevUI"; +import WrongNetworkAlertDialog from "../components/WrongNetworkAlertDialog"; import { Web3Provider } from "../helpers/Web3Context"; import "../styles/index.css"; @@ -59,6 +60,7 @@ function MyApp({ Component, pageProps }) { +