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

Change network detection to Web3Context #98

Open
wants to merge 7 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
42 changes: 24 additions & 18 deletions packages/react-app/components/cards/MediaCard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ function MediaCard({
secondaryActionOnClick,
secondaryAction,
privateProfile,
dRecruitContract,
tokenContract,
tokenMetadata,
}) {
Expand All @@ -68,6 +67,7 @@ function MediaCard({
const [currAllowance, setCurrAllowance] = useState();
const [unlimitedAllowanceWanted, setUnlimitedAllowanceWanted] = useState(true);
const context = useContext(Web3Context);
const dRecruitContract = context.writeContracts.DRecruitV1;

const toast = useToast();

Expand Down Expand Up @@ -175,12 +175,14 @@ function MediaCard({

useEffect(() => {
async function exec() {
const weiStakeAmount = ethers.utils.parseEther(debouncedStakeAmount);
const allowance = await tokenContract.allowance(context.address, dRecruitContract.address);
if (allowance.lt(weiStakeAmount)) {
setApprovalState("NOT_ENOUGH");
} else {
setApprovalState("ENOUGH");
if (context.rightNetwork) {
const weiStakeAmount = ethers.utils.parseEther(debouncedStakeAmount);
const allowance = await tokenContract.allowance(context.address, dRecruitContract.address);
if (allowance.lt(weiStakeAmount)) {
setApprovalState("NOT_ENOUGH");
} else {
setApprovalState("ENOUGH");
}
}
}
if (debouncedStakeAmount) {
Expand All @@ -197,8 +199,10 @@ function MediaCard({

useEffect(() => {
async function exec() {
const allowance = await tokenContract.allowance(context.address, dRecruitContract.address);
setCurrAllowance(allowance);
if (context.rightNetwork) {
const allowance = await tokenContract.allowance(context.address, dRecruitContract.address);
setCurrAllowance(allowance);
}
}
exec();
}, [isOpen]);
Expand Down Expand Up @@ -345,15 +349,17 @@ function MediaCard({
</Stack>
</Box>
)}
<Button
disabled={canView}
w={"full"}
mt={8}
// TODO: get dev main address
onClick={onOpen}
>
{canView ? "✔️ Information already unlocked" : primaryAction}
</Button>
{context.rightNetwork && (
<Button
disabled={canView}
w={"full"}
mt={8}
// TODO: get dev main address
onClick={onOpen}
>
{canView ? "✔️ Information already unlocked" : primaryAction}
</Button>
)}
</Box>
</Box>
</>
Expand Down
61 changes: 33 additions & 28 deletions packages/react-app/helpers/Web3Context.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N
const localChainId = localProvider && localProvider._network && localProvider._network.chainId;
const selectedChainId =
userSigner && userSigner.provider && userSigner.provider._network && userSigner.provider._network.chainId;
const rightNetwork = localChainId == selectedChainId;

// For more hooks, check out 🔗eth-hooks at: https://www.npmjs.com/package/eth-hooks

Expand Down Expand Up @@ -268,7 +269,7 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N
const networkLocal = NETWORK(localChainId);
if (selectedChainId === 1337 && localChainId === 31337) {
networkDisplay = (
<div style={{ zIndex: 2, position: "absolute", right: 0, top: 60, padding: 16 }}>
<div style={{ zIndex: 10, position: "absolute", right: 0, top: 80, padding: 16 }}>
<Alert
message="⚠️ Wrong Network ID"
description={
Expand Down Expand Up @@ -298,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 @@ -348,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 Expand Up @@ -410,6 +414,7 @@ export function Web3Provider({ children, network = "localhost", DEBUG = false, N
loadWeb3Modal,
logoutOfWeb3Modal,
contractConfig,
rightNetwork,
};

return <Web3Context.Provider value={providerProps}>{children}</Web3Context.Provider>;
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
Loading