Skip to content
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

Upgrade wagmi 2.2 #8

Merged
merged 3 commits into from
Jan 19, 2024
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
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"lint": "prettier -w . && eslint ./src"
},
"dependencies": {
"@tanstack/react-query": "^5.17.15",
"buffer": "^6.0.3",
"dayjs": "^1.11.9",
"events": "^3.3.0",
Expand All @@ -26,8 +27,8 @@
"react-svgmt": "^2.0.2",
"use-local-storage-state": "^19.0.4",
"util": "^0.12.5",
"viem": "^1.10.9",
"wagmi": "^1.4.1",
"viem": "2.x",
"wagmi": "^2.2.1",
"wouter": "^2.11.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function ConnectedOnly({ children }) {
const [_location, navigate] = useLocation();

useEffect(() => {
!isConnected && navigate("/connect");
!isConnected && navigate("/");
}, [isConnected]);

if (isConnected) {
Expand Down
15 changes: 2 additions & 13 deletions src/components/Profile/CustomRpc.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { TextInput } from "flowbite-react";
import { isEmpty } from "lodash";
import { PlugZap as PlugZapIcon } from "lucide-react";
import useLocalStorageState from "use-local-storage-state";

import { RPC_URI } from "../../constants";
import { CUSTOM_RPC_URI_KEY } from "../../rpc";

export default function CustomRpc() {
const [customRpc, setCustomRpc] = useLocalStorageState("customRPC", {
const [customRpc, setCustomRpc] = useLocalStorageState(CUSTOM_RPC_URI_KEY, {
defaultValue: "",
serializer: { stringify: String, parse: String },
});
Expand Down Expand Up @@ -36,13 +35,3 @@ export default function CustomRpc() {
</div>
);
}

CustomRpc.getRpc = function () {
const customRpc = window.localStorage.getItem("customRPC");

if (isEmpty(customRpc)) {
return RPC_URI;
}

return customRpc;
};
15 changes: 4 additions & 11 deletions src/components/Profile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,7 @@ import {
Wallet as WalletIcon,
} from "lucide-react";
import { useState } from "react";
import {
useAccount,
useBalance,
useDisconnect,
useNetwork,
useSwitchNetwork,
} from "wagmi";
import { useAccount, useBalance, useDisconnect, useSwitchChain } from "wagmi";

import { DEFAULT_CHAIN } from "../../constants";
import AddressMask from "../AddressMask";
Expand All @@ -20,9 +14,8 @@ import NavLink from "../NavLink";
import CustomRpc from "./CustomRpc";

export default function Profile({ children }) {
const { chain } = useNetwork();
const { switchNetwork } = useSwitchNetwork();
const { address, isConnected } = useAccount();
const { switchChain } = useSwitchChain();
const { chain, address, isConnected } = useAccount();
const { disconnect } = useDisconnect();
const { data: balance } = useBalance({ address: address });

Expand Down Expand Up @@ -68,7 +61,7 @@ export default function Profile({ children }) {

{invalidChain && (
<Button
onClick={() => switchNetwork(DEFAULT_CHAIN.id)}
onClick={() => switchChain({ chainId: DEFAULT_CHAIN.id })}
className="w-full"
>
Switch to {DEFAULT_CHAIN.name} to continue
Expand Down
2 changes: 1 addition & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { optimism } from "wagmi/chains";
import { optimism } from "viem/chains";

export const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
export const TOKEN_ICON = "/svg/coin.svg";
Expand Down
14 changes: 8 additions & 6 deletions src/hooks/token.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useQuery } from "@tanstack/react-query";
import { fetchBalance } from "@wagmi/core";
import { getBalance } from "@wagmi/core";

import { TOKEN_ADDRESSES } from "../constants";
import rpc from "../rpc";

async function fetchTokens(accountAddress) {
const tokens = TOKEN_ADDRESSES.map(async (tokenAddress) => {
const token = await fetchBalance({
const token = await getBalance(rpc, {
address: accountAddress,
token: tokenAddress as `0x${string}`,
});
Expand All @@ -16,12 +17,13 @@ async function fetchTokens(accountAddress) {
}

export function useTokens(accountAddress, opts = {}) {
return useQuery(["fetchTokens"], () => fetchTokens(accountAddress), {
return useQuery({
queryKey: ["fetchTokens"],
queryFn: () => fetchTokens(accountAddress),
...opts,
// @ts-ignore
placeholderData: [],
// 5 minute
cacheTime: 5_000 * 60,
// @ts-ignore
cacheTime: 5_000 * 60, // 5 minute
keepPreviousData: true,
});
}
64 changes: 9 additions & 55 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,77 +1,31 @@
import "./main.css";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { SafeConnector } from "@wagmi/connectors/safe";
import { InjectedConnector } from "@wagmi/core";
import { jsonRpcProvider } from "@wagmi/core/providers/jsonRpc";
import { Flowbite } from "flowbite-react";
import React from "react";
import ReactDOM from "react-dom/client";
import { ErrorBoundary } from "react-error-boundary";
import { configureChains, createConfig, WagmiConfig } from "wagmi";
import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";
import { WalletConnectConnector } from "wagmi/connectors/walletConnect";
import { WagmiProvider } from "wagmi";

import FlowbiteTheme from "../flowbite.config";
import App from "./App";
import DarkThemeToggle from "./components/DarkThemeToggle";
import CustomRpc from "./components/Profile/CustomRpc";
import { DEFAULT_CHAIN, WALLETCONNECT_PROJECT_ID } from "./constants";
import Error from "./Error";
import config from "./rpc";

const queryClient = new QueryClient();

const { chains, publicClient } = configureChains(
[DEFAULT_CHAIN],
[
jsonRpcProvider({
rpc: (_chain) => ({ http: CustomRpc.getRpc() }),
}),
],
);

export const wagmiConfig = createConfig({
publicClient,
autoConnect: true,
connectors: [
new InjectedConnector({
chains,
options: {
// @ts-ignore
name: "Browser Wallet",
shimDisconnect: true,
},
}),
new WalletConnectConnector({
chains,
options: {
projectId: WALLETCONNECT_PROJECT_ID,
},
}),
new CoinbaseWalletConnector({
chains,
options: {
appName: "GOVNFT",
jsonRpcUrl: CustomRpc.getRpc(),
},
}),
new SafeConnector({
chains,
}),
],
});

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Flowbite theme={{ ...FlowbiteTheme, dark: DarkThemeToggle.isDarkMode() }}>
{/* @ts-ignore */}
<ErrorBoundary FallbackComponent={Error}>
<WagmiConfig config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
{/* @ts-ignore */}
<ErrorBoundary FallbackComponent={Error}>
<App />
</QueryClientProvider>
</WagmiConfig>
</ErrorBoundary>
</ErrorBoundary>
</QueryClientProvider>
</WagmiProvider>
</Flowbite>
</React.StrictMode>,
);
37 changes: 37 additions & 0 deletions src/pages/Connect/components/ConnectorButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Button } from "flowbite-react";
import { useEffect, useState } from "react";

export default function ConnectorButton({ connector, onClick }) {
const [ready, setReady] = useState(false);
useEffect(() => {
(async () => {
const provider = await connector.getProvider();
setReady(!!provider);
})();
}, [connector, setReady]);

return (
<>
<Button
size="sm"
disabled={!ready}
onClick={onClick}
type="button"
className="w-full flex items-start !justify-start py-1 text-sm"
color="gray"
>
<div className="flex items-center gap-3 !justify-start">
<img
src={
connector.icon
? connector.icon
: `svg/icn-connect-${connector.id}.svg`
}
className="h-6"
/>
{connector.id == "injected" ? "Browser Wallet" : connector.name}
</div>
</Button>
</>
);
}
57 changes: 12 additions & 45 deletions src/pages/Connect/components/Connectors.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,17 @@
import { Button, Spinner } from "flowbite-react";
import { ExternalLink as ExternalLinkIcon } from "lucide-react";
import { useEffect } from "react";
import { useConnect } from "wagmi";
import { useChainId, useConnect } from "wagmi";

import { DEFAULT_CHAIN } from "../../../constants";
import { wagmiConfig } from "../../../main";
import ConnectorButton from "./ConnectorButton";

export default function Connectors({ className }) {
const { connect, connectors, isLoading, pendingConnector } = useConnect({
chainId: DEFAULT_CHAIN.id,
});

// Auto-connect to Safe if available
useEffect(() => {
const safeConnector = connectors.find((c) => c.id === "safe" && c.ready);

if (safeConnector) {
connect({ connector: safeConnector });
} else {
// Comment out to disable auto-connect...
wagmiConfig.autoConnect();
}
}, [connect, connectors]);
const chainId = useChainId();
const { connectors, connect } = useConnect();

return (
<div className={className}>
<div className="bg-black bg-opacity-5 dark:bg-white dark:bg-opacity-5 rounded-lg text-sm py-6 sm:py-10 px-5 sm:px-12 max-w-sm">
<p>
You'll need an Ethereum
<br /> Wallet to sign-in.{" "}
You'll need an Ethereum Wallet to sign-in.{" "}
<a
href="https://ethereum.org/en/wallets/"
target="_blank"
Expand All @@ -39,30 +22,14 @@ export default function Connectors({ className }) {
<ExternalLinkIcon size={12} className="inline ml-1" />
</a>
</p>

<div className="pt-6 space-y-2">
<div className="pt-6 pb-3 text-xs opacity-50">Connect with:</div>
<div className="space-y-2">
{connectors.map((connector) => (
<Button
size="sm"
disabled={!connector.ready || isLoading}
key={connector.id}
onClick={() => connect({ connector })}
className="w-full flex items-start !justify-start py-1"
color="gray"
>
{isLoading && connector.id === pendingConnector?.id && (
<div className="mr-2">
<Spinner size="xs" color="gray" />
</div>
)}
<div className="flex items-center gap-3 !justify-start">
<img
src={`svg/icn-connect-${connector.id}.svg`}
className="hidden sm:inline"
/>
<span className="text-sm">Connect with {connector.name}</span>
</div>
</Button>
<ConnectorButton
key={connector.uid}
connector={connector}
onClick={() => connect({ connector, chainId })}
/>
))}
</div>
</div>
Expand Down
9 changes: 1 addition & 8 deletions src/pages/Connect/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,12 @@ export default function Connect() {
<img src="govnft.svg" className="h-8 mr-1.5" alt="GOVNFT" />
<SvgLoader
src="/wordmark.svg"
className="hidden sm:block h-4 w-auto dark:text-white"
className="block h-4 w-auto dark:text-white"
alt="GOVNFT"
/>
</NavLink>

<div className="pt-16 pb-32">
<a href="/landing" className="inline lg:hidden">
<div className="flex justify-center py-16">
<div className="flex items-center">
<img src="govnft.svg" className="ml-2 mr-3 h-9" alt="GOVNFT" />
</div>
</div>
</a>
{!isConnected && <Connectors className="flex justify-center" />}
</div>

Expand Down
37 changes: 37 additions & 0 deletions src/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { isEmpty } from "lodash";
import { createConfig, http } from "wagmi";
import {
coinbaseWallet,
injected,
safe,
walletConnect,
} from "wagmi/connectors";

import { DEFAULT_CHAIN, RPC_URI, WALLETCONNECT_PROJECT_ID } from "./constants";
export const CUSTOM_RPC_URI_KEY = "customRPC";

export const getRpc = (): string => {
const customRpc = window.localStorage.getItem(CUSTOM_RPC_URI_KEY);

if (isEmpty(customRpc)) {
return RPC_URI;
}

return customRpc;
};

const config = createConfig({
chains: [DEFAULT_CHAIN],
transports: {
[DEFAULT_CHAIN.id]: http(getRpc()),
},
multiInjectedProviderDiscovery: false,
connectors: [
injected(),
walletConnect({ projectId: WALLETCONNECT_PROJECT_ID }),
coinbaseWallet({ appName: "GovNFT" }),
safe(),
],
});

export default config;
Loading