Guides
Add chains to the client

Add chains to the client

In this tutorial you modify a template application to use a public blockchain instead of anvil (opens in a new tab). Note that this is not required if you are going to use Lattice chains, redstone (opens in a new tab) and garnet (opens in a new tab)

Setup

Create a new MUD application from the template. Use the vanilla template.

pnpm create mud@latest tutorial --template vanilla
cd tutorial

You can also use the react-ecs or threejs templates without any changes to the tutorial. If you wish to use the react template you'll need to modify a bit to account for the use of Zustand instead of RECs.

File changes

You need to edit supportedChains.ts, and possibly also setupNetwork.ts.

  • Edit the file packages/client/src/mud/supportedChains.ts to add the chain definition from Viem. You can see the list of chains supported by Viem (opens in a new tab). If you need a different chain you can use defineChain (opens in a new tab).

    supportedChains.ts
    import { MUDChain, mudFoundry, redstone, garnet } from "@latticexyz/common/chains";
    import { holesky } from "viem/chains";
     
    export const supportedChains: MUDChain[] = [mudFoundry, redstone, garnet, holesky];
  • If the chain object in Viem doesn't have a webSocket endpoint, only an HTTP one, you need to edit packages/client/src/mud/setupNetwork.ts (opens in a new tab) to only use a webSocket endpoint when one is defined. You might also wish to deal with the possibility you only have a webSocket endpoint defined, depending on the chains you support.

Use the application

When you run the client, set two parameters:

  • chainId, the chain ID. You can set this information in the URL, or in the vite environment as VITE_CHAIN_ID.
  • initialBlockNumber, the block number where the World contract was first deployed. Without this value, the client will try to synchronize from the beginning of the blockchain, which could take a long time. You can set this value either in the URL, or the worlds.json file (as blockNumber).

For example, to connect to the Holesky World at address 0x78900cc99939b24a95b2892961ad0c701df97993 (opens in a new tab), which contains the standard contract code, you use this URL:

http://localhost:3000/?chainid=17000

And this file in packages/contracts/worlds.json:

{
  "31337": {
    "address": "0x8d8b6b8414e1e3dcfd4168561b9be6bd3bf6ec4b"
  },
  "17000": {
    "address": "0x78900cc99939b24a95b2892961ad0c701df97993",
    "blockNumber": 1844083
  }
}