@latticexyz/cli 2.2.21-041031d271b62a7f41f7c6dc0098c1c0ae222bd5 → 2.2.21-236ef3c7750b954dc7faf23f1d7c8599ce47a30f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -201,7 +201,7 @@ var package_default = {
201
201
  rxjs: "7.5.5",
202
202
  "throttle-debounce": "^5.0.0",
203
203
  toposort: "^2.0.2",
204
- viem: "2.21.19",
204
+ viem: "2.23.2",
205
205
  yargs: "^17.7.1",
206
206
  zod: "3.23.8",
207
207
  "zod-validation-error": "^1.3.0"
@@ -3154,4 +3154,4 @@ var commands = [
3154
3154
  export {
3155
3155
  commands
3156
3156
  };
3157
- //# sourceMappingURL=commands-S5XBCJLZ.js.map
3157
+ //# sourceMappingURL=commands-TRNELNFD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/index.ts","../src/commands/build.ts","../src/build.ts","../src/utils/printCommand.ts","../src/commands/devnode.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/runDeploy.ts","../package.json","../src/deploy/deploy.ts","../src/deploy/deployWorld.ts","../src/deploy/getWorldFactoryContracts.ts","../src/deploy/getWorldContracts.ts","../src/deploy/getWorldProxyFactoryContracts.ts","../src/deploy/ensureWorldFactory.ts","../src/debug.ts","../src/deploy/debug.ts","../src/deploy/logsToWorldDeploy.ts","../src/deploy/common.ts","../src/deploy/ensureTables.ts","../src/deploy/getTables.ts","../src/deploy/ensureSystems.ts","../src/deploy/getSystems.ts","../src/deploy/getResourceIds.ts","../src/deploy/getTableValue.ts","../src/deploy/getResourceAccess.ts","../src/deploy/getWorldDeploy.ts","../src/deploy/ensureFunctions.ts","../src/deploy/ensureModules.ts","../src/deploy/ensureNamespaceOwner.ts","../src/deploy/ensureResourceTags.ts","../src/utils/getContractArtifact.ts","../src/utils/findPlaceholders.ts","../src/deploy/createPrepareDeploy.ts","../src/deploy/deployCustomWorld.ts","../src/deploy/getLibraryMap.ts","../src/deploy/resolveConfig.ts","../src/utils/getContractData.ts","../src/deploy/findLibraries.ts","../src/deploy/orderByDependencies.ts","../src/deploy/compat/excludeUnstableCallWithSignatureModule.ts","../src/utils/postDeploy.ts","../src/deploy/configToModules.ts","../src/utils/importContractArtifact.ts","../src/deploy/compat/moduleArtifactPathFromName.ts","../src/utils/enableAutomine.ts","../src/defaultChains.ts","../src/commands/deploy.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../src/mudPackages.ts","../src/commands/test.ts","../src/commands/trace.ts","../src/commands/dev-contracts.ts","../src/verify.ts","../src/verify/verifyContract.ts","../src/commands/verify.ts","../src/commands/pull.ts","../src/pull/pull.ts","../src/deploy/getRecord.ts","../src/pull/debug.ts"],"sourcesContent":["import { CommandModule } from \"yargs\";\n\nimport { command as gasReport } from \"@latticexyz/gas-report/internal\";\nimport { command as abiTs } from \"@latticexyz/abi-ts/internal\";\n\nimport build from \"./build\";\nimport devnode from \"./devnode\";\nimport hello from \"./hello\";\nimport tablegen from \"./tablegen\";\nimport deploy from \"./deploy\";\nimport worldgen from \"./worldgen\";\nimport setVersion from \"./set-version\";\nimport test from \"./test\";\nimport trace from \"./trace\";\nimport devContracts from \"./dev-contracts\";\nimport verify from \"./verify\";\nimport pull from \"./pull\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each command has different options\nexport const commands: CommandModule<any, any>[] = [\n build,\n deploy,\n devnode,\n gasReport,\n hello,\n tablegen,\n worldgen,\n setVersion,\n test,\n trace,\n devContracts,\n abiTs,\n verify,\n pull,\n];\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { build } from \"../build\";\nimport path from \"node:path\";\n\ntype Options = {\n configPath?: string;\n profile?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"build\",\n\n describe: \"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the MUD config file\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n });\n },\n\n async handler(opts) {\n const configPath = await resolveConfigPath(opts.configPath);\n const config = (await loadConfig(configPath)) as WorldConfig;\n\n await build({ rootDir: path.dirname(configPath), config, foundryProfile: opts.profile });\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import { tablegen } from \"@latticexyz/store/codegen\";\nimport { buildSystemsManifest, worldgen } from \"@latticexyz/world/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"./utils/printCommand\";\n\ntype BuildOptions = {\n foundryProfile?: string;\n /**\n * MUD project root directory where all other relative paths are resolved from.\n *\n * Defaults to the directory of the nearest `mud.config.ts`, looking in `process.cwd()` and moving up the directory tree.\n */\n rootDir: string;\n config: WorldConfig;\n};\n\nexport async function build({ rootDir, config, foundryProfile }: BuildOptions): Promise<void> {\n await Promise.all([tablegen({ rootDir, config }), worldgen({ rootDir, config })]);\n await printCommand(\n execa(\"forge\", [\"build\"], {\n stdio: \"inherit\",\n env: { FOUNDRY_PROFILE: foundryProfile ?? process.env.FOUNDRY_PROFILE },\n }),\n );\n await buildSystemsManifest({ rootDir, config });\n await printCommand(execa(\"mud\", [\"abi-ts\"], { stdio: \"inherit\" }));\n}\n","import chalk from \"chalk\";\nimport { ChildProcess } from \"node:child_process\";\n\n/**\n * Prints the command used to spawn a child process\n * and returns the child process.\n *\n * Using it like this\n *\n * ```ts\n * printCommand(execa(\"echo\", [\"hello\"]));\n * ```\n *\n * will output\n *\n * ```plain\n * > echo hello\n * ```\n */\nexport function printCommand<proc>(proc: proc extends ChildProcess ? proc : ChildProcess): proc {\n console.log(\"\\n\" + chalk.gray(\"> \" + proc.spawnargs.join(\" \")));\n return proc as never;\n}\n","import { rmSync } from \"fs\";\nimport { homedir } from \"os\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"../utils/printCommand\";\n\ntype Options = {\n blocktime: number;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"devnode\",\n\n describe: \"Start a local Ethereum node for development\",\n\n builder(yargs) {\n return yargs.options({\n blocktime: { type: \"number\", default: 2, decs: \"Interval in which new blocks are produced\" },\n });\n },\n\n async handler({ blocktime }) {\n console.log(\"Clearing devnode history\");\n const userHomeDir = homedir();\n rmSync(path.join(userHomeDir, \".foundry\", \"anvil\", \"tmp\"), { recursive: true, force: true });\n\n const child = printCommand(\n execa(\"anvil\", [\"-b\", String(blocktime), \"--block-base-fee-per-gas\", \"0\"], {\n stdio: \"inherit\",\n }),\n );\n\n process.on(\"SIGINT\", () => {\n console.log(\"\\ngracefully shutting down from SIGINT (Crtl-C)\");\n child.kill();\n process.exit();\n });\n await child;\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\n\ntype Options = {\n name: string;\n upper: boolean | undefined;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"hello <name>\",\n\n describe: \"Greet <name> with Hello\",\n\n builder(yargs) {\n return yargs\n .options({\n upper: { type: \"boolean\" },\n })\n .positional(\"name\", { type: \"string\", demandOption: true });\n },\n\n handler({ name }) {\n const greeting = `Gm, ${name}!`;\n console.log(greeting);\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { Store as StoreConfig } from \"@latticexyz/store\";\nimport { tablegen } from \"@latticexyz/store/codegen\";\nimport path from \"node:path\";\n\ntype Options = {\n configPath?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"tablegen\",\n\n describe: \"Autogenerate MUD Store table libraries based on the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the MUD config file\" },\n });\n },\n\n async handler(opts) {\n const configPath = await resolveConfigPath(opts.configPath);\n const config = (await loadConfig(configPath)) as StoreConfig;\n\n await tablegen({ rootDir: path.dirname(configPath), config });\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import path from \"node:path\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport packageJson from \"../package.json\";\nimport { InferredOptionTypes, Options } from \"yargs\";\nimport { deploy } from \"./deploy/deploy\";\nimport { createWalletClient, http, Hex, isHex, stringToHex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { getOutDirectory, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { resolveConfig } from \"./deploy/resolveConfig\";\nimport { getChainId } from \"viem/actions\";\nimport { postDeploy } from \"./utils/postDeploy\";\nimport { WorldDeploy } from \"./deploy/common\";\nimport { build } from \"./build\";\nimport { kmsKeyToAccount } from \"@latticexyz/common/kms\";\nimport { configToModules } from \"./deploy/configToModules\";\nimport { findContractArtifacts } from \"@latticexyz/world/node\";\nimport { enableAutomine } from \"./utils/enableAutomine\";\nimport { defaultChains } from \"./defaultChains\";\n\nexport const deployOptions = {\n configPath: { type: \"string\", desc: \"Path to the MUD config file\" },\n printConfig: { type: \"boolean\", desc: \"Print the resolved config\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n saveDeployment: { type: \"boolean\", desc: \"Save the deployment info to a file\", default: true },\n rpc: { type: \"string\", desc: \"The RPC URL to use. Defaults to the RPC url from the local foundry.toml\" },\n rpcBatch: {\n type: \"boolean\",\n desc: \"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)\",\n },\n deployerAddress: {\n type: \"string\",\n desc: \"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)\",\n },\n worldAddress: { type: \"string\", desc: \"Deploy to an existing World at the given address\" },\n skipBuild: { type: \"boolean\", desc: \"Skip rebuilding the contracts before deploying\" },\n alwaysRunPostDeploy: {\n type: \"boolean\",\n desc: \"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed.\",\n },\n forgeScriptOptions: { type: \"string\", description: \"Options to pass to forge script PostDeploy.s.sol\" },\n salt: {\n type: \"string\",\n desc: \"The deployment salt to use. Defaults to a random salt.\",\n },\n kms: {\n type: \"boolean\",\n desc: \"Deploy the World with an AWS KMS key instead of local private key.\",\n },\n indexerUrl: {\n type: \"string\",\n desc: \"The indexer URL to use.\",\n required: false,\n },\n} as const satisfies Record<string, Options>;\n\nexport type DeployOptions = InferredOptionTypes<typeof deployOptions>;\n\n/**\n * Given some CLI arguments, finds and resolves a MUD config, foundry profile, and runs a deploy.\n * This is used by the deploy, test, and dev-contracts CLI commands.\n */\nexport async function runDeploy(opts: DeployOptions): Promise<WorldDeploy> {\n const salt = opts.salt != null ? (isHex(opts.salt) ? opts.salt : stringToHex(opts.salt)) : undefined;\n\n const profile = opts.profile;\n\n const configPath = await resolveConfigPath(opts.configPath);\n const config = (await loadConfig(configPath)) as WorldConfig;\n const rootDir = path.dirname(configPath);\n\n console.log(chalk.green(`\\nUsing ${packageJson.name}@${packageJson.version}`));\n\n if (opts.printConfig) {\n console.log(chalk.green(\"\\nResolved config:\\n\"), JSON.stringify(config, null, 2));\n }\n\n const outDir = await getOutDirectory(profile);\n\n const rpc = opts.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Deploying MUD contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`),\n ),\n );\n\n // Run build\n if (!opts.skipBuild) {\n await build({ rootDir, config, foundryProfile: profile });\n }\n\n const { systems, libraries } = await resolveConfig({\n rootDir,\n config,\n forgeOutDir: outDir,\n });\n\n const artifacts = await findContractArtifacts({ forgeOutDir: outDir });\n // TODO: pass artifacts into configToModules (https://github.com/latticexyz/mud/issues/3153)\n const modules = await configToModules(config, outDir);\n\n const tables = Object.values(config.namespaces)\n .flatMap((namespace) => Object.values(namespace.tables))\n .filter((table) => !table.deploy.disabled);\n\n const account = await (async () => {\n if (opts.kms) {\n const keyId = process.env.AWS_KMS_KEY_ID;\n if (!keyId) {\n throw new MUDError(\n \"Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.\",\n );\n }\n\n return await kmsKeyToAccount({ keyId });\n } else {\n const privateKey = process.env.PRIVATE_KEY;\n if (!privateKey) {\n throw new MUDError(\n `Missing PRIVATE_KEY environment variable.\n Run 'echo \"PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\" > .env'\n in your contracts directory to use the default anvil private key.`,\n );\n }\n\n return privateKeyToAccount(privateKey as Hex);\n }\n })();\n\n const client = createWalletClient({\n transport: http(rpc, {\n batch: opts.rpcBatch\n ? {\n batchSize: 100,\n wait: 1000,\n }\n : undefined,\n }),\n account,\n });\n\n const chainId = await getChainId(client);\n const indexerUrl = opts.indexerUrl ?? defaultChains.find((chain) => chain.id === chainId)?.indexerUrl;\n const worldDeployBlock = opts.worldAddress\n ? getWorldDeployBlock({\n worldAddress: opts.worldAddress,\n worldsFile: config.deploy.worldsFile,\n chainId,\n })\n : undefined;\n\n console.log(\"Deploying from\", client.account.address);\n\n // Attempt to enable automine for the duration of the deploy. Noop if automine is not available.\n const automine = await enableAutomine(client);\n\n const startTime = Date.now();\n const worldDeploy = await deploy({\n config,\n deployerAddress: opts.deployerAddress as Hex | undefined,\n salt,\n worldAddress: opts.worldAddress as Hex | undefined,\n worldDeployBlock,\n client,\n tables,\n systems,\n libraries,\n modules,\n artifacts,\n indexerUrl,\n chainId,\n });\n if (opts.worldAddress == null || opts.alwaysRunPostDeploy) {\n await postDeploy(\n config.deploy.postDeployScript,\n worldDeploy.address,\n rpc,\n profile,\n opts.forgeScriptOptions,\n opts.kms ? true : false,\n );\n }\n\n // Reset mining mode after deploy\n await automine?.reset();\n\n console.log(chalk.green(\"Deployment completed in\", (Date.now() - startTime) / 1000, \"seconds\"));\n\n const deploymentInfo = {\n worldAddress: worldDeploy.address,\n blockNumber: Number(worldDeploy.deployBlock),\n };\n\n if (opts.saveDeployment) {\n const deploysDir = path.join(config.deploy.deploysDirectory, chainId.toString());\n mkdirSync(deploysDir, { recursive: true });\n writeFileSync(path.join(deploysDir, \"latest.json\"), JSON.stringify(deploymentInfo, null, 2) + \"\\n\");\n writeFileSync(path.join(deploysDir, Date.now() + \".json\"), JSON.stringify(deploymentInfo, null, 2) + \"\\n\");\n\n const localChains = [1337, 31337];\n const deploys = existsSync(config.deploy.worldsFile)\n ? JSON.parse(readFileSync(config.deploy.worldsFile, \"utf-8\"))\n : {};\n deploys[chainId] = {\n address: deploymentInfo.worldAddress,\n // We expect the worlds file to be committed and since local deployments are often\n // a consistent address but different block number, we'll ignore the block number.\n blockNumber: localChains.includes(chainId) ? undefined : deploymentInfo.blockNumber,\n };\n writeFileSync(config.deploy.worldsFile, JSON.stringify(deploys, null, 2) + \"\\n\");\n\n console.log(\n chalk.bgGreen(\n chalk.whiteBright(`\\n Deployment result (written to ${config.deploy.worldsFile} and ${deploysDir}): \\n`),\n ),\n );\n }\n\n console.log(deploymentInfo);\n\n return worldDeploy;\n}\n\nfunction getWorldDeployBlock({\n chainId,\n worldAddress,\n worldsFile,\n}: {\n chainId: number;\n worldAddress: string;\n worldsFile: string;\n}): bigint | undefined {\n const deploys = existsSync(worldsFile) ? JSON.parse(readFileSync(worldsFile, \"utf-8\")) : {};\n const worldDeployBlock = deploys[chainId]?.address === worldAddress ? deploys[chainId].blockNumber : undefined;\n return worldDeployBlock ? BigInt(worldDeployBlock) : undefined;\n}\n","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"2.2.20\",\n \"description\": \"Command line interface for mud\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/latticexyz/mud.git\",\n \"directory\": \"packages/cli\"\n },\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"typesVersions\": {\n \"*\": {\n \"index\": [\n \"./dist/index.d.ts\"\n ]\n }\n },\n \"bin\": {\n \"mud\": \"./bin/mud.js\"\n },\n \"files\": [\n \"bin\",\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"pnpm run build:js && pnpm run build:test-tables\",\n \"build:js\": \"tsup && chmod +x ./dist/mud.js\",\n \"build:test-tables\": \"tsx ./scripts/generate-test-tables.ts\",\n \"clean\": \"pnpm run clean:js && pnpm run clean:test-tables\",\n \"clean:js\": \"shx rm -rf dist\",\n \"clean:test-tables\": \"shx rm -rf src/**/codegen\",\n \"dev\": \"tsup --watch\",\n \"lint\": \"eslint . --ext .ts\",\n \"test\": \"tsc --noEmit && forge test\",\n \"test:ci\": \"pnpm run test\"\n },\n \"dependencies\": {\n \"@ark/util\": \"0.2.2\",\n \"@aws-sdk/client-kms\": \"^3.556.0\",\n \"@latticexyz/abi-ts\": \"workspace:*\",\n \"@latticexyz/block-logs-stream\": \"workspace:*\",\n \"@latticexyz/common\": \"workspace:*\",\n \"@latticexyz/config\": \"workspace:*\",\n \"@latticexyz/gas-report\": \"workspace:*\",\n \"@latticexyz/protocol-parser\": \"workspace:*\",\n \"@latticexyz/schema-type\": \"workspace:*\",\n \"@latticexyz/store\": \"workspace:*\",\n \"@latticexyz/store-sync\": \"workspace:*\",\n \"@latticexyz/utils\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"@latticexyz/world-module-callwithsignature\": \"workspace:*\",\n \"@latticexyz/world-module-metadata\": \"workspace:*\",\n \"abitype\": \"1.0.6\",\n \"asn1.js\": \"^5.4.1\",\n \"chalk\": \"^5.0.1\",\n \"chokidar\": \"^3.5.3\",\n \"debug\": \"^4.3.4\",\n \"dotenv\": \"^16.0.3\",\n \"execa\": \"^9.5.2\",\n \"find-up\": \"^6.3.0\",\n \"glob\": \"^10.4.2\",\n \"openurl\": \"^1.1.1\",\n \"p-queue\": \"^7.4.1\",\n \"p-retry\": \"^5.1.2\",\n \"path\": \"^0.12.7\",\n \"rxjs\": \"7.5.5\",\n \"throttle-debounce\": \"^5.0.0\",\n \"toposort\": \"^2.0.2\",\n \"viem\": \"2.23.2\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"3.23.8\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/debug\": \"^4.1.7\",\n \"@types/ejs\": \"^3.1.1\",\n \"@types/openurl\": \"^1.0.0\",\n \"@types/throttle-debounce\": \"^5.0.0\",\n \"@types/toposort\": \"^2.0.6\",\n \"@types/yargs\": \"^17.0.10\",\n \"ds-test\": \"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0\",\n \"forge-std\": \"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1\"\n }\n}\n","import { Address, Hex, stringToHex } from \"viem\";\nimport { deployWorld } from \"./deployWorld\";\nimport { ensureTables } from \"./ensureTables\";\nimport {\n CommonDeployOptions,\n Library,\n Module,\n System,\n WorldDeploy,\n supportedStoreVersions,\n supportedWorldVersions,\n} from \"./common\";\nimport { ensureSystems } from \"./ensureSystems\";\nimport { getWorldDeploy } from \"./getWorldDeploy\";\nimport { ensureFunctions } from \"./ensureFunctions\";\nimport { ensureModules } from \"./ensureModules\";\nimport { ensureNamespaceOwner } from \"./ensureNamespaceOwner\";\nimport { debug } from \"./debug\";\nimport { resourceToHex, resourceToLabel } from \"@latticexyz/common\";\nimport { randomBytes } from \"crypto\";\nimport { Table } from \"@latticexyz/config\";\nimport { ensureResourceTags } from \"./ensureResourceTags\";\nimport { ContractArtifact } from \"@latticexyz/world/node\";\nimport { World } from \"@latticexyz/world\";\nimport { deployCustomWorld } from \"./deployCustomWorld\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\nimport { getLibraryMap } from \"./getLibraryMap\";\nimport { ensureContractsDeployed, ensureDeployer, waitForTransactions } from \"@latticexyz/common/internal\";\n\ntype DeployOptions = {\n config: World;\n tables: readonly Table[];\n systems: readonly System[];\n libraries: readonly Library[];\n modules?: readonly Module[];\n artifacts: readonly ContractArtifact[];\n salt?: Hex;\n worldAddress?: Address;\n /**\n * Block number of an existing world deployment.\n * Only used if `worldAddress` is provided.\n */\n worldDeployBlock?: bigint;\n /**\n * Address of determinstic deployment proxy: https://github.com/Arachnid/deterministic-deployment-proxy\n * By default, we look for a deployment at 0x4e59b44847b379578588920ca78fbf26c0b4956c and, if not, deploy one.\n * If the target chain does not support legacy transactions, we deploy the proxy bytecode anyway, but it will\n * not have a deterministic address.\n */\n deployerAddress?: Hex;\n withWorldProxy?: boolean;\n} & Omit<CommonDeployOptions, \"worldDeploy\">;\n\n/**\n * Given a viem client and MUD config, we attempt to introspect the world\n * (or deploy a new one if no world address is provided) and do the minimal\n * amount of work to make the world match the config (e.g. deploy new tables,\n * replace systems, etc.)\n */\nexport async function deploy({\n config,\n client,\n tables,\n systems,\n libraries,\n modules = [],\n artifacts,\n salt,\n worldAddress: existingWorldAddress,\n worldDeployBlock,\n deployerAddress: initialDeployerAddress,\n indexerUrl,\n chainId,\n}: DeployOptions): Promise<WorldDeploy> {\n const deployerAddress = initialDeployerAddress ?? (await ensureDeployer(client));\n\n const worldDeploy = existingWorldAddress\n ? await getWorldDeploy(client, existingWorldAddress, worldDeployBlock)\n : config.deploy.customWorld\n ? await deployCustomWorld({\n client,\n deployerAddress,\n artifacts,\n customWorld: config.deploy.customWorld,\n })\n : await deployWorld(\n client,\n deployerAddress,\n salt ?? `0x${randomBytes(32).toString(\"hex\")}`,\n config.deploy.upgradeableWorldImplementation,\n );\n\n const commonDeployOptions = {\n client,\n indexerUrl,\n chainId,\n worldDeploy,\n } satisfies CommonDeployOptions;\n\n if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {\n throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);\n }\n if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {\n throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);\n }\n\n const libraryMap = getLibraryMap(libraries);\n await ensureContractsDeployed({\n ...commonDeployOptions,\n deployerAddress,\n contracts: [\n ...libraries.map((library) => ({\n bytecode: library.prepareDeploy(deployerAddress, libraryMap).bytecode,\n deployedBytecodeSize: library.deployedBytecodeSize,\n debugLabel: `${library.path}:${library.name} library`,\n })),\n ...systems.map((system) => ({\n bytecode: system.prepareDeploy(deployerAddress, libraryMap).bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n debugLabel: `${resourceToLabel(system)} system`,\n })),\n ...modules.map((mod) => ({\n bytecode: mod.prepareDeploy(deployerAddress, libraryMap).bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n debugLabel: `${mod.name} module`,\n })),\n ],\n });\n\n const namespaceTxs = await ensureNamespaceOwner({\n ...commonDeployOptions,\n resourceIds: [...tables.map(({ tableId }) => tableId), ...systems.map(({ systemId }) => systemId)],\n });\n // Wait for namespaces to be available, otherwise referencing them below may fail.\n // This is only here because OPStack chains don't let us estimate gas with pending block tag.\n await waitForTransactions({ client, hashes: namespaceTxs, debugLabel: \"namespace registrations\" });\n\n const tableTxs = await ensureTables({\n ...commonDeployOptions,\n tables,\n });\n const systemTxs = await ensureSystems({\n ...commonDeployOptions,\n deployerAddress,\n libraryMap,\n systems,\n });\n // Wait for tables and systems to be available, otherwise referencing their resource IDs below may fail.\n // This is only here because OPStack chains don't let us estimate gas with pending block tag.\n await waitForTransactions({\n client,\n hashes: [...tableTxs, ...systemTxs],\n debugLabel: \"table and system registrations\",\n });\n\n const functionTxs = await ensureFunctions({\n ...commonDeployOptions,\n functions: systems.flatMap((system) => system.worldFunctions),\n });\n const moduleTxs = await ensureModules({\n ...commonDeployOptions,\n deployerAddress,\n libraryMap,\n modules,\n });\n\n const namespaceTags = uniqueBy(\n [...tables, ...systems]\n // only register labels if they differ from the resource ID\n .filter(({ namespace, namespaceLabel }) => namespaceLabel !== namespace)\n .map(({ namespace, namespaceLabel }) => ({\n resourceId: resourceToHex({ type: \"namespace\", namespace, name: \"\" }),\n tag: \"label\",\n value: namespaceLabel,\n })),\n (tag) => tag.resourceId,\n );\n\n const tableTags = tables\n // only register labels if they differ from the resource ID\n .filter((table) => table.label !== table.name)\n .map(({ tableId: resourceId, label }) => ({ resourceId, tag: \"label\", value: label }));\n\n const systemTags = systems.flatMap(({ name, systemId: resourceId, label, metadata }) => [\n // only register labels if they differ from the resource ID\n ...(label !== name ? [{ resourceId, tag: \"label\", value: label }] : []),\n { resourceId, tag: \"abi\", value: metadata.abi.join(\"\\n\") },\n { resourceId, tag: \"worldAbi\", value: metadata.worldAbi.join(\"\\n\") },\n ]);\n\n const tagTxs = await ensureResourceTags({\n ...commonDeployOptions,\n deployerAddress,\n libraryMap,\n tags: [...namespaceTags, ...tableTags, ...systemTags],\n valueToHex: stringToHex,\n });\n\n await waitForTransactions({\n client,\n hashes: [...functionTxs, ...moduleTxs, ...tagTxs],\n debugLabel: \"remaining transactions\",\n });\n\n debug(\"deploy complete\");\n return worldDeploy;\n}\n","import { Account, Chain, Client, Hex, Transport } from \"viem\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { ensureWorldFactory } from \"./ensureWorldFactory\";\nimport WorldFactoryAbi from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json\" assert { type: \"json\" };\nimport { writeContract } from \"@latticexyz/common\";\nimport { debug } from \"./debug\";\nimport { logsToWorldDeploy } from \"./logsToWorldDeploy\";\nimport { WorldDeploy } from \"./common\";\n\nexport async function deployWorld(\n client: Client<Transport, Chain | undefined, Account>,\n deployerAddress: Hex,\n salt: Hex,\n withWorldProxy?: boolean,\n): Promise<WorldDeploy> {\n const worldFactory = await ensureWorldFactory(client, deployerAddress, withWorldProxy);\n\n debug(\"deploying world\");\n const tx = await writeContract(client, {\n chain: client.chain ?? null,\n address: worldFactory,\n abi: WorldFactoryAbi,\n functionName: \"deployWorld\",\n args: [salt],\n });\n\n debug(\"waiting for world deploy\");\n const receipt = await waitForTransactionReceipt(client, { hash: tx });\n if (receipt.status !== \"success\") {\n console.error(\"world deploy failed\", receipt);\n throw new Error(\"world deploy failed\");\n }\n\n const deploy = logsToWorldDeploy(receipt.logs);\n debug(\"deployed world to\", deploy.address, \"at block\", deploy.deployBlock);\n\n return { ...deploy, stateBlock: deploy.deployBlock };\n}\n","import worldFactoryBuild from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json\" assert { type: \"json\" };\nimport worldFactoryAbi from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json\" assert { type: \"json\" };\nimport { Hex, encodeDeployData, size } from \"viem\";\nimport { getWorldContracts } from \"./getWorldContracts\";\nimport { getContractAddress } from \"@latticexyz/common/internal\";\n\nexport function getWorldFactoryContracts(deployerAddress: Hex) {\n const worldContracts = getWorldContracts(deployerAddress);\n\n const worldFactoryDeployedBytecodeSize = size(worldFactoryBuild.deployedBytecode.object as Hex);\n const worldFactoryBytecode = encodeDeployData({\n bytecode: worldFactoryBuild.bytecode.object as Hex,\n abi: worldFactoryAbi,\n args: [worldContracts.InitModule.address],\n });\n const worldFactory = getContractAddress({ deployerAddress, bytecode: worldFactoryBytecode });\n\n return {\n ...worldContracts,\n WorldFactory: {\n bytecode: worldFactoryBytecode,\n deployedBytecodeSize: worldFactoryDeployedBytecodeSize,\n debugLabel: \"world factory\",\n address: worldFactory,\n },\n };\n}\n","import accessManagementSystemBuild from \"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json\" assert { type: \"json\" };\nimport balanceTransferSystemBuild from \"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json\" assert { type: \"json\" };\nimport batchCallSystemBuild from \"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json\" assert { type: \"json\" };\nimport registrationSystemBuild from \"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json\" assert { type: \"json\" };\nimport initModuleBuild from \"@latticexyz/world/out/InitModule.sol/InitModule.json\" assert { type: \"json\" };\nimport initModuleAbi from \"@latticexyz/world/out/InitModule.sol/InitModule.abi.json\" assert { type: \"json\" };\nimport { Hex, encodeDeployData, size } from \"viem\";\nimport { getContractAddress } from \"@latticexyz/common/internal\";\n\nexport function getWorldContracts(deployerAddress: Hex) {\n const accessManagementSystemDeployedBytecodeSize = size(accessManagementSystemBuild.deployedBytecode.object as Hex);\n const accessManagementSystemBytecode = accessManagementSystemBuild.bytecode.object as Hex;\n const accessManagementSystem = getContractAddress({\n deployerAddress,\n bytecode: accessManagementSystemBytecode,\n });\n\n const balanceTransferSystemDeployedBytecodeSize = size(balanceTransferSystemBuild.deployedBytecode.object as Hex);\n const balanceTransferSystemBytecode = balanceTransferSystemBuild.bytecode.object as Hex;\n const balanceTransferSystem = getContractAddress({\n deployerAddress,\n bytecode: balanceTransferSystemBytecode,\n });\n\n const batchCallSystemDeployedBytecodeSize = size(batchCallSystemBuild.deployedBytecode.object as Hex);\n const batchCallSystemBytecode = batchCallSystemBuild.bytecode.object as Hex;\n const batchCallSystem = getContractAddress({ deployerAddress, bytecode: batchCallSystemBytecode });\n\n const registrationDeployedBytecodeSize = size(registrationSystemBuild.deployedBytecode.object as Hex);\n const registrationBytecode = registrationSystemBuild.bytecode.object as Hex;\n const registration = getContractAddress({\n deployerAddress,\n bytecode: registrationBytecode,\n });\n\n const initModuleDeployedBytecodeSize = size(initModuleBuild.deployedBytecode.object as Hex);\n const initModuleBytecode = encodeDeployData({\n bytecode: initModuleBuild.bytecode.object as Hex,\n abi: initModuleAbi,\n args: [accessManagementSystem, balanceTransferSystem, batchCallSystem, registration],\n });\n const initModule = getContractAddress({ deployerAddress, bytecode: initModuleBytecode });\n\n return {\n AccessManagementSystem: {\n bytecode: accessManagementSystemBytecode,\n deployedBytecodeSize: accessManagementSystemDeployedBytecodeSize,\n debugLabel: \"access management system\",\n address: accessManagementSystem,\n },\n BalanceTransferSystem: {\n bytecode: balanceTransferSystemBytecode,\n deployedBytecodeSize: balanceTransferSystemDeployedBytecodeSize,\n debugLabel: \"balance transfer system\",\n address: balanceTransferSystem,\n },\n BatchCallSystem: {\n bytecode: batchCallSystemBytecode,\n deployedBytecodeSize: batchCallSystemDeployedBytecodeSize,\n debugLabel: \"batch call system\",\n address: batchCallSystem,\n },\n RegistrationSystem: {\n bytecode: registrationBytecode,\n deployedBytecodeSize: registrationDeployedBytecodeSize,\n debugLabel: \"core registration system\",\n address: registration,\n },\n InitModule: {\n bytecode: initModuleBytecode,\n deployedBytecodeSize: initModuleDeployedBytecodeSize,\n debugLabel: \"core module\",\n address: initModule,\n },\n };\n}\n","import worldProxyFactoryBuild from \"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json\" assert { type: \"json\" };\nimport worldProxyFactoryAbi from \"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json\" assert { type: \"json\" };\nimport { Hex, encodeDeployData, size } from \"viem\";\nimport { getWorldContracts } from \"./getWorldContracts\";\nimport { getContractAddress } from \"@latticexyz/common/internal\";\n\nexport function getWorldProxyFactoryContracts(deployerAddress: Hex) {\n const worldContracts = getWorldContracts(deployerAddress);\n\n const worldProxyFactoryDeployedBytecodeSize = size(worldProxyFactoryBuild.deployedBytecode.object as Hex);\n const worldProxyFactoryBytecode = encodeDeployData({\n bytecode: worldProxyFactoryBuild.bytecode.object as Hex,\n abi: worldProxyFactoryAbi,\n args: [worldContracts.InitModule.address],\n });\n const worldProxyFactory = getContractAddress({ deployerAddress, bytecode: worldProxyFactoryBytecode });\n\n return {\n ...worldContracts,\n WorldProxyFactory: {\n bytecode: worldProxyFactoryBytecode,\n deployedBytecodeSize: worldProxyFactoryDeployedBytecodeSize,\n debugLabel: \"world proxy factory\",\n address: worldProxyFactory,\n },\n };\n}\n","import { Client, Transport, Chain, Account, Hex, Address } from \"viem\";\nimport { getWorldFactoryContracts } from \"./getWorldFactoryContracts\";\nimport { getWorldProxyFactoryContracts } from \"./getWorldProxyFactoryContracts\";\nimport { ensureContractsDeployed } from \"@latticexyz/common/internal\";\n\nexport async function ensureWorldFactory(\n client: Client<Transport, Chain | undefined, Account>,\n deployerAddress: Hex,\n withWorldProxy?: boolean,\n): Promise<Address> {\n if (withWorldProxy) {\n const contracts = getWorldProxyFactoryContracts(deployerAddress);\n // We can deploy these contracts in parallel because they do not call each other at this point.\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: Object.values(contracts),\n });\n return contracts.WorldProxyFactory.address;\n }\n\n const contracts = getWorldFactoryContracts(deployerAddress);\n // We can deploy these contracts in parallel because they do not call each other at this point.\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: Object.values(contracts),\n });\n return contracts.WorldFactory.address;\n}\n","import createDebug from \"debug\";\n\nexport const debug = createDebug(\"mud:cli\");\nexport const error = createDebug(\"mud:cli\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { AbiEventSignatureNotFoundError, Log, decodeEventLog, hexToString, parseAbi, getAddress } from \"viem\";\nimport { WorldDeploy, worldDeployEvents } from \"./common\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nexport function logsToWorldDeploy(logs: readonly Log<bigint, number, false>[]): Omit<WorldDeploy, \"stateBlock\"> {\n const deployLogs = logs\n .map((log) => {\n try {\n return {\n ...log,\n ...decodeEventLog({\n strict: true,\n abi: parseAbi(worldDeployEvents),\n topics: log.topics,\n data: log.data,\n }),\n // Log addresses are not checksummed, but we want them checksummed before writing to disk.\n // https://github.com/wevm/viem/issues/2207\n address: getAddress(log.address),\n };\n } catch (error: unknown) {\n if (error instanceof AbiEventSignatureNotFoundError) {\n return;\n }\n throw error;\n }\n })\n .filter(isDefined);\n\n // TODO: should this test for/validate that only one of each of these events is present? and that the address/block number don't change between each?\n const { address, deployBlock, worldVersion, storeVersion } = deployLogs.reduce<Partial<WorldDeploy>>(\n (deploy, log) => ({\n ...deploy,\n address: log.address,\n deployBlock: log.blockNumber,\n ...(log.eventName === \"HelloWorld\"\n ? { worldVersion: hexToString(log.args.worldVersion).replace(/\\0+$/, \"\") }\n : null),\n ...(log.eventName === \"HelloStore\"\n ? { storeVersion: hexToString(log.args.storeVersion).replace(/\\0+$/, \"\") }\n : null),\n }),\n {},\n );\n\n if (address == null) throw new Error(\"could not find world address\");\n if (deployBlock == null) throw new Error(\"could not find world deploy block number\");\n if (worldVersion == null) throw new Error(\"could not find world version\");\n if (storeVersion == null) throw new Error(\"could not find store version\");\n\n return { address, deployBlock, worldVersion, storeVersion };\n}\n","import { Abi, Account, Address, Chain, Client, Hex, Transport } from \"viem\";\nimport IBaseWorldAbi from \"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json\" assert { type: \"json\" };\nimport { helloStoreEvent } from \"@latticexyz/store\";\nimport { helloWorldEvent } from \"@latticexyz/world\";\nimport { LibraryMap } from \"./getLibraryMap\";\n\nexport const worldDeployEvents = [helloStoreEvent, helloWorldEvent] as const;\n\nexport const worldAbi = IBaseWorldAbi;\n\n// Ideally, this should be an append-only list. Before adding more versions here, be sure to add backwards-compatible support for old Store/World versions.\nexport const supportedStoreVersions = [\"2.0.0\", \"2.0.1\", \"2.0.2\"];\nexport const supportedWorldVersions = [\"2.0.0\", \"2.0.1\", \"2.0.2\"];\n\n// TODO: extend this to include factory+deployer address? so we can reuse the deployer for a world?\nexport type WorldDeploy = {\n readonly address: Address;\n readonly worldVersion: string;\n readonly storeVersion: string;\n /** Block number where the world was deployed */\n readonly deployBlock: bigint;\n /**\n * Block number at the time of fetching world deploy.\n * We use this block number when requesting data from the chain to align chain state\n * with the same block during the introspection steps of the deploy.\n */\n readonly stateBlock: bigint;\n};\n\nexport type WorldFunction = {\n readonly signature: string;\n readonly selector: Hex;\n readonly systemId: Hex;\n readonly systemFunctionSignature: string;\n readonly systemFunctionSelector: Hex;\n};\n\nexport type LibraryPlaceholder = {\n /**\n * Path to library source file, e.g. `src/libraries/SomeLib.sol`\n */\n path: string;\n /**\n * Library name, e.g. `SomeLib`\n */\n name: string;\n /**\n * Byte offset of placeholder in bytecode\n */\n start: number;\n /**\n * Size of placeholder to replace in bytes\n */\n length: number;\n};\n\nexport type DeterministicContract = {\n readonly prepareDeploy: (\n deployer: Address,\n libraryMap?: LibraryMap,\n ) => {\n readonly address: Address;\n readonly bytecode: Hex;\n };\n readonly deployedBytecodeSize: number;\n readonly abi: Abi;\n};\n\nexport type Library = DeterministicContract & {\n /**\n * Path to library source file, e.g. `src/libraries/SomeLib.sol`\n */\n path: string;\n /**\n * Library name, e.g. `SomeLib`\n */\n name: string;\n};\n\nexport type System = DeterministicContract & {\n // labels\n readonly label: string;\n readonly namespaceLabel: string;\n // resource ID\n readonly namespace: string;\n readonly name: string;\n readonly systemId: Hex;\n // access\n readonly allowAll: boolean;\n readonly allowedAddresses: readonly Hex[];\n readonly allowedSystemIds: readonly Hex[];\n // world registration\n // TODO: replace this with system manifest data\n readonly worldFunctions: readonly WorldFunction[];\n // metadata to register onchain\n readonly metadata: {\n // human readable ABIs\n readonly abi: readonly string[];\n readonly worldAbi: readonly string[];\n };\n};\n\nexport type DeployedSystem = Omit<\n System,\n \"label\" | \"namespaceLabel\" | \"abi\" | \"metadata\" | \"prepareDeploy\" | \"deployedBytecodeSize\" | \"allowedSystemIds\"\n> & {\n address: Address;\n};\n\nexport type Module = DeterministicContract & {\n readonly name: string;\n readonly installStrategy: \"root\" | \"delegation\" | \"default\";\n readonly installData: Hex; // TODO: figure out better naming for this\n /**\n * @internal\n * Optional modules warn instead of throw if they revert while being installed.\n */\n readonly optional?: boolean;\n};\n\nexport type CommonDeployOptions = {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly indexerUrl?: string;\n readonly chainId?: number;\n};\n","import { Hex } from \"viem\";\nimport { resourceToLabel, writeContract } from \"@latticexyz/common\";\nimport { CommonDeployOptions, WorldDeploy, worldAbi } from \"./common\";\nimport {\n valueSchemaToFieldLayoutHex,\n keySchemaToHex,\n valueSchemaToHex,\n getSchemaTypes,\n getValueSchema,\n getKeySchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { debug } from \"./debug\";\nimport { getTables } from \"./getTables\";\nimport pRetry from \"p-retry\";\nimport { Table } from \"@latticexyz/config\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nexport async function ensureTables({\n client,\n worldDeploy,\n tables,\n indexerUrl,\n chainId,\n}: CommonDeployOptions & {\n readonly worldDeploy: WorldDeploy;\n readonly tables: readonly Table[];\n}): Promise<readonly Hex[]> {\n const configTables = new Map(\n tables.map((table) => {\n const keySchema = getSchemaTypes(getKeySchema(table));\n const valueSchema = getSchemaTypes(getValueSchema(table));\n const keySchemaHex = keySchemaToHex(keySchema);\n const valueSchemaHex = valueSchemaToHex(valueSchema);\n return [\n table.tableId,\n {\n ...table,\n keySchema,\n keySchemaHex,\n valueSchema,\n valueSchemaHex,\n },\n ];\n }),\n );\n\n const worldTables = await getTables({ client, worldDeploy, indexerUrl, chainId });\n const existingTables = worldTables.filter(({ tableId }) => configTables.has(tableId));\n if (existingTables.length) {\n debug(\"existing tables:\", existingTables.map(resourceToLabel).join(\", \"));\n\n const schemaErrors = existingTables\n .map((table) => {\n const configTable = configTables.get(table.tableId)!;\n if (table.keySchemaHex !== configTable.keySchemaHex || table.valueSchemaHex !== configTable.valueSchemaHex) {\n return [\n `\"${resourceToLabel(table)}\" table:`,\n ` Registered schema: ${JSON.stringify({ schema: getSchemaTypes(table.schema), key: table.key })}`,\n ` Config schema: ${JSON.stringify({ schema: getSchemaTypes(configTable.schema), key: configTable.key })}`,\n ].join(\"\\n\");\n }\n })\n .filter(isDefined);\n\n if (schemaErrors.length) {\n throw new Error(\n [\n \"Table schemas are immutable, but found registered tables with a different schema than what you have configured.\",\n ...schemaErrors,\n \"You can either update your config with the registered schema or change the table name to register a new table.\",\n ].join(\"\\n\\n\") + \"\\n\",\n );\n }\n }\n\n const existingTableIds = new Set(existingTables.map(({ tableId }) => tableId));\n const missingTables = tables.filter((table) => !existingTableIds.has(table.tableId));\n if (missingTables.length) {\n debug(\"registering tables:\", missingTables.map(resourceToLabel).join(\", \"));\n return await Promise.all(\n missingTables.map((table) => {\n const keySchema = getSchemaTypes(getKeySchema(table));\n const valueSchema = getSchemaTypes(getValueSchema(table));\n return pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerTable\",\n args: [\n table.tableId,\n valueSchemaToFieldLayoutHex(valueSchema),\n keySchemaToHex(keySchema),\n valueSchemaToHex(valueSchema),\n Object.keys(keySchema),\n Object.keys(valueSchema),\n ],\n }),\n {\n retries: 3,\n onFailedAttempt: () => debug(`failed to register table ${resourceToLabel(table)}, retrying...`),\n },\n );\n }),\n );\n }\n\n return [];\n}\n","import { Client, Hex, decodeAbiParameters, parseAbiParameters } from \"viem\";\nimport { hexToResource } from \"@latticexyz/common\";\nimport { CommonDeployOptions } from \"./common\";\nimport { debug } from \"./debug\";\nimport { hexToSchema } from \"@latticexyz/protocol-parser/internal\";\nimport { Schema, Table } from \"@latticexyz/config\";\nimport storeConfig from \"@latticexyz/store/mud.config\";\nimport { getRecords } from \"@latticexyz/store-sync\";\n\n// TODO: add label and namespaceLabel once we register it onchain\ntype DeployedTable = Omit<Table, \"label\" | \"namespaceLabel\"> & {\n readonly keySchema: Schema;\n readonly keySchemaHex: Hex;\n readonly valueSchema: Schema;\n readonly valueSchemaHex: Hex;\n};\n\nexport async function getTables({\n client,\n worldDeploy,\n indexerUrl,\n chainId,\n}: Omit<CommonDeployOptions, \"client\"> & { client: Client }): Promise<readonly Omit<DeployedTable, \"label\">[]> {\n debug(\"looking up tables for\", worldDeploy.address);\n\n const { records } = await getRecords({\n table: storeConfig.namespaces.store.tables.Tables,\n worldAddress: worldDeploy.address,\n indexerUrl,\n chainId,\n client,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n });\n\n const tables = records.map((record) => {\n const { type, namespace, name } = hexToResource(record.tableId);\n\n const solidityKeySchema = hexToSchema(record.keySchema);\n const solidityValueSchema = hexToSchema(record.valueSchema);\n const keyNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), record.abiEncodedKeyNames)[0];\n const fieldNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), record.abiEncodedFieldNames)[0];\n\n const valueAbiTypes = [...solidityValueSchema.staticFields, ...solidityValueSchema.dynamicFields];\n\n const keySchema = Object.fromEntries(\n solidityKeySchema.staticFields.map((abiType, i) => [keyNames[i], { type: abiType, internalType: abiType }]),\n ) satisfies Schema;\n\n const valueSchema = Object.fromEntries(\n valueAbiTypes.map((abiType, i) => [fieldNames[i], { type: abiType, internalType: abiType }]),\n ) satisfies Schema;\n\n return {\n type: type as never,\n namespace,\n name,\n tableId: record.tableId,\n schema: { ...keySchema, ...valueSchema },\n key: Object.keys(keySchema),\n keySchema,\n keySchemaHex: record.keySchema,\n valueSchema,\n valueSchemaHex: record.valueSchema,\n };\n });\n\n // TODO: filter/detect duplicates?\n\n debug(\"found\", tables.length, \"tables for\", worldDeploy.address);\n\n return tables;\n}\n","import { Hex, getAddress, Address } from \"viem\";\nimport { writeContract, resourceToLabel } from \"@latticexyz/common\";\nimport { CommonDeployOptions, System, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { getSystems } from \"./getSystems\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport pRetry from \"p-retry\";\nimport { LibraryMap } from \"./getLibraryMap\";\nimport { ensureContractsDeployed } from \"@latticexyz/common/internal\";\n\n// TODO: move each system registration+access to batch call to be atomic\n\nexport async function ensureSystems({\n client,\n deployerAddress,\n libraryMap,\n worldDeploy,\n systems,\n indexerUrl,\n chainId,\n}: CommonDeployOptions & {\n readonly deployerAddress: Hex;\n readonly libraryMap: LibraryMap;\n readonly systems: readonly System[];\n}): Promise<readonly Hex[]> {\n const [worldSystems, worldAccess] = await Promise.all([\n getSystems({ client, worldDeploy, indexerUrl, chainId }),\n getResourceAccess({ client, worldDeploy, indexerUrl, chainId }),\n ]);\n\n // Register or replace systems\n\n const existingSystems = systems.filter((system) =>\n worldSystems.some(\n (worldSystem) =>\n worldSystem.systemId === system.systemId &&\n getAddress(worldSystem.address) === getAddress(system.prepareDeploy(deployerAddress, libraryMap).address),\n ),\n );\n if (existingSystems.length) {\n debug(\"existing systems:\", existingSystems.map(resourceToLabel).join(\", \"));\n }\n const existingSystemIds = existingSystems.map((system) => system.systemId);\n\n const missingSystems = systems.filter((system) => !existingSystemIds.includes(system.systemId));\n if (!missingSystems.length) return [];\n\n const systemsToUpgrade = missingSystems.filter((system) =>\n worldSystems.some(\n (worldSystem) =>\n worldSystem.systemId === system.systemId &&\n getAddress(worldSystem.address) !== getAddress(system.prepareDeploy(deployerAddress, libraryMap).address),\n ),\n );\n if (systemsToUpgrade.length) {\n debug(\"upgrading systems:\", systemsToUpgrade.map(resourceToLabel).join(\", \"));\n }\n\n const systemsToAdd = missingSystems.filter(\n (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId),\n );\n if (systemsToAdd.length) {\n debug(\"registering new systems:\", systemsToAdd.map(resourceToLabel).join(\", \"));\n }\n\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: missingSystems.map((system) => ({\n bytecode: system.prepareDeploy(deployerAddress, libraryMap).bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n debugLabel: `${resourceToLabel(system)} system`,\n })),\n });\n\n const registerTxs = await Promise.all(\n missingSystems.map((system) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerSystem\",\n args: [system.systemId, system.prepareDeploy(deployerAddress, libraryMap).address, system.allowAll],\n }),\n {\n retries: 3,\n onFailedAttempt: () => debug(`failed to register system ${resourceToLabel(system)}, retrying...`),\n },\n ),\n ),\n );\n\n // Adjust system access\n\n const systemIds = systems.map((system) => system.systemId);\n const currentAccess = worldAccess.filter(({ resourceId }) => systemIds.includes(resourceId));\n const desiredAccess = [\n ...systems.flatMap((system) =>\n system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address })),\n ),\n ...systems.flatMap((system) =>\n system.allowedSystemIds\n .map((systemId) => ({\n resourceId: system.systemId,\n address:\n worldSystems.find((s) => s.systemId === systemId)?.address ??\n systems.find((s) => s.systemId === systemId)?.prepareDeploy(deployerAddress, libraryMap).address,\n }))\n .filter((access): access is typeof access & { address: Address } => access.address != null),\n ),\n ];\n\n const accessToAdd = desiredAccess.filter(\n (access) =>\n !currentAccess.some(\n ({ resourceId, address }) =>\n resourceId === access.resourceId && getAddress(address) === getAddress(access.address),\n ),\n );\n\n const accessToRemove = currentAccess.filter(\n (access) =>\n !desiredAccess.some(\n ({ resourceId, address }) =>\n resourceId === access.resourceId && getAddress(address) === getAddress(access.address),\n ),\n );\n\n if (accessToRemove.length) {\n debug(\"revoking\", accessToRemove.length, \"access grants\");\n }\n if (accessToAdd.length) {\n debug(\"adding\", accessToAdd.length, \"access grants\");\n }\n\n const accessTxs = await Promise.all([\n ...accessToRemove.map((access) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"revokeAccess\",\n args: [access.resourceId, access.address],\n }),\n {\n retries: 3,\n onFailedAttempt: () => debug(\"failed to revoke access, retrying...\"),\n },\n ),\n ),\n ...accessToAdd.map((access) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"grantAccess\",\n args: [access.resourceId, access.address],\n }),\n {\n retries: 3,\n onFailedAttempt: () => debug(\"failed to grant access, retrying...\"),\n },\n ),\n ),\n ]);\n\n return [...registerTxs, ...accessTxs];\n}\n","import { CommonDeployOptions, DeployedSystem } from \"./common\";\nimport { hexToResource, resourceToLabel } from \"@latticexyz/common\";\nimport { getFunctions } from \"@latticexyz/store-sync/world\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { getTableValue } from \"./getTableValue\";\nimport { debug } from \"./debug\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\nimport { Client } from \"viem\";\n\nexport async function getSystems({\n client,\n worldDeploy,\n indexerUrl,\n chainId,\n}: Omit<CommonDeployOptions, \"client\"> & { client: Client }): Promise<readonly DeployedSystem[]> {\n const [resourceIds, functions, resourceAccess] = await Promise.all([\n getResourceIds({ client, worldDeploy, indexerUrl, chainId }),\n getFunctions({\n client,\n worldAddress: worldDeploy.address,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n indexerUrl,\n chainId,\n }),\n getResourceAccess({ client, worldDeploy, indexerUrl, chainId }),\n ]);\n const systems = resourceIds.map(hexToResource).filter((resource) => resource.type === \"system\");\n\n debug(\"looking up systems:\", systems.map(resourceToLabel).join(\", \"));\n return await Promise.all(\n systems.map(async (system): Promise<DeployedSystem> => {\n const { system: address, publicAccess } = await getTableValue({\n client,\n worldDeploy,\n table: worldConfig.namespaces.world.tables.Systems,\n key: { systemId: system.resourceId },\n });\n const worldFunctions = functions.filter((func) => func.systemId === system.resourceId);\n return {\n address,\n namespace: system.namespace,\n name: system.name,\n systemId: system.resourceId,\n allowAll: publicAccess,\n allowedAddresses: resourceAccess\n .filter(({ resourceId }) => resourceId === system.resourceId)\n .map(({ address }) => address),\n worldFunctions,\n };\n }),\n );\n}\n","import { Client, Hex } from \"viem\";\nimport { CommonDeployOptions } from \"./common\";\nimport { debug } from \"./debug\";\nimport storeConfig from \"@latticexyz/store/mud.config\";\nimport { getRecords } from \"@latticexyz/store-sync\";\n\nexport async function getResourceIds({\n client,\n worldDeploy,\n indexerUrl,\n chainId,\n}: Omit<CommonDeployOptions, \"client\"> & { client: Client }): Promise<readonly Hex[]> {\n debug(\"looking up resource IDs for\", worldDeploy.address);\n const { records } = await getRecords({\n table: storeConfig.namespaces.store.tables.ResourceIds,\n worldAddress: worldDeploy.address,\n indexerUrl,\n chainId,\n client,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n });\n const resourceIds = records.map((record) => record.resourceId);\n\n debug(\"found\", resourceIds.length, \"resource IDs for\", worldDeploy.address);\n return resourceIds;\n}\n","import {\n decodeValueArgs,\n encodeKey,\n getKeySchema,\n getSchemaPrimitives,\n getSchemaTypes,\n getValueSchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport { Client, Hex } from \"viem\";\nimport { readContract } from \"viem/actions\";\nimport { Table } from \"@latticexyz/config\";\n\nexport async function getTableValue<table extends Table>({\n client,\n worldDeploy,\n table,\n key,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n readonly table: table;\n readonly key: getSchemaPrimitives<getKeySchema<table>>;\n}): Promise<getSchemaPrimitives<getValueSchema<table>>> {\n const [staticData, encodedLengths, dynamicData] = (await readContract(client, {\n blockNumber: worldDeploy.stateBlock,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"getRecord\",\n args: [table.tableId, encodeKey(getSchemaTypes(getKeySchema(table)) as never, key as never)],\n // TODO: remove cast once https://github.com/wevm/viem/issues/2125 is resolved\n })) as [Hex, Hex, Hex];\n return decodeValueArgs(getSchemaTypes(getValueSchema(table)), {\n staticData,\n encodedLengths,\n dynamicData,\n });\n}\n","import { Hex, Address, getAddress, Client } from \"viem\";\nimport { CommonDeployOptions } from \"./common\";\nimport { debug } from \"./debug\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\nimport { getRecords } from \"@latticexyz/store-sync\";\n\nexport async function getResourceAccess({\n client,\n worldDeploy,\n indexerUrl,\n chainId,\n}: Omit<CommonDeployOptions, \"client\"> & { client: Client }): Promise<\n readonly { readonly resourceId: Hex; readonly address: Address }[]\n> {\n debug(\"looking up resource access for\", worldDeploy.address);\n\n const { records } = await getRecords({\n table: worldConfig.namespaces.world.tables.ResourceAccess,\n worldAddress: worldDeploy.address,\n indexerUrl,\n chainId,\n client,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n });\n const access = records\n .filter((record) => record.access)\n .map((record) => ({\n resourceId: record.resourceId,\n address: getAddress(record.caller),\n }));\n\n debug(\"found\", access.length, \"resource<>address access pairs\");\n\n return access;\n}\n","import { Client, Address, getAddress, parseAbi } from \"viem\";\nimport { getBlock } from \"viem/actions\";\nimport { fetchBlockLogs } from \"@latticexyz/block-logs-stream\";\nimport { WorldDeploy, worldDeployEvents } from \"./common\";\nimport { debug } from \"./debug\";\nimport { logsToWorldDeploy } from \"./logsToWorldDeploy\";\n\nconst deploys = new Map<Address, WorldDeploy>();\n\nexport async function getWorldDeploy(\n client: Client,\n worldAddress: Address,\n deployBlock?: bigint,\n): Promise<WorldDeploy> {\n const address = getAddress(worldAddress);\n const stateBlock = await getBlock(client, { blockTag: \"latest\" });\n\n let deploy = deploys.get(address);\n if (deploy != null) {\n return {\n ...deploy,\n stateBlock: stateBlock.number,\n };\n }\n\n debug(\"looking up world deploy for\", address);\n\n const [fromBlock, toBlock] = deployBlock\n ? [{ number: deployBlock }, { number: deployBlock }]\n : [await getBlock(client, { blockTag: \"earliest\" }), stateBlock];\n\n const blockLogs = await fetchBlockLogs({\n publicClient: client,\n address,\n events: parseAbi(worldDeployEvents),\n fromBlock: fromBlock.number,\n toBlock: toBlock.number,\n maxBlockRange: 100_000n,\n });\n\n if (blockLogs.length === 0) {\n throw new Error(\"could not find `HelloWorld` or `HelloStore` event\");\n }\n\n deploy = {\n ...logsToWorldDeploy(blockLogs.flatMap((block) => block.logs)),\n stateBlock: stateBlock.number,\n };\n deploys.set(address, deploy);\n\n debug(\"found world deploy for\", address, \"at block\", deploy.deployBlock);\n\n return deploy;\n}\n","import { Hex } from \"viem\";\nimport { hexToResource, writeContract } from \"@latticexyz/common\";\nimport { getFunctions } from \"@latticexyz/store-sync/world\";\nimport { CommonDeployOptions, WorldFunction, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport pRetry from \"p-retry\";\n\nexport async function ensureFunctions({\n client,\n worldDeploy,\n functions,\n indexerUrl,\n chainId,\n}: CommonDeployOptions & {\n readonly functions: readonly WorldFunction[];\n}): Promise<readonly Hex[]> {\n const worldFunctions = await getFunctions({\n client,\n worldAddress: worldDeploy.address,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n indexerUrl,\n chainId,\n });\n const worldSelectorToFunction = Object.fromEntries(worldFunctions.map((func) => [func.selector, func]));\n\n const toSkip = functions.filter((func) => worldSelectorToFunction[func.selector]);\n const toAdd = functions.filter((func) => !toSkip.includes(func));\n\n if (toSkip.length) {\n debug(\"functions already registered:\", toSkip.map((func) => func.signature).join(\", \"));\n const wrongSystem = toSkip.filter((func) => func.systemId !== worldSelectorToFunction[func.selector]?.systemId);\n if (wrongSystem.length) {\n console.warn(\n \"found\",\n wrongSystem.length,\n \"functions already registered but pointing at a different system ID:\",\n wrongSystem.map((func) => func.signature).join(\", \"),\n );\n }\n }\n\n if (!toAdd.length) return [];\n\n debug(\"registering functions:\", toAdd.map((func) => func.signature).join(\", \"));\n\n return Promise.all(\n toAdd.map((func) => {\n const { namespace } = hexToResource(func.systemId);\n\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n const params =\n namespace === \"\"\n ? ({\n functionName: \"registerRootFunctionSelector\",\n args: [\n func.systemId,\n // use system function signature as world signature\n func.systemFunctionSignature,\n func.systemFunctionSignature,\n ],\n } as const)\n : ({\n functionName: \"registerFunctionSelector\",\n args: [func.systemId, func.systemFunctionSignature],\n } as const);\n\n return pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n ...params,\n }),\n {\n retries: 3,\n onFailedAttempt: () => debug(`failed to register function ${func.signature}, retrying...`),\n },\n );\n }),\n );\n}\n","import { Client, Transport, Chain, Account, Hex, BaseError } from \"viem\";\nimport { resourceToHex, writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\nimport { LibraryMap } from \"./getLibraryMap\";\nimport { ensureContractsDeployed } from \"@latticexyz/common/internal\";\nimport { encodeSystemCalls } from \"@latticexyz/world/internal\";\nimport { systemsConfig as worldSystemsConfig } from \"@latticexyz/world/mud.config\";\n\nexport async function ensureModules({\n client,\n deployerAddress,\n libraryMap,\n worldDeploy,\n modules,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly libraryMap: LibraryMap;\n readonly worldDeploy: WorldDeploy;\n readonly modules: readonly Module[];\n}): Promise<readonly Hex[]> {\n if (!modules.length) return [];\n\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: modules.map((mod) => ({\n bytecode: mod.prepareDeploy(deployerAddress, libraryMap).bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n debugLabel: `${mod.name} module`,\n })),\n });\n\n debug(\"installing modules:\", modules.map((mod) => mod.name).join(\", \"));\n return (\n await Promise.all(\n modules.map((mod) =>\n pRetry(\n async () => {\n try {\n const moduleAddress = mod.prepareDeploy(deployerAddress, libraryMap).address;\n\n // TODO: fix strong types for world ABI etc\n // TODO: add return types to get better type safety\n const params = (() => {\n if (mod.installStrategy === \"root\") {\n return {\n functionName: \"installRootModule\",\n args: [moduleAddress, mod.installData],\n } as const;\n }\n\n if (mod.installStrategy === \"delegation\") {\n return {\n functionName: \"batchCall\",\n args: encodeSystemCalls([\n {\n abi: registrationSystemAbi,\n systemId: registrationSystemId,\n functionName: \"registerDelegation\",\n args: [moduleAddress, unlimitedDelegationControlId, \"0x\"],\n },\n {\n abi: registrationSystemAbi,\n systemId: registrationSystemId,\n functionName: \"installModule\",\n args: [moduleAddress, mod.installData],\n },\n {\n abi: registrationSystemAbi,\n systemId: registrationSystemId,\n functionName: \"unregisterDelegation\",\n args: [moduleAddress],\n },\n ]),\n } as const;\n }\n\n return {\n functionName: \"installModule\",\n args: [moduleAddress, mod.installData],\n } as const;\n })();\n\n return await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n // append module's ABI so that we can decode any custom errors\n abi: [...worldAbi, ...mod.abi],\n ...params,\n });\n } catch (error) {\n if (error instanceof BaseError && error.message.includes(\"Module_AlreadyInstalled\")) {\n debug(`module ${mod.name} already installed`);\n return;\n }\n if (mod.optional) {\n debug(`optional module ${mod.name} install failed, skipping`);\n debug(error);\n return;\n }\n throw error;\n }\n },\n {\n retries: 3,\n onFailedAttempt: () => debug(`failed to install module ${mod.name}, retrying...`),\n },\n ),\n ),\n )\n ).filter(isDefined);\n}\n\n// TODO: export from world\nconst unlimitedDelegationControlId = resourceToHex({ type: \"system\", namespace: \"\", name: \"unlimited\" });\n\nconst registrationSystemId = worldSystemsConfig.systems.RegistrationSystem.systemId;\n\n// world/src/modules/init/RegistrationSystem.sol\n// TODO: import from world once we fix strongly typed JSON imports\nconst registrationSystemAbi = [\n {\n type: \"function\",\n name: \"installModule\",\n inputs: [\n {\n name: \"module\",\n type: \"address\",\n internalType: \"contract IModule\",\n },\n {\n name: \"encodedArgs\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"registerDelegation\",\n inputs: [\n {\n name: \"delegatee\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"delegationControlId\",\n type: \"bytes32\",\n internalType: \"ResourceId\",\n },\n {\n name: \"initCallData\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"unregisterDelegation\",\n inputs: [\n {\n name: \"delegatee\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","import { Hex, getAddress } from \"viem\";\nimport { CommonDeployOptions, worldAbi } from \"./common\";\nimport { hexToResource, resourceToHex, writeContract } from \"@latticexyz/common\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { getTableValue } from \"./getTableValue\";\nimport { debug } from \"./debug\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\n\nexport async function ensureNamespaceOwner({\n client,\n worldDeploy,\n resourceIds,\n indexerUrl,\n chainId,\n}: CommonDeployOptions & {\n readonly resourceIds: readonly Hex[];\n}): Promise<readonly Hex[]> {\n const desiredNamespaces = Array.from(new Set(resourceIds.map((resourceId) => hexToResource(resourceId).namespace)));\n const existingResourceIds = await getResourceIds({ client, worldDeploy, indexerUrl, chainId });\n const existingNamespaces = new Set(existingResourceIds.map((resourceId) => hexToResource(resourceId).namespace));\n if (existingNamespaces.size) {\n debug(\n \"found\",\n existingNamespaces.size,\n \"existing namespaces:\",\n Array.from(existingNamespaces)\n .map((namespace) => (namespace === \"\" ? \"<root>\" : namespace))\n .join(\", \"),\n );\n }\n\n // Assert ownership of existing namespaces\n const existingDesiredNamespaces = desiredNamespaces.filter((namespace) => existingNamespaces.has(namespace));\n const namespaceOwners = await Promise.all(\n existingDesiredNamespaces.map(async (namespace) => {\n const { owner } = await getTableValue({\n client,\n worldDeploy,\n table: worldConfig.namespaces.world.tables.NamespaceOwner,\n key: { namespaceId: resourceToHex({ type: \"namespace\", namespace, name: \"\" }) },\n });\n return [namespace, owner];\n }),\n );\n\n const unauthorizedNamespaces = namespaceOwners\n .filter(([, owner]) => getAddress(owner) !== getAddress(client.account.address))\n .map(([namespace]) => namespace);\n\n if (unauthorizedNamespaces.length) {\n throw new Error(`You are attempting to deploy to namespaces you do not own: ${unauthorizedNamespaces.join(\", \")}`);\n }\n\n // Register missing namespaces\n const missingNamespaces = desiredNamespaces.filter((namespace) => !existingNamespaces.has(namespace));\n if (missingNamespaces.length > 0) {\n debug(\"registering namespaces:\", Array.from(missingNamespaces).join(\", \"));\n }\n const registrationTxs = Promise.all(\n missingNamespaces.map((namespace) =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"registerNamespace\",\n args: [resourceToHex({ namespace, type: \"namespace\", name: \"\" })],\n }),\n ),\n );\n\n return registrationTxs;\n}\n","import { Hex, stringToHex, BaseError, concatHex } from \"viem\";\nimport { debug } from \"./debug\";\nimport { hexToResource, writeContract } from \"@latticexyz/common\";\nimport { identity, isDefined } from \"@latticexyz/common/utils\";\nimport metadataConfig from \"@latticexyz/world-module-metadata/mud.config\";\nimport metadataAbi from \"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json\" assert { type: \"json\" };\nimport { ensureModules } from \"./ensureModules\";\nimport metadataModule from \"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json\" assert { type: \"json\" };\nimport { getContractArtifact } from \"../utils/getContractArtifact\";\nimport { createPrepareDeploy } from \"./createPrepareDeploy\";\nimport { LibraryMap } from \"./getLibraryMap\";\nimport { getKeyTuple, getSchemaPrimitives } from \"@latticexyz/protocol-parser/internal\";\nimport { getRecords } from \"@latticexyz/store-sync\";\nimport { CommonDeployOptions } from \"./common\";\nimport { waitForTransactions } from \"@latticexyz/common/internal\";\n\nconst metadataModuleArtifact = getContractArtifact(metadataModule);\n\nexport type ResourceTag<value> = {\n resourceId: Hex;\n tag: string;\n value: value;\n};\n\nexport async function ensureResourceTags<const value>({\n client,\n deployerAddress,\n libraryMap,\n worldDeploy,\n tags,\n valueToHex = identity,\n indexerUrl,\n chainId,\n}: CommonDeployOptions & {\n readonly deployerAddress: Hex;\n readonly libraryMap: LibraryMap;\n readonly tags: readonly ResourceTag<value>[];\n} & (value extends Hex\n ? { readonly valueToHex?: (value: value) => Hex }\n : { readonly valueToHex: (value: value) => Hex })): Promise<readonly Hex[]> {\n debug(\"ensuring\", tags.length, \"resource tags\");\n debug(\"looking up existing resource tags\");\n\n const { records } = await getRecords({\n table: metadataConfig.tables.metadata__ResourceTag,\n worldAddress: worldDeploy.address,\n chainId,\n indexerUrl,\n client,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n });\n\n debug(\"found\", records.length, \"resource tags\");\n\n const existingTags = new Map(\n records.map((tag) => {\n const key = concatHex(getKeyTuple(metadataConfig.tables.metadata__ResourceTag, tag));\n return [key, tag.value];\n }),\n );\n\n const desiredTags = tags.map(\n (tag): getSchemaPrimitives<typeof metadataConfig.tables.metadata__ResourceTag.schema> => ({\n resource: tag.resourceId,\n tag: stringToHex(tag.tag, { size: 32 }),\n value: valueToHex(tag.value),\n }),\n );\n\n const pendingTags = desiredTags.filter((tag) => {\n const key = concatHex(getKeyTuple(metadataConfig.tables.metadata__ResourceTag, tag));\n return existingTags.get(key) !== tag.value;\n });\n if (pendingTags.length === 0) return [];\n\n const moduleTxs = await ensureModules({\n client,\n deployerAddress,\n worldDeploy,\n libraryMap,\n modules: [\n {\n optional: true,\n name: \"MetadataModule\",\n installStrategy: \"delegation\",\n installData: \"0x\",\n prepareDeploy: createPrepareDeploy(metadataModuleArtifact.bytecode, metadataModuleArtifact.placeholders),\n deployedBytecodeSize: metadataModuleArtifact.deployedBytecodeSize,\n abi: metadataModuleArtifact.abi,\n },\n ],\n });\n\n // Wait for metadata module to be available, otherwise calling the metadata system below may fail.\n // This is only here because OPStack chains don't let us estimate gas with pending block tag.\n await waitForTransactions({\n client,\n hashes: moduleTxs,\n debugLabel: \"metadata module installation\",\n });\n\n debug(\"setting\", pendingTags.length, \"resource tags\");\n return (\n await Promise.all(\n pendingTags.map(async (tag) => {\n const resource = hexToResource(tag.resource);\n // TODO: move to resourceToDebugString\n const resourceString = `${resource.type}:${resource.namespace}:${resource.name}`;\n debug(`tagging ${resourceString} with ${tag.tag}: ${JSON.stringify(tag.value)}`);\n try {\n return await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: metadataAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"metadata__setResourceTag\",\n args: [tag.resource, tag.tag, tag.value],\n });\n } catch (error) {\n debug(\n `failed to set resource tag for ${resourceString}, skipping\\n ${error instanceof BaseError ? error.shortMessage : error}`,\n );\n }\n }),\n )\n ).filter(isDefined);\n}\n","import { Abi, Hex, isHex, size } from \"viem\";\nimport { LibraryPlaceholder } from \"../deploy/common\";\nimport { findPlaceholders } from \"./findPlaceholders\";\nimport { z } from \"zod\";\nimport { Abi as abiSchema } from \"abitype/zod\";\n\nexport type GetContractArtifactResult = {\n bytecode: Hex;\n placeholders: readonly LibraryPlaceholder[];\n abi: Abi;\n deployedBytecodeSize: number;\n};\n\nfunction isBytecode(value: string): value is Hex {\n return isHex(value, { strict: false });\n}\n\nconst bytecodeSchema = z.object({\n object: z.string().refine(isBytecode),\n linkReferences: z\n .record(\n z.record(\n z.array(\n z.object({\n start: z.number(),\n length: z.number(),\n }),\n ),\n ),\n )\n .optional(),\n});\n\nconst artifactSchema = z.object({\n bytecode: bytecodeSchema,\n deployedBytecode: bytecodeSchema,\n abi: abiSchema,\n});\n\nexport function getContractArtifact(artifactJson: unknown): GetContractArtifactResult {\n // TODO: improve errors or replace with arktype?\n const artifact = artifactSchema.parse(artifactJson);\n const placeholders = findPlaceholders(artifact.bytecode.linkReferences ?? {});\n\n return {\n abi: artifact.abi,\n bytecode: artifact.bytecode.object,\n placeholders,\n deployedBytecodeSize: size(artifact.deployedBytecode.object),\n };\n}\n","import { LibraryPlaceholder } from \"../deploy/common\";\n\n// TODO: move this to a broader solc artifact type\n/** From `artifact.bytecode.linkReferences` where `artifact` is the solc JSON output of a compiled Solidity contract */\nexport type LinkReferences = {\n [filename: string]: {\n [name: string]: {\n start: number;\n length: number;\n }[];\n };\n};\n\nexport function findPlaceholders(linkReferences: LinkReferences): readonly LibraryPlaceholder[] {\n return Object.entries(linkReferences).flatMap(([path, contracts]) =>\n Object.entries(contracts).flatMap(([contractName, locations]) =>\n locations.map(\n (location): LibraryPlaceholder => ({\n path,\n name: contractName,\n start: location.start,\n length: location.length,\n }),\n ),\n ),\n );\n}\n","import { DeterministicContract, LibraryPlaceholder } from \"./common\";\nimport { spliceHex } from \"@latticexyz/common\";\nimport { Hex, Address } from \"viem\";\nimport { LibraryMap } from \"./getLibraryMap\";\nimport { getContractAddress } from \"@latticexyz/common/internal\";\n\nexport function createPrepareDeploy(\n bytecodeWithPlaceholders: Hex,\n placeholders: readonly LibraryPlaceholder[],\n): DeterministicContract[\"prepareDeploy\"] {\n return function prepareDeploy(deployerAddress: Address, libraryMap?: LibraryMap) {\n let bytecode = bytecodeWithPlaceholders;\n\n if (placeholders.length === 0) {\n return { bytecode, address: getContractAddress({ deployerAddress, bytecode }) };\n }\n\n if (!libraryMap) {\n throw new Error(\"Libraries must be provided if there are placeholders\");\n }\n\n for (const placeholder of placeholders) {\n const address = libraryMap.getAddress({\n name: placeholder.name,\n path: placeholder.path,\n deployer: deployerAddress,\n });\n bytecode = spliceHex(bytecode, placeholder.start, placeholder.length, address);\n }\n return {\n bytecode,\n address: getContractAddress({ deployerAddress, bytecode }),\n };\n };\n}\n","import { Account, Chain, Client, Hex, Transport, concatHex, encodeDeployData, isHex } from \"viem\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { resourceToHex, sendTransaction, writeContract } from \"@latticexyz/common\";\nimport { debug } from \"./debug\";\nimport { logsToWorldDeploy } from \"./logsToWorldDeploy\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport { getWorldContracts } from \"./getWorldContracts\";\nimport { ensureContractsDeployed, getContractAddress, waitForTransactions } from \"@latticexyz/common/internal\";\nimport { ContractArtifact, ReferenceIdentifier } from \"@latticexyz/world/node\";\nimport { World } from \"@latticexyz/world\";\n\nfunction findArtifact(ref: ReferenceIdentifier, artifacts: readonly ContractArtifact[]): ContractArtifact {\n const artifact = artifacts.find((a) => a.sourcePath === ref.sourcePath && a.name === ref.name);\n if (!artifact) throw new Error(`Could not find referenced artifact at \"${ref.sourcePath}:${ref.name}\".`);\n return artifact;\n}\n\nfunction getDependencies(\n artifact: ContractArtifact,\n artifacts: readonly ContractArtifact[],\n): readonly ContractArtifact[] {\n return artifact.bytecode\n .filter((part): part is Exclude<typeof part, Hex> => !isHex(part))\n .flatMap((ref) => {\n return getDependencies(findArtifact(ref, artifacts), artifacts);\n });\n}\n\nfunction getDeployable(deployerAddress: Hex, artifact: ContractArtifact, artifacts: readonly ContractArtifact[]): Hex {\n return concatHex(\n artifact.bytecode.map((ref): Hex => {\n if (isHex(ref)) return ref;\n return getContractAddress({\n deployerAddress,\n bytecode: getDeployable(deployerAddress, findArtifact(ref, artifacts), artifacts),\n });\n }),\n );\n}\n\nexport async function deployCustomWorld({\n client,\n deployerAddress,\n artifacts,\n customWorld,\n}: {\n client: Client<Transport, Chain | undefined, Account>;\n deployerAddress: Hex;\n artifacts: readonly ContractArtifact[];\n customWorld: Exclude<World[\"deploy\"][\"customWorld\"], undefined>;\n}): Promise<WorldDeploy> {\n // deploy world prereqs (e.g. core modules)\n const contracts = getWorldContracts(deployerAddress);\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: Object.values(contracts),\n });\n\n const worldArtifact = findArtifact(customWorld, artifacts);\n // TODO: check that world ABI still satisfies the protocol (https://github.com/latticexyz/mud/issues/3152)\n\n // Find and deploy dependencies (i.e. public libraries)\n const deps = getDependencies(worldArtifact, artifacts);\n if (deps.length) {\n debug(`deploying ${deps.length} world dependencies`);\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: deps\n .map((dep) => getDeployable(deployerAddress, dep, artifacts))\n .reverse()\n .map((bytecode) => ({ bytecode })),\n });\n }\n\n // Deploy custom world without deterministic deployer for now\n debug(\"deploying custom world\");\n const deployTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n data: encodeDeployData({\n abi: worldArtifact.abi,\n args: [], // TODO (https://github.com/latticexyz/mud/issues/3150)\n bytecode: getDeployable(deployerAddress, worldArtifact, artifacts),\n }),\n });\n\n debug(\"waiting for custom world deploy\");\n const receipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (receipt.status !== \"success\") {\n console.error(\"world deploy failed\", receipt);\n throw new Error(\"world deploy failed\");\n }\n\n const deploy = logsToWorldDeploy(receipt.logs);\n debug(\"deployed custom world to\", deploy.address, \"at block\", deploy.deployBlock);\n\n // initialize world via init module\n const initTx = await writeContract(client, {\n chain: client.chain ?? null,\n address: deploy.address,\n abi: worldAbi,\n functionName: \"initialize\",\n args: [contracts.InitModule.address],\n });\n await waitForTransactions({ client, hashes: [initTx], debugLabel: \"world init\" });\n\n // transfer root namespace to deployer after init module is installed so `transferOwnership` method is available\n const transferOwnershipTx = await writeContract(client, {\n chain: client.chain ?? null,\n address: deploy.address,\n abi: worldAbi,\n functionName: \"transferOwnership\",\n args: [resourceToHex({ type: \"namespace\", namespace: \"\", name: \"\" }), client.account.address],\n });\n await waitForTransactions({ client, hashes: [transferOwnershipTx], debugLabel: \"world ownership transfer\" });\n\n return { ...deploy, stateBlock: deploy.deployBlock };\n}\n","import { Address } from \"viem\";\nimport { Library } from \"./common\";\n\nexport type LibraryMap = {\n getAddress: (opts: { path: string; name: string; deployer: Address }) => Address;\n};\n\nfunction getLibraryKey({ path, name }: { path: string; name: string }): string {\n return `${path}:${name}`;\n}\n\ntype LibraryCache = {\n [key: string]: Library & {\n address?: {\n [deployer: Address]: Address;\n };\n };\n};\n\nexport function getLibraryMap(libraries: readonly Library[]): LibraryMap {\n const cache: LibraryCache = Object.fromEntries(libraries.map((library) => [getLibraryKey(library), library]));\n const libraryMap = {\n getAddress: ({ path, name, deployer }) => {\n const library = cache[getLibraryKey({ path, name })];\n if (!library) {\n throw new Error(`Could not find library for bytecode placeholder ${path}:${name}`);\n }\n library.address ??= {};\n // Store the prepared address in the library cache to avoid preparing the same library twice\n library.address[deployer] ??= library.prepareDeploy(deployer, libraryMap).address;\n return library.address[deployer];\n },\n } satisfies LibraryMap;\n return libraryMap;\n}\n","import path from \"path\";\nimport { loadSystemsManifest, resolveSystems } from \"@latticexyz/world/node\";\nimport { Library, System, WorldFunction } from \"./common\";\nimport { Hex, isHex, toFunctionSelector, toFunctionSignature } from \"viem\";\nimport { getContractData } from \"../utils/getContractData\";\nimport { groupBy } from \"@latticexyz/common/utils\";\nimport { findLibraries } from \"./findLibraries\";\nimport { createPrepareDeploy } from \"./createPrepareDeploy\";\nimport { World } from \"@latticexyz/world\";\nimport { findUp } from \"find-up\";\nimport { createRequire } from \"node:module\";\nimport { excludeCallWithSignatureModule } from \"./compat/excludeUnstableCallWithSignatureModule\";\n\n// TODO: replace this with a manifest/combined config output\n\nexport async function resolveConfig({\n rootDir,\n config,\n forgeOutDir,\n}: {\n rootDir: string;\n config: World;\n forgeOutDir: string;\n}): Promise<{\n readonly systems: readonly System[];\n readonly libraries: readonly Library[];\n}> {\n const requirePath = await findUp(\"package.json\");\n if (!requirePath) throw new Error(\"Could not find package.json to import relative to.\");\n const require = createRequire(requirePath);\n\n const moduleOutDirs = config.modules.filter(excludeCallWithSignatureModule).flatMap((mod) => {\n if (mod.artifactPath == undefined) {\n return [];\n }\n\n // Navigate up two dirs to get the contract output directory\n const moduleOutDir = path.join(require.resolve(mod.artifactPath), \"../../\");\n return [moduleOutDir];\n });\n\n const libraries = [forgeOutDir, ...moduleOutDirs].flatMap((outDir) =>\n findLibraries(outDir).map((library): Library => {\n // foundry/solc flattens artifacts, so we just use the path basename\n const contractData = getContractData(path.basename(library.path), library.name, outDir);\n return {\n path: library.path,\n name: library.name,\n abi: contractData.abi,\n prepareDeploy: createPrepareDeploy(contractData.bytecode, contractData.placeholders),\n deployedBytecodeSize: contractData.deployedBytecodeSize,\n };\n }),\n );\n\n const baseSystemContractData = getContractData(\"System.sol\", \"System\", forgeOutDir);\n const baseSystemFunctions = baseSystemContractData.abi\n .filter((item): item is typeof item & { type: \"function\" } => item.type === \"function\")\n .map(toFunctionSignature);\n\n const configSystems = await resolveSystems({ rootDir, config });\n const systemsManifest = await loadSystemsManifest({ rootDir, config });\n\n const systems = configSystems\n .filter((system) => !system.deploy.disabled)\n .map((system): System => {\n const manifest = systemsManifest.systems.find(({ systemId }) => systemId === system.systemId);\n if (!manifest) {\n throw new Error(\n `System \"${system.label}\" not found in systems manifest. Run \\`mud build\\` before trying again.`,\n );\n }\n\n const contractData = getContractData(`${system.label}.sol`, system.label, forgeOutDir);\n\n // TODO: replace this with manifest\n const worldFunctions = system.deploy.registerWorldFunctions\n ? contractData.abi\n .filter((item): item is typeof item & { type: \"function\" } => item.type === \"function\")\n .map(toFunctionSignature)\n .filter((sig) => !baseSystemFunctions.includes(sig))\n .map((sig): WorldFunction => {\n // TODO: figure out how to not duplicate contract behavior (https://github.com/latticexyz/mud/issues/1708)\n const worldSignature = system.namespace === \"\" ? sig : `${system.namespace}__${sig}`;\n return {\n signature: worldSignature,\n selector: toFunctionSelector(worldSignature),\n systemId: system.systemId,\n systemFunctionSignature: sig,\n systemFunctionSelector: toFunctionSelector(sig),\n };\n })\n : [];\n\n // TODO: move to resolveSystems? or system manifest?\n const allowedAddresses = system.accessList.filter((target): target is Hex => isHex(target));\n const allowedSystemIds = system.accessList\n .filter((target) => !isHex(target))\n .map((label) => {\n const system = configSystems.find((s) => s.label === label)!;\n return system.systemId;\n });\n\n return {\n ...system,\n allowAll: system.openAccess,\n allowedAddresses,\n allowedSystemIds,\n prepareDeploy: createPrepareDeploy(contractData.bytecode, contractData.placeholders),\n deployedBytecodeSize: contractData.deployedBytecodeSize,\n worldFunctions,\n abi: contractData.abi,\n metadata: {\n abi: manifest.abi,\n worldAbi: manifest.worldAbi,\n },\n };\n });\n\n // Check for overlapping system IDs (since names get truncated when turning into IDs)\n // TODO: move this into the world config resolve step once it resolves system IDs\n const systemsById = groupBy(systems, (system) => system.systemId);\n const overlappingSystems = Array.from(systemsById.values())\n .filter((matches) => matches.length > 1)\n .flat();\n if (overlappingSystems.length) {\n const names = overlappingSystems.map((system) => system.name);\n throw new Error(\n `Found systems with overlapping system ID: ${names.join(\n \", \",\n )}.\\n\\nSystem IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`,\n );\n }\n\n return {\n systems,\n libraries,\n };\n}\n","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { Abi, Hex, size } from \"viem\";\nimport { LibraryPlaceholder } from \"../deploy/common\";\nimport { findPlaceholders } from \"./findPlaceholders\";\n\n/**\n * Load the contract's abi and bytecode from the file system\n * @param contractName: Name of the contract to load\n */\nexport function getContractData(\n filename: string,\n contractName: string,\n forgeOutDirectory: string,\n): { bytecode: Hex; placeholders: readonly LibraryPlaceholder[]; abi: Abi; deployedBytecodeSize: number } {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let data: any;\n const contractDataPath = path.join(forgeOutDirectory, filename, contractName + \".json\");\n try {\n data = JSON.parse(readFileSync(contractDataPath, \"utf8\"));\n } catch (error) {\n throw new MUDError(`Error reading file at ${contractDataPath}`);\n }\n\n const bytecode = data?.bytecode?.object;\n if (!bytecode) throw new MUDError(`No bytecode found in ${contractDataPath}`);\n\n const deployedBytecode = data?.deployedBytecode?.object;\n if (!deployedBytecode) throw new MUDError(`No deployed bytecode found in ${contractDataPath}`);\n\n const abi = data?.abi;\n if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);\n\n const placeholders = findPlaceholders(data?.bytecode?.linkReferences ?? {});\n\n return { abi, bytecode, placeholders, deployedBytecodeSize: size(deployedBytecode as Hex) };\n}\n","import { readFileSync } from \"fs\";\nimport { globSync } from \"glob\";\nimport { orderByDependencies } from \"./orderByDependencies\";\nimport { LinkReferences } from \"../utils/findPlaceholders\";\n\nexport function findLibraries(forgeOutDir: string): readonly {\n readonly path: string;\n readonly name: string;\n}[] {\n const artifacts = globSync(`${forgeOutDir}/**/*.json`, { ignore: \"**/*.abi.json\" })\n .sort()\n .map((path) => JSON.parse(readFileSync(path, \"utf8\")));\n\n const libraries = artifacts.flatMap((artifact) => {\n if (!artifact.metadata) return [];\n\n const contractPath = Object.keys(artifact.metadata.settings.compilationTarget)[0];\n const contractName = artifact.metadata.settings.compilationTarget[contractPath];\n const linkReferences = artifact.bytecode.linkReferences as LinkReferences;\n\n return Object.entries(linkReferences).flatMap(([libraryPath, reference]) =>\n Object.keys(reference).map((libraryName) => ({\n path: libraryPath,\n name: libraryName,\n dependentPath: contractPath,\n dependentName: contractName,\n })),\n );\n });\n\n return orderByDependencies(\n libraries,\n (lib) => `${lib.path}:${lib.name}`,\n (lib) => [`${lib.dependentPath}:${lib.dependentName}`],\n );\n}\n","import toposort from \"toposort\";\n\nexport function orderByDependencies<T>(\n items: readonly T[],\n itemKey: (item: T) => string,\n dependencyKeys: (item: T) => string[],\n): readonly T[] {\n const dependencyOrder = toposort(\n items.flatMap((item) => dependencyKeys(item).map((dependency) => [itemKey(item), dependency] as [string, string])),\n );\n return [...items].sort((a, b) => dependencyOrder.indexOf(itemKey(a)) - dependencyOrder.indexOf(itemKey(b)));\n}\n","import { Module } from \"@latticexyz/world/internal\";\n\n/** @internal For use with `config.modules.filter(...)` */\nexport function excludeCallWithSignatureModule(mod: Module): boolean {\n if (\n mod.artifactPath ===\n \"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json\"\n ) {\n console.warn(\n [\n \"\",\n `⚠️ Your \\`mud.config.ts\\` is using \\`Unstable_CallWithSignatureModule\\`. This module can be removed from your config as it is now installed by default during deploy.`,\n \"\",\n ].join(\"\\n\"),\n );\n return false;\n }\n return true;\n}\n","import { existsSync } from \"fs\";\nimport path from \"path\";\nimport { getScriptDirectory } from \"@latticexyz/common/foundry\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"./printCommand\";\n\nexport async function postDeploy(\n postDeployScript: string,\n worldAddress: string,\n rpc: string,\n profile: string | undefined,\n forgeOptions: string | undefined,\n kms: boolean,\n): Promise<void> {\n // TODO: make this more robust as it is likely to fail for any args that have a space in them\n const userOptions = forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + \".s.sol\");\n if (!existsSync(postDeployPath)) {\n console.log(`No script at ${postDeployPath}, skipping post deploy hook`);\n return;\n }\n\n await printCommand(\n execa(\n \"forge\",\n [\n \"script\",\n postDeployScript,\n [\"--sig\", \"run(address)\", worldAddress],\n [\"--rpc-url\", rpc],\n \"--broadcast\",\n \"-vvv\",\n kms ? [\"--aws\"] : [],\n ...userOptions,\n ].flat(),\n {\n stdio: \"inherit\",\n env: {\n FOUNDRY_PROFILE: profile ?? process.env.FOUNDRY_PROFILE,\n },\n },\n ),\n );\n}\n","import path from \"node:path\";\nimport { Module } from \"./common\";\nimport { encodeField } from \"@latticexyz/protocol-parser/internal\";\nimport { SchemaAbiType, SchemaAbiTypeToPrimitiveType } from \"@latticexyz/schema-type/internal\";\nimport { bytesToHex } from \"viem\";\nimport { createPrepareDeploy } from \"./createPrepareDeploy\";\nimport { World } from \"@latticexyz/world\";\nimport { importContractArtifact } from \"../utils/importContractArtifact\";\nimport { resolveWithContext } from \"@latticexyz/world/internal\";\nimport callWithSignatureModule from \"@latticexyz/world-module-callwithsignature/out/CallWithSignatureModule.sol/CallWithSignatureModule.json\" assert { type: \"json\" };\nimport { getContractArtifact } from \"../utils/getContractArtifact\";\nimport { excludeCallWithSignatureModule } from \"./compat/excludeUnstableCallWithSignatureModule\";\nimport { moduleArtifactPathFromName } from \"./compat/moduleArtifactPathFromName\";\n\nconst callWithSignatureModuleArtifact = getContractArtifact(callWithSignatureModule);\n\nexport async function configToModules<config extends World>(\n config: config,\n // TODO: remove/replace `forgeOutDir`\n forgeOutDir: string,\n): Promise<readonly Module[]> {\n // metadata module is installed inside `ensureResourceTags`\n const defaultModules: Module[] = [\n {\n // optional for now\n // TODO: figure out approach to install on existing worlds where deployer may not own root namespace\n optional: true,\n name: \"CallWithSignatureModule\",\n installStrategy: \"root\",\n installData: \"0x\",\n prepareDeploy: createPrepareDeploy(\n callWithSignatureModuleArtifact.bytecode,\n callWithSignatureModuleArtifact.placeholders,\n ),\n deployedBytecodeSize: callWithSignatureModuleArtifact.deployedBytecodeSize,\n abi: callWithSignatureModuleArtifact.abi,\n },\n ];\n\n const modules = await Promise.all(\n config.modules\n .filter(excludeCallWithSignatureModule)\n .map(moduleArtifactPathFromName(forgeOutDir))\n .map(async (mod): Promise<Module> => {\n const name = path.basename(mod.artifactPath, \".json\");\n const artifact = await importContractArtifact({ artifactPath: mod.artifactPath });\n\n // TODO: replace args with something more strongly typed\n const installArgs = mod.args\n .map((arg) => resolveWithContext(arg, { config }))\n .map((arg) => {\n const value = arg.value instanceof Uint8Array ? bytesToHex(arg.value) : arg.value;\n return encodeField(arg.type as SchemaAbiType, value as SchemaAbiTypeToPrimitiveType<SchemaAbiType>);\n });\n\n if (installArgs.length > 1) {\n throw new Error(`${name} module should only have 0-1 args, but had ${installArgs.length} args.`);\n }\n\n return {\n name,\n installStrategy: mod.root ? \"root\" : mod.useDelegation ? \"delegation\" : \"default\",\n installData: installArgs.length === 0 ? \"0x\" : installArgs[0],\n prepareDeploy: createPrepareDeploy(artifact.bytecode, artifact.placeholders),\n deployedBytecodeSize: artifact.deployedBytecodeSize,\n abi: artifact.abi,\n };\n }),\n );\n\n return [...defaultModules, ...modules];\n}\n","import { createRequire } from \"node:module\";\nimport { findUp } from \"find-up\";\nimport { GetContractArtifactResult, getContractArtifact } from \"./getContractArtifact\";\n\nexport type ImportContractArtifactOptions = {\n /**\n * Path to `package.json` where `artifactPath`s are resolved relative to.\n *\n * Defaults to nearest `package.json` relative to `process.cwd()`.\n */\n packageJsonPath?: string;\n /**\n * Import path to contract's forge/solc JSON artifact with the contract's compiled bytecode.\n *\n * This path is resolved using node's module resolution relative to `configPath`, so this supports both\n * relative file paths (`../path/to/MyModule.json`) as well as JS import paths (`@latticexyz/world-contracts/out/CallWithSignatureModule.sol/CallWithSignatureModule.json`).\n */\n artifactPath: string;\n};\n\nexport async function importContractArtifact({\n packageJsonPath,\n artifactPath,\n}: ImportContractArtifactOptions): Promise<GetContractArtifactResult> {\n let artfactJson;\n try {\n const requirePath = packageJsonPath ?? (await findUp(\"package.json\", { cwd: process.cwd() }));\n if (!requirePath) throw new Error(\"Could not find package.json to import relative to.\");\n\n const require = createRequire(requirePath);\n artfactJson = require(artifactPath);\n } catch (error) {\n console.error();\n console.error(\"Could not import contract artifact at\", artifactPath);\n console.error();\n throw error;\n }\n\n return getContractArtifact(artfactJson);\n}\n","import { Module } from \"@latticexyz/world/internal\";\nimport path from \"node:path\";\n\n// Please don't add to this list!\n//\n// These are kept for backwards compatibility and assumes the downstream project has this module installed as a dependency.\nconst knownModuleArtifacts = {\n KeysWithValueModule: \"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json\",\n KeysInTableModule: \"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json\",\n UniqueEntityModule: \"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json\",\n};\n\n/** @internal For use with `config.modules.map(...)` */\nexport function moduleArtifactPathFromName(\n forgeOutDir: string,\n): (mod: Module) => Module & { readonly artifactPath: string } {\n return (mod) => {\n if (mod.artifactPath) return mod as never;\n if (!mod.name) throw new Error(\"No `artifactPath` provided for module.\");\n\n const artifactPath =\n knownModuleArtifacts[mod.name as keyof typeof knownModuleArtifacts] ??\n path.join(forgeOutDir, `${mod.name}.sol`, `${mod.name}.json`);\n\n console.warn(\n [\n \"\",\n `⚠️ Your \\`mud.config.ts\\` is using a module with a \\`name\\`, but this option is deprecated.`,\n \"\",\n \"To resolve this, you can replace this:\",\n \"\",\n ` name: ${JSON.stringify(mod.name)}`,\n \"\",\n \"with this:\",\n \"\",\n ` artifactPath: ${JSON.stringify(artifactPath)}`,\n \"\",\n ].join(\"\\n\"),\n );\n\n return { ...mod, artifactPath };\n };\n}\n","import { getAutomine, getBlock, setAutomine, setIntervalMining } from \"viem/actions\";\nimport { debug } from \"../debug\";\nimport { Client } from \"viem\";\nimport { getAction } from \"viem/utils\";\n\ntype MiningMode =\n | {\n type: \"automine\";\n }\n | {\n type: \"interval\";\n blockTime: number;\n };\n\nexport type EnableAutomineResult = undefined | { reset: () => Promise<void> };\n\nexport async function enableAutomine(client: Client): Promise<EnableAutomineResult> {\n const miningMode = await getMiningMode(client).catch(() => undefined);\n // doesn't support automine or is already in automine\n if (!miningMode || miningMode.type === \"automine\") return;\n\n debug(\"Enabling automine\");\n await setMiningMode(client, { type: \"automine\" });\n return {\n reset: () => {\n debug(\"Disabling automine\");\n return setMiningMode(client, miningMode);\n },\n };\n}\n\nasync function getMiningMode(client: Client): Promise<MiningMode> {\n const localClient = { mode: \"anvil\", ...client }; // set default mode to \"anvil\", potential error is caught by enableAutomine\n const isAutomine = await getAction(localClient, getAutomine, \"getAutomine\")({});\n if (isAutomine) {\n return { type: \"automine\" };\n }\n\n const blockTime = await getBlockTime(client);\n return { type: \"interval\", blockTime };\n}\n\nasync function setMiningMode(client: Client, miningMode: MiningMode): Promise<void> {\n if (miningMode.type === \"automine\") {\n await getAction(client, setAutomine, \"setAutomine\")(true);\n } else {\n await getAction(client, setIntervalMining, \"setIntervalMining\")({ interval: miningMode.blockTime });\n }\n}\n\nasync function getBlockTime(client: Client): Promise<number> {\n const latestBlock = await getAction(client, getBlock, \"getBlock\")({ blockTag: \"latest\" });\n const previousBlock = await getAction(client, getBlock, \"getBlock\")({ blockNumber: latestBlock.number - 1n });\n const blockTime = latestBlock.timestamp - previousBlock.timestamp;\n return Number(blockTime);\n}\n","import { redstone, garnet, rhodolite } from \"@latticexyz/common/chains\";\n\nexport const defaultChains = [redstone, garnet, rhodolite];\n","import type { CommandModule } from \"yargs\";\nimport { logError } from \"../utils/errors\";\nimport { DeployOptions, deployOptions, runDeploy } from \"../runDeploy\";\n\nconst commandModule: CommandModule<typeof deployOptions, DeployOptions> = {\n command: \"deploy\",\n\n describe: \"Deploy MUD contracts\",\n\n builder(yargs) {\n return yargs.options(deployOptions);\n },\n\n async handler(opts) {\n // Wrap in try/catch, because yargs seems to swallow errors\n try {\n await runDeploy(opts);\n } catch (error) {\n logError(error);\n process.exit(1);\n }\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import path from \"node:path\";\nimport type { CommandModule } from \"yargs\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { worldgen } from \"@latticexyz/world/node\";\n\ntype Options = {\n configPath?: string;\n clean?: boolean;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"worldgen\",\n\n describe: \"Autogenerate interfaces for Systems and World based on existing contracts and the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the MUD config file\" },\n clean: {\n type: \"boolean\",\n desc: \"Clear the worldgen directory before generating new interfaces (defaults to true)\",\n default: true,\n },\n });\n },\n\n async handler(args) {\n await worldgenHandler(args);\n process.exit(0);\n },\n};\n\nexport async function worldgenHandler(args: Options) {\n const configPath = await resolveConfigPath(args.configPath);\n const config = (await loadConfig(configPath)) as WorldConfig;\n const rootDir = path.dirname(configPath);\n\n await worldgen({ rootDir, config, clean: args.clean });\n}\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport { readFileSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { logError } from \"../utils/errors\";\nimport localPackageJson from \"../../package.json\" assert { type: \"json\" };\nimport { globSync } from \"glob\";\nimport { mudPackages } from \"../mudPackages\";\n\ntype Options = {\n backup?: boolean;\n force?: boolean;\n restore?: boolean;\n mudVersion?: string;\n tag?: string;\n commit?: string;\n link?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"set-version\",\n\n describe: \"Set MUD version in all package.json files and optionally backup the previously installed version\",\n\n builder(yargs) {\n return yargs.options({\n mudVersion: { alias: \"v\", type: \"string\", description: \"Set MUD to the given version\" },\n tag: {\n alias: \"t\",\n type: \"string\",\n description: \"Set MUD to the latest version with the given tag from npm\",\n },\n commit: {\n alias: \"c\",\n type: \"string\",\n description: \"Set MUD to the version based on a given git commit hash from npm\",\n },\n link: { alias: \"l\", type: \"string\", description: \"Relative path to the local MUD root directory to link\" },\n });\n },\n\n async handler(options) {\n try {\n const mutuallyExclusiveOptions = [\"mudVersion\", \"link\", \"tag\", \"commit\", \"restore\"];\n const numMutuallyExclusiveOptions = mutuallyExclusiveOptions.reduce(\n (acc, opt) => (options[opt] ? acc + 1 : acc),\n 0,\n );\n\n if (numMutuallyExclusiveOptions === 0) {\n throw new MUDError(`You need to provide one these options: ${mutuallyExclusiveOptions.join(\", \")}`);\n }\n\n if (numMutuallyExclusiveOptions > 1) {\n throw new MUDError(`These options are mutually exclusive: ${mutuallyExclusiveOptions.join(\", \")}`);\n }\n\n // If the --link flag is not set, we call resolveVersion to get the version\n // Resolve the version number from available options like `tag` or `commit`\n if (!options.link) {\n options.mudVersion = await resolveVersion(options);\n }\n\n // Update all package.json below the current working directory (except in node_modules)\n const packageJsons = globSync(\"**/package.json\")\n .sort()\n .filter((p) => !p.includes(\"node_modules\"));\n\n for (const packageJson of packageJsons) {\n updatePackageJson(packageJson, options);\n }\n } catch (e) {\n logError(e);\n } finally {\n process.exit(0);\n }\n },\n};\n\nasync function resolveVersion(options: Options) {\n // Backwards compatibility to previous behavior of this script where passing \"canary\" as the version resolved to the latest commit on main\n if (options.mudVersion === \"canary\") options.tag = \"main\";\n\n // TODO: it seems like this was already being treated as any due to fetch not\n // resolving here. See comment at https://github.com/latticexyz/mud/pull/2828\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let npmResult: any;\n try {\n console.log(chalk.blue(`Fetching available versions`));\n npmResult = await (await fetch(`https://registry.npmjs.org/${localPackageJson.name}`)).json();\n } catch (e) {\n throw new MUDError(`Could not fetch available MUD versions`);\n }\n\n if (options.tag) {\n const version = npmResult[\"dist-tags\"][options.tag];\n if (!version) {\n throw new MUDError(`Could not find npm version with tag \"${options.tag}\"`);\n }\n console.log(chalk.green(`Latest version with tag ${options.tag}: ${version}`));\n return version;\n }\n\n if (options.commit) {\n // Find a version with this commit hash\n const commit = options.commit.substring(0, 8); // changesets uses the first 8 characters of the commit hash as version for prereleases/snapshot releases\n const version = Object.keys(npmResult[\"versions\"]).find((v) => (v as string).includes(commit));\n if (!version) {\n throw new MUDError(`Could not find npm version based on commit \"${options.commit}\"`);\n }\n console.log(chalk.green(`Version from commit ${options.commit}: ${version}`));\n return version;\n }\n\n // If neither a tag nor a commit option is given, return the `mudVersion`\n return options.mudVersion;\n}\n\nfunction updatePackageJson(filePath: string, options: Options): { workspaces?: string[] } {\n const { link } = options;\n let { mudVersion } = options;\n\n const packageJson = readPackageJson(filePath);\n const mudPackageNames = Object.keys(mudPackages);\n\n // Find all MUD dependencies\n const mudDependencies: Record<string, string> = {};\n for (const packageName in packageJson.dependencies) {\n if (mudPackageNames.includes(packageName)) {\n mudDependencies[packageName] = packageJson.dependencies[packageName];\n }\n }\n\n // Find all MUD devDependencies\n const mudDevDependencies: Record<string, string> = {};\n for (const packageName in packageJson.devDependencies) {\n if (mudPackageNames.includes(packageName)) {\n mudDevDependencies[packageName] = packageJson.devDependencies[packageName];\n }\n }\n\n // Update the dependencies\n for (const packageName in packageJson.dependencies) {\n if (mudPackageNames.includes(packageName)) {\n packageJson.dependencies[packageName] = resolveMudVersion(packageName, \"dependencies\");\n }\n }\n\n // Update the devDependencies\n for (const packageName in packageJson.devDependencies) {\n if (mudPackageNames.includes(packageName)) {\n packageJson.devDependencies[packageName] = resolveMudVersion(packageName, \"devDependencies\");\n }\n }\n\n // Write the updated package.json\n writeFileSync(filePath, JSON.stringify(packageJson, null, 2) + \"\\n\");\n\n console.log(`Updating ${filePath}`);\n logComparison(mudDependencies, packageJson.dependencies);\n logComparison(mudDevDependencies, packageJson.devDependencies);\n\n return packageJson;\n\n function resolveMudVersion(key: string, type: \"dependencies\" | \"devDependencies\") {\n if (link) mudVersion = resolveLinkPath(filePath, link, key);\n if (!mudVersion) return packageJson[type][key];\n return mudVersion;\n }\n}\n\nfunction readPackageJson(path: string): {\n workspaces?: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n} {\n try {\n const jsonString = readFileSync(path, \"utf8\");\n return JSON.parse(jsonString);\n } catch {\n throw new MUDError(\"Could not read JSON at \" + path);\n }\n}\n\nfunction logComparison(prev: Record<string, string>, curr: Record<string, string>) {\n for (const key in prev) {\n if (prev[key] !== curr[key]) {\n console.log(`${key}: ${chalk.red(prev[key])} -> ${chalk.green(curr[key])}`);\n }\n }\n}\n\n/**\n * Returns path of the package to link, given a path to a local MUD clone and a package\n */\nfunction resolveLinkPath(packageJsonPath: string, mudLinkPath: string, packageName: string) {\n const packageJsonToRootPath = path.relative(path.dirname(packageJsonPath), process.cwd());\n const linkPath = path.join(packageJsonToRootPath, mudLinkPath, mudPackages[packageName].localPath);\n return \"link:\" + linkPath;\n}\n\nexport default commandModule;\n","import { ZodError, z } from \"zod\";\nimport { MudPackages } from \"./common\";\n\nconst envSchema = z.object({\n MUD_PACKAGES: z.string().transform((value) => JSON.parse(value) as MudPackages),\n});\n\nfunction parseEnv(): z.infer<typeof envSchema> {\n try {\n return envSchema.parse({\n // tsup replaces the env vars with their values at compile time\n MUD_PACKAGES: process.env.MUD_PACKAGES,\n });\n } catch (error) {\n if (error instanceof ZodError) {\n const { ...invalidEnvVars } = error.format();\n console.error(`\\nMissing or invalid environment variables:\\n\\n ${Object.keys(invalidEnvVars).join(\"\\n \")}\\n`);\n process.exit(1);\n }\n throw error;\n }\n}\n\nexport const mudPackages = parseEnv().MUD_PACKAGES;\n","import type { CommandModule, InferredOptionTypes, Options } from \"yargs\";\nimport { getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { deployOptions, runDeploy } from \"../runDeploy\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"../utils/printCommand\";\n\nconst testOptions = {\n ...deployOptions,\n port: { type: \"number\", description: \"Port to run internal node for fork testing on\", default: 4242 },\n worldAddress: {\n type: \"string\",\n description:\n \"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing.\",\n },\n forgeOptions: { type: \"string\", description: \"Options to pass to forge test\" },\n} as const satisfies Record<string, Options>;\n\ntype TestOptions = InferredOptionTypes<typeof testOptions>;\n\nconst commandModule: CommandModule<typeof testOptions, TestOptions> = {\n command: \"test\",\n\n describe: \"Run tests in MUD contracts\",\n\n builder(yargs) {\n return yargs.options(testOptions);\n },\n\n async handler(opts) {\n // Start an internal anvil process if no world address is provided\n if (!opts.worldAddress) {\n printCommand(\n execa(\"anvil\", [\"--quiet\", [\"--port\", String(opts.port)], [\"--block-base-fee-per-gas\", \"0\"]].flat(), {\n stdio: \"inherit\",\n env: { FOUNDRY_PROFILE: opts.profile ?? process.env.FOUNDRY_PROFILE },\n }),\n );\n }\n\n const forkRpc = opts.worldAddress ? await getRpcUrl(opts.profile) : `http://127.0.0.1:${opts.port}`;\n\n const worldAddress =\n opts.worldAddress ??\n (\n await runDeploy({\n ...opts,\n saveDeployment: false,\n rpc: forkRpc,\n })\n ).address;\n\n console.log(chalk.blue(\"World address\", worldAddress));\n\n const userOptions = opts.forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n try {\n await printCommand(\n execa(\"forge\", [\"test\", [\"--fork-url\", forkRpc], ...userOptions].flat(), {\n stdio: \"inherit\",\n env: {\n FOUNDRY_PROFILE: opts.profile ?? process.env.FOUNDRY_PROFILE,\n WORLD_ADDRESS: worldAddress,\n },\n }),\n );\n process.exit(0);\n } catch (e) {\n console.error(e);\n process.exit(1);\n }\n },\n};\n\nexport default commandModule;\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { CommandModule } from \"yargs\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { getRpcUrl } from \"@latticexyz/common/foundry\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\nimport { Hex, createClient, http } from \"viem\";\nimport { getChainId, readContract } from \"viem/actions\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { resolveSystems } from \"@latticexyz/world/node\";\nimport { worldAbi } from \"../deploy/common\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"../utils/printCommand\";\n\nconst systemsTableId = worldConfig.namespaces.world.tables.Systems.tableId;\n\nfunction getWorldAddress(worldsFile: string, chainId: number): Hex {\n if (!fs.existsSync(worldsFile)) {\n throw new MUDError(`Missing expected worlds.json file at \"${worldsFile}\"`);\n }\n\n const deploys = JSON.parse(fs.readFileSync(worldsFile, \"utf-8\"));\n\n if (!deploys[chainId]) {\n throw new MUDError(`Missing chain ID ${chainId} in \"${worldsFile}\"`);\n }\n\n return deploys[chainId].address as Hex;\n}\n\ntype Options = {\n tx: string;\n worldAddress?: string;\n configPath?: string;\n profile?: string;\n rpc?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"trace\",\n\n describe: \"Display the trace of a transaction\",\n\n builder(yargs) {\n return yargs.options({\n tx: { type: \"string\", required: true, description: \"Transaction hash to replay\" },\n worldAddress: {\n type: \"string\",\n description: \"World contract address. Defaults to the value from worlds.json, based on rpc's chainId\",\n },\n configPath: { type: \"string\", description: \"Path to the MUD config file\" },\n profile: { type: \"string\", description: \"The foundry profile to use\" },\n rpc: { type: \"string\", description: \"json rpc endpoint. Defaults to foundry's configured eth_rpc_url\" },\n });\n },\n\n async handler(args) {\n const configPath = await resolveConfigPath(args.configPath);\n const rootDir = path.dirname(configPath);\n\n const profile = args.profile;\n const rpc = args.rpc ?? (await getRpcUrl(profile));\n\n const config = (await loadConfig(configPath)) as WorldConfig;\n\n const client = createClient({ transport: http(rpc) });\n const chainId = await getChainId(client);\n const worldAddress = (args.worldAddress ?? getWorldAddress(config.deploy.worldsFile, chainId)) as Hex;\n\n const systems = await resolveSystems({ rootDir, config });\n\n const labels = await Promise.all(\n systems.map(async (system) => ({\n label: system.label,\n address: await readContract(client, {\n abi: worldAbi,\n address: worldAddress,\n functionName: \"getField\",\n args: [systemsTableId, [system.systemId], 0],\n }),\n })),\n );\n\n await printCommand(\n execa(\n \"cast\",\n [\n \"run\",\n [\"--label\", `${worldAddress}:World`],\n ...labels.map(({ label, address }) => [\"--label\", `${address}:${label}`]),\n args.tx,\n ].flat(),\n {\n stdio: \"inherit\",\n env: { FOUNDRY_PROFILE: profile ?? process.env.FOUNDRY_PROFILE },\n },\n ),\n );\n },\n};\n\nexport default commandModule;\n","import type { CommandModule, InferredOptionTypes } from \"yargs\";\nimport { getScriptDirectory, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport chokidar from \"chokidar\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport path from \"path\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { homedir } from \"os\";\nimport { rmSync } from \"fs\";\nimport { deployOptions, runDeploy } from \"../runDeploy\";\nimport { BehaviorSubject, debounceTime, exhaustMap, filter } from \"rxjs\";\nimport { Address } from \"viem\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { execa } from \"execa\";\nimport { printCommand } from \"../utils/printCommand\";\n\nconst devOptions = {\n rpc: deployOptions.rpc,\n configPath: deployOptions.configPath,\n alwaysRunPostDeploy: deployOptions.alwaysRunPostDeploy,\n forgeScriptOptions: deployOptions.forgeScriptOptions,\n worldAddress: deployOptions.worldAddress,\n};\n\nconst commandModule: CommandModule<typeof devOptions, InferredOptionTypes<typeof devOptions>> = {\n command: \"dev-contracts\",\n\n describe: \"Start a development server for MUD contracts\",\n\n builder(yargs) {\n return yargs.options(devOptions);\n },\n\n async handler(opts) {\n let rpc = opts.rpc;\n const configPath = opts.configPath ?? (await resolveConfigPath(opts.configPath));\n const srcDir = await getSrcDirectory();\n const scriptDir = await getScriptDirectory();\n const initialConfig = (await loadConfig(configPath)) as WorldConfig;\n\n // Start an anvil instance in the background if no RPC url is provided\n if (!opts.rpc) {\n // Clean anvil cache as 1s block times can fill up the disk\n // - https://github.com/foundry-rs/foundry/issues/3623\n // - https://github.com/foundry-rs/foundry/issues/4989\n // - https://github.com/foundry-rs/foundry/issues/3699\n // - https://github.com/foundry-rs/foundry/issues/3512\n console.log(chalk.gray(\"Cleaning devnode cache\"));\n const userHomeDir = homedir();\n rmSync(path.join(userHomeDir, \".foundry\", \"anvil\", \"tmp\"), { recursive: true, force: true });\n\n await printCommand(\n execa(\"anvil\", [\"--quiet\", [\"--block-time\", \"2\"], [\"--block-base-fee-per-gas\", \"0\"]].flat(), {\n stdio: \"inherit\",\n }),\n );\n\n rpc = \"http://127.0.0.1:8545\";\n }\n\n // Watch for changes\n const lastChange$ = new BehaviorSubject<number>(Date.now());\n chokidar.watch([configPath, srcDir, scriptDir], { ignoreInitial: true }).on(\"all\", async (_, updatePath) => {\n if (updatePath.includes(configPath)) {\n console.log(chalk.blue(\"Config changed, queuing deploy…\"));\n lastChange$.next(Date.now());\n }\n if (updatePath.includes(srcDir) || updatePath.includes(scriptDir)) {\n // Ignore changes to codegen files to avoid an infinite loop\n if (!updatePath.includes(initialConfig.codegen.outputDirectory)) {\n console.log(chalk.blue(\"Contracts changed, queuing deploy…\"));\n lastChange$.next(Date.now());\n }\n }\n });\n\n let worldAddress = opts.worldAddress as Address | undefined;\n\n const deploys$ = lastChange$.pipe(\n // debounce so that a large batch of file changes only triggers a deploy after it settles down, rather than the first change it sees (and then redeploying immediately after)\n debounceTime(200),\n exhaustMap(async (lastChange) => {\n if (worldAddress) {\n console.log(chalk.blue(\"Rebuilding and upgrading world…\"));\n }\n\n try {\n const deploy = await runDeploy({\n ...opts,\n configPath,\n rpc,\n rpcBatch: false,\n skipBuild: false,\n printConfig: false,\n profile: undefined,\n saveDeployment: true,\n deployerAddress: undefined,\n worldAddress,\n salt: \"0x\",\n kms: undefined,\n indexerUrl: undefined,\n });\n worldAddress = deploy.address;\n // if there were changes while we were deploying, trigger it again\n if (lastChange < lastChange$.value) {\n lastChange$.next(lastChange$.value);\n } else {\n console.log(chalk.gray(\"\\nWaiting for file changes…\\n\"));\n }\n return deploy;\n } catch (error) {\n console.error(chalk.bgRed(chalk.whiteBright(\"\\n Error while attempting deploy \\n\")));\n console.error(error);\n console.log(chalk.gray(\"\\nWaiting for file changes…\\n\"));\n }\n }),\n filter(isDefined),\n );\n\n deploys$.subscribe();\n },\n};\n\nexport default commandModule;\n","import { Chain, Client, Hex, Transport, sliceHex, zeroHash } from \"viem\";\nimport { getWorldFactoryContracts } from \"./deploy/getWorldFactoryContracts\";\nimport { verifyContract } from \"./verify/verifyContract\";\nimport PQueue from \"p-queue\";\nimport { getWorldProxyFactoryContracts } from \"./deploy/getWorldProxyFactoryContracts\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { Library, Module, System } from \"./deploy/common\";\nimport { getStorageAt } from \"viem/actions\";\nimport { execa } from \"execa\";\nimport { getContractAddress, getDeployer } from \"@latticexyz/common/internal\";\nimport { getLibraryMap } from \"./deploy/getLibraryMap\";\n\ntype VerifyOptions = {\n client: Client<Transport, Chain | undefined>;\n rpc: string;\n verifier: string;\n verifierUrl?: string;\n libraries: readonly Library[];\n systems: readonly System[];\n modules: readonly Module[];\n worldAddress: Hex;\n /**\n * Address of determinstic deployment proxy: https://github.com/Arachnid/deterministic-deployment-proxy\n * By default, we look for a deployment at 0x4e59b44847b379578588920ca78fbf26c0b4956c.\n * If it is not deployed or the target chain does not support legacy transactions, the user must set the deployer manually.\n */\n deployerAddress?: Hex;\n};\n\nconst ERC1967_IMPLEMENTATION_SLOT = \"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\";\n\nexport async function verify({\n client,\n rpc,\n systems,\n libraries,\n modules,\n worldAddress,\n deployerAddress: initialDeployerAddress,\n verifier,\n verifierUrl,\n}: VerifyOptions): Promise<void> {\n const deployerAddress = initialDeployerAddress ?? (await getDeployer(client));\n if (!deployerAddress) {\n throw new MUDError(\"No deployer address provided or found.\");\n }\n\n // If the proxy implementation storage slot is set on the World, the World was deployed as a proxy.\n const implementationStorage = await getStorageAt(client, {\n address: worldAddress,\n slot: ERC1967_IMPLEMENTATION_SLOT,\n });\n const usesProxy = implementationStorage && implementationStorage !== zeroHash;\n\n const verifyQueue = new PQueue({ concurrency: 4 });\n\n const libraryMap = getLibraryMap(libraries);\n\n systems.map((system) =>\n verifyQueue.add(() => {\n const address = getContractAddress({\n deployerAddress,\n bytecode: system.prepareDeploy(deployerAddress, libraryMap).bytecode,\n });\n\n return verifyContract({\n name: system.label,\n rpc,\n verifier,\n verifierUrl,\n address,\n }).catch((error) => {\n console.error(`Error verifying system contract ${system.label}:`, error);\n });\n }),\n );\n\n // If the verifier is Sourcify, attempt to verify MUD core contracts\n // There are path issues with verifying Blockscout and Etherscan\n if (verifier === \"sourcify\") {\n // Install subdependencies so contracts can compile\n await execa(\"npm\", [\"install\"], {\n cwd: \"node_modules/@latticexyz/store\",\n });\n await execa(\"npm\", [\"install\"], {\n cwd: \"node_modules/@latticexyz/world\",\n });\n await execa(\"npm\", [\"install\"], {\n cwd: \"node_modules/@latticexyz/world-modules\",\n });\n\n Object.entries(\n usesProxy ? getWorldProxyFactoryContracts(deployerAddress) : getWorldFactoryContracts(deployerAddress),\n ).map(([name, { bytecode }]) =>\n verifyQueue.add(() =>\n verifyContract({\n cwd: \"node_modules/@latticexyz/world\",\n name,\n rpc,\n verifier,\n verifierUrl,\n address: getContractAddress({\n deployerAddress,\n bytecode: bytecode,\n }),\n }).catch((error) => {\n console.error(`Error verifying world factory contract ${name}:`, error);\n }),\n ),\n );\n\n modules.map(({ name, prepareDeploy }) => {\n const { address } = prepareDeploy(deployerAddress);\n return verifyQueue.add(() =>\n verifyContract({\n // TODO: figure out dir from artifactPath via import.meta.resolve?\n cwd: \"node_modules/@latticexyz/world-modules\",\n name,\n rpc,\n verifier,\n verifierUrl,\n address,\n }).catch((error) => {\n console.error(`Error verifying module contract ${name}:`, error);\n }),\n );\n });\n\n // If the world was deployed as a Proxy, verify the proxy and implementation.\n if (usesProxy) {\n const implementationAddress = sliceHex(implementationStorage, -20);\n\n verifyQueue.add(() =>\n verifyContract({\n cwd: \"node_modules/@latticexyz/world\",\n name: \"WorldProxy\",\n rpc,\n verifier,\n verifierUrl,\n address: worldAddress,\n }).catch((error) => {\n console.error(`Error verifying WorldProxy contract:`, error);\n }),\n );\n\n verifyQueue.add(() =>\n verifyContract({\n cwd: \"node_modules/@latticexyz/world\",\n name: \"World\",\n rpc,\n verifier,\n verifierUrl,\n address: implementationAddress,\n }).catch((error) => {\n console.error(`Error verifying World contract:`, error);\n }),\n );\n } else {\n verifyQueue.add(() =>\n verifyContract({\n cwd: \"node_modules/@latticexyz/world\",\n name: \"World\",\n rpc,\n verifier,\n verifierUrl,\n address: worldAddress,\n }).catch((error) => {\n console.error(`Error verifying World contract:`, error);\n }),\n );\n }\n } else {\n console.log(\"\");\n console.log(\n `Note: MUD is currently unable to verify store, world, and world-modules contracts with ${verifier}. We are planning to expand support in a future version.`,\n );\n console.log(\"\");\n }\n}\n","import { execa } from \"execa\";\nimport { Address } from \"viem\";\nimport { printCommand } from \"../utils/printCommand\";\n\ntype VerifyContractOptions = {\n name: string;\n rpc: string;\n verifier?: string;\n verifierUrl?: string;\n address: Address;\n cwd?: string;\n};\n\nexport async function verifyContract(options: VerifyContractOptions) {\n await printCommand(\n execa(\n \"forge\",\n [\n \"verify-contract\",\n options.address,\n options.name,\n [\"--rpc-url\", options.rpc],\n options.verifier ? [\"--verifier\", options.verifier] : [],\n options.verifierUrl ? [\"--verifier-url\", options.verifierUrl] : [],\n ].flat(),\n { stdio: \"inherit\" },\n ),\n );\n}\n","import type { CommandModule, InferredOptionTypes } from \"yargs\";\nimport { verify } from \"../verify\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { getOutDirectory, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport { Hex, createWalletClient, http } from \"viem\";\nimport chalk from \"chalk\";\nimport { configToModules } from \"../deploy/configToModules\";\nimport path from \"node:path\";\nimport { resolveConfig } from \"../deploy/resolveConfig\";\n\nconst verifyOptions = {\n deployerAddress: {\n type: \"string\",\n desc: \"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)\",\n },\n worldAddress: { type: \"string\", required: true, desc: \"Verify an existing World at the given address\" },\n configPath: { type: \"string\", desc: \"Path to the MUD config file\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n rpc: { type: \"string\", desc: \"The RPC URL to use. Defaults to the RPC url from the local foundry.toml\" },\n rpcBatch: {\n type: \"boolean\",\n desc: \"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)\",\n },\n verifier: { type: \"string\", desc: \"The verifier to use. Defaults to blockscout\", default: \"blockscout\" },\n verifierUrl: {\n type: \"string\",\n desc: \"The verification provider.\",\n },\n} as const;\n\ntype Options = InferredOptionTypes<typeof verifyOptions>;\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"verify\",\n\n describe: \"Verify contracts\",\n\n builder(yargs) {\n return yargs.options(verifyOptions);\n },\n\n async handler(opts) {\n const profile = opts.profile;\n\n const configPath = await resolveConfigPath(opts.configPath);\n const rootDir = path.dirname(configPath);\n\n const config = (await loadConfig(configPath)) as WorldConfig;\n const outDir = await getOutDirectory(profile);\n\n const modules = await configToModules(config, outDir);\n\n const { systems, libraries } = await resolveConfig({\n rootDir,\n config,\n forgeOutDir: outDir,\n });\n\n const rpc = opts.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Verifying MUD contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`),\n ),\n );\n\n const client = createWalletClient({\n transport: http(rpc, {\n batch: opts.rpcBatch\n ? {\n batchSize: 100,\n wait: 1000,\n }\n : undefined,\n }),\n });\n\n await verify({\n client,\n rpc,\n systems,\n libraries,\n modules,\n deployerAddress: opts.deployerAddress as Hex | undefined,\n worldAddress: opts.worldAddress as Hex,\n verifier: opts.verifier,\n verifierUrl: opts.verifierUrl,\n });\n },\n};\n\nexport default commandModule;\n","import type { CommandModule, InferredOptionTypes } from \"yargs\";\nimport { getRpcUrl } from \"@latticexyz/common/foundry\";\nimport { Address, createClient, http } from \"viem\";\nimport chalk from \"chalk\";\nimport { WriteFileExistsError, pull } from \"../pull/pull\";\nimport path from \"node:path\";\nimport { build } from \"../build\";\nimport { getChainId } from \"viem/actions\";\nimport { defaultChains } from \"../defaultChains\";\n\nconst options = {\n worldAddress: { type: \"string\", required: true, desc: \"Remote world address\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n rpc: { type: \"string\", desc: \"The RPC URL to use. Defaults to the RPC url from the local foundry.toml\" },\n rpcBatch: {\n type: \"boolean\",\n desc: \"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)\",\n },\n replace: {\n type: \"boolean\",\n desc: \"Replace existing files and directories with data from remote world.\",\n },\n indexerUrl: {\n type: \"string\",\n desc: \"The indexer URL to pull from.\",\n required: false,\n },\n} as const;\n\ntype Options = InferredOptionTypes<typeof options>;\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"pull\",\n\n describe: \"Pull mud.config.ts and interfaces from an existing world.\",\n\n builder(yargs) {\n return yargs.options(options);\n },\n\n async handler(opts) {\n const profile = opts.profile;\n const rpc = opts.rpc ?? (await getRpcUrl(profile));\n const client = createClient({\n transport: http(rpc, {\n batch: opts.rpcBatch\n ? {\n batchSize: 100,\n wait: 1000,\n }\n : undefined,\n }),\n });\n const chainId = await getChainId(client);\n const indexerUrl = opts.indexerUrl ?? defaultChains.find((chain) => chain.id === chainId)?.indexerUrl;\n\n console.log(chalk.bgBlue(chalk.whiteBright(`\\n Pulling MUD config from world at ${opts.worldAddress} \\n`)));\n const rootDir = process.cwd();\n\n try {\n const { config } = await pull({\n rootDir,\n client,\n worldAddress: opts.worldAddress as Address,\n indexerUrl,\n chainId,\n replace: opts.replace,\n });\n await build({ rootDir, config, foundryProfile: profile });\n } catch (error) {\n if (error instanceof WriteFileExistsError) {\n console.log();\n console.log(chalk.bgRed(chalk.whiteBright(\" Error \")));\n console.log(` Attempted to write file at \"${path.relative(rootDir, error.filename)}\", but it already exists.`);\n console.log();\n console.log(\" To overwrite files, use `--replace` when running this command.\");\n console.log();\n return;\n }\n throw error;\n }\n },\n};\n\nexport default commandModule;\n","import { Address, Client, hexToString, parseAbiItem, stringToHex } from \"viem\";\nimport { getTables } from \"../deploy/getTables\";\nimport { getWorldDeploy } from \"../deploy/getWorldDeploy\";\nimport { getSchemaTypes } from \"@latticexyz/protocol-parser/internal\";\nimport { hexToResource, resourceToHex } from \"@latticexyz/common\";\nimport metadataConfig from \"@latticexyz/world-module-metadata/mud.config\";\nimport { getRecord } from \"../deploy/getRecord\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { getResourceIds } from \"../deploy/getResourceIds\";\nimport { getFunctions } from \"@latticexyz/store-sync/world\";\nimport { abiToInterface, formatSolidity, formatTypescript } from \"@latticexyz/common/codegen\";\nimport { debug } from \"./debug\";\nimport { defineWorld } from \"@latticexyz/world\";\nimport { findUp } from \"find-up\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nconst ignoredNamespaces = new Set([\"store\", \"world\", \"metadata\"]);\n\nfunction namespaceToHex(namespace: string) {\n return resourceToHex({ type: \"namespace\", namespace, name: \"\" });\n}\n\nexport class WriteFileExistsError extends Error {\n name = \"WriteFileExistsError\";\n constructor(public filename: string) {\n super(`Attempted to write file at \"${filename}\", but it already exists.`);\n }\n}\n\nexport type PullOptions = {\n rootDir: string;\n client: Client;\n worldAddress: Address;\n /**\n * Replace existing files and directories with data from remote world.\n * Defaults to `true` if `rootDir` is within a git repo, otherwise `false`.\n * */\n replace?: boolean;\n indexerUrl?: string;\n chainId?: number;\n};\n\nexport async function pull({ rootDir, client, worldAddress, replace, indexerUrl, chainId }: PullOptions) {\n const replaceFiles = replace ?? (await findUp(\".git\", { cwd: rootDir })) != null;\n\n const worldDeploy = await getWorldDeploy(client, worldAddress);\n const resourceIds = await getResourceIds({ client, worldDeploy, indexerUrl, chainId });\n const resources = resourceIds.map(hexToResource).filter((resource) => !ignoredNamespaces.has(resource.namespace));\n const tables = await getTables({ client, worldDeploy, indexerUrl, chainId });\n\n const labels = Object.fromEntries(\n (\n await Promise.all(\n resourceIds.map(async (resourceId) => {\n const { value: bytesValue } = await getRecord({\n client,\n worldDeploy,\n table: metadataConfig.tables.metadata__ResourceTag,\n key: { resource: resourceId, tag: stringToHex(\"label\", { size: 32 }) },\n });\n const value = hexToString(bytesValue);\n return [resourceId, value === \"\" ? null : value];\n }),\n )\n ).filter(([, label]) => label != null),\n );\n // ensure we always have a root namespace label\n labels[namespaceToHex(\"\")] ??= \"root\";\n\n const worldFunctions = await getFunctions({\n client,\n worldAddress: worldDeploy.address,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n indexerUrl,\n chainId,\n });\n\n const namespaces = resources.filter((resource) => resource.type === \"namespace\");\n const systems = await Promise.all(\n resources\n .filter((resource) => resource.type === \"system\")\n .map(async ({ namespace, name, resourceId: systemId }) => {\n const namespaceId = namespaceToHex(namespace);\n // the system name from the system ID can be potentially truncated, so we'll strip off\n // any partial \"System\" suffix and replace it with a full \"System\" suffix so that it\n // matches our criteria for system names\n const systemLabel = labels[systemId] ?? name.replace(/(S(y(s(t(e(m)?)?)?)?)?)?$/, \"System\");\n\n const [metadataAbi, metadataWorldAbi] = await Promise.all([\n getRecord({\n client,\n worldDeploy,\n table: metadataConfig.tables.metadata__ResourceTag,\n key: { resource: systemId, tag: stringToHex(\"abi\", { size: 32 }) },\n })\n .then((record) => hexToString(record.value))\n .then((value) => (value !== \"\" ? value.split(\"\\n\") : [])),\n getRecord({\n client,\n worldDeploy,\n table: metadataConfig.tables.metadata__ResourceTag,\n key: { resource: systemId, tag: stringToHex(\"worldAbi\", { size: 32 }) },\n })\n .then((record) => hexToString(record.value))\n .then((value) => (value !== \"\" ? value.split(\"\\n\") : [])),\n ]);\n\n const functions = worldFunctions.filter((func) => func.systemId === systemId);\n\n // If empty or unset ABI in metadata table, backfill with world functions.\n // These don't have parameter names or return values, but better than nothing?\n const abi = (\n metadataAbi.length ? metadataAbi : functions.map((func) => `function ${func.systemFunctionSignature}`)\n )\n .map((sig) => {\n try {\n return parseAbiItem(sig);\n } catch {\n debug(`Skipping invalid system signature: ${sig}`);\n }\n })\n .filter(isDefined);\n\n const worldAbi = (\n metadataWorldAbi.length ? metadataWorldAbi : functions.map((func) => `function ${func.signature}`)\n )\n .map((sig) => {\n try {\n return parseAbiItem(sig);\n } catch {\n debug(`Skipping invalid world signature: ${sig}`);\n }\n })\n .filter(isDefined);\n\n return {\n namespaceId,\n namespaceLabel: labels[namespaceId] ?? namespace,\n label: systemLabel,\n systemId,\n namespace,\n name,\n abi,\n worldAbi,\n };\n }),\n );\n\n debug(\"generating config\");\n const configInput = {\n namespaces: Object.fromEntries(\n namespaces.map(({ namespace, resourceId: namespaceId }) => {\n const namespaceLabel = labels[namespaceId] ?? namespace;\n return [\n namespaceLabel,\n {\n ...(namespaceLabel !== namespace ? { namespace } : null),\n tables: Object.fromEntries(\n tables\n .filter((table) => table.namespace === namespace)\n .map((table) => {\n const tableLabel = labels[table.tableId] ?? table.name;\n return [\n tableLabel,\n {\n ...(tableLabel !== table.name ? { name: table.name } : null),\n ...(table.type !== \"table\" ? { type: table.type } : null),\n schema: getSchemaTypes(table.schema),\n key: table.key,\n deploy: { disabled: true },\n },\n ];\n }),\n ),\n },\n ];\n }),\n ),\n };\n\n // use the config before writing it so we make sure its valid\n // and because we'll use the default paths to write interfaces\n debug(\"validating config\");\n const config = defineWorld(configInput);\n\n debug(\"writing config\");\n await writeFile(\n path.join(rootDir, \"mud.config.ts\"),\n await formatTypescript(`\n import { defineWorld } from \"@latticexyz/world\";\n\n export default defineWorld(${JSON.stringify(configInput)});\n `),\n { overwrite: replaceFiles },\n );\n\n const remoteDir = path.join(config.sourceDirectory, \"remote\");\n if (replaceFiles) {\n await fs.rm(remoteDir, { recursive: true, force: true });\n }\n\n for (const system of systems.filter((system) => system.abi.length)) {\n const interfaceName = `I${system.label}`;\n const interfaceFile = path.join(remoteDir, \"namespaces\", system.namespaceLabel, `${interfaceName}.sol`);\n\n debug(\"writing system interface\", interfaceName, \"to\", interfaceFile);\n const source = abiToInterface({ name: interfaceName, systemId: system.systemId, abi: system.abi });\n await writeFile(path.join(rootDir, interfaceFile), await formatSolidity(source), { overwrite: replaceFiles });\n }\n\n const worldAbi = systems.flatMap((system) => system.worldAbi);\n if (worldAbi.length) {\n const interfaceName = \"IWorldSystems\";\n const interfaceFile = path.join(remoteDir, `${interfaceName}.sol`);\n\n debug(\"writing world systems interface to\", interfaceFile);\n const source = abiToInterface({ name: interfaceName, abi: worldAbi });\n await writeFile(path.join(rootDir, interfaceFile), await formatSolidity(source), { overwrite: replaceFiles });\n }\n\n return { config };\n}\n\nexport async function exists(filename: string) {\n return fs.access(filename).then(\n () => true,\n () => false,\n );\n}\n\nexport async function writeFile(filename: string, contents: string, opts: { overwrite?: boolean } = {}) {\n if (!opts.overwrite && (await exists(filename))) {\n throw new WriteFileExistsError(filename);\n }\n await fs.mkdir(path.dirname(filename), { recursive: true });\n await fs.writeFile(filename, contents);\n}\n","import {\n decodeValueArgs,\n getKeySchema,\n getKeyTuple,\n getSchemaPrimitives,\n getSchemaTypes,\n getValueSchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport { Client, Hex } from \"viem\";\nimport { readContract } from \"viem/actions\";\nimport { Table } from \"@latticexyz/config\";\nimport { mapObject } from \"@latticexyz/common/utils\";\nimport { show } from \"@ark/util\";\n\nexport async function getRecord<table extends Table>({\n client,\n worldDeploy,\n table,\n key,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n readonly table: table;\n readonly key: getSchemaPrimitives<getKeySchema<table>>;\n}): Promise<show<getSchemaPrimitives<table[\"schema\"]>>> {\n const [staticData, encodedLengths, dynamicData] = (await readContract(client, {\n blockNumber: worldDeploy.stateBlock,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"getRecord\",\n args: [table.tableId, getKeyTuple(table, key)],\n // TODO: remove cast once https://github.com/wevm/viem/issues/2125 is resolved\n // has something to do function overloads and TS having a hard time inferring which args to use\n })) as [Hex, Hex, Hex];\n const record = {\n ...key,\n ...decodeValueArgs(getSchemaTypes(getValueSchema(table)), {\n staticData,\n encodedLengths,\n dynamicData,\n }),\n };\n // return in schema order\n return mapObject(table.schema, (value, key) => record[key as never]) as never;\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"pull\");\nexport const error = parentDebug.extend(\"pull\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n"],"mappings":";;;;;AAEA,SAAS,WAAW,iBAAiB;AACrC,SAAS,WAAW,aAAa;;;ACFjC,SAAS,YAAY,yBAAyB;;;ACD9C,SAAS,gBAAgB;AACzB,SAAS,sBAAsB,gBAAgB;AAE/C,SAAS,aAAa;;;ACHtB,OAAO,WAAW;AAmBX,SAAS,aAAmB,MAA6D;AAC9F,UAAQ,IAAI,OAAO,MAAM,KAAK,OAAO,KAAK,UAAU,KAAK,GAAG,CAAC,CAAC;AAC9D,SAAO;AACT;;;ADLA,eAAsB,MAAM,EAAE,SAAS,QAAQ,eAAe,GAAgC;AAC5F,QAAM,QAAQ,IAAI,CAAC,SAAS,EAAE,SAAS,OAAO,CAAC,GAAG,SAAS,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC;AACh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,IACH,CAAC;AACD,UAAM,UAAU,MAAMC,YAAW,MAAM;AACvC,UAAM,aAAa,KAAK,cAAc,cAAc,KAAK,CAAC,UAAU,MAAM,OAAO,OAAO,GAAG;AAE3F,YAAQ,IAAIC,OAAM,OAAOA,OAAM,YAAY;AAAA,oCAAuC,KAAK,YAAY;AAAA,CAAK,CAAC,CAAC;AAC1G,UAAM,UAAU,QAAQ,IAAI;AAE5B,QAAI;AACF,YAAM,EAAE,OAAO,IAAI,MAAM,KAAK;AAAA,QAC5B;AAAA,QACA;AAAA,QACA,cAAc,KAAK;AAAA,QACnB;AAAA,QACA;AAAA,QACA,SAAS,KAAK;AAAA,MAChB,CAAC;AACD,YAAM,MAAM,EAAE,SAAS,QAAQ,gBAAgB,QAAQ,CAAC;AAAA,IAC1D,SAASC,QAAO;AACd,UAAIA,kBAAiB,sBAAsB;AACzC,gBAAQ,IAAI;AACZ,gBAAQ,IAAID,OAAM,MAAMA,OAAM,YAAY,SAAS,CAAC,CAAC;AACrD,gBAAQ,IAAI,iCAAiCE,OAAK,SAAS,SAASD,OAAM,QAAQ,CAAC,2BAA2B;AAC9G,gBAAQ,IAAI;AACZ,gBAAQ,IAAI,kEAAkE;AAC9E,gBAAQ,IAAI;AACZ;AAAA,MACF;AACA,YAAMA;AAAA,IACR;AAAA,EACF;AACF;AAEA,IAAO,eAAQN;;;AzDjER,IAAM,WAAsC;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["path","execa","commandModule","path","execa","commandModule","loadConfig","resolveConfigPath","tablegen","path","commandModule","path","existsSync","readFileSync","stringToHex","encodeDeployData","size","getContractAddress","size","encodeDeployData","encodeDeployData","size","getContractAddress","size","encodeDeployData","contracts","debug","error","error","deploy","debug","deploy","writeContract","debug","isDefined","debug","writeContract","getAddress","writeContract","resourceToLabel","hexToResource","resourceToLabel","storeConfig","getRecords","debug","getKeySchema","getSchemaTypes","getValueSchema","getSchemaTypes","getKeySchema","getValueSchema","getAddress","getRecords","debug","getAddress","worldConfig","hexToResource","debug","resourceToLabel","address","pRetry","ensureContractsDeployed","getAddress","debug","resourceToLabel","writeContract","getAddress","parseAbi","getAddress","deploy","debug","parseAbi","hexToResource","writeContract","getFunctions","pRetry","getFunctions","debug","hexToResource","writeContract","writeContract","isDefined","pRetry","ensureContractsDeployed","debug","writeContract","error","getAddress","hexToResource","resourceToHex","writeContract","worldConfig","hexToResource","debug","resourceToHex","getAddress","writeContract","resourceToHex","resourceToLabel","BaseError","hexToResource","writeContract","isDefined","size","path","size","getContractAddress","getRecords","debug","hexToResource","writeContract","error","BaseError","isDefined","concatHex","encodeDeployData","isHex","waitForTransactionReceipt","resourceToHex","writeContract","ensureContractsDeployed","getContractAddress","waitForTransactions","isHex","concatHex","debug","encodeDeployData","waitForTransactionReceipt","deploy","writeContract","resourceToHex","path","ensureContractsDeployed","waitForTransactions","resourceToLabel","resourceToHex","stringToHex","debug","isHex","stringToHex","loadConfig","resolveConfigPath","chalk","MUDError","path","isHex","path","size","path","error","size","readFileSync","path","readFileSync","require","path","isHex","system","path","execa","path","execa","path","createRequire","findUp","findUp","require","createRequire","error","path","path","getBlock","getBlock","isHex","stringToHex","resolveConfigPath","loadConfig","path","chalk","MUDError","deploys","existsSync","readFileSync","commandModule","error","path","loadConfig","resolveConfigPath","worldgen","commandModule","chalk","readFileSync","writeFileSync","path","MUDError","globSync","z","error","commandModule","options","MUDError","globSync","chalk","writeFileSync","path","readFileSync","getRpcUrl","chalk","execa","commandModule","execa","getRpcUrl","chalk","path","loadConfig","resolveConfigPath","MUDError","getRpcUrl","worldConfig","http","getChainId","readContract","resolveSystems","execa","worldConfig","MUDError","deploys","commandModule","resolveConfigPath","path","getRpcUrl","loadConfig","http","getChainId","resolveSystems","readContract","execa","getScriptDirectory","chalk","loadConfig","resolveConfigPath","path","homedir","rmSync","isDefined","execa","commandModule","resolveConfigPath","getScriptDirectory","loadConfig","chalk","homedir","rmSync","path","execa","deploy","error","isDefined","execa","options","execa","MUDError","execa","getContractAddress","MUDError","getContractAddress","error","execa","loadConfig","resolveConfigPath","getOutDirectory","getRpcUrl","createWalletClient","http","chalk","path","commandModule","resolveConfigPath","path","loadConfig","getOutDirectory","getRpcUrl","chalk","createWalletClient","http","getRpcUrl","createClient","http","chalk","hexToString","stringToHex","getSchemaTypes","hexToResource","resourceToHex","metadataConfig","decodeValueArgs","getKeyTuple","getSchemaTypes","getValueSchema","readContract","getKeyTuple","decodeValueArgs","getSchemaTypes","getValueSchema","key","path","fs","getFunctions","debug","error","findUp","isDefined","resourceToHex","hexToResource","metadataConfig","stringToHex","hexToString","getFunctions","metadataAbi","debug","worldAbi","getSchemaTypes","path","fs","system","path","getChainId","commandModule","getRpcUrl","createClient","http","getChainId","chalk","error","path"]}