### Setup Local Explorer Example Source: https://github.com/latticexyz/mud/blob/main/packages/explorer/README.md Navigate to the local-explorer example directory and install its dependencies. ```sh cd examples/local-explorer pnpm install ``` -------------------------------- ### Install dependencies and start the development server Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/adding-delegation.mdx Run these commands to install required Node packages and launch the application locally. ```sh pnpm install pnpm dev ``` -------------------------------- ### Start Development Server Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Navigates to the project directory, installs dependencies, and launches the development environment. ```sh cd tutorial pnpm install pnpm dev ``` -------------------------------- ### Install dependencies and start development services Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/emojimon/2-getting-started.mdx Run this command to install project dependencies and launch the anvil node, contracts deployer, and client. ```bash cd emojimon && pnpm install && pnpm dev ``` -------------------------------- ### Install MUD Project Dependencies Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/hello-world/add-chain-client.mdx Installs project dependencies and starts the development server for a new MUD application created from the vanilla template. ```sh pnpm create mud@latest --name tutorial --template vanilla cd tutorial pnpm install pnpm dev ``` -------------------------------- ### Install and run store-indexer Source: https://github.com/latticexyz/mud/blob/main/packages/store-indexer/README.md Commands to install the package and execute the indexer binaries. ```sh npm install @latticexyz/store-indexer npm sqlite-indexer # or npm postgres-indexer & npm postgres-frontend ``` ```sh npx -p @latticexyz/store-indexer sqlite-indexer # or npx -p @latticexyz/store-indexer postgres-indexer & npx -p @latticexyz/store-indexer postgres-frontend ``` -------------------------------- ### Module Installation Steps Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/modules.mdx Individual steps for deploying and installing a module within a script. ```solidity KeysWithValueModule keysWithValueModule = new KeysWithValueModule(); ``` ```solidity ResourceId sourceTableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: "", name: "Tasks" }); ``` ```solidity world.installRootModule(keysWithValueModule, abi.encode(sourceTableId)); ``` -------------------------------- ### Clone and navigate to the example repository Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/adding-delegation.mdx Use these commands to clone the MUD monorepo and enter the multiple-accounts example directory. ```sh git clone https://github.com/latticexyz/mud cd mud/examples/multiple-accounts ``` -------------------------------- ### Start the user interface Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Launch the development server using pnpm. ```sh pnpm vite ``` -------------------------------- ### Install and Run abi-ts Source: https://github.com/latticexyz/mud/blob/main/packages/abi-ts/CHANGELOG.md Commands to install the package and execute the generation process. ```console pnpm add @latticexyz/abi-ts pnpm abi-ts ``` ```console pnpm abi-ts --input 'abi/IWorld.sol/IWorld.abi.json' ``` -------------------------------- ### Start Lattice Faucet Server Source: https://github.com/latticexyz/mud/blob/main/packages/faucet/README.md Use this command to start the faucet service. Ensure environment variables are exported beforehand. ```sh npx @latticexyz/faucet ``` -------------------------------- ### Install Module Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/world-external.mdx Installs a module into the system with optional encoded arguments. ```solidity function installModule(IModule module, bytes memory encodedArgs) external; ``` -------------------------------- ### Install Foundry Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Commands to install the Foundry toolchain. ```sh curl -L https://foundry.paradigm.xyz | bash export PATH=$PATH:~/.foundry/bin ``` ```sh curl -L https://foundry.paradigm.xyz | bash export PATH=$PATH:~/.foundry/bin ``` -------------------------------- ### Environment Configuration Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/balance.mdx Example .env file configuration for local development and deployment. ```text # This .env file is for demonstration purposes only. # # This should usually be excluded via .gitignore and the env vars attached to # your deployment environment, but we're including this here for ease of local # development. Please do not commit changes to this file! # # Enable debug logs for MUD CLI DEBUG=mud:* # # Anvil default private key: PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # Address for the world we are extending WORLD_ADDRESS=0xC14fBdb7808D9e2a37c1a45b635C8C3fF64a1cc1 ``` -------------------------------- ### install Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx Installs the module as a non-root module within the World context. ```APIDOC ## install ### Description Installs the module. This function is invoked by the World contract during the installModule process. ### Parameters #### Request Body - **encodedArgs** (bytes) - Required - The ABI encoded arguments that may be needed during the installation process. ``` -------------------------------- ### Install Git Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Commands to install Git across various operating systems. ```sh sudo dnf install git-all ``` ```sh sudo apt install git-all ``` ```sh brew install git ``` ```powershell choco install git ``` -------------------------------- ### Create a New MUD Project Source: https://context7.com/latticexyz/mud/llms.txt Use the create-mud CLI tool to scaffold a new MUD project. Follow the prompts to select a template and then install dependencies and start development. ```bash # Create a new MUD project pnpm create mud@latest # Follow the prompts to select a template: # - vanilla: Minimal setup # - react: React with hooks # - react-ecs: React with ECS pattern # - phaser: Phaser game engine # - threejs: Three.js 3D graphics # Start development cd my-project pnpm install pnpm dev ``` -------------------------------- ### Install and Run abi-ts Source: https://github.com/latticexyz/mud/blob/main/packages/abi-ts/README.md Install the package using pnpm and run the command to generate type declaration files. ```bash pnpm add @latticexyz/abi-ts pnpm abi-ts ``` -------------------------------- ### Install Stash and Store Packages Source: https://github.com/latticexyz/mud/blob/main/packages/stash/README.md Install the necessary packages for the Stash client state library and the MUD store. ```bash pnpm add @latticexyz/stash @latticexyz/store ``` -------------------------------- ### InitModule installRoot Function Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/internal/init-module.mdx The root installation function for the InitModule. It registers core tables, systems, and function selectors within the World. This function must be called during the initial setup of a World. ```solidity function installRoot(bytes memory) public override; ``` -------------------------------- ### Setup Network with SQL API Source: https://github.com/latticexyz/mud/blob/main/docs/pages/indexer/sql.mdx Update `packages/client/src/mud/setupNetwork.ts` to integrate the SQL API for selective data synchronization. This setup includes configuring viem clients, contract interactions, and the MUD indexer. ```typescript /* * The MUD client code is built on top of viem * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, ClientConfig, getContract, } from "viem"; import { SyncFilter, getSnapshot, selectFrom } from "@latticexyz/store-sync/internal"; import { syncToZustand } from "@latticexyz/store-sync/zustand"; import { getNetworkConfig } from "./getNetworkConfig"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; /* * Import our MUD config, which includes strong types for * our tables and other config options. We use this to generate * things like RECS components and get back strong types for them. * * See https://mud.dev/templates/typescript/contracts#mudconfigts * for the source of this information. */ import mudConfig from "contracts/mud.config"; export type SetupNetworkResult = Awaited>; export async function setupNetwork() { const networkConfig = await getNetworkConfig(); /* * Create a viem public (read only) client * (https://viem.sh/docs/clients/public.html) */ const clientOptions = { chain: networkConfig.chain, transport: transportObserver(fallback([webSocket(), http()])), pollingInterval: 1000, } as const satisfies ClientConfig; const publicClient = createPublicClient(clientOptions); /* * Create an observable for contract writes that we can * pass into MUD dev tools for transaction observability. */ const write$ = new Subject(); /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). */ const burnerAccount = createBurnerAccount(networkConfig.privateKey as Hex); const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, }) .extend(transactionQueue()) .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. */ const worldContract = getContract({ address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, }); const indexerUrl = "https://indexer.mud.garnetchain.com/q"; const yesterday = Date.now() / 1000 - 24 * 60 * 60; const filters: SyncFilter[] = [ selectFrom({ table: mudConfig.tables.app__Tasks, where: `"createdAt" > ${yesterday}`, }), { table: mudConfig.tables.app__Creator }, ]; const { initialBlockLogs } = await getSnapshot({ indexerUrl, storeAddress: networkConfig.worldAddress as Hex, filters, chainId: networkConfig.chainId, }); const liveSyncFilters = filters.map((filter) => ({ tableId: filter.table.tableId, })); /* * Sync on-chain state into RECS and keeps our client in sync. * Uses the MUD indexer if available, otherwise falls back * to the viem publicClient to make RPC calls to fetch MUD * events from the chain. */ const { tables, useStore, latestBlock$, storedBlockLogs$, waitForTransaction } = await syncToZustand({ initialBlockLogs, filters: liveSyncFilters, config: mudConfig, address: networkConfig.worldAddress as Hex, publicClient, startBlock: BigInt(networkConfig.initialBlockNumber), }); return { tables, useStore, publicClient, walletClient: burnerWalletClient, latestBlock$, storedBlockLogs$, waitForTransaction, worldContract, write$: write$.asObservable().pipe(share()), }; } ``` -------------------------------- ### Install and Run World Explorer Source: https://github.com/latticexyz/mud/blob/main/packages/explorer/README.md Install the World Explorer package and run it using pnpm. Alternatively, use npx to execute it directly. ```sh pnpm add @latticexyz/explorer pnpm explorer ``` ```sh npx @latticexyz/explorer ``` -------------------------------- ### Install Node.js v20 Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Commands to install Node.js version 20 on different operating systems. ```sh curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash nvm install 20 ``` ```powershell # installs Chocolatey (Windows Package Manager) Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')); # download and install Node.js choco install nodejs --version="^20" ``` -------------------------------- ### Configure Start Block for syncToRecs Source: https://github.com/latticexyz/mud/blob/main/packages/store-sync/CHANGELOG.md Specify a starting block number to optimize synchronization performance. ```ts import { syncToRecs } from "@latticexyz/store-sync/recs"; import worlds from "contracts/worlds.json"; syncToRecs({ startBlock: worlds['31337'].blockNumber, ... }); ``` -------------------------------- ### Clone MUD Repository and Install Dependencies Source: https://github.com/latticexyz/mud/blob/main/packages/explorer/README.md Clone the MUD repository, navigate to the root directory, install all project dependencies, and build the project. ```sh git clone git@github.com:latticexyz/mud.git cd mud pnpm install pnpm build ``` -------------------------------- ### IBaseWorld Initialization Source: https://github.com/latticexyz/mud/blob/main/docs/pages/changelog.mdx Initializes the World contract by installing the core module. ```APIDOC ## POST IBaseWorld/initialize ### Description Initializes the World contract. This can be called once by the creator to install the core module and register core tables. ### Method PUBLIC (Solidity) ### Parameters #### Request Body - **coreModule** (IModule) - Required - The core module to install. ``` -------------------------------- ### Install MUD Dev Tools Source: https://github.com/latticexyz/mud/blob/main/packages/dev-tools/README.md Install the MUD Dev Tools package using npm. ```bash npm install @latticexyz/dev-tools ``` -------------------------------- ### ModuleInstallationSystem Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/internal/init-module-implementation.mdx Handles the installation of modules into the World. ```APIDOC ## ModuleInstallationSystem ### Description A system contract to handle the installation of (non-root) modules in the World. ### Functions #### installModule Installs a module into the World under a specified namespace. _Validates the given module against the IModule interface and delegates the installation process. The module is then registered in the InstalledModules table._ ### Method `public onlyDelegatecall` ### Endpoint N/A (Smart Contract Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "module": "", "encodedArgs": "" } ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Install and Run Postgres Indexer Source: https://github.com/latticexyz/mud/blob/main/docs/pages/indexer/postgres-event-only.mdx Installs and runs the schemaless indexer using npx. This indexer stores MUD event records into a single monolithic table. ```bash npx -y -p @latticexyz/store-indexer postgres-indexer ``` -------------------------------- ### installRoot Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx Installs the module as a root module within the World context. ```APIDOC ## installRoot ### Description Installs the module as a root module. This function is invoked by the World contract during the installRootModule process. ### Parameters #### Request Body - **encodedArgs** (bytes) - Required - The ABI encoded arguments that may be needed during the installation process. ``` -------------------------------- ### Install and Build MUD Packages Source: https://github.com/latticexyz/mud/blob/main/docs/pages/contribute.mdx Install project dependencies and build the MUD packages using pnpm. This command is essential after cloning the repository. ```sh pnpm install pnpm build ``` -------------------------------- ### Install Module - IModule Interface Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx Use this function to install a module. It is invoked by the World contract and expects to be called via `msg.sender`. Logic might differ from `installRoot`. ```solidity function install(bytes memory encodedArgs) external; ``` -------------------------------- ### Start Postgres Decoded Indexer with Frontend Source: https://github.com/latticexyz/mud/blob/main/docs/pages/changelog.mdx This command starts both the indexer backend and the frontend for the Postgres decoded store-indexer. It's useful for local development and testing. ```bash pnpm start:postgres-decoded ``` -------------------------------- ### Install MUD Store package Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Add the @latticexyz/store package to your project dependencies. ```sh pnpm add @latticexyz/store@latest ``` -------------------------------- ### Get Subslice from Bytes (Start to End) in Solidity Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Returns a Slice representing a portion of a bytes array from a start index to the end, without copying data. This is a pure internal function. ```solidity function getSubslice(bytes memory data, uint256 start) internal pure returns (Slice); ``` -------------------------------- ### IBaseWorld Initialization Source: https://github.com/latticexyz/mud/blob/main/CHANGELOG.md Interface for initializing the World contract and installing core modules. ```APIDOC ## POST IBaseWorld/initialize ### Description Initializes the World contract by installing the core module. This can only be called once by the creator of the World. ### Method POST ### Parameters #### Request Body - **coreModule** (IModule) - Required - The core module to install. ### Response #### Success Response (200) - **status** (string) - Confirmation of successful initialization. ``` -------------------------------- ### Get Subslice from Bytes (Start and End) in Solidity Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Returns a Slice representing a portion of a bytes array between a start (inclusive) and end (exclusive) index, without copying data. This is a pure internal function. ```solidity function getSubslice(bytes memory data, uint256 start, uint256 end) internal pure returns (Slice); ``` -------------------------------- ### Usage Source: https://github.com/latticexyz/mud/blob/main/packages/vite-plugin-mud/README.md Example configurations for integrating vite-plugin-mud into your Vite project. ```typescript // vite.config.ts import { defineConfig } from "vite"; import { mud } from "vite-plugin-mud"; export default defineConfig({ plugins: [mud({ worldsFile: "worlds.json" })], }); ``` ```json // tsconfig.json { "compilerOptions": { "types": ["vite/client", "vite-plugin-mud/env"] } } ``` -------------------------------- ### Get Slice Pointer Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Returns the starting position (pointer) of a given slice in memory. Requires a Slice object. ```solidity function pointer(Slice self) internal pure returns (uint256); ``` -------------------------------- ### Get Bytes1 from Bytes32 Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Extracts a single byte from a bytes32 value starting at a specific position. This function is used by codegen libraries. ```Solidity function getBytes1(bytes32 data, uint256 start) internal pure returns (bytes1 output); ``` -------------------------------- ### Deploy and Register System Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Instantiates the MessageSystem and registers it with the World. ```solidity MessageSystem messageSystem = new MessageSystem(); world.registerSystem(systemResource, messageSystem, true); ``` -------------------------------- ### Get Bytes2 Sequence Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Extracts a 2-byte sequence from a bytes blob starting at a specific position. This function is used for retrieving specific byte ranges. ```Solidity function getBytes2(bytes memory data, uint256 start) internal pure returns (bytes2 output); ``` -------------------------------- ### Get Bytes1 from Bytes Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/misc.mdx Extracts a single byte from a bytes blob starting at a specific position. This is useful for accessing individual bytes within a larger byte array. ```Solidity function getBytes1(bytes memory data, uint256 start) internal pure returns (bytes1 output); ``` -------------------------------- ### Install and Run Postgres Indexer Source: https://github.com/latticexyz/mud/blob/main/docs/pages/indexer/postgres-decoded.mdx Set environment variables and run the store-indexer with npx. Ensure RPC_HTTP_URL and DATABASE_URL are configured. ```bash export RPC_HTTP_URL=http://127.0.0.1:8545 export DATABASE_URL=postgres://127.0.0.1/postgres npx -y -p @latticexyz/store-indexer postgres-decoded-indexer ``` -------------------------------- ### Environment configuration for World upgrade Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/upgrades.mdx Example .env file containing the private key and the target World proxy address for deployment scripts. ```bash # This .env file is for demonstration purposes only. # # This should usually be excluded via .gitignore and the env vars attached to # your deployment environment, but we're including this here for ease of local # development. Please do not commit changes to this file! # # Enable debug logs for MUD CLI DEBUG=mud:* # # Anvil default private key: PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 WORLD_ADDRESS=0xbe6b85dc88f969e45d8d8ae128c5a9c9744d6464 ``` -------------------------------- ### Get Dynamic Field Slice Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/store.mdx Retrieves a byte slice of a dynamic field. This operation is unchecked and may return invalid data if the start and end indices overflow. ```solidity function getDynamicFieldSlice( ResourceId tableId, bytes32[] memory keyTuple, uint8 dynamicFieldIndex, uint256 start, uint256 end ) external view returns (bytes memory data); ``` -------------------------------- ### Setup Network with Filtering Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/hello-world/filter-sync.mdx Configure the network client and set up data synchronization with specific filters. Imports 'pad' from viem and applies filters to the 'app__Counter' and 'app__History' tables. ```typescript /* * The MUD client code is built on top of viem * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, ClientConfig, getContract, } from "viem"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { pad } from "viem"; import { Subject, share } from "rxjs"; /* * Import our MUD config, which includes strong types for * our tables and other config options. We use this to generate * things like RECS components and get back strong types for them. * * See https://mud.dev/templates/typescript/contracts#mudconfigts * for the source of this information. */ import mudConfig from "contracts/mud.config"; export type SetupNetworkResult = Awaited>; export async function setupNetwork() { const networkConfig = await getNetworkConfig(); /* * Create a viem public (read only) client * (https://viem.sh/docs/clients/public.html) */ const clientOptions = { chain: networkConfig.chain, transport: transportObserver(fallback([webSocket(), http()])), pollingInterval: 1000, } as const satisfies ClientConfig; const publicClient = createPublicClient(clientOptions); /* * Create an observable for contract writes that we can * pass into MUD dev tools for transaction observability. */ const write$ = new Subject(); /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). */ const burnerAccount = createBurnerAccount(networkConfig.privateKey as Hex); const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, }) .extend(transactionQueue()) .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. */ const worldContract = getContract({ address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, }); /* * Sync on-chain state into RECS and keeps our client in sync. * Uses the MUD indexer if available, otherwise falls back * to the viem publicClient to make RPC calls to fetch MUD * events from the chain. */ const { components, latestBlock$, storedBlockLogs$, waitForTransaction } = await syncToRecs({ world, config: mudConfig, address: networkConfig.worldAddress as Hex, publicClient, startBlock: BigInt(networkConfig.initialBlockNumber), filters: [ { tableId: mudConfig.tables.app__Counter.tableId, }, { tableId: mudConfig.tables.app__History.tableId, key0: pad("0x01"), }, { tableId: mudConfig.tables.app__History.tableId, key0: pad("0x05"), }, ], }); return { world, components, playerEntity: encodeEntity({ address: "address" }, { address: burnerWalletClient.account.address }), publicClient, walletClient: burnerWalletClient, latestBlock$, storedBlockLogs$, waitForTransaction, worldContract, write$: write$.asObservable().pipe(share()), }; } ``` -------------------------------- ### Create a MUD World Project Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/modules.mdx Initialize a new MUD project with the 'react' template and start the development server. ```sh pnpm create mud@latest world --template react cd world pnpm dev ``` -------------------------------- ### Get Dynamic Field Slice Solidity Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/store-core.mdx Retrieves a portion (slice) of a dynamic field from a record. Specify the table ID, key tuple, field index, and the start and end positions for the slice. ```solidity function getDynamicFieldSlice( ResourceId tableId, bytes32[] memory keyTuple, uint8 dynamicFieldIndex, uint256 start, uint256 end ) public view virtual returns (bytes memory); ``` -------------------------------- ### Get Dynamic Field Data Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/store-core.mdx Retrieves a single dynamic field's data from a specified table using its key tuple. The dynamic field index is relative to the start of dynamic fields. ```solidity function getDynamicField( ResourceId tableId, bytes32[] memory keyTuple, uint8 dynamicFieldIndex ) internal view returns (bytes memory); ``` -------------------------------- ### Create MUD Project with Vanilla Template Source: https://github.com/latticexyz/mud/blob/main/docs/pages/templates/typescript/vanilla.mdx Use this command to start a new MUD project using the vanilla template. ```sh pnpm create mud@latest tutorial --template vanilla ``` -------------------------------- ### Get Dynamic Field Slice in Solidity Source: https://github.com/latticexyz/mud/blob/main/docs/pages/store/reference/store-core.mdx Extracts a byte slice from a dynamic field within a table, identified by its ID and key tuple. Specify the start and end indices for the desired slice. The end index is exclusive. ```solidity function getDynamicFieldSlice( ResourceId tableId, bytes32[] memory keyTuple, uint8 dynamicFieldIndex, uint256 start, uint256 end ) internal view returns (bytes memory); ``` -------------------------------- ### Setup Network Configuration Source: https://github.com/latticexyz/mud/blob/main/docs/pages/state-query/typescript/zustand.mdx Imports necessary libraries and configures the network for MUD client-side applications. This includes setting up viem clients for public and wallet interactions, and initializing MUD's state synchronization with RECS and Zustand. ```typescript /* * The MUD client code is built on top of viem * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig, } from "viem"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; import { syncToZustand } from "@latticexyz/store-sync/zustand"; import { Subject, share } from "rxjs"; /* * Import our MUD config, which includes strong types for * our tables and other config options. We use this to generate * things like RECS components and get back strong types for them. * * See https://mud.dev/templates/typescript/contracts#mudconfigts * for the source of this information. */ import mudConfig from "contracts/mud.config"; export type SetupNetworkResult = Awaited>; export async function setupNetwork() { const networkConfig = await getNetworkConfig(); /* * Create a viem public (read only) client * (https://viem.sh/docs/clients/public.html) */ const clientOptions = { chain: networkConfig.chain, transport: transportObserver(fallback([webSocket(), http()])), pollingInterval: 1000, } as const satisfies ClientConfig; const publicClient = createPublicClient(clientOptions); /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). */ const burnerAccount = createBurnerAccount(networkConfig.privateKey as Hex); const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, }); /* * Create an observable for contract writes that we can * pass into MUD dev tools for transaction observability. */ const write$ = new Subject(); /* * Create an object for communicating with the deployed World. */ const worldContract = getContract({ address: networkConfig.worldAddress as Hex, abi: IWorldAbi, publicClient, walletClient: burnerWalletClient, onWrite: (write) => write$.next(write), }); /* * Sync on-chain state into RECS and keeps our client in sync. * Uses the MUD indexer if available, otherwise falls back * to the viem publicClient to make RPC calls to fetch MUD * events from the chain. */ const { components, latestBlock$, storedBlockLogs$, waitForTransaction } = await syncToRecs({ world, config: mudConfig, address: networkConfig.worldAddress as Hex, publicClient, startBlock: BigInt(networkConfig.initialBlockNumber), }); const { tables, useStore, /* latestBlock$, storedBlockLogs$, waitForTransaction */ } = await syncToZustand({ config: mudConfig, address: networkConfig.worldAddress as Hex, publicClient, startBlock: BigInt(networkConfig.initialBlockNumber), }); return { tables, useStore, world, components, playerEntity: encodeEntity({ address: "address" }, { address: burnerWalletClient.account.address }), publicClient, walletClient: burnerWalletClient, latestBlock$, storedBlockLogs$, waitForTransaction, worldContract, write$: write$.asObservable().pipe(share()), }; } ``` -------------------------------- ### Configure ERC721 Module Installation Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/modules.mdx Modify `mud.config.ts` to install the ERC721 module. Requires `viem` package installation in `packages/contracts`. ```typescript import { defineWorld, } from "@latticexyz/world"; import { encodeAbiParameters } from "viem"; const erc721ModuleArgs = encodeAbiParameters( [ { type: "bytes14" }, { type: "tuple", components: [{ type: "string" }, { type: "string" }, { type: "string" }], }, ], ["0x44444444".padEnd(30, "0"), ["No Valuable Token", "NVT", "http://www.example.com/base/uri/goes/here"]], ); export default defineWorld({ namespace: "app", tables: { Counter: { schema: { value: "uint32", }, key: [], }, }, modules: [ { artifactPath: "@latticexyz/world-modules/out/PuppetModule.sol/PuppetModule.json", root: false, args: [], }, { artifactPath: "@latticexyz/world-modules/out/ERC721Module.sol/ERC721Module.json", root: false, args: [ { type: "bytes", value: erc721ModuleArgs, }, ], }, ], }); ``` -------------------------------- ### Clone the Emojimon repository Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/emojimon/2-getting-started.mdx Use this command to download the starter kit project files. ```bash git clone https://github.com/latticexyz/emojimon.git ``` -------------------------------- ### Define module installation in mud.config.ts Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/modules/keysintable.mdx Install modules by specifying the 'modules:' array in your mud.config.ts. Each entry defines a module to be installed. ```typescript modules: [ { ``` -------------------------------- ### Implement and Deploy a System Hook in Solidity Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/system-hooks.mdx A complete example showing the implementation of a SystemHook that reverts after a call, and a deployment script to register it. ```solidity // SPDX-License-Identifier: MIT pragma solidity >=0.8.24; import { Script } from "forge-std/Script.sol"; import { console } from "forge-std/console.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; import { SystemHook } from "@latticexyz/world/src/SystemHook.sol"; import { ResourceId, WorldResourceIdLib, WorldResourceIdInstance } from "@latticexyz/world/src/WorldResourceId.sol"; import { RESOURCE_SYSTEM } from "@latticexyz/world/src/worldResourceTypes.sol"; import { BEFORE_CALL_SYSTEM, AFTER_CALL_SYSTEM } from "@latticexyz/world/src/systemHookTypes.sol"; contract JustSayNo is SystemHook { function onBeforeCallSystem(address msgSender, ResourceId systemId, bytes memory callData) external { return; } function onAfterCallSystem(address msgSender, ResourceId systemId, bytes memory callData) external { revert("Just say no"); } } contract SystemHookDeploy is Script { function run() external { address worldAddress = 0xC14fBdb7808D9e2a37c1a45b635C8C3fF64a1cc1; // Load the private key from the `PRIVATE_KEY` environment variable (in .env) uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); // Start broadcasting transactions from the deployer account vm.startBroadcast(deployerPrivateKey); // Deploy JustSayNo JustSayNo justSayNo = new JustSayNo(); console.log(address(justSayNo)); ResourceId systemId = WorldResourceIdLib.encode({ typeId: RESOURCE_SYSTEM, namespace: "", name: "TasksSystem" }); IWorld(worldAddress).registerSystemHook(systemId, justSayNo, AFTER_CALL_SYSTEM); vm.stopBroadcast(); } } ``` ```solidity import { SystemHook } from "@latticexyz/world/src/SystemHook.sol"; ``` ```solidity import { ResourceId, WorldResourceIdLib, WorldResourceIdInstance } from "@latticexyz/world/src/WorldResourceId.sol"; import { RESOURCE_SYSTEM } from "@latticexyz/world/src/worldResourceTypes.sol"; ``` ```solidity import { BEFORE_CALL_SYSTEM, AFTER_CALL_SYSTEM } from "@latticexyz/world/src/systemHookTypes.sol"; ``` ```solidity contract JustSayNo is SystemHook { function onBeforeCallSystem(address msgSender, ResourceId systemId, bytes memory callData) external { return ; } function onAfterCallSystem(address msgSender, ResourceId systemId, bytes memory callData) external { ``` ```solidity revert("Just say no"); } } ``` ```solidity contract SystemHookDeploy is Script { function run() external { ... ``` ```solidity // Deploy JustSayNo JustSayNo justSayNo = new JustSayNo(); ``` ```solidity ResourceId systemId = WorldResourceIdLib.encode( { typeId: RESOURCE_SYSTEM, namespace: "", name: "TasksSystem" }); ``` ```solidity IWorld(worldAddress) .registerSystemHook(systemId, justSayNo, AFTER_CALL_SYSTEM); } } ``` -------------------------------- ### Install Root Module in World Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/world-external.mdx Installs a root module in the World contract. Requires the caller to own the root namespace. The module is delegatecalled and installed in the root namespace. ```solidity function installRootModule(IModule module, bytes memory encodedArgs) external; ``` -------------------------------- ### Upgrade a System contract Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/systems.mdx Full script example for deploying a new System contract and registering it to replace an existing one in the MUD World. ```solidity // SPDX-License-Identifier: MIT pragma solidity >=0.8.24; import { Script } from "forge-std/Script.sol"; import { console } from "forge-std/console.sol"; import { System } from "@latticexyz/world/src/System.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; import { Counter } from "../src/codegen/index.sol"; import { ResourceId, WorldResourceIdLib, WorldResourceIdInstance } from "@latticexyz/world/src/WorldResourceId.sol"; import { RESOURCE_SYSTEM } from "@latticexyz/world/src/worldResourceTypes.sol"; contract IncrementSystem2 is System { function increment() public returns (uint32) { uint32 counter = Counter.get(); uint32 newValue = counter + 2; Counter.set(newValue); return newValue; } } contract UpdateASystem is Script { function run() external { address worldAddress = 0xC14fBdb7808D9e2a37c1a45b635C8C3fF64a1cc1; // Load the private key from the `PRIVATE_KEY` environment variable (in .env) uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); // Start broadcasting transactions from the deployer account vm.startBroadcast(deployerPrivateKey); // Deploy IncrementSystem2 IncrementSystem2 incrementSystem2 = new IncrementSystem2(); ResourceId systemId = WorldResourceIdLib.encode({ typeId: RESOURCE_SYSTEM, namespace: "", name: "IncrementSystem" }); IWorld(worldAddress).registerSystem(systemId, incrementSystem2, true); vm.stopBroadcast(); } } ``` -------------------------------- ### Run Development Server for World Explorer Source: https://github.com/latticexyz/mud/blob/main/packages/explorer/README.md Start the development server for the World Explorer. Changes in the 'packages/explorer' directory will be reflected in the running instance. ```sh pnpm dev ``` -------------------------------- ### Navigate to Contracts Package Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/hello-world/deploy.mdx Change your directory to the 'contracts' package to prepare for deployment. ```sh cd packages/contracts ``` -------------------------------- ### Install pnpm Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Command to install pnpm globally using npm. ```sh sudo npm install -g pnpm ``` -------------------------------- ### Initialize MUD Project Source: https://github.com/latticexyz/mud/blob/main/docs/pages/quickstart.mdx Creates a new project from the latest MUD template. ```sh pnpm create mud@latest ``` -------------------------------- ### install Function Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module.mdx Installs the module. This function is invoked by the World contract during the installModule process. ```APIDOC ## Function: install Installs the module. _This function is invoked by the World contract during `installModule` process. The module expects to be called via the World contract and thus installs itself on the `msg.sender`. Logic might differ from `installRoot`, for example, this might accept namespace parameters._ ### Method ```solidity function install(bytes memory encodedArgs) public virtual; ``` ### Parameters #### Path Parameters - **encodedArgs** (bytes) - Required - The ABI encoded arguments that may be needed during the installation process. ``` -------------------------------- ### Deploy World Instance Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/world.mdx Deploys a new World contract deterministically using Create2 and installs the init module. ```solidity function deployWorld(bytes memory salt) public returns (address worldAddress); ``` -------------------------------- ### Clone and Build Deterministic Deployment Proxy Source: https://github.com/latticexyz/mud/blob/main/packages/common/src/deploy/create2/README.md Steps to clone the repository, checkout a specific commit, install dependencies, and build the project. ```bash git clone https://github.com/Arachnid/deterministic-deployment-proxy.git cd deterministic-deployment-proxy git checkout b3bb19c npm install npm run build ``` -------------------------------- ### Module Already Installed Error Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx This error is raised if the module being installed is already present. ```solidity error Module_AlreadyInstalled(); ``` -------------------------------- ### Install KeysWithValueModule in World Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/modules/keyswithvalue.mdx This line installs the KeysWithValueModule into the World contract, associating it with the specified source table. It's currently installed as a root module to allow it to hook into the table's write operations. ```solidity world.installRootModule(keysWithValueModule, abi.encode(sourceTableId)); ``` -------------------------------- ### Initialize MUD Three.js Project Source: https://github.com/latticexyz/mud/blob/main/docs/pages/templates/typescript/threejs.mdx Command to scaffold a new project using the Three.js template. ```sh pnpm create mud@latest tutorial --template threejs ``` -------------------------------- ### Module Non-Root Install Not Supported Error Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx This error is raised if installing a module in a non-root context is not supported. ```solidity error Module_NonRootInstallNotSupported(); ``` -------------------------------- ### Module Root Install Not Supported Error Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/reference/module-external.mdx This error is raised if installing a module in a root context is not supported. ```solidity error Module_RootInstallNotSupported(); ``` -------------------------------- ### Import SystemSwitch Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/systems.mdx Import the SystemSwitch utility to enable cross-namespace system calls. ```solidity import { SystemSwitch } from "@latticexyz/world-modules/src/utils/SystemSwitch.sol"; ``` -------------------------------- ### Module Installation Revert Source: https://github.com/latticexyz/mud/blob/main/packages/world-modules/CHANGELOG.md Modules now revert with `Module_AlreadyInstalled` if attempting to install more than once with the same calldata. This is a temporary measure for the deploy pipeline. ```solidity world.installModule(new PuppetModule(), new bytes(0)); ``` -------------------------------- ### Replace setupMUDV2Network with syncToRecs Source: https://github.com/latticexyz/mud/blob/main/packages/cli/CHANGELOG.md Initialize the new sync process and clients to replace the legacy setupMUDV2Network function. ```diff - const result = await setupMUDV2Network({ - ... - }); + const clientOptions = { + chain: networkConfig.chain, + transport: transportObserver(fallback([webSocket(), http()])), + pollingInterval: 1000, + } as const satisfies ClientConfig; + const publicClient = createPublicClient(clientOptions); + const burnerAccount = createBurnerAccount(networkConfig.privateKey as Hex); + const burnerWalletClient = createWalletClient({ + ...clientOptions, + account: burnerAccount, + }); + const { components, latestBlock$, blockStorageOperations$, waitForTransaction } = await syncToRecs({ + world, + config: storeConfig, + address: networkConfig.worldAddress as Hex, + publicClient, + components: contractComponents, + startBlock: BigInt(networkConfig.initialBlockNumber), + indexerUrl: networkConfig.indexerUrl ?? undefined, + }); + const worldContract = createContract({ + address: networkConfig.worldAddress as Hex, + abi: IWorld__factory.abi, + publicClient, + walletClient: burnerWalletClient, + }); ``` -------------------------------- ### Using createActionSystem with syncToRecs Source: https://github.com/latticexyz/mud/blob/main/packages/recs/CHANGELOG.md Demonstrates how to use the updated `createActionSystem` with `syncToRecs` by passing necessary arguments. Ensure `isDefined` is imported if used. ```typescript import { syncToRecs } from "@latticexyz/store-sync/recs"; import { createActionSystem } from "@latticexyz/recs/deprecated"; import { from, mergeMap } from "rxjs"; const { blockLogsStorage$, waitForTransaction } = syncToRecs({ world, ... }); const txReduced$ = blockLogsStorage$.pipe( mergeMap(({ operations }) => from(operations.map((op) => op.log?.transactionHash).filter(isDefined))) ); const actionSystem = createActionSystem(world, txReduced$, waitForTransaction); ``` -------------------------------- ### StoreCore Initialization and Table Registration Source: https://github.com/latticexyz/mud/blob/main/docs/pages/changelog.mdx Explains the separation of StoreCore's initialize method into distinct functions for setting store address and registering core tables, allowing for more granular control during setup. ```APIDOC ## StoreCore Initialization and Table Registration ### Description The `StoreCore`'s `initialize` function has been split into `initialize` (to set the `StoreSwitch`'s `storeAddress`) and `registerCoreTables` (to register the `Tables` and `StoreHooks` tables). This change provides consumers with more granular control over the setup flow. Consequently, the `StoreRead` contract no longer calls `StoreCore.initialize` in its constructor. Consumers are now expected to call `StoreCore.initialize` and `StoreCore.registerCoreTable` within their own setup logic. ### Method N/A (Conceptual change in library usage) ### Endpoint N/A (Library internal methods) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Install and Configure MUD Vite Plugin Source: https://github.com/latticexyz/mud/blob/main/docs/pages/changelog.mdx Install the required dependencies and add the MUD plugin to your Vite configuration file. ```bash pnpm add -D vite@^6 vite-plugin-mud ``` ```typescript // vite.config.ts import { defineConfig } from "vite"; import { mud } from "vite-plugin-mud"; export default defineConfig({ plugins: [mud({ worldsFile: "worlds.json" })], }); ``` -------------------------------- ### Change to client directory Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Navigate to the client package directory. ```sh cd ../client ``` -------------------------------- ### Install Puppet Module Source: https://github.com/latticexyz/mud/blob/main/docs/pages/world/modules.mdx Declaration for installing the Puppet module, specifying its artifact path, root permissions, and empty arguments. ```typescript { artifactPath: "@latticexyz/world-modules/out/PuppetModule.sol/PuppetModule.json", root: false, args: [], } ``` -------------------------------- ### Create and Run a New MUD Project Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Use this command to create a new MUD project from the vanilla template and start the development server. This sets up a basic World for you to extend. ```sh pnpm create mud@latest extendMe --template vanilla cd extendMe pnpm dev ``` -------------------------------- ### Install Module in World Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/modules.mdx Install a deployed module into the World contract. This makes the module's functionalities available through the World. ```sh cast send $WORLD_ADDRESS "installModule(address,bytes)" $MODULE_ADDRESS 0x --private-key $PRIVATE_KEY --rpc-url http://127.0.0.1:8545 ``` -------------------------------- ### Namespace directory structure Source: https://github.com/latticexyz/mud/blob/main/packages/store/CHANGELOG.md Example of the required source directory structure when using multiple namespaces. ```text ~/guilds ├── mud.config.ts └── src └── namespaces ├── game │   └── codegen │   └── tables │   ├── Player.sol │   └── Position.sol └── guilds ├── MembershipSystem.sol ├── TreasurySystem.sol └── codegen └── tables └── Guild.sol ``` -------------------------------- ### Get Value Source: https://github.com/latticexyz/mud/blob/main/docs/pages/templates/typescript/contracts.mdx Retrieves the current value of the table. `getValue()` and `get()` are for general use, while `_getValue()` and `_get()` are for World context. ```APIDOC ## GET /getValue ### Description Get the table's value. For singleton tables, this retrieves the first entry. ### Method GET ### Endpoint /getValue ### Parameters None ### Response #### Success Response (200) - **value** (uint32) - The current value. #### Response Example ```json { "value": 123 } ``` ``` -------------------------------- ### Start Broadcast Source: https://github.com/latticexyz/mud/blob/main/docs/pages/guides/extending-a-world.mdx Initiates the transaction broadcast using the deployer private key. ```solidity vm.startBroadcast(deployerPrivateKey); ```