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

feat(examples): add external wallet support example #2268

Closed
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": ["../../.eslintrc", "plugin:react/recommended", "plugin:react-hooks/recommended"],
"plugins": ["react", "react-hooks"],
"rules": {
"react/react-in-jsx-scope": "off"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/dist/
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>a minimal MUD client</title>
</head>
<body>
<div id="react-root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "client-react-external-wallet",
"version": "0.0.0",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"build": "vite build",
"dev": "wait-port localhost:8545 && vite",
"preview": "vite preview",
"test": "tsc"
},
"dependencies": {
"@latticexyz/common": "link:../../../../packages/common",
"@latticexyz/dev-tools": "link:../../../../packages/dev-tools",
"@latticexyz/store-sync": "link:../../../../packages/store-sync",
"contracts": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "7.5.5",
"viem": "1.14.0",
"wagmi": "1.4.13"
},
"devDependencies": {
"@types/react": "18.2.22",
"@types/react-dom": "18.2.7",
"@vitejs/plugin-react": "^3.1.0",
"eslint-plugin-react": "7.31.11",
"eslint-plugin-react-hooks": "4.6.0",
"vite": "^4.2.1",
"wait-port": "^1.0.4"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useMUDRead } from "./mud/read";
import { useMUDWrite } from "./mud/write";

