Skip to content

Feat(web): Add web3 boilerplate #307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 23, 2022
Merged
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
8 changes: 7 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
"license": "MIT",
"alias": {
"src": "./src",
"utils": "./src/utils",
"assets": "./src/assets",
"components": "./src/components",
"connectors": "./src/connectors",
"context": "./src/context",
"layout": "./src/layout",
"consts": "./src/consts",
Expand Down Expand Up @@ -57,16 +59,20 @@
"@graphql-codegen/typescript-operations": "^2.5.3",
"@kleros/kleros-v2-contracts": "workspace:^",
"@kleros/ui-components-library": "^1.7.0",
"@web3-react/core": "^6.1.9",
"@web3-react/injected-connector": "^6.0.7",
"@web3-react/types": "^6.0.7",
"chart.js": "^3.9.1",
"chartjs-adapter-moment": "^1.0.0",
"core-js": "^3.21.1",
"ethers": "^5.6.5",
"ethers": "^5.7.0",
"graphql": "^16.4.0",
"graphql-request": "^4.2.0",
"moment": "^2.29.4",
"react": "^18.2.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4",
"react-is": "^18.2.0",
"react-router-dom": "6",
"styled-components": "^5.3.5",
Expand Down
32 changes: 19 additions & 13 deletions web/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import React from "react";
import StyledComponentsProvider from "context/StyledComponentsProvider";
import { SWRConfig } from "swr";
import { request } from "graphql-request";
import { Routes, Route } from "react-router-dom";
import Web3Provider from "context/Web3Provider";
import StyledComponentsProvider from "context/StyledComponentsProvider";
import WrongChainBoundary from "components/WrongChainBoundary";
import Layout from "layout/index";
import Home from "./pages/Home";
import Cases from "./pages/Cases";
Expand All @@ -25,18 +27,22 @@ const App: React.FC = () => {
),
}}
>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="cases" element={<Cases />} />
<Route path="courts" element={<h1>Courts</h1>} />
<Route path="dashboard" element={<Dashboard />} />
<Route
path="*"
element={<h1>Justice not found here ¯\_( ͡° ͜ʖ ͡°)_/¯</h1>}
/>
</Route>
</Routes>
<Web3Provider>
<WrongChainBoundary>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="cases" element={<Cases />} />
<Route path="courts" element={<h1>Courts</h1>} />
<Route path="dashboard" element={<Dashboard />} />
<Route
path="*"
element={<h1>Justice not found here ¯\_( ͡° ͜ʖ ͡°)_/¯</h1>}
/>
</Route>
</Routes>
</WrongChainBoundary>
</Web3Provider>
</SWRConfig>
</StyledComponentsProvider>
);
Expand Down
6 changes: 3 additions & 3 deletions web/src/components/CasesDisplay/Stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ const fields = [
const Stats: React.FC = () => (
<div>
{fields.map(({ label, value }, i) => (
<>
<Field key={i} {...{ label, value }} />
<React.Fragment key={i}>
<Field {...{ label, value }} />
{i + 1 < fields.length ? <Separator /> : null}
</>
</React.Fragment>
))}
</div>
);
Expand Down
48 changes: 47 additions & 1 deletion web/src/components/ConnectButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,52 @@
import React from "react";
import styled from "styled-components";
import { shortenAddress } from "utils/shortenAddress";
import { Button } from "@kleros/ui-components-library";
import { useWeb3 } from "hooks/useWeb3";
import { useConnect } from "hooks/useConnect";
import { SUPPORTED_CHAINS } from "consts/supportedChains";

const ConnectButton: React.FC = () => <Button small text={"Connect"} />;
const AccountDisplay: React.FC = () => {
const { account, chainId } = useWeb3();
const chainName = chainId ? SUPPORTED_CHAINS[chainId].chainName : undefined;
const shortAddress = account ? shortenAddress(account) : undefined;
return (
<StyledContainer>
<small>{chainName}</small>
<label>{shortAddress}</label>
</StyledContainer>
);
};

const StyledContainer = styled.div`
width: fit-content;
height: 34px;
padding: 16px;
gap: 0.5rem;
border-radius: 300px;
background-color: ${({ theme }) => theme.whiteLowOpacity};
display: flex;
align-items: center;
> label {
color: ${({ theme }) => theme.primaryText};
}
:before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background-color: ${({ theme }) => theme.success};
}
`;

const ConnectButton: React.FC = () => {
const { active } = useWeb3();
const { activate, connecting } = useConnect();
return active ? (
<AccountDisplay />
) : (
<Button disabled={connecting} small text={"Connect"} onClick={activate} />
);
};

export default ConnectButton;
44 changes: 44 additions & 0 deletions web/src/components/WrongChainBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React, { useState } from "react";
import styled from "styled-components";
import { ErrorBoundary } from "react-error-boundary";
import { Button } from "@kleros/ui-components-library";
import { switchChain } from "utils/switchChain";

const WrongChainRecovery: React.FC<{ resetErrorBoundary: () => void }> = ({
resetErrorBoundary,
}) => {
const [loading, setLoading] = useState(false);
return (
<Container>
<Button
disabled={loading}
text="Switch to Arbitrum"
onClick={() => {
setLoading(true);
switchChain(421611)
.then(resetErrorBoundary)
.finally(() => setLoading(false));
}}
/>
</Container>
);
};

const Container = styled.div`
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: ${({ theme }) => theme.whiteBackground};
`;

const WrongChainBoundary: React.FC<{ children: React.ReactNode }> = ({
children,
}) => (
<ErrorBoundary FallbackComponent={WrongChainRecovery}>
{children}
</ErrorBoundary>
);

export default WrongChainBoundary;
6 changes: 6 additions & 0 deletions web/src/connectors/injected.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { InjectedConnector } from "@web3-react/injected-connector";
import { SUPPORTED_CHAINIDS } from "consts/supportedChains";

export const injected = new InjectedConnector({
supportedChainIds: SUPPORTED_CHAINIDS,
});
12 changes: 12 additions & 0 deletions web/src/consts/supportedChains.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const SUPPORTED_CHAINS = {
421611: {
chainName: "Arbitrum Rinkeby",
nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
rpcUrls: ["https://rinkeby.arbitrum.io/rpc"],
blockExplorerUrls: ["https://testnet.arbiscan.io/"],
},
};

export const SUPPORTED_CHAINIDS = Object.keys(SUPPORTED_CHAINS).map((x) =>
parseInt(x)
);
15 changes: 15 additions & 0 deletions web/src/context/Web3Provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from "react";
import { Web3ReactProvider } from "@web3-react/core";
import {
Web3Provider as EthersProvider,
ExternalProvider,
} from "@ethersproject/providers";

const getLibrary = (provider: ExternalProvider): EthersProvider =>
new EthersProvider(provider);

const Web3Provider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => <Web3ReactProvider {...{ getLibrary }}> {children} </Web3ReactProvider>;

export default Web3Provider;
46 changes: 46 additions & 0 deletions web/src/hooks/useConnect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useEffect, useState } from "react";
import { useWeb3React, UnsupportedChainIdError } from "@web3-react/core";
import { injected } from "connectors/injected";

