@latticexyz/cli 3.0.0-main-61895408d → 3.0.0-main-2da9e48cd
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.
- package/dist/commands-JLSR2MGQ.js +39 -0
- package/dist/commands-JLSR2MGQ.js.map +1 -0
- package/dist/mud.js +1 -1
- package/package.json +10 -10
- package/dist/commands-UVPI4WHN.js +0 -39
- package/dist/commands-UVPI4WHN.js.map +0 -1
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/commands/index.ts","../src/commands/build.ts","../src/build.ts","../src/commands/devnode.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/runDeploy.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/debug.ts","../src/deploy/debug.ts","../src/deploy/getDeployer.ts","../src/deploy/deployWorld.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureContract.ts","../src/deploy/common.ts","../src/deploy/getWorldFactoryContracts.ts","../src/deploy/getWorldContracts.ts","../src/deploy/getWorldProxyFactoryContracts.ts","../src/deploy/ensureWorldFactory.ts","../src/deploy/logsToWorldDeploy.ts","../src/deploy/ensureTables.ts","../src/deploy/getTables.ts","../src/deploy/ensureSystems.ts","../src/deploy/getResourceIds.ts","../src/deploy/getSystems.ts","../src/deploy/getTableValue.ts","../src/deploy/getFunctions.ts","../src/deploy/getResourceAccess.ts","../src/deploy/deploy.ts","../src/deploy/getWorldDeploy.ts","../src/deploy/ensureFunctions.ts","../src/deploy/ensureModules.ts","../src/deploy/ensureNamespaceOwner.ts","../src/deploy/resolveConfig.ts","../src/utils/getContractData.ts","../src/utils/findPlaceholders.ts","../src/deploy/findLibraries.ts","../src/deploy/orderByDependencies.ts","../src/deploy/createPrepareDeploy.ts","../src/utils/postDeploy.ts","../src/deploy/configToModules.ts","../src/utils/getContractArtifact.ts","../src/utils/knownModuleArtifacts.ts","../src/commands/deploy.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../package.json","../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"],"sourcesContent":["import { CommandModule } from \"yargs\";\n\nimport gasReport from \"@latticexyz/gas-report\";\nimport abiTs from \"@latticexyz/abi-ts\";\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\";\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 as CommandModule,\n hello,\n tablegen,\n worldgen,\n setVersion,\n test,\n trace,\n devContracts,\n abiTs,\n verify,\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 { worldgen } from \"@latticexyz/world/node\";\nimport { World as WorldConfig } from \"@latticexyz/world\";\nimport { forge, getRemappings } from \"@latticexyz/common/foundry\";\nimport { execa } from \"execa\";\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({\n rootDir,\n config,\n foundryProfile = process.env.FOUNDRY_PROFILE,\n}: BuildOptions): Promise<void> {\n const remappings = await getRemappings(foundryProfile);\n\n await Promise.all([tablegen({ rootDir, config, remappings }), worldgen({ rootDir, config })]);\n\n await forge([\"build\"], { profile: foundryProfile });\n await execa(\"mud\", [\"abi-ts\"], { stdio: \"inherit\" });\n}\n","import { rmSync } from \"fs\";\nimport { homedir } from \"os\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { execa } from \"execa\";\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: 1, 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 anvilArgs = [\"-b\", String(blocktime), \"--block-base-fee-per-gas\", \"0\"];\n console.log(`Running: anvil ${anvilArgs.join(\" \")}`);\n const child = execa(\"anvil\", anvilArgs, {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\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 { getRemappings } from \"@latticexyz/common/foundry\";\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 const remappings = await getRemappings();\n\n await tablegen({ rootDir: path.dirname(configPath), config, remappings });\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 { InferredOptionTypes, Options } from \"yargs\";\nimport { deploy } from \"./deploy/deploy\";\nimport { createWalletClient, http, Hex, isHex } 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\";\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} 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;\n if (salt != null && !isHex(salt)) {\n throw new MUDError(\"Expected hex string for salt\");\n }\n\n const profile = opts.profile ?? process.env.FOUNDRY_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 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 const modules = await configToModules(config, outDir);\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 console.log(\"Deploying from\", client.account.address);\n\n const tables = Object.values(config.namespaces).flatMap((namespace) => Object.values(namespace.tables));\n\n const startTime = Date.now();\n const worldDeploy = await deploy({\n deployerAddress: opts.deployerAddress as Hex | undefined,\n salt,\n worldAddress: opts.worldAddress as Hex | undefined,\n client,\n tables,\n systems,\n libraries,\n modules,\n withWorldProxy: config.deploy.upgradeableWorldImplementation,\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 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 chainId = await getChainId(client);\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 writeFileSync(path.join(deploysDir, Date.now() + \".json\"), JSON.stringify(deploymentInfo, null, 2));\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 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","import { Account, Address, Chain, Client, Transport } from \"viem\";\nimport { getBalance, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\nimport { getDeployer } from \"./getDeployer\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {\n const existingDeployer = await getDeployer(client);\n if (existingDeployer !== undefined) {\n return existingDeployer;\n }\n\n // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,\n // so we have to attempt to create the deployer first and, if it fails, fall back\n // to a regular deploy.\n\n // Send gas to deployment signer\n const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);\n const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });\n const gasNeeded = gasRequired - currentBalance;\n if (gasNeeded > 0) {\n debug(\"sending gas for CREATE2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: gasNeeded,\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n }\n\n // Deploy the deployer\n debug(\"deploying CREATE2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(\n (error) => {\n // Do a regular contract create if the presigned transaction doesn't work due to replay protection\n if (String(error).includes(\"only replay-protected (EIP-155) transactions allowed over RPC\")) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\\n\\n We recommend running your chain's node with \\`--rpc.allow-unprotected-txs\\` to enable determinstic deployments.\\n`,\n );\n debug(\"deploying CREATE2 deployer\");\n return sendTransaction(client, {\n chain: client.chain ?? null,\n data: `0x${deployment.creationCode}`,\n });\n }\n throw error;\n },\n );\n\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (!deployReceipt.contractAddress) {\n throw new Error(\"Deploy receipt did not have contract address, was the deployer not deployed?\");\n }\n\n if (deployReceipt.contractAddress !== deployer) {\n console.warn(\n `\\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,\n );\n }\n\n return deployReceipt.contractAddress;\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\",\n \"creationCode\": \"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3\"\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 { Address, Chain, Client, Transport, sliceHex } from \"viem\";\nimport { getBytecode } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined> {\n const bytecode = await getBytecode(client, { address: deployer });\n if (bytecode) {\n debug(\"found CREATE2 deployer at\", deployer);\n // check if deployed bytecode is the same as the expected bytecode (minus 14-bytes creation code prefix)\n if (bytecode !== sliceHex(`0x${deployment.creationCode}`, 14)) {\n console.warn(\n `\\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\\n`,\n );\n }\n return deployer;\n }\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 { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { debug } from \"./debug\";\nimport { Contract, ensureContract } from \"./ensureContract\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\n\nexport async function ensureContractsDeployed({\n client,\n deployerAddress,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n // Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode\n const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);\n\n const txs = (\n await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))\n ).flat();\n\n if (txs.length) {\n debug(\"waiting for contracts\");\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const tx of txs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\n }\n\n return txs;\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from \"viem\";\nimport { getBytecode } from \"viem/actions\";\nimport { contractSizeLimit, salt } from \"./common\";\nimport { sendTransaction } from \"@latticexyz/common\";\nimport { debug } from \"./debug\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize: number;\n label?: string;\n};\n\nexport async function ensureContract({\n client,\n deployerAddress,\n bytecode,\n deployedBytecodeSize,\n label = \"contract\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n} & Contract): Promise<readonly Hex[]> {\n if (bytecode.includes(\"__$\")) {\n throw new Error(`Found unlinked public library in ${label} bytecode`);\n }\n\n const address = getCreate2Address({ from: deployerAddress, salt, bytecode });\n\n const contractCode = await getBytecode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", label, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n `\\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n }\n\n debug(\"deploying\", label, \"at\", address);\n return [\n await pRetry(\n () =>\n sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployerAddress,\n data: concatHex([salt, bytecode]),\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to deploy ${label}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n ),\n ];\n}\n","import { Abi, Address, Hex, padHex } 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\";\n\nexport const salt = padHex(\"0x\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\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 libraries: readonly Library[],\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 // TODO: add label\n readonly namespace: string;\n readonly name: string;\n readonly systemId: Hex;\n readonly allowAll: boolean;\n readonly allowedAddresses: readonly Hex[];\n readonly allowedSystemIds: readonly Hex[];\n readonly functions: readonly WorldFunction[];\n};\n\nexport type DeployedSystem = Omit<System, \"abi\" | \"prepareDeploy\" | \"deployedBytecodeSize\" | \"allowedSystemIds\"> & {\n address: Address;\n};\n\nexport type Module = DeterministicContract & {\n readonly name: string;\n readonly installAsRoot: boolean;\n readonly installData: Hex; // TODO: figure out better naming for this\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, getCreate2Address, encodeDeployData, size } from \"viem\";\nimport { salt } from \"./common\";\nimport { getWorldContracts } from \"./getWorldContracts\";\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 = getCreate2Address({ from: deployerAddress, bytecode: worldFactoryBytecode, salt });\n\n return {\n ...worldContracts,\n WorldFactory: {\n bytecode: worldFactoryBytecode,\n deployedBytecodeSize: worldFactoryDeployedBytecodeSize,\n label: \"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, getCreate2Address, encodeDeployData, size } from \"viem\";\nimport { salt } from \"./common\";\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 = getCreate2Address({\n from: deployerAddress,\n bytecode: accessManagementSystemBytecode,\n salt,\n });\n\n const balanceTransferSystemDeployedBytecodeSize = size(balanceTransferSystemBuild.deployedBytecode.object as Hex);\n const balanceTransferSystemBytecode = balanceTransferSystemBuild.bytecode.object as Hex;\n const balanceTransferSystem = getCreate2Address({\n from: deployerAddress,\n bytecode: balanceTransferSystemBytecode,\n salt,\n });\n\n const batchCallSystemDeployedBytecodeSize = size(batchCallSystemBuild.deployedBytecode.object as Hex);\n const batchCallSystemBytecode = batchCallSystemBuild.bytecode.object as Hex;\n const batchCallSystem = getCreate2Address({ from: deployerAddress, bytecode: batchCallSystemBytecode, salt });\n\n const registrationDeployedBytecodeSize = size(registrationSystemBuild.deployedBytecode.object as Hex);\n const registrationBytecode = registrationSystemBuild.bytecode.object as Hex;\n const registration = getCreate2Address({\n from: deployerAddress,\n bytecode: registrationBytecode,\n salt,\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 = getCreate2Address({ from: deployerAddress, bytecode: initModuleBytecode, salt });\n\n return {\n AccessManagementSystem: {\n bytecode: accessManagementSystemBytecode,\n deployedBytecodeSize: accessManagementSystemDeployedBytecodeSize,\n label: \"access management system\",\n address: accessManagementSystem,\n },\n BalanceTransferSystem: {\n bytecode: balanceTransferSystemBytecode,\n deployedBytecodeSize: balanceTransferSystemDeployedBytecodeSize,\n label: \"balance transfer system\",\n address: balanceTransferSystem,\n },\n BatchCallSystem: {\n bytecode: batchCallSystemBytecode,\n deployedBytecodeSize: batchCallSystemDeployedBytecodeSize,\n label: \"batch call system\",\n address: batchCallSystem,\n },\n RegistrationSystem: {\n bytecode: registrationBytecode,\n deployedBytecodeSize: registrationDeployedBytecodeSize,\n label: \"core registration system\",\n address: registration,\n },\n InitModule: {\n bytecode: initModuleBytecode,\n deployedBytecodeSize: initModuleDeployedBytecodeSize,\n label: \"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, getCreate2Address, encodeDeployData, size } from \"viem\";\nimport { salt } from \"./common\";\nimport { getWorldContracts } from \"./getWorldContracts\";\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 = getCreate2Address({ from: deployerAddress, bytecode: worldProxyFactoryBytecode, salt });\n\n return {\n ...worldContracts,\n WorldProxyFactory: {\n bytecode: worldProxyFactoryBytecode,\n deployedBytecodeSize: worldProxyFactoryDeployedBytecodeSize,\n label: \"world proxy factory\",\n address: worldProxyFactory,\n },\n };\n}\n","import { Client, Transport, Chain, Account, Hex, Address } from \"viem\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\nimport { getWorldFactoryContracts } from \"./getWorldFactoryContracts\";\nimport { getWorldProxyFactoryContracts } from \"./getWorldProxyFactoryContracts\";\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 { AbiEventSignatureNotFoundError, Log, decodeEventLog, hexToString, parseAbi } 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 };\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 { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { resourceToLabel, writeContract } from \"@latticexyz/common\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport {\n valueSchemaToFieldLayoutHex,\n keySchemaToHex,\n valueSchemaToHex,\n getSchemaTypes,\n getValueSchema,\n getKeySchema,\n KeySchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { debug } from \"./debug\";\nimport { getTables } from \"./getTables\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\nimport { Table } from \"@latticexyz/config\";\n\nexport async function ensureTables({\n client,\n worldDeploy,\n tables,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly tables: readonly Table[];\n}): Promise<readonly Hex[]> {\n const worldTables = await getTables({ client, worldDeploy });\n const worldTableIds = worldTables.map((table) => table.tableId);\n\n const existingTables = tables.filter((table) => worldTableIds.includes(table.tableId));\n if (existingTables.length) {\n debug(\"existing tables\", existingTables.map(resourceToLabel).join(\", \"));\n }\n\n const missingTables = tables.filter((table) => !worldTableIds.includes(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 as KeySchema),\n valueSchemaToHex(valueSchema),\n Object.keys(keySchema),\n Object.keys(valueSchema),\n ],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register table ${resourceToLabel(table)}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n );\n }),\n );\n }\n\n return [];\n}\n","import { Client, parseAbiItem, decodeAbiParameters, parseAbiParameters } from \"viem\";\nimport { hexToResource } from \"@latticexyz/common\";\nimport { WorldDeploy } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSetRecordEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport {\n decodeKey,\n decodeValueArgs,\n getKeySchema,\n getSchemaTypes,\n getValueSchema,\n hexToSchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { Schema, Table } from \"@latticexyz/config\";\nimport storeConfig from \"@latticexyz/store/mud.config\";\n\n// TODO: add label once we register it onchain\ntype DeployedTable = Omit<Table, \"label\">;\n\nexport async function getTables({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly Omit<DeployedTable, \"label\">[]> {\n // This assumes we only use `Tables._set(...)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n // TODO: consider moving this to a batched getRecord for Tables table\n\n debug(\"looking up tables for\", worldDeploy.address);\n const logs = await getLogs(client, {\n strict: true,\n // this may fail for certain RPC providers with block range limits\n // if so, could potentially use our fetchLogs helper (which does pagination)\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n event: parseAbiItem(storeSetRecordEvent),\n args: { tableId: storeConfig.namespaces.store.tables.Tables.tableId },\n });\n\n // TODO: combine with store-sync logToTable and export from somewhere\n const tables = logs.map((log): DeployedTable => {\n const { tableId } = decodeKey(\n getSchemaTypes(getKeySchema(storeConfig.namespaces.store.tables.Tables)),\n log.args.keyTuple,\n );\n const { type, namespace, name } = hexToResource(tableId);\n const value = decodeValueArgs(getSchemaTypes(getValueSchema(storeConfig.namespaces.store.tables.Tables)), log.args);\n\n const solidityKeySchema = hexToSchema(value.keySchema);\n const solidityValueSchema = hexToSchema(value.valueSchema);\n const keyNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), value.abiEncodedKeyNames)[0];\n const fieldNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), value.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,\n schema: { ...keySchema, ...valueSchema },\n key: Object.keys(keySchema),\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 { Client, Transport, Chain, Account, Hex, getAddress, Address } from \"viem\";\nimport { writeContract, resourceToLabel } from \"@latticexyz/common\";\nimport { Library, System, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { getSystems } from \"./getSystems\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport { wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\n\n// TODO: move each system registration+access to batch call to be atomic\n\nexport async function ensureSystems({\n client,\n deployerAddress,\n libraries,\n worldDeploy,\n systems,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly libraries: readonly Library[];\n readonly worldDeploy: WorldDeploy;\n readonly systems: readonly System[];\n}): Promise<readonly Hex[]> {\n const [worldSystems, worldAccess] = await Promise.all([\n getSystems({ client, worldDeploy }),\n getResourceAccess({ client, worldDeploy }),\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, libraries).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, libraries).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, libraries).bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n label: `${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, libraries).address, system.allowAll],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register system ${resourceToLabel(system)}, retrying in ${delay}ms...`);\n await wait(delay);\n },\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, libraries).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: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to revoke access, retrying in ${delay}ms...`);\n await wait(delay);\n },\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: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to grant access, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n ),\n ),\n ]);\n\n return [...registerTxs, ...accessTxs];\n}\n","import { Client, parseAbiItem, Hex, HttpRequestError } from \"viem\";\nimport { getLogs } from \"viem/actions\";\nimport { storeSpliceStaticDataEvent } from \"@latticexyz/store\";\nimport { WorldDeploy } from \"./common\";\nimport { debug } from \"./debug\";\nimport pRetry from \"p-retry\";\nimport storeConfig from \"@latticexyz/store/mud.config\";\n\nexport async function getResourceIds({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly Hex[]> {\n // This assumes we only use `ResourceIds._setExists(true)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n\n debug(\"looking up resource IDs for\", worldDeploy.address);\n const logs = await pRetry(\n () =>\n getLogs(client, {\n strict: true,\n address: worldDeploy.address,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n event: parseAbiItem(storeSpliceStaticDataEvent),\n args: { tableId: storeConfig.namespaces.store.tables.ResourceIds.tableId },\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const shouldRetry =\n error instanceof HttpRequestError && error.status === 400 && error.message.includes(\"block is out of range\");\n\n if (!shouldRetry) {\n throw error;\n }\n },\n },\n );\n const resourceIds = logs.map((log) => log.args.keyTuple[0]);\n debug(\"found\", resourceIds.length, \"resource IDs for\", worldDeploy.address);\n\n return resourceIds;\n}\n","import { DeployedSystem, WorldDeploy } from \"./common\";\nimport { Client } from \"viem\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { hexToResource, resourceToLabel } from \"@latticexyz/common\";\nimport { getTableValue } from \"./getTableValue\";\nimport { debug } from \"./debug\";\nimport { getFunctions } from \"./getFunctions\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\n\nexport async function getSystems({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly DeployedSystem[]> {\n const [resourceIds, functions, resourceAccess] = await Promise.all([\n getResourceIds({ client, worldDeploy }),\n getFunctions({ client, worldDeploy }),\n getResourceAccess({ client, worldDeploy }),\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 systemFunctions = 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 functions: systemFunctions,\n };\n }),\n );\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 { Client, parseAbiItem } from \"viem\";\nimport { WorldDeploy, WorldFunction } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSetRecordEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport {\n decodeKey,\n decodeValueArgs,\n getKeySchema,\n getSchemaTypes,\n getValueSchema,\n} from \"@latticexyz/protocol-parser/internal\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\n\nexport async function getFunctions({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly WorldFunction[]> {\n // This assumes we only use `FunctionSelectors._set(...)`, which is true as of this writing.\n debug(\"looking up function selectors for\", worldDeploy.address);\n const selectorLogs = await getLogs(client, {\n strict: true,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n event: parseAbiItem(storeSetRecordEvent),\n args: { tableId: worldConfig.namespaces.world.tables.FunctionSelectors.tableId },\n });\n\n const selectors = selectorLogs.map((log) => {\n return {\n ...decodeValueArgs(\n getSchemaTypes(getValueSchema(worldConfig.namespaces.world.tables.FunctionSelectors)),\n log.args,\n ),\n ...decodeKey(\n getSchemaTypes(getKeySchema(worldConfig.namespaces.world.tables.FunctionSelectors)),\n log.args.keyTuple,\n ),\n };\n });\n debug(\"found\", selectors.length, \"function selectors for\", worldDeploy.address);\n\n // This assumes we only use `FunctionSignatures._set(...)`, which is true as of this writing.\n debug(\"looking up function signatures for\", worldDeploy.address);\n const signatureLogs = await getLogs(client, {\n strict: true,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n event: parseAbiItem(storeSetRecordEvent),\n args: { tableId: worldConfig.namespaces.world.tables.FunctionSignatures.tableId },\n });\n\n const selectorToSignature = Object.fromEntries(\n signatureLogs.map((log) => {\n return [\n decodeKey(\n getSchemaTypes(getKeySchema(worldConfig.namespaces.world.tables.FunctionSignatures)),\n log.args.keyTuple,\n ).functionSelector,\n decodeValueArgs(\n getSchemaTypes(getValueSchema(worldConfig.namespaces.world.tables.FunctionSignatures)),\n log.args,\n ).functionSignature,\n ];\n }),\n );\n debug(\"found\", signatureLogs.length, \"function signatures for\", worldDeploy.address);\n\n const functions = selectors.map(({ worldFunctionSelector, systemFunctionSelector, systemId }) => ({\n selector: worldFunctionSelector,\n signature: selectorToSignature[worldFunctionSelector],\n systemFunctionSelector,\n systemFunctionSignature: selectorToSignature[systemFunctionSelector],\n systemId,\n }));\n\n return functions;\n}\n","import { Client, parseAbiItem, Hex, Address, getAddress } from \"viem\";\nimport { WorldDeploy } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSpliceStaticDataEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport { decodeKey, getKeySchema, getSchemaTypes } from \"@latticexyz/protocol-parser/internal\";\nimport { getTableValue } from \"./getTableValue\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\n\nexport async function getResourceAccess({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly { readonly resourceId: Hex; readonly address: Address }[]> {\n // This assumes we only use `ResourceAccess._set(...)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n\n debug(\"looking up resource access for\", worldDeploy.address);\n\n const logs = await getLogs(client, {\n strict: true,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n // our usage of `ResourceAccess._set(...)` emits a splice instead of set record\n // TODO: https://github.com/latticexyz/mud/issues/479\n event: parseAbiItem(storeSpliceStaticDataEvent),\n args: { tableId: worldConfig.namespaces.world.tables.ResourceAccess.tableId },\n });\n\n const keys = logs.map((log) =>\n decodeKey(getSchemaTypes(getKeySchema(worldConfig.namespaces.world.tables.ResourceAccess)), log.args.keyTuple),\n );\n\n const access = (\n await Promise.all(\n keys.map(\n async (key) =>\n [\n key,\n await getTableValue({\n client,\n worldDeploy,\n table: worldConfig.namespaces.world.tables.ResourceAccess,\n key,\n }),\n ] as const,\n ),\n )\n )\n .filter(([, value]) => value.access)\n .map(([key]) => ({\n resourceId: key.resourceId,\n address: getAddress(key.caller),\n }));\n\n debug(\"found\", access.length, \"resource<>address access pairs\");\n\n return access;\n}\n","import { Account, Address, Chain, Client, Hex, Transport } from \"viem\";\nimport { ensureDeployer } from \"./ensureDeployer\";\nimport { deployWorld } from \"./deployWorld\";\nimport { ensureTables } from \"./ensureTables\";\nimport { Library, Module, System, WorldDeploy, supportedStoreVersions, supportedWorldVersions } from \"./common\";\nimport { ensureSystems } from \"./ensureSystems\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { getWorldDeploy } from \"./getWorldDeploy\";\nimport { ensureFunctions } from \"./ensureFunctions\";\nimport { ensureModules } from \"./ensureModules\";\nimport { ensureNamespaceOwner } from \"./ensureNamespaceOwner\";\nimport { debug } from \"./debug\";\nimport { resourceToLabel } from \"@latticexyz/common\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\nimport { randomBytes } from \"crypto\";\nimport { ensureWorldFactory } from \"./ensureWorldFactory\";\nimport { Table } from \"@latticexyz/config\";\n\ntype DeployOptions = {\n client: Client<Transport, Chain | undefined, Account>;\n tables: readonly Table[];\n systems: readonly System[];\n libraries: readonly Library[];\n modules?: readonly Module[];\n salt?: Hex;\n worldAddress?: Address;\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};\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 client,\n tables,\n systems,\n libraries,\n modules = [],\n salt,\n worldAddress: existingWorldAddress,\n deployerAddress: initialDeployerAddress,\n withWorldProxy,\n}: DeployOptions): Promise<WorldDeploy> {\n const deployerAddress = initialDeployerAddress ?? (await ensureDeployer(client));\n\n await ensureWorldFactory(client, deployerAddress, withWorldProxy);\n\n // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.\n await ensureContractsDeployed({\n client,\n deployerAddress,\n contracts: [\n ...libraries.map((library) => ({\n bytecode: library.prepareDeploy(deployerAddress, libraries).bytecode,\n deployedBytecodeSize: library.deployedBytecodeSize,\n label: `${library.path}:${library.name} library`,\n })),\n ...systems.map((system) => ({\n bytecode: system.prepareDeploy(deployerAddress, libraries).bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n label: `${resourceToLabel(system)} system`,\n })),\n ...modules.map((mod) => ({\n bytecode: mod.prepareDeploy(deployerAddress, libraries).bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n label: `${mod.name} module`,\n })),\n ],\n });\n\n const worldDeploy = existingWorldAddress\n ? await getWorldDeploy(client, existingWorldAddress)\n : await deployWorld(client, deployerAddress, salt ?? `0x${randomBytes(32).toString(\"hex\")}`, withWorldProxy);\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 namespaceTxs = await ensureNamespaceOwner({\n client,\n worldDeploy,\n resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],\n });\n\n debug(\"waiting for all namespace registration transactions to confirm\");\n for (const tx of namespaceTxs) {\n await waitForTransactionReceipt(client, { hash: tx });\n }\n\n const tableTxs = await ensureTables({\n client,\n worldDeploy,\n tables,\n });\n const systemTxs = await ensureSystems({\n client,\n deployerAddress,\n libraries,\n worldDeploy,\n systems,\n });\n const functionTxs = await ensureFunctions({\n client,\n worldDeploy,\n functions: systems.flatMap((system) => system.functions),\n });\n const moduleTxs = await ensureModules({\n client,\n deployerAddress,\n libraries,\n worldDeploy,\n modules,\n });\n\n const txs = [...tableTxs, ...systemTxs, ...functionTxs, ...moduleTxs];\n\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n debug(\"waiting for all transactions to confirm\");\n for (const tx of txs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\n\n debug(\"deploy complete\");\n return worldDeploy;\n}\n","import { Client, Address, getAddress, parseAbi } from \"viem\";\nimport { getBlockNumber, getLogs } from \"viem/actions\";\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(client: Client, worldAddress: Address): Promise<WorldDeploy> {\n const address = getAddress(worldAddress);\n\n let deploy = deploys.get(address);\n if (deploy != null) {\n return deploy;\n }\n\n debug(\"looking up world deploy for\", address);\n\n const stateBlock = await getBlockNumber(client);\n const logs = await getLogs(client, {\n strict: true,\n address,\n events: parseAbi(worldDeployEvents),\n // this may fail for certain RPC providers with block range limits\n // if so, could potentially use our fetchLogs helper (which does pagination)\n fromBlock: \"earliest\",\n toBlock: stateBlock,\n });\n\n deploy = {\n ...logsToWorldDeploy(logs),\n stateBlock,\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 { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { hexToResource, writeContract } from \"@latticexyz/common\";\nimport { WorldDeploy, WorldFunction, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { getFunctions } from \"./getFunctions\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\n\nexport async function ensureFunctions({\n client,\n worldDeploy,\n functions,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly functions: readonly WorldFunction[];\n}): Promise<readonly Hex[]> {\n const worldFunctions = await getFunctions({ client, worldDeploy });\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 if (namespace === \"\") {\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: \"registerRootFunctionSelector\",\n args: [func.systemId, func.systemFunctionSignature, func.systemFunctionSignature],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n );\n }\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: \"registerFunctionSelector\",\n args: [func.systemId, func.systemFunctionSignature],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n );\n }),\n );\n}\n","import { Client, Transport, Chain, Account, Hex, BaseError } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Library, Module, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { isDefined, wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\n\nexport async function ensureModules({\n client,\n deployerAddress,\n libraries,\n worldDeploy,\n modules,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly libraries: readonly Library[];\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, libraries).bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n label: `${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 // append module's ABI so that we can decode any custom errors\n const abi = [...worldAbi, ...mod.abi];\n const moduleAddress = mod.prepareDeploy(deployerAddress, libraries).address;\n return mod.installAsRoot\n ? await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"installRootModule\",\n args: [moduleAddress, mod.installData],\n })\n : await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"installModule\",\n args: [moduleAddress, mod.installData],\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 throw error;\n }\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n },\n ),\n ),\n )\n ).filter(isDefined);\n}\n","import { Account, Chain, Client, Hex, Transport, getAddress } from \"viem\";\nimport { WorldDeploy, 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}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\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 });\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 path from \"path\";\nimport { 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\";\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 libraries = findLibraries(forgeOutDir).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, forgeOutDir);\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 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\n const systems = configSystems.map((system): System => {\n const contractData = getContractData(`${system.label}.sol`, system.label, forgeOutDir);\n\n const systemFunctions = 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 // TODO: move to resolveSystems?\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 abi: contractData.abi,\n functions: systemFunctions,\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 { 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 { 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 { DeterministicContract, Library, LibraryPlaceholder, salt } from \"./common\";\nimport { spliceHex } from \"@latticexyz/common\";\nimport { Hex, getCreate2Address, Address } from \"viem\";\n\nexport function createPrepareDeploy(\n bytecodeWithPlaceholders: Hex,\n placeholders: readonly LibraryPlaceholder[],\n): DeterministicContract[\"prepareDeploy\"] {\n return function prepareDeploy(deployer: Address, libraries: readonly Library[]) {\n let bytecode = bytecodeWithPlaceholders;\n for (const placeholder of placeholders) {\n const library = libraries.find((lib) => lib.path === placeholder.path && lib.name === placeholder.name);\n if (!library) {\n throw new Error(`Could not find library for bytecode placeholder ${placeholder.path}:${placeholder.name}`);\n }\n bytecode = spliceHex(\n bytecode,\n placeholder.start,\n placeholder.length,\n library.prepareDeploy(deployer, libraries).address,\n );\n }\n return {\n bytecode,\n address: getCreate2Address({ from: deployer, bytecode, salt }),\n };\n };\n}\n","import { existsSync } from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getScriptDirectory, forge } from \"@latticexyz/common/foundry\";\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 console.log(chalk.blue(`Executing post deploy script at ${postDeployPath}`));\n\n await forge(\n [\n \"script\",\n postDeployScript,\n \"--broadcast\",\n \"--sig\",\n \"run(address)\",\n worldAddress,\n \"--rpc-url\",\n rpc,\n \"-vvv\",\n kms ? \"--aws\" : \"\",\n ...userOptions,\n ],\n {\n profile: profile,\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 { getContractArtifact } from \"../utils/getContractArtifact\";\nimport { knownModuleArtifacts } from \"../utils/knownModuleArtifacts\";\nimport { resolveWithContext } from \"@latticexyz/world/internal\";\n\nexport async function configToModules<config extends World>(\n config: config,\n // TODO: remove/replace `forgeOutDir`\n forgeOutDir: string,\n): Promise<readonly Module[]> {\n const modules = await Promise.all(\n config.modules.map(async (mod): Promise<Module> => {\n let artifactPath = mod.artifactPath;\n\n // Backwards compatibility\n // TODO: move this up a level so we don't need `forgeOutDir` in here?\n if (!artifactPath) {\n if (mod.name) {\n artifactPath =\n knownModuleArtifacts[mod.name as keyof typeof knownModuleArtifacts] ??\n path.join(forgeOutDir, `${mod.name}.sol`, `${mod.name}.json`);\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 } else {\n throw new Error(\"No `artifactPath` provided for module.\");\n }\n }\n\n const name = path.basename(artifactPath, \".json\");\n const artifact = await getContractArtifact({ 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 installAsRoot: mod.root,\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 modules;\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\";\nimport { createRequire } from \"node:module\";\nimport { findUp } from \"find-up\";\n\nexport type GetContractArtifactOptions = {\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 type GetContractArtifactResult = {\n bytecode: Hex;\n placeholders: readonly LibraryPlaceholder[];\n abi: Abi;\n deployedBytecodeSize: number;\n};\n\nconst bytecodeSchema = z.object({\n object: z.string().refine(isHex),\n linkReferences: z.record(\n z.record(\n z.array(\n z.object({\n start: z.number(),\n length: z.number(),\n }),\n ),\n ),\n ),\n});\n\nconst artifactSchema = z.object({\n bytecode: bytecodeSchema,\n deployedBytecode: bytecodeSchema,\n abi: abiSchema,\n});\n\nexport async function getContractArtifact({\n packageJsonPath,\n artifactPath,\n}: GetContractArtifactOptions): Promise<GetContractArtifactResult> {\n let importedArtifact;\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 importedArtifact = 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 // TODO: improve errors or replace with arktype?\n const artifact = artifactSchema.parse(importedArtifact);\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","/** @deprecated Please don't add to this list! These are kept for backwards compatibility and assumes the downstream project has this module installed as a dependency. */\nexport const 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 Unstable_CallWithSignatureModule:\n \"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json\",\n};\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","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"2.0.12\",\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\": \"./dist/mud.js\"\n },\n \"files\": [\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\": \"rimraf dist\",\n \"clean:test-tables\": \"rimraf src/codegen\",\n \"dev\": \"tsup --watch\",\n \"lint\": \"eslint . --ext .ts\",\n \"prepare\": \"mkdir -p ./dist && touch ./dist/mud.js\",\n \"test\": \"tsc --noEmit && forge test\",\n \"test:ci\": \"pnpm run test\"\n },\n \"dependencies\": {\n \"@aws-sdk/client-kms\": \"^3.556.0\",\n \"@latticexyz/abi-ts\": \"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/utils\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"abitype\": \"1.0.0\",\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\": \"^7.0.0\",\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 \"typescript\": \"5.4.2\",\n \"viem\": \"2.9.20\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"^3.22.2\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/debug\": \"^4.1.7\",\n \"@types/ejs\": \"^3.1.1\",\n \"@types/node\": \"^18.15.11\",\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 \"tsup\": \"^6.7.0\",\n \"tsx\": \"^3.12.6\",\n \"vitest\": \"0.34.6\"\n }\n}\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 { anvil, forge, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { deployOptions, runDeploy } from \"../runDeploy\";\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 const anvilArgs = [\"--block-base-fee-per-gas\", \"0\", \"--port\", String(opts.port)];\n anvil(anvilArgs);\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 forge([\"test\", \"--fork-url\", forkRpc, ...userOptions], {\n profile: opts.profile,\n env: {\n WORLD_ADDRESS: worldAddress,\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 { cast, 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\";\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 ?? process.env.FOUNDRY_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 const result = await cast([\n \"run\",\n \"--label\",\n `${worldAddress}:World`,\n ...labels.map(({ label, address }) => [\"--label\", `${address}:${label}`]).flat(),\n `${args.tx}`,\n ]);\n console.log(result);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule, InferredOptionTypes } from \"yargs\";\nimport { anvil, 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\";\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 const anvilArgs = [\"--block-time\", \"1\", \"--block-base-fee-per-gas\", \"0\"];\n anvil(anvilArgs);\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 });\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, getCreate2Address, 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 { getDeployer } from \"./deploy/getDeployer\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { Module, salt } from \"./deploy/common\";\nimport { getStorageAt } from \"viem/actions\";\nimport { execa } from \"execa\";\n\ntype VerifyOptions = {\n client: Client<Transport, Chain | undefined>;\n rpc: string;\n verifier: string;\n verifierUrl?: string;\n systems: { name: string; bytecode: Hex }[];\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 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 systems.map(({ name, bytecode }) =>\n verifyQueue.add(() =>\n verifyContract({\n name,\n rpc,\n verifier,\n verifierUrl,\n address: getCreate2Address({\n from: deployerAddress,\n bytecode: bytecode,\n salt,\n }),\n }).catch((error) => {\n console.error(`Error verifying system contract ${name}:`, 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: getCreate2Address({\n from: deployerAddress,\n bytecode: bytecode,\n salt,\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 { forge } from \"@latticexyz/common/foundry\";\nimport { Address } from \"viem\";\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 const args = [\"verify-contract\", options.address, options.name, \"--rpc-url\", options.rpc];\n\n if (options.verifier) {\n args.push(\"--verifier\", options.verifier);\n }\n if (options.verifierUrl) {\n args.push(\"--verifier-url\", options.verifierUrl);\n }\n await forge(args, { cwd: options.cwd });\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 { resolveSystems } from \"@latticexyz/world/node\";\nimport { getOutDirectory, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport { getContractData } from \"../utils/getContractData\";\nimport { Hex, createWalletClient, http } from \"viem\";\nimport chalk from \"chalk\";\nimport { configToModules } from \"../deploy/configToModules\";\nimport path from \"node:path\";\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 ?? process.env.FOUNDRY_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\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 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 // TODO: replace with `resolveConfig` and support for linked libs\n const configSystems = await resolveSystems({ rootDir, config });\n const systems = configSystems.map((system) => {\n const contractData = getContractData(`${system.name}.sol`, system.name, outDir);\n return {\n name: system.name,\n bytecode: contractData.bytecode,\n };\n });\n\n const modules = await configToModules(config, outDir);\n\n await verify({\n client,\n rpc,\n systems,\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"],"mappings":"wCAEA,OAAOA,OAAe,yBACtB,OAAOC,OAAW,qBCFlB,OAAS,cAAAC,GAAY,qBAAAC,OAAyB,0BCD9C,OAAS,YAAAC,OAAgB,4BACzB,OAAS,YAAAC,OAAgB,yBAEzB,OAAS,SAAAC,GAAO,iBAAAC,OAAqB,6BACrC,OAAS,SAAAC,OAAa,QAatB,eAAsBC,EAAM,CAC1B,QAAAC,EACA,OAAAC,EACA,eAAAC,EAAiB,QAAQ,IAAI,eAC/B,EAAgC,CAC9B,IAAMC,EAAa,MAAMN,GAAcK,CAAc,EAErD,MAAM,QAAQ,IAAI,CAACR,GAAS,CAAE,QAAAM,EAAS,OAAAC,EAAQ,WAAAE,CAAW,CAAC,EAAGR,GAAS,CAAE,QAAAK,EAAS,OAAAC,CAAO,CAAC,CAAC,CAAC,EAE5F,MAAML,GAAM,CAAC,OAAO,EAAG,CAAE,QAASM,CAAe,CAAC,EAClD,MAAMJ,GAAM,MAAO,CAAC,QAAQ,EAAG,CAAE,M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E,EAAU,MAAMC,GAAgBhB,EAAQE,CAAM,EAEpD,MAAMe,GAAO,CACX,OAAAV,EACA,IAAAH,EACA,QAAAM,EACA,QAAAK,EACA,gBAAiBpB,EAAK,gBACtB,aAAcA,EAAK,aACnB,SAAUA,EAAK,SACf,YAAaA,EAAK,WACpB,CAAC,CACH,CACF,EAEOuB,GAAQzB,GtD9ER,IAAM0B,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EACF","names":["gasReport","abiTs","loadConfig","resolveConfigPath","tablegen","worldgen","forge","getRemappings","execa","build","rootDir","config","foundryProfile","remappings","path","commandModule","yargs","opts","configPath","resolveConfigPath","config","loadConfig","build","build_default","rmSync","homedir","path","execa","commandModule","yargs","blocktime","userHomeDir","anvilArgs","child","devnode_default","commandModule","yargs","name","greeting","hello_default","loadConfig","resolveConfigPath","tablegen","getRemappings","path","commandModule","yargs","opts","configPath","config","remappings","tablegen_default","path","existsSync","mkdirSync","readFileSync","writeFileSync","getBalance","sendRawTransaction","sendTransaction","waitForTransactionReceipt","deployment_default","createDebug","debug","error","debug","error","sliceHex","getBytecode","deployer","deployment_default","getDeployer","client","bytecode","getBytecode","debug","sliceHex","deployer","deployment_default","ensureDeployer","client","existingDeployer","getDeployer","gasRequired","currentBalance","getBalance","gasNeeded","debug","gasTx","sendTransaction","gasReceipt","waitForTransactionReceipt","deployTx","sendRawTransaction","error","deployReceipt","waitForTransactionReceipt","waitForTransactionReceipt","concatHex","getCreate2Address","getBytecode","padHex","IBaseWorldAbi","helloStoreEvent","helloWorldEvent","salt","contractSizeLimit","worldDeployEvents","worldAbi","supportedStoreVersions","supportedWorldVersions","sendTransaction","pRetry","wait","ensureContract","client","deployerAddress","bytecode","deployedBytecodeSize","label","address","getCreate2Address","salt","getBytecode","debug","contractSizeLimit","sendTransaction","concatHex","error","delay","uniqueBy","ensureContractsDeployed","client","deployerAddress","contracts","uniqueContracts","contract","txs","ensureContract","debug","tx","waitForTransactionReceipt","worldFactoryBuild","worldFactoryAbi","getCreate2Address","encodeDeployData","size","accessManagementSystemBuild","balanceTransferSystemBuild","batchCallSystemBuild","registrationSystemBuild","initModuleBuild","initModuleAbi","getCreate2Address","encodeDeployData","size","getWorldContracts","deployerAddress","accessManagementSystemDeployedBytecodeSize","size","accessManagementSystemBuild","accessManagementSystemBytecode","accessManagementSystem","getCreate2Address","salt","balanceTransferSystemDeployedBytecodeSize","balanceTransferSystemBuild","balanceTransferSystemBytecode","balanceTransferSystem","batchCallSystemDeployedBytecodeSize","batchCallSystemBuild","batchCallSystemBytecode","batchCallSystem","registrationDeployedBytecodeSize","registrationSystemBuild","registrationBytecode","registration","initModuleDeployedBytecodeSize","initModuleBuild","initModuleBytecode","encodeDeployData","initModuleAbi","initModule","getWorldFactoryContracts","deployerAddress","worldContracts","getWorldContracts","worldFactoryDeployedBytecodeSize","size","worldFactoryBuild","worldFactoryBytecode","encodeDeployData","worldFactoryAbi","worldFactory","getCreate2Address","salt","worldProxyFactoryBuild","worldProxyFactoryAbi","getCreate2Address","encodeDeployData","size","getWorldProxyFactoryContracts","deployerAddress","worldContracts","getWorldContracts","worldProxyFactoryDeployedBytecodeSize","size","worldProxyFactoryBuild","worldProxyFactoryBytecode","encodeDeployData","worldProxyFactoryAbi","worldProxyFactory","getCreate2Address","salt","ensureWorldFactory","client","deployerAddress","withWorldProxy","contracts","getWorldProxyFactoryContracts","ensureContractsDeployed","getWorldFactoryContracts","WorldFactoryAbi","writeContract","AbiEventSignatureNotFoundError","decodeEventLog","hexToString","parseAbi","isDefined","logsToWorldDeploy","logs","deployLogs","log","decodeEventLog","parseAbi","worldDeployEvents","error","AbiEventSignatureNotFoundError","address","deployBlock","worldVersion","storeVersion","deploy","hexToString","deployWorld","client","deployerAddress","salt","withWorldProxy","worldFactory","ensureWorldFactory","debug","tx","writeContract","WorldFactoryAbi","receipt","waitForTransactionReceipt","deploy","logsToWorldDeploy","resourceToLabel","writeContract","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","getSchemaTypes","getValueSchema","getKeySchema","parseAbiItem","decodeAbiParameters","parseAbiParameters","hexToResource","storeSetRecordEvent","getLogs","decodeKey","decodeValueArgs","getKeySchema","getSchemaTypes","getValueSchema","hexToSchema","storeConfig","getTables","client","worldDeploy","debug","tables","parseAbiItem","log","tableId","type","namespace","name","hexToResource","value","solidityKeySchema","solidityValueSchema","keyNames","decodeAbiParameters","parseAbiParameters","fieldNames","valueAbiTypes","keySchema","abiType","i","valueSchema","pRetry","wait","ensureTables","client","worldDeploy","tables","worldTableIds","getTables","table","existingTables","debug","resourceToLabel","missingTables","keySchema","getSchemaTypes","getKeySchema","valueSchema","getValueSchema","writeContract","worldAbi","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","error","delay","getAddress","writeContract","resourceToLabel","parseAbiItem","HttpRequestError","getLogs","storeSpliceStaticDataEvent","pRetry","storeConfig","getResourceIds","client","worldDeploy","debug","resourceIds","getLogs","parseAbiItem","storeSpliceStaticDataEvent","error","HttpRequestError","log","hexToResource","resourceToLabel","decodeValueArgs","encodeKey","getKeySchema","getSchemaTypes","getValueSchema","readContract","getTableValue","client","worldDeploy","table","key","staticData","encodedLengths","dynamicData","worldAbi","encodeKey","getSchemaTypes","getKeySchema","decodeValueArgs","getValueSchema","parseAbiItem","storeSetRecordEvent","getLogs","decodeKey","decodeValueArgs","getKeySchema","getSchemaTypes","getValueSchema","worldConfig","getFunctions","client","worldDeploy","debug","selectors","parseAbiItem","log","signatureLogs","selectorToSignature","worldFunctionSelector","systemFunctionSelector","systemId","parseAbiItem","getAddress","storeSpliceStaticDataEvent","getLogs","decodeKey","getKeySchema","getSchemaTypes","worldConfig","getResourceAccess","client","worldDeploy","debug","keys","getLogs","parseAbiItem","storeSpliceStaticDataEvent","log","decodeKey","getSchemaTypes","getKeySchema","access","key","getTableValue","value","getAddress","worldConfig","getSystems","client","worldDeploy","resourceIds","functions","resourceAccess","getResourceIds","getFunctions","getResourceAccess","systems","hexToResource","resource","debug","resourceToLabel","system","address","publicAccess","getTableValue","systemFunctions","func","resourceId","wait","pRetry","ensureSystems","client","deployerAddress","libraries","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","existingSystems","system","worldSystem","getAddress","debug","resourceToLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","ensureContractsDeployed","registerTxs","pRetry","writeContract","worldAbi","error","delay","wait","systemIds","currentAccess","resourceId","desiredAccess","address","systemId","s","access","accessToAdd","accessToRemove","accessTxs","waitForTransactionReceipt","getAddress","parseAbi","getBlockNumber","getLogs","deploys","getWorldDeploy","client","worldAddress","address","getAddress","deploy","debug","stateBlock","getBlockNumber","logs","getLogs","parseAbi","worldDeployEvents","logsToWorldDeploy","hexToResource","writeContract","pRetry","wait","ensureFunctions","client","worldDeploy","functions","worldFunctions","getFunctions","worldSelectorToFunction","func","toSkip","toAdd","debug","wrongSystem","namespace","hexToResource","writeContract","worldAbi","error","delay","BaseError","writeContract","isDefined","wait","pRetry","ensureModules","client","deployerAddress","libraries","worldDeploy","modules","ensureContractsDeployed","mod","debug","pRetry","abi","worldAbi","moduleAddress","writeContract","error","BaseError","delay","wait","isDefined","getAddress","hexToResource","resourceToHex","writeContract","worldConfig","ensureNamespaceOwner","client","worldDeploy","resourceIds","desiredNamespaces","resourceId","hexToResource","existingResourceIds","getResourceIds","existingNamespaces","debug","namespace","existingDesiredNamespaces","unauthorizedNamespaces","owner","getTableValue","resourceToHex","getAddress","missingNamespaces","writeContract","worldAbi","resourceToLabel","randomBytes","deploy","client","tables","systems","libraries","modules","salt","existingWorldAddress","initialDeployerAddress","withWorldProxy","deployerAddress","ensureDeployer","ensureWorldFactory","ensureContractsDeployed","library","system","resourceToLabel","mod","worldDeploy","getWorldDeploy","deployWorld","randomBytes","supportedStoreVersions","supportedWorldVersions","namespaceTxs","ensureNamespaceOwner","table","debug","tx","waitForTransactionReceipt","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","createWalletClient","http","isHex","privateKeyToAccount","loadConfig","resolveConfigPath","getOutDirectory","getRpcUrl","chalk","MUDError","path","resolveSystems","isHex","toFunctionSelector","toFunctionSignature","readFileSync","path","MUDError","size","findPlaceholders","linkReferences","path","contracts","contractName","locations","location","getContractData","filename","contractName","forgeOutDirectory","data","contractDataPath","path","readFileSync","MUDError","bytecode","deployedBytecode","abi","placeholders","findPlaceholders","size","groupBy","readFileSync","globSync","toposort","orderByDependencies","items","itemKey","dependencyKeys","dependencyOrder","item","dependency","a","b","findLibraries","forgeOutDir","libraries","globSync","path","readFileSync","artifact","contractPath","contractName","linkReferences","libraryPath","reference","libraryName","orderByDependencies","lib","spliceHex","getCreate2Address","createPrepareDeploy","bytecodeWithPlaceholders","placeholders","deployer","libraries","bytecode","placeholder","library","lib","salt","resolveConfig","rootDir","config","forgeOutDir","libraries","findLibraries","library","contractData","getContractData","path","createPrepareDeploy","baseSystemFunctions","item","toFunctionSignature","configSystems","resolveSystems","systems","system","systemFunctions","sig","worldSignature","toFunctionSelector","allowedAddresses","target","isHex","allowedSystemIds","label","s","systemsById","groupBy","overlappingSystems","matches","names","getChainId","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","forgeOptions","kms","userOptions","postDeployPath","kmsKeyToAccount","path","encodeField","bytesToHex","isHex","size","z","abiSchema","createRequire","findUp","bytecodeSchema","isHex","artifactSchema","getContractArtifact","packageJsonPath","artifactPath","importedArtifact","requirePath","error","artifact","placeholders","findPlaceholders","size","knownModuleArtifacts","resolveWithContext","configToModules","config","forgeOutDir","mod","artifactPath","knownModuleArtifacts","path","name","artifact","getContractArtifact","installArgs","arg","value","bytesToHex","encodeField","createPrepareDeploy","deployOptions","runDeploy","opts","salt","isHex","MUDError","profile","configPath","resolveConfigPath","config","loadConfig","rootDir","path","chalk","outDir","getOutDirectory","rpc","getRpcUrl","build","systems","libraries","resolveConfig","modules","configToModules","account","keyId","kmsKeyToAccount","privateKey","privateKeyToAccount","client","createWalletClient","http","tables","namespace","startTime","worldDeploy","deploy","postDeploy","deploymentInfo","chainId","getChainId","deploysDir","mkdirSync","writeFileSync","localChains","deploys","existsSync","readFileSync","commandModule","yargs","deployOptions","opts","runDeploy","error","logError","deploy_default","path","loadConfig","resolveConfigPath","worldgen","commandModule","yargs","args","worldgenHandler","configPath","config","rootDir","worldgen_default","chalk","readFileSync","writeFileSync","path","MUDError","package_default","globSync","ZodError","z","envSchema","value","parseEnv","error","invalidEnvVars","mudPackages","commandModule","yargs","options","mutuallyExclusiveOptions","numMutuallyExclusiveOptions","acc","opt","MUDError","resolveVersion","packageJsons","globSync","p","packageJson","updatePackageJson","e","logError","npmResult","chalk","package_default","version","commit","v","filePath","link","mudVersion","readPackageJson","mudPackageNames","mudPackages","mudDependencies","packageName","mudDevDependencies","resolveMudVersion","writeFileSync","logComparison","key","type","resolveLinkPath","path","jsonString","readFileSync","prev","curr","packageJsonPath","mudLinkPath","packageJsonToRootPath","set_version_default","anvil","forge","getRpcUrl","chalk","testOptions","deployOptions","commandModule","yargs","opts","anvilArgs","anvil","forkRpc","getRpcUrl","worldAddress","runDeploy","chalk","userOptions","forge","e","test_default","path","fs","loadConfig","resolveConfigPath","MUDError","cast","getRpcUrl","worldConfig","createClient","http","getChainId","readContract","resolveSystems","systemsTableId","worldConfig","getWorldAddress","worldsFile","chainId","fs","MUDError","deploys","commandModule","yargs","args","configPath","resolveConfigPath","rootDir","path","profile","rpc","getRpcUrl","config","loadConfig","client","createClient","http","getChainId","worldAddress","systems","resolveSystems","labels","system","readContract","worldAbi","result","cast","label","address","trace_default","anvil","getScriptDirectory","getSrcDirectory","chalk","chokidar","loadConfig","resolveConfigPath","path","homedir","rmSync","BehaviorSubject","debounceTime","exhaustMap","filter","isDefined","devOptions","deployOptions","commandModule","yargs","opts","rpc","configPath","resolveConfigPath","srcDir","getSrcDirectory","scriptDir","getScriptDirectory","initialConfig","loadConfig","chalk","userHomeDir","homedir","rmSync","path","anvil","lastChange$","chokidar","_","updatePath","worldAddress","lastChange","deploy","runDeploy","error","dev_contracts_default","getCreate2Address","sliceHex","zeroHash","forge","verifyContract","options","args","PQueue","MUDError","getStorageAt","execa","ERC1967_IMPLEMENTATION_SLOT","verify","client","rpc","systems","modules","worldAddress","initialDeployerAddress","verifier","verifierUrl","deployerAddress","getDeployer","MUDError","implementationStorage","usesProxy","zeroHash","verifyQueue","PQueue","name","bytecode","verifyContract","getCreate2Address","salt","error","getWorldProxyFactoryContracts","getWorldFactoryContracts","prepareDeploy","address","implementationAddress","sliceHex","loadConfig","resolveConfigPath","resolveSystems","getOutDirectory","getRpcUrl","createWalletClient","http","chalk","path","verifyOptions","commandModule","yargs","opts","profile","configPath","resolveConfigPath","rootDir","config","loadConfig","outDir","getOutDirectory","rpc","getRpcUrl","chalk","client","createWalletClient","http","systems","resolveSystems","system","contractData","getContractData","modules","configToModules","verify","verify_default","commands","build_default","deploy_default","devnode_default","gasReport","hello_default","tablegen_default","worldgen_default","set_version_default","test_default","trace_default","dev_contracts_default","abiTs","verify_default"]}
|
package/dist/mud.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-JCLK7DZO.js"),{commands:t}=await import("./commands-
|
2
|
+
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-JCLK7DZO.js"),{commands:t}=await import("./commands-JLSR2MGQ.js");r(e(process.argv)).scriptName("mud").command(t).strict().fail((a,n)=>{console.error(o.red(a)),a.includes("Missing required argument")&&console.log(o.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),n!=null&&(s(n),console.log("")),process.exit(1)}).alias({h:"help"}).argv}l();
|
3
3
|
//# sourceMappingURL=mud.js.map
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@latticexyz/cli",
|
3
|
-
"version": "3.0.0-main-
|
3
|
+
"version": "3.0.0-main-2da9e48cd",
|
4
4
|
"description": "Command line interface for mud",
|
5
5
|
"repository": {
|
6
6
|
"type": "git",
|
@@ -48,15 +48,15 @@
|
|
48
48
|
"yargs": "^17.7.1",
|
49
49
|
"zod": "^3.22.2",
|
50
50
|
"zod-validation-error": "^1.3.0",
|
51
|
-
"@latticexyz/abi-ts": "3.0.0-main-
|
52
|
-
"@latticexyz/common": "3.0.0-main-
|
53
|
-
"@latticexyz/config": "3.0.0-main-
|
54
|
-
"@latticexyz/gas-report": "3.0.0-main-
|
55
|
-
"@latticexyz/protocol-parser": "3.0.0-main-
|
56
|
-
"@latticexyz/schema-type": "3.0.0-main-
|
57
|
-
"@latticexyz/store": "3.0.0-main-
|
58
|
-
"@latticexyz/utils": "3.0.0-main-
|
59
|
-
"@latticexyz/world": "3.0.0-main-
|
51
|
+
"@latticexyz/abi-ts": "3.0.0-main-2da9e48cd",
|
52
|
+
"@latticexyz/common": "3.0.0-main-2da9e48cd",
|
53
|
+
"@latticexyz/config": "3.0.0-main-2da9e48cd",
|
54
|
+
"@latticexyz/gas-report": "3.0.0-main-2da9e48cd",
|
55
|
+
"@latticexyz/protocol-parser": "3.0.0-main-2da9e48cd",
|
56
|
+
"@latticexyz/schema-type": "3.0.0-main-2da9e48cd",
|
57
|
+
"@latticexyz/store": "3.0.0-main-2da9e48cd",
|
58
|
+
"@latticexyz/utils": "3.0.0-main-2da9e48cd",
|
59
|
+
"@latticexyz/world": "3.0.0-main-2da9e48cd"
|
60
60
|
},
|
61
61
|
"devDependencies": {
|
62
62
|
"@types/debug": "^4.1.7",
|