export const App = () => {
const { useStore, tables } = useMUDRead();
const mudWrite = useMUDWrite();

const counter = useStore((state) => state.getValue(tables.CounterTable, {}));

return (
<div>
<div>Counter: {counter?.value ?? "unset"}</div>
<div>
{mudWrite && (
<button type="button" onClick={() => mudWrite.systemCalls.increment()}>
Increment
</button>
)}
</div>
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect } from "react";
import { useMUDRead } from "./mud/read";
import { useMUDWrite } from "./mud/write";

export const DevTools = () => {
const mudRead = useMUDRead();
const mudWrite = useMUDWrite();

useEffect(() => {
if (!mudWrite) return;

// TODO: Handle unmount properly by updating the dev-tools implementation.
let unmount: (() => void) | null = null;

import("@latticexyz/dev-tools")
.then(({ mount }) =>
mount({
config: mudRead.mudConfig,
publicClient: mudRead.publicClient,
walletClient: mudWrite.walletClient,
latestBlock$: mudRead.latestBlock$,
storedBlockLogs$: mudRead.storedBlockLogs$,
worldAddress: mudRead.worldAddress,
worldAbi: mudWrite.worldContract.abi,
write$: mudWrite.write$,
useStore: mudRead.useStore,
})
)
.then((result) => {
if (result) {
unmount = result;
}
});

return () => {
if (unmount) {
unmount();
}
};
}, [mudWrite?.walletClient.account.address]);

return null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { BaseError } from "viem";
import { useAccount, useConnect, useDisconnect, useNetwork, useSwitchNetwork } from "wagmi";

export const ExternalWallet = () => {
const { isConnected } = useAccount();

return (
<div>
<Connect />
{isConnected && <Network />}
</div>
);
};

// Based on https://github.com/wevm/create-wagmi/blob/create-wagmi%401.0.5/templates/vite-react/default/src/components/Connect.tsx
function Connect() {
const { connector, isConnected } = useAccount();
const { connect, connectors, error, isLoading, pendingConnector } = useConnect();
const { disconnect } = useDisconnect();

return (
<div>
<div>
{isConnected && <button onClick={() => disconnect()}>Disconnect from {connector?.name}</button>}

{connectors
.filter((x) => x.ready && x.id !== connector?.id)
.map((x) => (
<button key={x.id} onClick={() => connect({ connector: x })}>
Connect {x.name}
{isLoading && x.id === pendingConnector?.id && " (connecting)"}
</button>
))}
</div>

{error && <div>{(error as BaseError).shortMessage}</div>}
</div>
);
}

// Based on https://github.com/wevm/create-wagmi/blob/create-wagmi%401.0.5/templates/vite-react/default/src/components/NetworkSwitcher.tsx
function Network() {
const { chain } = useNetwork();
const { chains, error, isLoading, pendingChainId, switchNetwork } = useSwitchNetwork();
const { address } = useAccount();

const otherChains = chains.filter((x) => x.id !== chain?.id);

return (
<div>
<div>{address}</div>
<div>
Connected to {chain?.name ?? chain?.id}
{chain?.unsupported && " (unsupported)"}
</div>
{switchNetwork && !!otherChains.length && (
<div>
Switch to:{" "}
{otherChains.map((x) => (
<button key={x.id} onClick={() => switchNetwork(x.id)}>
{x.name}
{isLoading && x.id === pendingChainId && " (switching)"}
</button>
))}
</div>
)}

<div>{error?.message}</div>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import ReactDOM from "react-dom/client";
import { WagmiConfig } from "wagmi";
import { ExternalWallet } from "./ExternalWallet";
import { MUDReadProvider } from "./mud/read";
import { MUDWriteProvider } from "./mud/write";
import { App } from "./App";
import { DevTools } from "./DevTools";
import { setup } from "./mud/setup";

const rootElement = document.getElementById("react-root");
if (!rootElement) throw new Error("React root not found");
const root = ReactDOM.createRoot(rootElement);

// TODO: figure out if we actually want this to be async or if we should render something else in the meantime
setup().then(({ mud, wagmiConfig }) => {
root.render(
<WagmiConfig config={wagmiConfig}>
<ExternalWallet />
<MUDReadProvider value={mud}>
<MUDWriteProvider>
<App />
{import.meta.env.DEV && <DevTools />}
</MUDWriteProvider>
</MUDReadProvider>
</WagmiConfig>
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { type MUDRead } from "./read";
import { type MUDWrite } from "./write";

export const createSystemCalls = (mudRead: MUDRead, mudWrite: MUDWrite) => ({
increment: async () => {
const tx = await mudWrite.worldContract.write.increment();
mudRead.waitForTransaction(tx);
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { type Hex } from "viem";
import worlds from "contracts/worlds.json";
import { supportedChains } from "./supportedChains";

export function getNetworkConfig() {
const params = new URLSearchParams(window.location.search);

const chainId = Number(params.get("chainId") || params.get("chainid") || import.meta.env.VITE_CHAIN_ID || 31337);

const chainIndex = supportedChains.findIndex((c) => c.id === chainId);
const chain = supportedChains[chainIndex];
if (!chain) {
throw new Error(`Chain ${chainId} not found`);
}

const world = worlds[chain.id.toString()];
const worldAddress = params.get("worldAddress") || world?.address;
if (!worldAddress) {
throw new Error(`No world address found for chain ${chainId}. Did you run \`mud deploy\`?`);
}

const initialBlockNumber = params.has("initialBlockNumber")
? Number(params.get("initialBlockNumber"))
: world?.blockNumber ?? 0;

return {
chainId,
chain,
worldAddress: worldAddress as Hex,
initialBlockNumber,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { createContext, type ReactNode, useContext } from "react";
import { type SetupNetworkResult } from "./setupNetwork";

export type MUDRead = SetupNetworkResult;

const MUDReadContext = createContext<MUDRead | null>(null);

type Props = {
children: ReactNode;
value: MUDRead;
};

export const MUDReadProvider = ({ children, value }: Props) => {
const currentValue = useContext(MUDReadContext);
if (currentValue) throw new Error("MUDReadProvider can only be used once");
return <MUDReadContext.Provider value={value}>{children}</MUDReadContext.Provider>;
};

export const useMUDRead = () => {
const value = useContext(MUDReadContext);
if (!value) throw new Error("Must be used within a MUDReadProvider");
return value;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createConfig } from "wagmi";
import { InjectedConnector } from "wagmi/connectors/injected";
import { setupNetwork } from "./setupNetwork";

export async function setup() {
const mud = await setupNetwork();

const wagmiConfig = createConfig({
autoConnect: true,
connectors: [
new InjectedConnector({
chains: [mud.publicClient.chain],
}),
],
publicClient: mud.publicClient,
});

return {
mud,
wagmiConfig,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { createPublicClient, fallback, webSocket, http, type ClientConfig } from "viem";
import { syncToZustand } from "@latticexyz/store-sync/zustand";
import { getNetworkConfig } from "./getNetworkConfig";
import { transportObserver } from "@latticexyz/common";
import mudConfig from "contracts/mud.config";

export type SetupNetworkResult = Awaited<ReturnType<typeof setupNetwork>>;

export async function setupNetwork() {
const networkConfig = getNetworkConfig();

const clientOptions = {
chain: networkConfig.chain,
transport: transportObserver(fallback([webSocket(), http()])),
pollingInterval: 1000,
} as const satisfies ClientConfig;

const publicClient = createPublicClient(clientOptions);

const { tables, useStore, latestBlock$, storedBlockLogs$, waitForTransaction } = await syncToZustand({
config: mudConfig,
address: networkConfig.worldAddress,
publicClient,
startBlock: BigInt(networkConfig.initialBlockNumber),
});

return {
worldAddress: networkConfig.worldAddress,
mudConfig,
tables,
useStore,
publicClient,
latestBlock$,
storedBlockLogs$,
waitForTransaction,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { type MUDChain, mudFoundry } from "@latticexyz/common/chains";

export const supportedChains: MUDChain[] = [mudFoundry];
Loading
Loading