export const useConnect = () => {
const { activate, error } = useWeb3React();
const [connecting, setConnecting] = useState(false);
const [activationError, setActivationError] = useState<Error>();

const activateInjected = () => {
setConnecting(true);
activate(injected, undefined, true)
.catch((error) => setActivationError(error))
.finally(() => setConnecting(false));
};

const activateInjectedWithAccountsCheck = (accounts: string[]) =>
accounts.length > 0 && activateInjected();

useEffect(() => {
const { ethereum } = window as any;
if (ethereum && ethereum.on) {
ethereum.on("chainChanged", activateInjected);
ethereum.on("accountsChanged", activateInjectedWithAccountsCheck);
return () => {
if (ethereum.removeListener) {
ethereum.removeListener("chainChanged", activateInjected);
ethereum.removeListener(
"accountsChanged",
activateInjectedWithAccountsCheck
);
}
};
} else return;
});

useEffect(() => {
if (
activationError &&
activationError.name === UnsupportedChainIdError.name
)
throw activationError;
}, [activationError]);

return { activate: activateInjected, connecting, error };
};
4 changes: 4 additions & 0 deletions web/src/hooks/useWeb3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Web3Provider } from "@ethersproject/providers";
import { useWeb3React } from "@web3-react/core";

export const useWeb3 = () => useWeb3React<Web3Provider>();
43 changes: 30 additions & 13 deletions web/src/layout/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useRef } from "react";
import React, { useState, useRef, useContext } from "react";
import styled from "styled-components";
import { Link } from "react-router-dom";
import HamburgerIcon from "svgs/header/hamburger.svg";
Expand Down Expand Up @@ -26,31 +26,48 @@ const Container = styled.div`
`;

const StyledLightButton = styled(LightButton)`
padding-right: 0;
padding: 0;

.button-svg {
margin-right: 0px;
fill: white;
}
.button-text {
display: none;
}
`;

const OpenContext = React.createContext({
isOpen: false,
toggleIsOpen: () => {
// Placeholder
},
});

export const useOpenContext = () => {
return useContext(OpenContext);
};

const Header: React.FC = () => {
const [isOpen, setIsOpen] = useState<boolean>(false);
const toggleIsOpen = () => setIsOpen(!isOpen);
const containerRef = useRef(null);
useFocusOutside(containerRef, () => setIsOpen(false));
return (
<Container>
<Link className="kleros-court-link" to={"/"}>
<KlerosCourtLogo />
</Link>
<div ref={containerRef}>
<NavBar {...{ isOpen }} />
<StyledLightButton
text=""
Icon={HamburgerIcon}
onClick={toggleIsOpen}
/>
</div>
<OpenContext.Provider value={{ isOpen, toggleIsOpen }}>
<Link className="kleros-court-link" to={"/"}>
<KlerosCourtLogo />
</Link>
<div ref={containerRef}>
<NavBar />
<StyledLightButton
text=""
Icon={HamburgerIcon}
onClick={toggleIsOpen}
/>
</div>
</OpenContext.Provider>
</Container>
);
};
Expand Down
28 changes: 16 additions & 12 deletions web/src/layout/Header/navbar/Explore.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";
import styled from "styled-components";
import { Link } from "react-router-dom";
import { useOpenContext } from "../index";

const Container = styled.div``;

Expand All @@ -21,17 +22,20 @@ const links = [
{ to: "/dashboard", text: "Dashboard" },
];

const Explore: React.FC = () => (
<Container>
<h1>Explore</h1>
{links.map(({ to, text }) => (
<LinkContainer key={text}>
<Link {...{ to }} className="sm-link">
{text}
</Link>
</LinkContainer>
))}
</Container>
);
const Explore: React.FC = () => {
const { toggleIsOpen } = useOpenContext();
return (
<Container>
<h1>Explore</h1>
{links.map(({ to, text }) => (
<LinkContainer key={text}>
<Link {...{ to }} onClick={toggleIsOpen} className="sm-link">
{text}
</Link>
</LinkContainer>
))}
</Container>
);
};

export default Explore;
Loading