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

draft: rainbow kit support #1548

Closed
wants to merge 8 commits into from
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
6 changes: 3 additions & 3 deletions packages/common/src/chains/mudFoundry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { MUDChain } from "./types";

export const mudFoundry = {
...foundry,
fees: {
defaultPriorityFee: 0n,
},
// fees: {
// defaultPriorityFee: 0n,
// },
Copy link
Member

@holic holic Sep 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you encounter serialization errors with this? I think @yonadaaa saw a similar thing.

If you have the error handy, we can bubble this up to the wagmi repo/team to get it fixed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea commented out to make things work for now. The error is:

Uncaught (in promise) TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)
    at getWalletConnectConnector (index.js:303:33)
    at createConnector (index.js:544:50)
    at index.js:96:71
    at Array.forEach (<anonymous>)
    at index.js:73:21
    at new Config (chunk-LAFZBYO7.js:398:60)
    at createConfig (chunk-LAFZBYO7.js:636:19)
    at createConfig2 (index.js:37:18)
    at setupNetwork (setupNetwork.ts:63:23)
    ```

} as const satisfies MUDChain;
1 change: 0 additions & 1 deletion packages/common/src/createContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
getAbiItem,
getContract,
getFunctionSelector,
trim,
} from "viem";
import pRetry from "p-retry";
import { AbiFunction } from "abitype";
Expand Down
4 changes: 3 additions & 1 deletion templates/react/packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@
"@latticexyz/store-sync": "link:../../../../packages/store-sync",
"@latticexyz/utils": "link:../../../../packages/utils",
"@latticexyz/world": "link:../../../../packages/world",
"@rainbow-me/rainbowkit": "^1.0.11",
"contracts": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "7.5.5",
"viem": "1.6.0"
"viem": "1.6.0",
"wagmi": "^1.4.2"
},
"devDependencies": {
"@types/react": "18.2.22",
Expand Down
40 changes: 34 additions & 6 deletions templates/react/packages/client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import "@rainbow-me/rainbowkit/styles.css";
import { ConnectButton } from "@rainbow-me/rainbowkit";
import { useWalletClient, useAccount } from "wagmi";
import { useComponentValue } from "@latticexyz/react";
import { useMUD } from "./MUDContext";
import { setup } from "./mud/setup";
import { singletonEntity } from "@latticexyz/store-sync/recs";
import { useSystemCalls } from "./hooks/useSystemCalls";
import { useDelegationControl } from "./hooks/useDelegationControl";

export const App = () => {
const {
components: { Counter },
systemCalls: { increment },
} = useMUD();
type Props = {
setup: Awaited<ReturnType<typeof setup>>;
};

export const App = ({ setup }: Props) => {
const { network, components } = setup;

// TODO rename to delegatee
const { walletClient: burnerWalletClient } = network;
const { Counter } = components;

const walletClient = useWalletClient();
const account = useAccount();
const systemCalls = useSystemCalls(network, components, walletClient.data);
const delegationControlId = useDelegationControl(walletClient.data, burnerWalletClient, components);
const counter = useComponentValue(Counter, singletonEntity);

return (
Expand All @@ -19,11 +34,24 @@ export const App = () => {
type="button"
onClick={async (event) => {
event.preventDefault();
console.log("new counter value:", await increment());
console.log("new counter value:", await systemCalls?.increment());
}}
>
Increment
</button>
<ConnectButton />
{account.isConnected && !delegationControlId ? (
<button
type="button"
onClick={async (event) => {
event.preventDefault();
console.log("registering delegation");
await systemCalls?.registerDelegation(burnerWalletClient.account.address);
}}
>
Delegate actions to burner wallet: {burnerWalletClient.account.address}
</button>
) : null}
</>
);
};
33 changes: 27 additions & 6 deletions templates/react/packages/client/src/MUDContext.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
import { createContext, ReactNode, useContext } from "react";
import { SetupResult } from "./mud/setup";
import { createContext, ReactNode, useContext, useState, useEffect, useMemo } from "react";
import { setup, SetupResult } from "./mud/setup";
import { usePromise } from "@latticexyz/react";

const MUDContext = createContext<SetupResult | null>(null);

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

export const MUDProvider = ({ children, value }: Props) => {
// THis is not used. Context doesn't play well with async data fetch so used hook instead
export const MUDProvider = ({ children }: Props) => {
const currentValue = useContext(MUDContext);
if (currentValue) throw new Error("MUDProvider can only be used once");
return <MUDContext.Provider value={value}>{children}</MUDContext.Provider>;

// Had weird re-rendering issue with the approach below
// const setupResult = usePromise(setup());

// if (setupResult.status === "rejected") throw new Error("Ecountered error while setting up MUD");

// if (setupResult.status !== "fulfilled") return;
const setupPromise = useMemo(() => {
return setup();
}, []);

const [setupResult, setSetupResult] = useState<Awaited<ReturnType<typeof setup>> | null>(null);

useEffect(() => {
setupPromise.then((result) => setSetupResult(result));

return () => {
setupPromise.then((result) => result.network.world.dispose());
};
}, [setupPromise]);

return <MUDContext.Provider value={setupResult}>{children}</MUDContext.Provider>;
};

export const useMUD = () => {
const value = useContext(MUDContext);
if (!value) throw new Error("Must be used within a MUDProvider");
return value;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { ComponentValue, Type, getComponentValue } from "@latticexyz/recs";
import { useEffect, useState } from "react";
import { WalletClient, Transport, Chain, Account } from "viem";
import { encodeEntity } from "@latticexyz/store-sync/recs";
import { ClientComponents } from "../mud/createClientComponents";

export function useDelegationControl(
delegator: WalletClient<Transport, Chain, Account> | null | undefined,
delegatee: WalletClient<Transport, Chain, Account>,
components: ClientComponents
) {
const [delegationControlId, setDelegationControlId] = useState<
| ComponentValue<
{
__staticData: Type.OptionalString;
__encodedLengths: Type.OptionalString;
__dynamicData: Type.OptionalString;
} & {
delegationControlId: Type.String;
},
unknown
>
| undefined
>(undefined);

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

const delegationsKeyEntity = encodeEntity(components.Delegations.metadata.keySchema, {
delegator: delegator.account.address,
delegatee: delegatee.account.address,
});
const delegationControlId = getComponentValue(components.Delegations, delegationsKeyEntity);

setDelegationControlId(delegationControlId);

// TODO what's the cleanup fn?
}, [delegator]);

return delegationControlId;
}
24 changes: 24 additions & 0 deletions templates/react/packages/client/src/hooks/usePromiseValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useEffect, useState, useRef } from "react";

export const usePromiseValue = <T>(promise: Promise<T> | null) => {
const promiseRef = useRef<typeof promise>(promise);
const [value, setValue] = useState<T | null>(null);
useEffect(() => {
if (!promise) return;
let isMounted = true;
promiseRef.current = promise;
// TODO: do something with promise errors?
promise.then((resolvedValue) => {
// skip if unmounted (state changes will cause errors otherwise)
if (!isMounted) return;
// If our promise was replaced before it resolved, ignore the result
if (promiseRef.current !== promise) return;

setValue(resolvedValue);
});
return () => {
isMounted = false;
};
}, [promise]);
return value;
};
17 changes: 17 additions & 0 deletions templates/react/packages/client/src/hooks/useSetup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect, useMemo } from "react";
import { usePromiseValue } from "./usePromiseValue";
import { setup } from "../mud/setup";

export const useSetup = () => {
const setupPromise = useMemo(() => {
return setup();
}, []);

useEffect(() => {
return () => {
setupPromise.then((result) => result.network.world.dispose());
};
}, [setupPromise]);

return usePromiseValue(setupPromise);
};
25 changes: 25 additions & 0 deletions templates/react/packages/client/src/hooks/useSystemCalls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useEffect, useState } from "react";
import { WalletClient, Transport, Chain, Account } from "viem";
import { createSystemCalls } from "../mud/createSystemCalls";
import { SetupNetworkResult } from "../mud/setupNetwork";
import { ClientComponents } from "../mud/createClientComponents";

export function useSystemCalls(
network: SetupNetworkResult,
components: ClientComponents,
client: WalletClient<Transport, Chain, Account> | null | undefined
) {
// TODO type systemCalls
const [systemCalls, setSystemCalls] = useState<ReturnType<typeof createSystemCalls> | undefined>(undefined);

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

const systemCalls = createSystemCalls(network, components, client);
setSystemCalls(systemCalls);

// TODO what's the cleanup fn?
}, [client]);

return systemCalls;
}
59 changes: 35 additions & 24 deletions templates/react/packages/client/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,45 @@
import ReactDOM from "react-dom/client";
import { App } from "./App";
import { setup } from "./mud/setup";
import { MUDProvider } from "./MUDContext";
import { RainbowKitProvider } from "@rainbow-me/rainbowkit";
import { WagmiConfig } from "wagmi";
import { share } from "rxjs";
import mudConfig from "contracts/mud.config";
import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json";
import { App } from "./App";
import { MUDProvider, useMUD } from "./MUDContext";
import { useSetup } from "./hooks/useSetup";

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(async (result) => {
root.render(
<MUDProvider value={result}>
<App />
</MUDProvider>
);
const AppWithWalletContext = () => {
const setup = useSetup();

// https://vitejs.dev/guide/env-and-mode.html
if (import.meta.env.DEV) {
const { mount: mountDevTools } = await import("@latticexyz/dev-tools");
mountDevTools({
config: mudConfig,
publicClient: result.network.publicClient,
walletClient: result.network.walletClient,
latestBlock$: result.network.latestBlock$,
storedBlockLogs$: result.network.storedBlockLogs$,
worldAddress: result.network.worldContract.address,
worldAbi: result.network.worldContract.abi,
write$: result.network.write$,
recsWorld: result.network.world,
});
if (import.meta.env.DEV && setup) {
import("@latticexyz/dev-tools").then(({ mount: mountDevTools }) =>
mountDevTools({
config: mudConfig,
publicClient: setup.network.publicClient,
walletClient: setup.network.walletClient,
latestBlock$: setup.network.latestBlock$,
storedBlockLogs$: setup.network.storedBlockLogs$,
worldAddress: setup.network.worldAddress,
worldAbi: IWorldAbi,
write$: setup.network.write$.asObservable().pipe(share()),
recsWorld: setup.network.world,
})
);
}
});

if (!setup) return <>Loading...</>;
return (
<WagmiConfig config={setup.network.wagmiConfig}>
<RainbowKitProvider chains={[setup.network.chain]}>
<App setup={setup} />
</RainbowKitProvider>
</WagmiConfig>
);
};

root.render(<AppWithWalletContext />);
7 changes: 7 additions & 0 deletions templates/react/packages/client/src/mud/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { encodePacked, toHex } from "viem";

const ROOT_NAMESPACE = 0;

const encodedRootSpace = toHex(ROOT_NAMESPACE, { size: 16 });
const encodedDelegationId = toHex("unlimited.d", { size: 16 });
export const UNLIMITED_DELEGATION = encodePacked(["bytes16", "bytes16"], [encodedRootSpace, encodedDelegationId]);
33 changes: 27 additions & 6 deletions templates/react/packages/client/src/mud/createSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
* Create the system calls that the client can use to ask
* for changes in the World state (using the System contracts).
*/

import { Hex, WalletClient, Transport, Chain, Account } from "viem";
import { getComponentValue } from "@latticexyz/recs";
import { ClientComponents } from "./createClientComponents";
import { SetupNetworkResult } from "./setupNetwork";
import { singletonEntity } from "@latticexyz/store-sync/recs";
import { SetupNetworkResult } from "./setupNetwork";
import { ClientComponents } from "./createClientComponents";
import { UNLIMITED_DELEGATION } from "./constants";
import { createContract } from "@latticexyz/common";
import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json";

export type SystemCalls = ReturnType<typeof createSystemCalls>;

Expand All @@ -28,8 +31,9 @@ export function createSystemCalls(
* through createClientComponents.ts, but it originates in
* syncToRecs (https://github.com/latticexyz/mud/blob/26dabb34321eedff7a43f3fcb46da4f3f5ba3708/templates/react/packages/client/src/mud/setupNetwork.ts#L39).
*/
{ worldContract, waitForTransaction }: SetupNetworkResult,
{ Counter }: ClientComponents
{ worldAddress, waitForTransaction, getResourceSelector, publicClient, write$, worldContract }: SetupNetworkResult,
{ Counter }: ClientComponents,
walletClient: WalletClient<Transport, Chain, Account>
) {
const increment = async () => {
/*
Expand All @@ -38,12 +42,29 @@ export function createSystemCalls(
* is in the root namespace, `.increment` can be called directly
* on the World contract.
*/
const tx = await worldContract.write.increment();
// gas added here is a workaround for intrinsic gas too high error
// likely something along with commenting out the defaultPriorityFee on chain config?
const tx = await worldContract.write.increment({ gas: 1500000 });
await waitForTransaction(tx);
return getComponentValue(Counter, singletonEntity);
};

const registerDelegation = async (delegatee: Hex) => {
const contractWithDelegator = createContract({
address: worldAddress as Hex,
abi: IWorldAbi,
publicClient,
walletClient,
onWrite: (write) => write$.next(write),
getResourceSelector,
});
const callData = "0x";
const tx = await contractWithDelegator.write.registerDelegation([delegatee, UNLIMITED_DELEGATION, callData]);
await waitForTransaction(tx);
};

return {
increment,
registerDelegation,
};
}
Loading