Skip to content
This repository has been archived by the owner on Dec 17, 2021. It is now read-only.

Commit

Permalink
Add AlertDialog for wrong network message and fix chainChanged callback
Browse files Browse the repository at this point in the history
  • Loading branch information
damianmarti committed Dec 1, 2021
1 parent 77311ee commit 3a98910
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 83 deletions.
90 changes: 90 additions & 0 deletions packages/react-app/components/WrongNetworkAlertDialog.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<AlertDialog isOpen={isAlertOpen} leastDestructiveRef={cancelRef}>
<AlertDialogOverlay>
<AlertDialogContent>
<AlertDialogHeader fontSize="lg" fontWeight="bold">
Switch network
</AlertDialogHeader>

<AlertDialogBody>
To use this app you must switch to the {context.targetNetwork.name} network.
</AlertDialogBody>

<AlertDialogFooter>
<Button
ref={cancelRef}
style={{ marginRight: 20 }}
onClick={() => {
setIsAlertOpen(false);
}}
>
Close
</Button>
<Button onClick={onNetworkSwitch} colorScheme="blue">
Switch
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialogOverlay>
</AlertDialog>
);
}

export default WrongNetworkAlertDialog;
112 changes: 30 additions & 82 deletions packages/react-app/helpers/Web3Context.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,61 +284,6 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N
/>
</div>
);
} else {
networkDisplay = (
<div style={{ zIndex: 10, position: "absolute", right: 0, top: 80, padding: 16 }}>
<Alert
message="⚠️ Wrong Network"
description={
<div>
You have <b>{networkSelected && networkSelected.name}</b> selected and you need to be on{" "}
<Button
onClick={async () => {
const ethereum = window.ethereum;
const data = [
{
chainId: "0x" + targetNetwork.chainId.toString(16),
chainName: targetNetwork.name,
nativeCurrency: targetNetwork.nativeCurrency,
rpcUrls: [targetNetwork.rpcUrl],
blockExplorerUrls: [targetNetwork.blockExplorer],
},
];
console.log("data", data);

let switchTx;
// https://docs.metamask.io/guide/rpc-api.html#other-rpc-methods
try {
switchTx = await ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: data[0].chainId }],
});
} catch (switchError) {
// not checking specific error code, because maybe we're not using MetaMask
try {
switchTx = await ethereum.request({
method: "wallet_addEthereumChain",
params: data,
});
} catch (addError) {
// handle "add" error
}
}

if (switchTx) {
console.log(switchTx);
}
}}
>
<b>{networkLocal && networkLocal.name}</b>
</Button>
</div>
}
type="error"
closable={false}
/>
</div>
);
}
} else {
networkDisplay = (
Expand All @@ -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 => {
Expand All @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion packages/react-app/pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -59,6 +60,7 @@ function MyApp({ Component, pageProps }) {
</Menu.Item>
</Menu>
<DevUI />
<WrongNetworkAlertDialog />
<Component {...pageProps} />
</>
</ThemeSwitcherProvider>
Expand Down

0 comments on commit 3a98910

Please sign in to comment.