@latticexyz/cli 2.0.0-alpha.1.76 → 2.0.0-alpha.1.78
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.
|
@@ -43,7 +43,7 @@ Error while running the gas report (see above)`)),n}let t=new RegExp(/GAS REPORT
|
|
|
43
43
|
Resolved config:
|
|
44
44
|
`),JSON.stringify(m,null,2));try{let l=process.env.PRIVATE_KEY;if(!l)throw new Go("Missing PRIVATE_KEY environment variable");let x=await Ke(m,p,{...e,rpc:s,privateKey:l});if(e.saveDeployment){let $=await qe(s),g=oe.join(m.deploysDirectory,$.toString());Bo(g,{recursive:!0}),Ze(oe.join(g,"latest.json"),JSON.stringify(x,null,2)),Ze(oe.join(g,Date.now()+".json"),JSON.stringify(x,null,2)),console.log(L.bgGreen(L.whiteBright(`
|
|
45
45
|
Deployment result (written to ${g}):
|
|
46
|
-
`)))}return console.log(x),x}catch(l){_(l),process.exit(1)}}var Lo={command:"deploy-v2",describe:"Deploy MUD v2 contracts",builder(e){return e.options(re)},async handler(e){await ne(e),process.exit(0)}},Ye=Lo;import{loadConfig as No}from"@latticexyz/config";import{worldgen as Jo}from"@latticexyz/world";import{getSrcDirectory as Vo}from"@latticexyz/common/foundry";import _o from"glob";import Qe,{basename as zo}from"path";import{rmSync as Ko}from"fs";var qo={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces"}})},async handler(e){let{configPath:o,clean:t}=e,r=await Vo(),n=_o.sync(`${r}/**/*.sol`).map(p=>({path:p,basename:zo(p,".sol")})),s=await No(o),i=Qe.join(r,s.codegenDirectory);t&&Ko(Qe.join(i,s.worldgenDirectory),{recursive:!0,force:!0}),await Jo(s,n,i),process.exit(0)}},Xe=qo;import U from"chalk";import{existsSync as Zo,readFileSync as Yo,rmSync as Qo,writeFileSync as tt}from"fs";import I from"path";import{MUDError as J}from"@latticexyz/config";var et={name:"@latticexyz/cli",version:"1.42.0",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js",mud2:"./dist/mud2.js"},scripts:{build:"pnpm run build:js","build:js":"tsup && chmod +x ./dist/mud.js ./dist/mud2.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch","generate-test-tables":"tsx ./scripts/generate-test-tables.ts",lint:"eslint . --ext .ts",
|
|
46
|
+
`)))}return console.log(x),x}catch(l){_(l),process.exit(1)}}var Lo={command:"deploy-v2",describe:"Deploy MUD v2 contracts",builder(e){return e.options(re)},async handler(e){await ne(e),process.exit(0)}},Ye=Lo;import{loadConfig as No}from"@latticexyz/config";import{worldgen as Jo}from"@latticexyz/world";import{getSrcDirectory as Vo}from"@latticexyz/common/foundry";import _o from"glob";import Qe,{basename as zo}from"path";import{rmSync as Ko}from"fs";var qo={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces"}})},async handler(e){let{configPath:o,clean:t}=e,r=await Vo(),n=_o.sync(`${r}/**/*.sol`).map(p=>({path:p,basename:zo(p,".sol")})),s=await No(o),i=Qe.join(r,s.codegenDirectory);t&&Ko(Qe.join(i,s.worldgenDirectory),{recursive:!0,force:!0}),await Jo(s,n,i),process.exit(0)}},Xe=qo;import U from"chalk";import{existsSync as Zo,readFileSync as Yo,rmSync as Qo,writeFileSync as tt}from"fs";import I from"path";import{MUDError as J}from"@latticexyz/config";var et={name:"@latticexyz/cli",version:"1.42.0",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js",mud2:"./dist/mud2.js"},scripts:{build:"pnpm run build:js","build:js":"tsup && chmod +x ./dist/mud.js ./dist/mud2.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch","generate-test-tables":"tsx ./scripts/generate-test-tables.ts",lint:"eslint . --ext .ts",test:"tsc --noEmit && pnpm run generate-test-tables && forge test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/solecs":"workspace:*","@latticexyz/std-contracts":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/world":"workspace:*","@typechain/ethers-v5":"^10.2.0",chalk:"^5.0.1",chokidar:"^3.5.3",dotenv:"^16.0.3","ds-test":"https://github.com/dapphub/ds-test.git#c9ce3f25bde29fc5eb9901842bf02850dfd2d084",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0","forge-std":"https://github.com/foundry-rs/forge-std.git#b4f121555729b3afb3c5ffccb62ff4b6e2818fd3",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.1",path:"^0.12.7",table:"^6.8.1",typechain:"^8.1.1",typescript:"^4.9.5",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/yargs":"^17.0.10",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.30.1"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};var q=".mudbackup",N="@latticexyz",Xo={command:"set-version",describe:"Install a custom MUD version and optionally backup the previously installed version",builder(e){return e.options({backup:{type:"boolean",description:`Back up the current MUD versions to "${q}"`},force:{type:"boolean",description:`Backup fails if a "${q}" file is found, unless --force is provided`},restore:{type:"boolean",description:`Restore the previous MUD versions from "${q}"`},mudVersion:{alias:"v",type:"string",description:"The MUD version to install"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{if(!e.mudVersion&&!e.link&&!e.restore)throw new J("`--mudVersion` or `--link` is required unless --restore is provided.");if(e.link&&e.mudVersion)throw new J("Options `--link` and `--mudVersion` are mutually exclusive");e.mudVersion=e.mudVersion==="canary"?await er(et.name):e.mudVersion;let o="./package.json",{workspaces:t}=ot(o,e);if(t)for(let r of t){let n=I.join(r,"/package.json");ot(n,e)}}catch(o){_(o)}finally{process.exit(0)}}};function ot(e,o){let{restore:t,force:r,link:n}=o,{backup:s,mudVersion:i}=o,p=I.join(I.dirname(e),q),m=Zo(p);if(n&&!m&&(s=!0),s&&!r&&m)throw new J(`A backup file already exists at ${p}.
|
|
47
47
|
Use --force to overwrite it or --restore to restore it.`);let l=rt(e),x=t?rt(p):void 0,$={};for(let u in l.dependencies)u.startsWith(N)&&($[u]=l.dependencies[u]);let g={};for(let u in l.devDependencies)u.startsWith(N)&&(g[u]=l.devDependencies[u]);s&&(tt(p,JSON.stringify({dependencies:$,devDependencies:g},null,2)),console.log(U.green(`Backed up MUD dependencies from ${e} to ${p}`)));for(let u in l.dependencies)u.startsWith(N)&&(l.dependencies[u]=b(u,"dependencies"));for(let u in l.devDependencies)u.startsWith(N)&&(l.devDependencies[u]=b(u,"devDependencies"));return tt(e,JSON.stringify(l,null,2)+`
|
|
48
48
|
`),console.log(`Updating ${e}`),nt($,l.dependencies),nt(g,l.devDependencies),t&&!s&&(Qo(p),console.log(U.green(`Cleaned up ${p}`))),l;function b(u,E){return t&&x?x[E][u]:(n&&(i=tr(e,n,u)),i||l[E][u])}}function rt(e){try{let o=Yo(e,"utf8");return JSON.parse(o)}catch{throw new J("Could not read JSON at "+e)}}async function er(e){try{console.log(U.blue("fetching MUD canary version..."));let t=(await(await fetch(`https://registry.npmjs.org/${e}`)).json())["dist-tags"].canary;return console.log(U.green("MUD canary version:",t)),t}catch{throw new J(`Could not fetch canary version of ${e}`)}}function nt(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${U.red(e[t])} -> ${U.green(o[t])}`)}function tr(e,o,t){let r=t.replace(N,""),n=I.relative(I.dirname(e),process.cwd());return"link:"+I.join(n,o,"packages",r)}var st=Xo;import{anvil as or,forge as rr,getRpcUrl as nr}from"@latticexyz/common/foundry";import sr from"chalk";import{rmSync as ir,writeFileSync as ar}from"fs";var it=".mudtest",cr={command:"test-v2",describe:"Run tests in MUD v2 contracts",builder(e){return e.options({...re,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}})},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];or(n)}let o=e.worldAddress?await nr(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await ne({...e,saveDeployment:!1,rpc:o})).worldAddress;console.log(sr.blue("World address",t)),ar(it,t);let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{let n=await rr(["test","--fork-url",o,...r],{profile:e.profile});console.log(n)}catch(n){console.error(n)}ir(it),process.exit(0)}},at=cr;var Zs=[Ye,Me,Pe,Ie,Ue,Ee,Ge,Xe,st,at];export{me as a,ge as b,wr as c,be as d,he as e,ve as f,Or as g,Tt as h,Ce as i,Hr as j,Xr as k,_ as l,Zs as m};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-4AVGUQ7C.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/errors.ts","../src/commands/devnode.ts","../src/utils/deprecated/exec.ts","../src/utils/deprecated/ids.ts","../src/utils/deprecated/codegen.ts","../src/utils/deprecated/deploy.ts","../src/utils/deprecated/findLog.ts","../src/utils/deprecated/typegen.ts","../src/utils/deprecated/build.ts","../src/utils/deprecated/constants.ts","../src/utils/deprecated/hsr.ts","../src/commands/faucet.ts","../src/commands/gas-report.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/commands/tsgen.ts","../src/commands/deploy-v2.ts","../src/utils/deploy-v2.ts","../src/utils/getChainId.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../package.json","../src/commands/test-v2.ts","../src/commands/index.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/config\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n","import { rmSync } from \"fs\";\nimport { homedir } from \"os\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { execLog } from \"../utils/deprecated\";\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 const child = execLog(\"anvil\", [\"-b\", String(blocktime), \"--block-base-fee-per-gas\", \"0\"]);\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 { execa } from \"execa\";\n\n/**\n * Wrapper for execa that logs the full command.\n * @param command - The program/script to execute.\n * @param options - Arguments to pass to `command` on execution.\n * @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.\n */\nexport function execLog(command: string, options: string[]) {\n console.log(\"Cmd:\");\n console.log([command, ...options].join(\" \"));\n\n // TODO piping outputs and doing custom logging would be better for readability\n // (see https://github.com/latticexyz/mud/issues/446)\n return execa(command, options, {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n}\n","import { keccak256 as keccak256Bytes, toUtf8Bytes } from \"ethers/lib/utils.js\";\nimport { readFileSync } from \"fs\";\n\nexport const IDregex = new RegExp(/(?<=uint256 constant ID = uint256\\(keccak256\\(\")(.*)(?=\"\\))/);\n\nexport function extractIdFromFile(path: string): string | null {\n const content = readFileSync(path).toString();\n const regexResult = IDregex.exec(content);\n return regexResult && regexResult[0];\n}\n\nexport function keccak256(data: string) {\n return keccak256Bytes(toUtf8Bytes(data));\n}\n","import { readFile, writeFile } from \"fs/promises\";\nimport ejs from \"ejs\";\nimport path from \"path\";\n\nconst contractsDirectory = new URL(\"../src/contracts\", import.meta.url).pathname;\n\nconst stubLibDeploy = readFile(path.join(contractsDirectory, \"LibDeployStub.sol\"));\n\n/**\n * Generate LibDeploy.sol from deploy.json\n * @param configPath path to deploy.json\n * @param out output directory for LibDeploy.sol\n * @param systems optional, only generate deploy code for the given systems\n * @returns path to generated LibDeploy.sol\n */\nexport async function generateLibDeploy(configPath: string, out: string, systems?: string | string[]) {\n // Parse config\n const config = JSON.parse(await readFile(configPath, { encoding: \"utf8\" }));\n\n // Initializers are optional\n config.initializers ??= [];\n\n // Filter systems\n if (systems) {\n const systemsArray = Array.isArray(systems) ? systems : [systems];\n config.systems = config.systems.filter((system: { name: string }) => systemsArray.includes(system.name));\n }\n\n console.log(`Deploy config: \\n`, JSON.stringify(config, null, 2));\n\n // Generate LibDeploy\n console.log(\"Generating deployment script\");\n const LibDeploy = await ejs.renderFile(path.join(contractsDirectory, \"LibDeploy.ejs\"), config, { async: true });\n const libDeployPath = path.join(out, \"LibDeploy.sol\");\n await writeFile(libDeployPath, LibDeploy);\n\n return libDeployPath;\n}\n\nexport async function resetLibDeploy(out: string) {\n await writeFile(path.join(out, \"LibDeploy.sol\"), await stubLibDeploy);\n}\n","import { constants, Wallet } from \"ethers\";\nimport { generateLibDeploy, resetLibDeploy } from \"./codegen\";\nimport { findLog } from \"./findLog\";\nimport { generateTypes } from \"./typegen\";\nimport { execa } from \"execa\";\nimport { StaticJsonRpcProvider } from \"@ethersproject/providers\";\nimport path from \"path\";\n\nconst contractsDirectory = new URL(\"../src/contracts\", import.meta.url).pathname;\n\n/**\n * Deploy world, components and systems from deploy.json\n * @param deployerPrivateKey private key of deployer\n * @param rpc rpc url\n * @param worldAddress optional, address of existing world\n * @param reuseComponents optional, reuse existing components\n * @returns address of deployed world\n */\nexport async function deploy(\n deployerPrivateKey?: string,\n rpc = \"http://localhost:8545\",\n worldAddress?: string,\n reuseComponents?: boolean,\n gasPrice?: number\n) {\n const address = deployerPrivateKey ? new Wallet(deployerPrivateKey).address : constants.AddressZero;\n\n if (gasPrice == null) {\n try {\n console.log(\"Fetching gas price...\");\n const provider = new StaticJsonRpcProvider(rpc, { name: \"AnyNetwork\", chainId: 1234 });\n gasPrice = (await provider.getGasPrice()).toNumber() * 1.3; // 30% multiplier for faster inclusion\n console.log(\"Gas price:\", gasPrice);\n } catch (e) {\n console.log(\"Could not fetch gas price\");\n }\n }\n\n const child = execa(\n \"forge\",\n [\n \"script\",\n path.join(contractsDirectory, \"/Deploy.sol\"),\n \"--target-contract\",\n \"Deploy\",\n \"-vvv\",\n ...(!deployerPrivateKey ? [] : [\"--broadcast\", \"--private-keys\", deployerPrivateKey]),\n \"--sig\",\n \"broadcastDeploy(address,address,bool)\",\n address, // Deployer\n worldAddress || constants.AddressZero, // World address (0 = deploy a new world)\n reuseComponents ? \"true\" : \"false\", // Reuse components?\n \"--fork-url\",\n rpc,\n ...(gasPrice != null ? [\"--with-gas-price\", String(Math.round(gasPrice))] : []),\n ],\n { stdio: [\"inherit\", \"pipe\", \"pipe\"] }\n );\n\n child.stderr?.on(\"data\", (data) => console.log(\"stderr:\", data.toString()));\n child.stdout?.on(\"data\", (data) => console.log(data.toString()));\n\n // Extract world address from deploy script\n const lines = (await child).stdout?.split(\"\\n\");\n const deployedWorldAddress = findLog(lines, \"world: address\");\n const initialBlockNumber = findLog(lines, \"initialBlockNumber: uint256\");\n\n return { child: await child, deployedWorldAddress, initialBlockNumber };\n}\n\nexport type DeployOptions = {\n config: string;\n deployerPrivateKey?: string;\n worldAddress?: string;\n rpc: string;\n systems?: string | string[];\n reuseComponents?: boolean;\n clear?: boolean;\n gasPrice?: number;\n};\n\nexport async function generateAndDeploy(args: DeployOptions) {\n let libDeployPath: string | undefined;\n let deployedWorldAddress: string | undefined;\n let initialBlockNumber: string | undefined;\n\n try {\n // Generate LibDeploy\n libDeployPath = await generateLibDeploy(args.config, contractsDirectory, args.systems);\n\n // Build and generate fresh types\n await generateTypes(undefined, \"./types\", { clear: args.clear });\n\n // Call deploy script\n const result = await deploy(\n args.deployerPrivateKey,\n args.rpc,\n args.worldAddress,\n Boolean(args.reuseComponents),\n args.gasPrice\n );\n deployedWorldAddress = result.deployedWorldAddress;\n initialBlockNumber = result.initialBlockNumber;\n } finally {\n // Remove generated LibDeploy\n console.log(\"Cleaning up deployment script\");\n if (libDeployPath) await resetLibDeploy(contractsDirectory);\n }\n\n return { deployedWorldAddress, initialBlockNumber };\n}\n","export function findLog(deployLogLines: string[], log: string): string {\n for (const logLine of deployLogLines) {\n if (logLine.includes(log)) {\n return logLine.split(log)[1].trim();\n }\n }\n throw new Error(\"Can not find log\");\n}\n","import { runTypeChain, glob as typechainGlob } from \"typechain\";\nimport glob from \"glob\";\nimport { extractIdFromFile } from \"./ids\";\nimport { rmSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport { filterAbi, forgeBuild } from \"./build\";\nimport { getOutDirectory, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { systemsDir } from \"./constants\";\n\nexport async function generateAbiTypes(\n inputDir: string,\n outputDir: string,\n options?: { clear?: boolean; cwd?: string }\n) {\n if (options?.clear) {\n console.log(\"Clearing typechain output directory\", outputDir);\n rmSync(outputDir, { recursive: true, force: true });\n }\n\n const cwd = options?.cwd ?? process.cwd();\n\n const allFiles = typechainGlob(cwd, [`${inputDir}/**/+([a-zA-Z0-9_]).json`]);\n\n const result = await runTypeChain({\n cwd,\n filesToProcess: allFiles,\n allFiles,\n outDir: outputDir,\n target: \"ethers-v5\",\n });\n\n console.log(`Successfully generated ${result.filesGenerated} files`);\n}\n\nexport async function generateSystemTypes(outputDir: string, options?: { clear?: boolean }) {\n if (options?.clear) {\n console.log(\"Clearing system type output files\", outputDir);\n rmSync(path.join(outputDir, \"/SystemTypes.ts\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemAbis.mts\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemAbis.mjs\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemMappings.ts\"), { force: true });\n }\n\n let abis: string[] = [];\n let systems: string[] = [];\n let ids: string[] = [];\n let typePaths: string[] = [];\n\n const srcDir = await getSrcDirectory();\n const systemsPath = path.join(srcDir, systemsDir, \"*.sol\");\n\n const matches = glob.sync(systemsPath);\n\n systems = matches.map((path) => {\n const fragments = path.split(\"/\");\n return fragments[fragments.length - 1].split(\".sol\")[0];\n });\n\n ids = matches.map((path, index) => {\n const id = extractIdFromFile(path);\n if (!id) {\n console.log(\"Path:\", path);\n console.log(\"ID:\", id);\n throw new Error(\n \"No ID found for\" +\n matches[index] +\n \". Make sure your system source file includes a ID definition (uint256 constant ID = uint256(keccak256(<ID>));)\"\n );\n }\n return id;\n });\n\n abis = systems.map((system) => `../abi/${system}.json`);\n\n typePaths = systems.map((system) => `./ethers-contracts/${system}.ts`);\n\n console.log(\"Matches\", systems);\n console.log(\"Solidity\", ids);\n console.log(\"Type paths\", typePaths);\n console.log(\"ABIs\", abis);\n\n const SystemMappings = `// Autogenerated using mud system-types\nexport const systemToId = {\n${systems.map((system, index) => ` ${system}: \"${ids[index]}\",`).join(\"\\n\")}\n};\n\nexport const idToSystem = {\n${ids.map((id, index) => ` \"${id}\": \"${systems[index]}\",`).join(\"\\n\")}\n};\n `;\n\n const SystemTypes = `// Autogenerated using mud system-types\n${typePaths.map((path, index) => `import { ${systems[index]} } from \"${path.replace(\".ts\", \"\")}\";`).join(\"\\n\")}\n \nexport type SystemTypes = {\n${systems.map((system, index) => ` \"${ids[index]}\": ${system};`).join(\"\\n\")}\n};\n`;\n\n const SystemAbis = `// Autogenerated using mud system-types\n${abis.map((path, index) => `import ${systems[index]} from \"${path}\";`).join(\"\\n\")}\n\nexport const SystemAbis = {\n${systems.map((system, index) => ` \"${ids[index]}\": ${system}.abi,`).join(\"\\n\")}\n};\n`;\n\n console.log(\"Generating files:\");\n console.log(\"SystemTypes.ts\", SystemTypes);\n console.log(\"SystemAbis.mts\", SystemAbis);\n console.log(\"SystemMappings.ts\", SystemMappings);\n\n writeFileSync(`${outputDir}/SystemTypes.ts`, SystemTypes);\n writeFileSync(`${outputDir}/SystemAbis.mts`, SystemAbis);\n writeFileSync(`${outputDir}/SystemAbis.mjs`, SystemAbis);\n writeFileSync(`${outputDir}/SystemMappings.ts`, SystemMappings);\n}\n\n/**\n * @param abiDir If not provided, the contracts are built and abis are exported to ./abi\n */\nexport async function generateTypes(abiDir?: string, outputDir = \"./types\", options?: { clear?: boolean }) {\n if (!abiDir) {\n console.log(\"Compiling contracts\");\n const buildOutput = await getOutDirectory();\n abiDir = \"./abi\";\n await forgeBuild(options);\n filterAbi(buildOutput, abiDir);\n }\n\n await generateAbiTypes(abiDir, path.join(outputDir, \"ethers-contracts\"), options);\n await generateSystemTypes(outputDir, options);\n}\n","import { execa } from \"execa\";\nimport { copyFileSync, mkdirSync, readdirSync, rmSync } from \"fs\";\nimport path from \"path\";\nimport { getOutDirectory } from \"@latticexyz/common/foundry\";\n\nexport async function forgeBuild(options?: { clear?: boolean }) {\n if (options?.clear) {\n const out = await getOutDirectory();\n console.log(\"Clearing forge build output directory\", out);\n rmSync(out, { recursive: true, force: true });\n }\n\n console.log(\"Running forge build\");\n const child = execa(\"forge\", [\"build\"], {\n stdio: [\"inherit\", \"pipe\", \"inherit\"],\n });\n\n return (await child).stdout;\n}\n\nfunction getContractsInDirectory(dir: string, exclude?: string[]) {\n return readdirSync(dir)\n .filter((item) => item.includes(\".sol\"))\n .map((item) => item.replace(\".sol\", \"\"))\n .filter((item) => !exclude?.includes(item));\n}\n\nfunction copyAbi(inDir: string, outDir: string, contract: string) {\n try {\n return copyFileSync(path.join(inDir, contract + \".sol\", contract + \".json\"), path.join(outDir, contract + \".json\"));\n } catch (e) {\n console.log(\"Skipping\", contract);\n }\n}\n\nexport function filterAbi(abiIn = \"./out\", abiOut = \"./abi\", exclude: string[] = [\"Component\", \"IComponent\"]) {\n // Clean our dir\n console.log(`Cleaning output directory (${abiOut}})`);\n rmSync(abiOut, { recursive: true, force: true });\n mkdirSync(abiOut);\n\n // Only include World, LibQuery, *Component, *System\n const include = [\"Component\", \"System\", \"World\", \"LibQuery\"];\n const contracts = getContractsInDirectory(abiIn, exclude).filter((item) => include.find((i) => item.includes(i)));\n\n console.log(\"Selected ABIs: \", contracts);\n\n // Move selected ABIs to ./abi\n for (const contract of contracts) {\n if (contract.includes(\".t\")) continue;\n copyAbi(abiIn, abiOut, contract);\n }\n\n console.log(\"Successfully moved selected ABIs to ./abi\");\n}\n","export const systemsDir = \"systems\";\nexport const componentsDir = \"components\";\n","import chokidar from \"chokidar\";\nimport { readFileSync } from \"fs\";\n\nconst ImportsRegex = new RegExp(/(?<=import \").*(?=\";)|(?<=from \").*(?=\";)/g);\n\n/**\n * Extract file imports from a given file\n * @param path File to extracts imports from\n * @returns Array of imported filenames\n */\nfunction extractImports(path: string): string[] {\n const content = readFileSync(path).toString();\n const regexResult = [...content.matchAll(ImportsRegex)]\n .map((match) => match[0])\n .map((path) => path.split(\"/\").at(-1)!);\n return regexResult;\n}\n\nfunction findDependencies(\n file: string,\n dependencyGraph: { [file: string]: string[] },\n visited: string[] = []\n): string[] {\n const dependencies = dependencyGraph[file] ?? [];\n const subDependencies = dependencies.flatMap((d) => {\n if (visited.includes(d)) {\n console.warn(\"Circular dependency detected: \", d, dependencyGraph[d]);\n return [];\n }\n return findDependencies(d, dependencyGraph, [...visited, d]);\n });\n return [...new Set([...dependencies, ...subDependencies])];\n}\n\n// Hot System Replacement\nexport function hsr(root: string, replaceSystems: (systems: string[]) => Promise<unknown>) {\n const dependencyGraph: { [file: string]: string[] } = {};\n const systems = new Set<string>();\n\n console.log(\"Watching system file changes...\");\n\n chokidar.watch(root).on(\"all\", async (event, path) => {\n console.log(`[${event}]: ${path}`);\n\n // Find changed file\n const changedFile = path.split(\"/\").at(-1)!;\n\n if ([\"add\", \"change\"].includes(event)) {\n // Construct dependency graph based in file imports\n const imports = extractImports(path);\n for (const importedFile of imports) {\n dependencyGraph[importedFile] ??= [];\n dependencyGraph[importedFile].push(changedFile);\n }\n\n // Track system files\n if (path.includes(\"systems\") && path.includes(\".sol\")) systems.add(changedFile);\n }\n\n if (event === \"change\") {\n // Find all files depending on the changed file\n const dependencies = findDependencies(changedFile, dependencyGraph);\n const changedSystems = [\n ...new Set([changedFile, ...dependencies].filter((f) => systems.has(f)).map((f) => f.replace(\".sol\", \"\"))),\n ];\n console.log(\"Systems to replace\", changedSystems);\n if (changedSystems.length > 0) await replaceSystems(changedSystems);\n console.log(\"Watching system file changes...\");\n }\n });\n}\n","import type { CommandModule } from \"yargs\";\nimport { FaucetServiceDefinition } from \"@latticexyz/services/faucet\";\nimport { createChannel, createClient } from \"nice-grpc-web\";\nimport chalk from \"chalk\";\nimport { NodeHttpTransport } from \"@improbable-eng/grpc-web-node-http-transport\";\n\ntype Options = {\n dripDev?: boolean;\n faucetUrl: string;\n address: string;\n};\n\n/**\n * Create a FaucetServiceClient\n * @param url FaucetService URL\n * @returns FaucetServiceClient\n */\nfunction createFaucetService(url: string) {\n return createClient(FaucetServiceDefinition, createChannel(url, NodeHttpTransport()));\n}\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"faucet\",\n\n describe: \"Interact with a MUD faucet\",\n\n builder(yargs) {\n return yargs.options({\n dripDev: {\n type: \"boolean\",\n desc: \"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)\",\n default: true,\n },\n faucetUrl: {\n type: \"string\",\n desc: \"URL of the MUD faucet\",\n default: \"https://faucet.testnet-mud-services.linfra.xyz\",\n },\n address: {\n type: \"string\",\n desc: \"Ethereum address to fund\",\n required: true,\n },\n });\n },\n\n async handler({ dripDev, faucetUrl, address }) {\n const faucet = createFaucetService(faucetUrl);\n\n if (dripDev) {\n console.log(chalk.yellow(\"Dripping to\", address));\n await faucet.dripDev({ address });\n console.log(chalk.yellow(\"Success\"));\n }\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { readFileSync, writeFileSync, rmSync } from \"fs\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { table, getBorderCharacters } from \"table\";\n\n/**\n * Print the gas report to the console, save it to a file and compare it to a previous gas report if provided.\n * Requires forge to be installed, and gas test files including `// !gasreport` comments, like this:\n *\n * ```solidity\n * contract GasTest is DSTestPlus {\n * function testBuffer() public pure {\n * // !gasreport allocate a buffer\n * Buffer buffer = Buffer_.allocate(32);\n *\n * bytes32 value = keccak256(\"some data\");\n *\n * // !gasreport append 32 bytes to a buffer\n * buffer.append(value);\n * }\n * }\n * ```\n */\n\ntype Options = {\n path: string[];\n save?: string;\n compare?: string;\n};\n\ntype GasReportEntry = {\n source: string;\n name: string;\n functionCall: string;\n gasUsed: number;\n prevGasUsed?: number;\n};\n\ntype GasReport = GasReportEntry[];\n\nconst tempFileSuffix = \"MudGasReport\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"gas-report\",\n\n describe: \"Create a gas report\",\n\n builder(yargs) {\n return yargs.options({\n path: { type: \"array\", string: true, default: [\"Gas.t.sol\"], desc: \"File containing the gas tests\" },\n save: { type: \"string\", desc: \"Save the gas report to a file\" },\n compare: { type: \"string\", desc: \"Compare to an existing gas report\" },\n });\n },\n\n async handler({ path: files, save, compare }) {\n const validFiles = files.filter((file) => file.endsWith(\".t.sol\"));\n const tempFiles = await Promise.all(validFiles.map((file) => createGasReport(file)));\n\n process.once(\"SIGINT\", () => {\n console.log(\"caught sigint, deleting temp files\");\n tempFiles.forEach((file) => rmSync(file));\n });\n\n let gasReport: GasReport;\n try {\n gasReport = await runGasReport();\n } catch {\n setTimeout(() => process.exit());\n return;\n } finally {\n // Delete the temporary files\n tempFiles.forEach((file) => rmSync(file));\n }\n\n // If this gas report should be compared to an existing one, load the existing one\n if (compare) {\n try {\n const compareGasReport: GasReport = JSON.parse(readFileSync(compare, \"utf8\"));\n // Merge the previous gas report with the new one\n gasReport = gasReport.map((entry) => {\n const prevEntry = compareGasReport.find(\n (e) => e.name === entry.name && e.functionCall === entry.functionCall\n );\n return { ...entry, prevGasUsed: prevEntry?.gasUsed };\n });\n } catch {\n console.log(chalk.red(`Gas report to compare not found: ${compare}`));\n compare = undefined;\n }\n }\n\n // Print gas report\n printGasReport(gasReport, compare);\n\n // Save gas report to file if requested\n if (save) saveGasReport(gasReport, save);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n\nasync function createGasReport(filename: string): Promise<string> {\n console.log(\"Creating gas report for\", chalk.bold(filename));\n\n // Parse the given test file, and add gas reporting wherever requested by a `// !gasreport` comment\n const fileContents = readFileSync(filename, \"utf8\");\n let newFile = fileContents;\n\n // Use a regex to find first line of each function\n const functionRegex = new RegExp(/function (.*){/g);\n // Insert a line to declare the _gasreport variable at the start of each function\n let functionMatch;\n while ((functionMatch = functionRegex.exec(fileContents)) !== null) {\n const functionSignature = functionMatch[0];\n newFile = newFile.replace(functionSignature, `${functionSignature}\\nuint256 _gasreport;`);\n }\n\n // A gasreport comment has a name (written after the comment) and a function call (written on the next line)\n // Create a regex to extract both the name and the function call\n const regex = new RegExp(/\\/\\/ !gasreport (.*)\\n(.*)/g);\n\n // Apply the regex and loop through the matches,\n // and create a new file with the gasreport comments replaced by the gas report\n let match;\n while ((match = regex.exec(fileContents)) !== null) {\n const name = match[1];\n const functionCall = match[2].trim();\n\n newFile = newFile.replace(\n match[0],\n `\n_gasreport = gasleft();\n${functionCall}\n_gasreport = _gasreport - gasleft();\nconsole.log(\"GAS REPORT(${filename}): ${name} [${functionCall.replaceAll('\"', '\\\\\"')}]:\", _gasreport);`\n );\n }\n\n // Remove all occurrences of `pure` with `view`\n newFile = newFile.replace(/pure/g, \"view\");\n\n // Write the new file to disk (temporarily)\n // Create the temp file by replacing the previous file name with MudGasReport\n const tempFileName = filename.replace(/\\.t\\.sol$/, `${tempFileSuffix}.t.sol`);\n writeFileSync(tempFileName, newFile);\n\n return tempFileName;\n}\n\nasync function runGasReport(): Promise<GasReport> {\n console.log(\"Running gas report\");\n const gasReport: GasReport = [];\n\n // Extract the logs from the child process\n let logs = \"\";\n try {\n // Run the generated file using forge\n const child = execa(\"forge\", [\"test\", \"--match-path\", `*${tempFileSuffix}*`, \"-vvv\"], {\n stdio: [\"inherit\", \"pipe\", \"inherit\"],\n });\n logs = (await child).stdout;\n } catch (error: any) {\n console.log(error.stdout ?? error);\n console.log(chalk.red(\"\\n-----------\\nError while running the gas report (see above)\"));\n throw error;\n }\n\n // Extract the gas reports from the logs\n\n // Create a regex to find all lines starting with `GAS REPORT:` and extract the name, function call and gas used\n const gasReportRegex = new RegExp(/GAS REPORT\\((.*)\\): (.*) \\[(.*)\\]: (.*)/g);\n\n // Loop through the matches and print the gas report\n let gasReportMatch;\n while ((gasReportMatch = gasReportRegex.exec(logs)) !== null) {\n const source = gasReportMatch[1];\n const name = gasReportMatch[2];\n const functionCall = gasReportMatch[3].replace(\";\", \"\");\n const gasUsed = parseInt(gasReportMatch[4]);\n gasReport.push({ source, name, functionCall, gasUsed });\n }\n\n gasReport.sort((a, b) => a.source.localeCompare(b.source));\n\n return gasReport;\n}\n\nfunction printGasReport(gasReport: GasReport, compare?: string) {\n if (compare) console.log(chalk.bold(`Gas report compared to ${compare}`));\n\n const headers = [\n chalk.bold(\"Source\"),\n chalk.bold(\"Name\"),\n chalk.bold(\"Function call\"),\n chalk.bold(\"Gas used\"),\n ...(compare ? [chalk.bold(\"Prev gas used\"), chalk.bold(\"Difference\")] : []),\n ];\n\n const values = gasReport.map((entry) => {\n const diff = entry.prevGasUsed ? entry.gasUsed - entry.prevGasUsed : 0;\n const diffEntry = diff > 0 ? chalk.red(`+${diff}`) : diff < 0 ? chalk.green(`${diff}`) : diff;\n const compareColumns = compare ? [entry.prevGasUsed ?? \"n/a\", diffEntry] : [];\n const gasUsedEntry = diff > 0 ? chalk.red(entry.gasUsed) : diff < 0 ? chalk.green(entry.gasUsed) : entry.gasUsed;\n return [entry.source, entry.name, entry.functionCall, gasUsedEntry, ...compareColumns];\n });\n\n const rows = [headers, ...values];\n\n console.log(table(rows, { border: getBorderCharacters(\"norc\") }));\n}\n\nfunction saveGasReport(gasReport: GasReport, path: string) {\n console.log(chalk.bold(`Saving gas report to ${path}`));\n writeFileSync(path, `${JSON.stringify(gasReport, null, 2)}\\n`);\n}\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 path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig, tablegen } from \"@latticexyz/store\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\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 config file\" },\n });\n },\n\n async handler({ configPath }) {\n const config = (await loadConfig(configPath)) as StoreConfig;\n const srcDir = await getSrcDirectory();\n\n await tablegen(config, path.join(srcDir, config.codegenDirectory));\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { tsgen } from \"../render-ts/tsgen\";\n\ntype Options = {\n configPath: string;\n out: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"tsgen\",\n\n describe: \"Autogenerate MUD typescript definitions based on the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", demandOption: true, desc: \"Path to the config file\" },\n out: { type: \"string\", demandOption: true, desc: \"Directory to output MUD typescript definition files\" },\n });\n },\n\n async handler(args) {\n const { configPath, out } = args;\n\n const config = (await loadConfig(configPath)) as StoreConfig;\n\n await tsgen(config, out);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport glob from \"glob\";\nimport path, { basename } from \"path\";\nimport type { CommandModule, Options } from \"yargs\";\nimport { loadConfig, MUDError } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { deploy } from \"../utils/deploy-v2\";\nimport { logError } from \"../utils/errors\";\nimport { forge, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { mkdirSync, writeFileSync } from \"fs\";\nimport { getChainId } from \"../utils/getChainId\";\n\nexport type DeployOptions = {\n configPath?: string;\n printConfig?: boolean;\n profile?: string;\n priorityFeeMultiplier: number;\n clean?: boolean;\n debug?: boolean;\n saveDeployment?: boolean;\n rpc?: string;\n worldAddress?: string;\n srcDir?: string;\n};\n\nexport const yDeployOptions = {\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n clean: { type: \"boolean\", desc: \"Remove the build forge artifacts and cache directories before building\" },\n printConfig: { type: \"boolean\", desc: \"Print the resolved config\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n debug: { type: \"boolean\", desc: \"Print debug logs, like full error messages\" },\n priorityFeeMultiplier: {\n type: \"number\",\n desc: \"Multiply the estimated priority fee by the provided factor\",\n default: 1,\n },\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 worldAddress: { type: \"string\", desc: \"Deploy to an existing World at the given address\" },\n srcDir: { type: \"string\", desc: \"Source directory. Defaults to foundry src directory.\" },\n} satisfies Record<keyof DeployOptions, Options>;\n\nexport async function deployHandler(args: Parameters<(typeof commandModule)[\"handler\"]>[0]) {\n args.profile = args.profile ?? process.env.FOUNDRY_PROFILE;\n const { configPath, printConfig, profile, clean } = args;\n\n const rpc = args.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Deploying MUD v2 contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`)\n )\n );\n\n if (clean) await forge([\"clean\"], { profile });\n\n // Run forge build\n await forge([\"build\"], { profile });\n\n // Get a list of all contract names\n const srcDir = args?.srcDir ?? (await getSrcDirectory());\n const existingContracts = glob\n .sync(`${srcDir}/**/*.sol`)\n // Get the basename of the file\n .map((path) => basename(path, \".sol\"));\n\n // Load the config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n if (printConfig) console.log(chalk.green(\"\\nResolved config:\\n\"), JSON.stringify(mudConfig, null, 2));\n\n try {\n const privateKey = process.env.PRIVATE_KEY;\n if (!privateKey) throw new MUDError(\"Missing PRIVATE_KEY environment variable\");\n const deploymentInfo = await deploy(mudConfig, existingContracts, { ...args, rpc, privateKey });\n\n if (args.saveDeployment) {\n // Write deployment result to file (latest and timestamp)\n const chainId = await getChainId(rpc);\n const outputDir = path.join(mudConfig.deploysDirectory, chainId.toString());\n mkdirSync(outputDir, { recursive: true });\n writeFileSync(path.join(outputDir, \"latest.json\"), JSON.stringify(deploymentInfo, null, 2));\n writeFileSync(path.join(outputDir, Date.now() + \".json\"), JSON.stringify(deploymentInfo, null, 2));\n\n console.log(chalk.bgGreen(chalk.whiteBright(`\\n Deployment result (written to ${outputDir}): \\n`)));\n }\n\n console.log(deploymentInfo);\n return deploymentInfo;\n } catch (error: any) {\n logError(error);\n process.exit(1);\n }\n}\n\nconst commandModule: CommandModule<DeployOptions, DeployOptions> = {\n command: \"deploy-v2\",\n\n describe: \"Deploy MUD v2 contracts\",\n\n builder(yargs) {\n return yargs.options(yDeployOptions);\n },\n\n async handler(args) {\n await deployHandler(args);\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { existsSync, readFileSync } from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { BigNumber, ContractInterface, ethers } from \"ethers\";\nimport { defaultAbiCoder as abi, Fragment, ParamType } from \"ethers/lib/utils.js\";\n\nimport { getOutDirectory, getScriptDirectory, cast, forge } from \"@latticexyz/common/foundry\";\nimport { resolveWithContext } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/config\";\nimport { encodeSchema } from \"@latticexyz/schema-type\";\nimport { StoreConfig, resolveAbiOrUserType } from \"@latticexyz/store\";\nimport { WorldConfig, resolveWorldConfig } from \"@latticexyz/world\";\nimport { IBaseWorld } from \"@latticexyz/world/types/ethers-contracts/IBaseWorld\";\n\nimport WorldData from \"@latticexyz/world/abi/World.sol/World.json\" assert { type: \"json\" };\nimport IBaseWorldData from \"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json\" assert { type: \"json\" };\nimport CoreModuleData from \"@latticexyz/world/abi/CoreModule.sol/CoreModule.json\" assert { type: \"json\" };\nimport KeysWithValueModuleData from \"@latticexyz/world/abi/KeysWithValueModule.sol/KeysWithValueModule.json\" assert { type: \"json\" };\nimport KeysInTableModuleData from \"@latticexyz/world/abi/KeysInTableModule.sol/KeysInTableModule.json\" assert { type: \"json\" };\nimport UniqueEntityModuleData from \"@latticexyz/world/abi/UniqueEntityModule.sol/UniqueEntityModule.json\" assert { type: \"json\" };\n\nexport interface DeployConfig {\n profile?: string;\n rpc: string;\n privateKey: string;\n priorityFeeMultiplier: number;\n debug?: boolean;\n worldAddress?: string;\n}\n\nexport interface DeploymentInfo {\n blockNumber: number;\n worldAddress: string;\n}\n\nexport async function deploy(\n mudConfig: StoreConfig & WorldConfig,\n existingContracts: string[],\n deployConfig: DeployConfig\n): Promise<DeploymentInfo> {\n const resolvedConfig = resolveWorldConfig(mudConfig, existingContracts);\n\n const startTime = Date.now();\n const { worldContractName, namespace, postDeployScript } = mudConfig;\n const { profile, rpc, privateKey, priorityFeeMultiplier, debug, worldAddress } = deployConfig;\n const forgeOutDirectory = await getOutDirectory(profile);\n\n // Set up signer for deployment\n const provider = new ethers.providers.StaticJsonRpcProvider(rpc);\n const signer = new ethers.Wallet(privateKey, provider);\n\n // Manual nonce handling to allow for faster sending of transactions without waiting for previous transactions\n let nonce = await signer.getTransactionCount();\n console.log(\"Initial nonce\", nonce);\n\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n let maxPriorityFeePerGas: number;\n let maxFeePerGas: BigNumber;\n setInternalFeePerGas(priorityFeeMultiplier);\n\n // Catch all to await any promises before exiting the script\n let promises: Promise<unknown>[] = [];\n\n // Get block number before deploying\n const blockNumber = Number(await cast([\"block-number\", \"--rpc-url\", rpc], { profile }));\n console.log(\"Start deployment at block\", blockNumber);\n\n // Deploy World\n const worldPromise = {\n World: worldAddress\n ? Promise.resolve(worldAddress)\n : worldContractName\n ? deployContractByName(worldContractName)\n : deployContract(IBaseWorldData.abi, WorldData.bytecode, \"World\"),\n };\n\n // Deploy Systems\n const systemPromises = Object.keys(resolvedConfig.systems).reduce<Record<string, Promise<string>>>(\n (acc, systemName) => {\n acc[systemName] = deployContractByName(systemName);\n return acc;\n },\n {}\n );\n\n // Deploy default World modules\n const defaultModules: Record<string, Promise<string>> = {\n // TODO: these only need to be deployed once per chain, add a check if they exist already\n CoreModule: deployContract(CoreModuleData.abi, CoreModuleData.bytecode, \"CoreModule\"),\n KeysWithValueModule: deployContract(\n KeysWithValueModuleData.abi,\n KeysWithValueModuleData.bytecode,\n \"KeysWithValueModule\"\n ),\n KeysInTableModule: deployContract(KeysInTableModuleData.abi, KeysInTableModuleData.bytecode, \"KeysInTableModule\"),\n UniqueEntityModule: deployContract(\n UniqueEntityModuleData.abi,\n UniqueEntityModuleData.bytecode,\n \"UniqueEntityModule\"\n ),\n };\n\n // Deploy user Modules\n const modulePromises = mudConfig.modules\n .filter((module) => !defaultModules[module.name]) // Only deploy user modules here, not default modules\n .reduce<Record<string, Promise<string>>>((acc, module) => {\n acc[module.name] = deployContractByName(module.name);\n return acc;\n }, defaultModules);\n\n // Combine all contracts into one object\n const contractPromises: Record<string, Promise<string>> = { ...worldPromise, ...systemPromises, ...modulePromises };\n\n // Create World contract instance from deployed address\n const WorldContract = new ethers.Contract(await contractPromises.World, IBaseWorldData.abi, signer) as IBaseWorld;\n\n // Install core Modules\n if (!worldAddress) {\n console.log(chalk.blue(\"Installing core World modules\"));\n await fastTxExecute(WorldContract, \"installRootModule\", [await modulePromises.CoreModule, \"0x\"]);\n console.log(chalk.green(\"Installed core World modules\"));\n }\n\n // Register namespace\n if (namespace) await fastTxExecute(WorldContract, \"registerNamespace\", [toBytes16(namespace)]);\n\n // Register tables\n const tableIds: { [tableName: string]: Uint8Array } = {};\n promises = [\n ...promises,\n ...Object.entries(mudConfig.tables).map(async ([tableName, { name, schema, primaryKeys }]) => {\n console.log(chalk.blue(`Registering table ${tableName} at ${namespace}/${name}`));\n\n // Store the tableId for later use\n tableIds[tableName] = toResourceSelector(namespace, name);\n\n // Register table\n const schemaTypes = Object.values(schema).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);\n return schemaType;\n });\n\n const keyTypes = Object.values(primaryKeys).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);\n return schemaType;\n });\n\n await fastTxExecute(WorldContract, \"registerTable\", [\n toBytes16(namespace),\n toBytes16(name),\n encodeSchema(schemaTypes),\n encodeSchema(keyTypes),\n ]);\n\n // Register table metadata\n await fastTxExecute(WorldContract, \"setMetadata(bytes16,bytes16,string,string[])\", [\n toBytes16(namespace),\n toBytes16(name),\n tableName,\n Object.keys(schema),\n ]);\n\n console.log(chalk.green(`Registered table ${tableName} at ${name}`));\n }),\n ];\n\n // Register systems (using forEach instead of for..of to avoid blocking on async calls)\n promises = [\n ...promises,\n ...Object.entries(resolvedConfig.systems).map(\n async ([systemName, { name, openAccess, registerFunctionSelectors }]) => {\n // Register system at route\n console.log(chalk.blue(`Registering system ${systemName} at ${namespace}/${name}`));\n await fastTxExecute(WorldContract, \"registerSystem\", [\n toBytes16(namespace),\n toBytes16(name),\n await contractPromises[systemName],\n openAccess,\n ]);\n console.log(chalk.green(`Registered system ${systemName} at ${namespace}/${name}`));\n\n // Register function selectors for the system\n if (registerFunctionSelectors) {\n const functionSignatures: FunctionSignature[] = await loadFunctionSignatures(systemName);\n const isRoot = namespace === \"\";\n // Using Promise.all to avoid blocking on async calls\n await Promise.all(\n functionSignatures.map(async ({ functionName, functionArgs }) => {\n const functionSignature = isRoot\n ? functionName + functionArgs\n : `${namespace}_${name}_${functionName}${functionArgs}`;\n\n console.log(chalk.blue(`Registering function \"${functionSignature}\"`));\n if (isRoot) {\n const worldFunctionSelector = toFunctionSelector(\n functionSignature === \"\"\n ? { functionName: systemName, functionArgs } // Register the system's fallback function as `<systemName>(<args>)`\n : { functionName, functionArgs }\n );\n const systemFunctionSelector = toFunctionSelector({ functionName, functionArgs });\n await fastTxExecute(WorldContract, \"registerRootFunctionSelector\", [\n toBytes16(namespace),\n toBytes16(name),\n worldFunctionSelector,\n systemFunctionSelector,\n ]);\n } else {\n await fastTxExecute(WorldContract, \"registerFunctionSelector\", [\n toBytes16(namespace),\n toBytes16(name),\n functionName,\n functionArgs,\n ]);\n }\n console.log(chalk.green(`Registered function \"${functionSignature}\"`));\n })\n );\n }\n }\n ),\n ];\n\n // Wait for resources to be registered before granting access to them\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Grant access to systems\n for (const [systemName, { name, accessListAddresses, accessListSystems }] of Object.entries(resolvedConfig.systems)) {\n const resourceSelector = `${namespace}/${name}`;\n\n // Grant access to addresses\n promises = [\n ...promises,\n ...accessListAddresses.map(async (address) => {\n console.log(chalk.blue(`Grant ${address} access to ${systemName} (${resourceSelector})`));\n await fastTxExecute(WorldContract, \"grantAccess\", [toBytes16(namespace), toBytes16(name), address]);\n console.log(chalk.green(`Granted ${address} access to ${systemName} (${namespace}/${name})`));\n }),\n ];\n\n // Grant access to other systems\n promises = [\n ...promises,\n ...accessListSystems.map(async (granteeSystem) => {\n console.log(chalk.blue(`Grant ${granteeSystem} access to ${systemName} (${resourceSelector})`));\n await fastTxExecute(WorldContract, \"grantAccess\", [\n toBytes16(namespace),\n toBytes16(name),\n await contractPromises[granteeSystem],\n ]);\n console.log(chalk.green(`Granted ${granteeSystem} access to ${systemName} (${resourceSelector})`));\n }),\n ];\n }\n\n // Wait for access to be granted before installing modules\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Install modules\n promises = [\n ...promises,\n ...mudConfig.modules.map(async (module) => {\n console.log(chalk.blue(`Installing${module.root ? \" root \" : \" \"}module ${module.name}`));\n // Resolve arguments\n const resolvedArgs = await Promise.all(\n module.args.map((arg) => resolveWithContext(arg, { tableIds, systemAddresses: contractPromises }))\n );\n const values = resolvedArgs.map((arg) => arg.value);\n const types = resolvedArgs.map((arg) => arg.type);\n const moduleAddress = await contractPromises[module.name];\n if (!moduleAddress) throw new Error(`Module ${module.name} not found`);\n\n // Send transaction to install module\n await fastTxExecute(WorldContract, module.root ? \"installRootModule\" : \"installModule\", [\n moduleAddress,\n abi.encode(types, values),\n ]);\n\n console.log(chalk.green(`Installed${module.root ? \" root \" : \" \"}module ${module.name}`));\n }),\n ];\n\n // Await all promises before executing PostDeploy script\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Execute postDeploy forge script\n const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + \".s.sol\");\n if (existsSync(postDeployPath)) {\n console.log(chalk.blue(`Executing post deploy script at ${postDeployPath}`));\n await forge(\n [\n \"script\",\n postDeployScript,\n \"--sig\",\n \"run(address)\",\n await contractPromises.World,\n \"--broadcast\",\n \"--rpc-url\",\n rpc,\n \"-vvv\",\n ],\n {\n profile,\n }\n );\n } else {\n console.log(`No script at ${postDeployPath}, skipping post deploy hook`);\n }\n\n console.log(chalk.green(\"Deployment completed in\", (Date.now() - startTime) / 1000, \"seconds\"));\n\n return { worldAddress: await contractPromises.World, blockNumber };\n\n // ------------------- INTERNAL FUNCTIONS -------------------\n // (Inlined to avoid having to pass around nonce, signer and forgeOutDir)\n\n /**\n * Deploy a contract and return the address\n * @param contractName Name of the contract to deploy (must exist in the file system)\n * @returns Address of the deployed contract\n */\n async function deployContractByName(contractName: string): Promise<string> {\n console.log(chalk.blue(\"Deploying\", contractName));\n\n const { abi, bytecode } = await getContractData(contractName);\n return deployContract(abi, bytecode, contractName);\n }\n\n /**\n * Deploy a contract and return the address\n * @param abi The contract interface\n * @param bytecode The contract bytecode\n * @param contractName The contract name (optional, used for logs)\n * @returns Address of the deployed contract\n */\n async function deployContract(\n abi: ContractInterface,\n bytecode: string | { object: string },\n contractName?: string,\n retryCount = 0\n ): Promise<string> {\n try {\n const factory = new ethers.ContractFactory(abi, bytecode, signer);\n console.log(chalk.gray(`executing deployment of ${contractName} with nonce ${nonce}`));\n const deployPromise = factory.deploy({\n nonce: nonce++,\n maxPriorityFeePerGas,\n maxFeePerGas,\n });\n promises.push(deployPromise);\n const { address } = await deployPromise;\n\n console.log(chalk.green(\"Deployed\", contractName, \"to\", address));\n return address;\n } catch (error: any) {\n if (debug) console.error(error);\n if (retryCount === 0 && error?.message.includes(\"transaction already imported\")) {\n // If the deployment failed because the transaction was already imported,\n // retry with a higher priority fee\n setInternalFeePerGas(priorityFeeMultiplier * 1.1);\n return deployContract(abi, bytecode, contractName, retryCount++);\n } else if (error?.message.includes(\"invalid bytecode\")) {\n throw new MUDError(\n `Error deploying ${contractName}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use \"external\" functions.`\n );\n } else if (error?.message.includes(\"CreateContractLimit\")) {\n throw new MUDError(`Error deploying ${contractName}: CreateContractLimit exceeded.`);\n } else throw error;\n }\n }\n\n /**\n * Deploy a contract and return the address\n * @param contractName Name of the contract to deploy (must exist in the file system)\n * @returns Address of the deployed contract\n *\n * NOTE: Forge deploy seems to be slightly slower than ethers\n * (probably due to the extra overhead spawning a child process to run forge),\n * so we mostly use ethersDeployContract here.\n * However, for contracts not in the user directory (eg. the vanilla World contract),\n * using forge is more convenient because it automatically finds the contract in the @latticexyz/world package.\n */\n // async function forgeDeployContract(contractName: string): Promise<string> {\n // console.log(chalk.blue(\"Deploying\", contractName));\n\n // const { deployedTo } = JSON.parse(\n // await forge(\n // [\"create\", contractName, \"--rpc-url\", rpc, \"--private-key\", privateKey, \"--json\", \"--nonce\", String(nonce++)],\n // { profile, silent: true }\n // )\n // );\n // return deployedTo;\n // }\n\n async function loadFunctionSignatures(contractName: string): Promise<FunctionSignature[]> {\n const { abi } = await getContractData(contractName);\n\n return abi\n .filter((item) => [\"fallback\", \"function\"].includes(item.type))\n .map((item) => {\n if (item.type === \"fallback\") return { functionName: \"\", functionArgs: \"\" };\n\n return {\n functionName: item.name,\n functionArgs: parseComponents(item.inputs),\n };\n });\n }\n\n /**\n * Recursively turn (nested) structs in signatures into tuples\n */\n function parseComponents(params: ParamType[]): string {\n const components = params.map((param) => (param.type === \"tuple\" ? parseComponents(param.components) : param.type));\n return `(${components})`;\n }\n\n /**\n * Only await gas estimation (for speed), only execute if gas estimation succeeds (for safety)\n */\n async function fastTxExecute<C extends { estimateGas: any; [key: string]: any }, F extends keyof C>(\n contract: C,\n func: F,\n args: Parameters<C[F]>,\n retryCount = 0,\n confirmations = 1\n ): Promise<Awaited<ReturnType<Awaited<ReturnType<C[F]>>[\"wait\"]>>> {\n const functionName = `${func as string}(${args.map((arg) => `'${arg}'`).join(\",\")})`;\n try {\n const gasLimit = await contract.estimateGas[func].apply(null, args);\n console.log(chalk.gray(`executing transaction: ${functionName} with nonce ${nonce}`));\n const txPromise = contract[func]\n .apply(null, [...args, { gasLimit, nonce: nonce++, maxPriorityFeePerGas, maxFeePerGas }])\n .then((tx: any) => tx.wait(confirmations));\n promises.push(txPromise);\n return txPromise;\n } catch (error: any) {\n if (debug) console.error(error);\n if (retryCount === 0 && error?.message.includes(\"transaction already imported\")) {\n // If the deployment failed because the transaction was already imported,\n // retry with a higher priority fee\n setInternalFeePerGas(priorityFeeMultiplier * 1.1);\n return fastTxExecute(contract, func, args, retryCount++, confirmations);\n } else throw new MUDError(`Gas estimation error for ${functionName}: ${error?.reason}`);\n }\n }\n\n /**\n * Load the contract's abi and bytecode from the file system\n * @param contractName: Name of the contract to load\n */\n async function getContractData(contractName: string): Promise<{ bytecode: string; abi: Fragment[] }> {\n let data: any;\n const contractDataPath = path.join(forgeOutDirectory, contractName + \".sol\", contractName + \".json\");\n try {\n data = JSON.parse(readFileSync(contractDataPath, \"utf8\"));\n } catch (error: any) {\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 abi = data?.abi;\n if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);\n\n return { abi, bytecode };\n }\n\n /**\n * Set the maxFeePerGas and maxPriorityFeePerGas based on the current base fee and the given multiplier.\n * The multiplier is used to allow replacing pending transactions.\n * @param multiplier Multiplier to apply to the base fee\n */\n async function setInternalFeePerGas(multiplier: number) {\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n const feeData = await provider.getFeeData();\n if (!feeData.lastBaseFeePerGas) throw new MUDError(\"Can not fetch lastBaseFeePerGas from RPC\");\n\n // Set the priority fee to 0 for development chains with no base fee, to allow transactions from unfunded wallets\n maxPriorityFeePerGas = feeData.lastBaseFeePerGas.eq(0) ? 0 : Math.floor(1_500_000_000 * multiplier);\n maxFeePerGas = feeData.lastBaseFeePerGas.mul(2).add(maxPriorityFeePerGas);\n }\n}\n\n// TODO: use stringToBytes16 from utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toBytes16(input: string) {\n if (input.length > 16) throw new Error(\"String does not fit into 16 bytes\");\n\n const result = new Uint8Array(16);\n // Set ascii bytes\n for (let i = 0; i < input.length; i++) {\n result[i] = input.charCodeAt(i);\n }\n // Set the remaining bytes to 0\n for (let i = input.length; i < 16; i++) {\n result[i] = 0;\n }\n return result;\n}\n\n// TODO: use TableId from utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toResourceSelector(namespace: string, file: string): Uint8Array {\n const namespaceBytes = toBytes16(namespace);\n const fileBytes = toBytes16(file);\n const result = new Uint8Array(32);\n result.set(namespaceBytes);\n result.set(fileBytes, 16);\n return result;\n}\n\ninterface FunctionSignature {\n functionName: string;\n functionArgs: string;\n}\n\n// TODO: move this to utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toFunctionSelector({ functionName, functionArgs }: FunctionSignature): string {\n const functionSignature = functionName + functionArgs;\n if (functionSignature === \"\") return \"0x\";\n return sigHash(functionSignature);\n}\n\n// TODO: move this to utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction sigHash(signature: string) {\n return ethers.utils.hexDataSlice(ethers.utils.keccak256(ethers.utils.toUtf8Bytes(signature)), 0, 4);\n}\n","import { ethers } from \"ethers\";\n\n// TODO: Use viem's getChainId\nexport async function getChainId(rpc: string) {\n const { result: chainId } = await ethers.utils.fetchJson(\n rpc,\n '{ \"id\": 42, \"jsonrpc\": \"2.0\", \"method\": \"eth_chainId\", \"params\": [ ] }'\n );\n return Number(chainId);\n}\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig, worldgen } from \"@latticexyz/world\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport glob from \"glob\";\nimport path, { basename } from \"path\";\nimport { rmSync } from \"fs\";\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 config file\" },\n clean: { type: \"boolean\", desc: \"Clear the worldgen directory before generating new interfaces\" },\n });\n },\n\n async handler(args) {\n const { configPath, clean } = args;\n const srcDir = await getSrcDirectory();\n\n // Get a list of all contract names\n const existingContracts = glob.sync(`${srcDir}/**/*.sol`).map((path) => ({\n path,\n basename: basename(path, \".sol\"),\n }));\n\n // Load the config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n const outputBaseDirectory = path.join(srcDir, mudConfig.codegenDirectory);\n\n // clear the worldgen directory\n if (clean) rmSync(path.join(outputBaseDirectory, mudConfig.worldgenDirectory), { recursive: true, force: true });\n\n // generate new interfaces\n await worldgen(mudConfig, existingContracts, outputBaseDirectory);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { MUDError } from \"@latticexyz/config\";\nimport { logError } from \"../utils/errors\";\nimport localPackageJson from \"../../package.json\" assert { type: \"json\" };\n\ntype Options = {\n backup?: boolean;\n force?: boolean;\n restore?: boolean;\n mudVersion?: string;\n link?: string;\n};\n\nconst BACKUP_FILE = \".mudbackup\";\nconst MUD_PREFIX = \"@latticexyz\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"set-version\",\n\n describe: \"Install a custom MUD version and optionally backup the previously installed version\",\n\n builder(yargs) {\n return yargs.options({\n backup: { type: \"boolean\", description: `Back up the current MUD versions to \"${BACKUP_FILE}\"` },\n force: {\n type: \"boolean\",\n description: `Backup fails if a \"${BACKUP_FILE}\" file is found, unless --force is provided`,\n },\n restore: { type: \"boolean\", description: `Restore the previous MUD versions from \"${BACKUP_FILE}\"` },\n mudVersion: { alias: \"v\", type: \"string\", description: \"The MUD version to install\" },\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 if (!options.mudVersion && !options.link && !options.restore) {\n throw new MUDError(\"`--mudVersion` or `--link` is required unless --restore is provided.\");\n }\n\n // `link` and `mudVersion` are mutually exclusive\n if (options.link && options.mudVersion) {\n throw new MUDError(\"Options `--link` and `--mudVersion` are mutually exclusive\");\n }\n\n // Resolve the `canary` version number if needed\n options.mudVersion =\n options.mudVersion === \"canary\" ? await getCanaryVersion(localPackageJson.name) : options.mudVersion;\n\n // Read the current package.json\n const rootPath = \"./package.json\";\n const { workspaces } = updatePackageJson(rootPath, options);\n\n // Load the package.json of each workspace\n if (workspaces) {\n for (const workspace of workspaces) {\n const filePath = path.join(workspace, \"/package.json\");\n updatePackageJson(filePath, options);\n }\n }\n } catch (e) {\n logError(e);\n } finally {\n process.exit(0);\n }\n },\n};\n\nfunction updatePackageJson(filePath: string, options: Options): { workspaces?: string[] } {\n const { restore, force, link } = options;\n let { backup, mudVersion } = options;\n\n const backupFilePath = path.join(path.dirname(filePath), BACKUP_FILE);\n const backupFileExists = existsSync(backupFilePath);\n\n // Create a backup file for previous MUD versions by default if linking to local MUD\n if (link && !backupFileExists) backup = true;\n\n // If `backup` is true and force not set, check if a backup file already exists and throw an error if it does\n if (backup && !force && backupFileExists) {\n throw new MUDError(\n `A backup file already exists at ${backupFilePath}.\\nUse --force to overwrite it or --restore to restore it.`\n );\n }\n\n const packageJson = readPackageJson(filePath);\n\n // Load .mudbackup if `restore` is true\n const backupJson = restore ? readPackageJson(backupFilePath) : undefined;\n\n // Find all MUD dependencies\n const mudDependencies: Record<string, string> = {};\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDependencies[key] = packageJson.dependencies[key];\n }\n }\n\n // Find all MUD devDependencies\n const mudDevDependencies: Record<string, string> = {};\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDevDependencies[key] = packageJson.devDependencies[key];\n }\n }\n\n // Back up the current dependencies if `backup` is true\n if (backup) {\n writeFileSync(\n backupFilePath,\n JSON.stringify({ dependencies: mudDependencies, devDependencies: mudDevDependencies }, null, 2)\n );\n console.log(chalk.green(`Backed up MUD dependencies from ${filePath} to ${backupFilePath}`));\n }\n\n // Update the dependencies\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.dependencies[key] = resolveMudVersion(key, \"dependencies\");\n }\n }\n\n // Update the devDependencies\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.devDependencies[key] = resolveMudVersion(key, \"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 // Remove the backup file if `restore` is true and `backup` is false\n // because the old backup file is no longer needed\n if (restore && !backup) {\n rmSync(backupFilePath);\n console.log(chalk.green(`Cleaned up ${backupFilePath}`));\n }\n\n return packageJson;\n\n function resolveMudVersion(key: string, type: \"dependencies\" | \"devDependencies\") {\n if (restore && backupJson) return backupJson[type][key];\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\nasync function getCanaryVersion(pkg: string) {\n try {\n console.log(chalk.blue(\"fetching MUD canary version...\"));\n const result = await (await fetch(`https://registry.npmjs.org/${pkg}`)).json();\n const canary = result[\"dist-tags\"].canary;\n console.log(chalk.green(\"MUD canary version:\", canary));\n return canary;\n } catch (e) {\n throw new MUDError(`Could not fetch canary version of ${pkg}`);\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, pkg: string) {\n const pkgName = pkg.replace(MUD_PREFIX, \"\");\n const packageJsonToRootPath = path.relative(path.dirname(packageJsonPath), process.cwd());\n const linkPath = path.join(packageJsonToRootPath, mudLinkPath, \"packages\", pkgName);\n return \"link:\" + linkPath;\n}\n\nexport default commandModule;\n","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"1.42.0\",\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 \"types\": \"src/index.ts\",\n \"bin\": {\n \"mud\": \"./dist/mud.js\",\n \"mud2\": \"./dist/mud2.js\"\n },\n \"scripts\": {\n \"build\": \"pnpm run build:js\",\n \"build:js\": \"tsup && chmod +x ./dist/mud.js ./dist/mud2.js\",\n \"clean\": \"pnpm run clean:js\",\n \"clean:js\": \"rimraf dist\",\n \"dev\": \"tsup --watch\",\n \"generate-test-tables\": \"tsx ./scripts/generate-test-tables.ts\",\n \"lint\": \"eslint . --ext .ts\",\n \"release\": \"npm publish --access=public\",\n \"test\": \"tsc --noEmit && pnpm run generate-test-tables && forge test\"\n },\n \"dependencies\": {\n \"@ethersproject/abi\": \"^5.7.0\",\n \"@ethersproject/providers\": \"^5.7.2\",\n \"@improbable-eng/grpc-web\": \"^0.15.0\",\n \"@improbable-eng/grpc-web-node-http-transport\": \"^0.15.0\",\n \"@latticexyz/common\": \"workspace:*\",\n \"@latticexyz/config\": \"workspace:*\",\n \"@latticexyz/schema-type\": \"workspace:*\",\n \"@latticexyz/services\": \"workspace:*\",\n \"@latticexyz/solecs\": \"workspace:*\",\n \"@latticexyz/std-contracts\": \"workspace:*\",\n \"@latticexyz/store\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"@typechain/ethers-v5\": \"^10.2.0\",\n \"chalk\": \"^5.0.1\",\n \"chokidar\": \"^3.5.3\",\n \"dotenv\": \"^16.0.3\",\n \"ds-test\": \"https://github.com/dapphub/ds-test.git#c9ce3f25bde29fc5eb9901842bf02850dfd2d084\",\n \"ejs\": \"^3.1.8\",\n \"ethers\": \"^5.7.2\",\n \"execa\": \"^7.0.0\",\n \"forge-std\": \"https://github.com/foundry-rs/forge-std.git#b4f121555729b3afb3c5ffccb62ff4b6e2818fd3\",\n \"glob\": \"^8.0.3\",\n \"nice-grpc-web\": \"^2.0.1\",\n \"openurl\": \"^1.1.1\",\n \"path\": \"^0.12.7\",\n \"table\": \"^6.8.1\",\n \"typechain\": \"^8.1.1\",\n \"typescript\": \"^4.9.5\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"^3.21.4\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/ejs\": \"^3.1.1\",\n \"@types/glob\": \"^7.2.0\",\n \"@types/node\": \"^18.15.11\",\n \"@types/openurl\": \"^1.0.0\",\n \"@types/yargs\": \"^17.0.10\",\n \"tsup\": \"^6.7.0\",\n \"tsx\": \"^3.12.6\",\n \"vitest\": \"0.30.1\"\n },\n \"gitHead\": \"914a1e0ae4a573d685841ca2ea921435057deb8f\"\n}\n","import type { CommandModule } from \"yargs\";\nimport { deployHandler, DeployOptions, yDeployOptions } from \"./deploy-v2\";\nimport { anvil, forge, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { rmSync, writeFileSync } from \"fs\";\n\ntype Options = DeployOptions & { port?: number; worldAddress?: string; forgeOptions?: string };\n\nconst WORLD_ADDRESS_FILE = \".mudtest\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"test-v2\",\n\n describe: \"Run tests in MUD v2 contracts\",\n\n builder(yargs) {\n return yargs.options({\n ...yDeployOptions,\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 });\n },\n\n async handler(args) {\n // Start an internal anvil process if no world address is provided\n if (!args.worldAddress) {\n const anvilArgs = [\"--block-base-fee-per-gas\", \"0\", \"--port\", String(args.port)];\n anvil(anvilArgs);\n }\n\n const forkRpc = args.worldAddress ? await getRpcUrl(args.profile) : `http://127.0.0.1:${args.port}`;\n\n const worldAddress =\n args.worldAddress ??\n (\n await deployHandler({\n ...args,\n saveDeployment: false,\n rpc: forkRpc,\n })\n ).worldAddress;\n\n console.log(chalk.blue(\"World address\", worldAddress));\n\n // Create a temporary file to pass the world address to the tests\n writeFileSync(WORLD_ADDRESS_FILE, worldAddress);\n\n const userOptions = args.forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n try {\n const testResult = await forge([\"test\", \"--fork-url\", forkRpc, ...userOptions], {\n profile: args.profile,\n });\n console.log(testResult);\n } catch (e) {\n console.error(e);\n }\n\n rmSync(WORLD_ADDRESS_FILE);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import { CommandModule } from \"yargs\";\n\nimport devnode from \"./devnode\";\nimport faucet from \"./faucet\";\nimport gasReport from \"./gas-report\";\nimport hello from \"./hello\";\nimport tablegen from \"./tablegen\";\nimport tsgen from \"./tsgen\";\nimport deployV2 from \"./deploy-v2\";\nimport worldgen from \"./worldgen\";\nimport setVersion from \"./set-version\";\nimport testV2 from \"./test-v2\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each command has different options\nexport const commands: CommandModule<any, any>[] = [\n deployV2,\n devnode,\n faucet,\n gasReport,\n hello,\n tablegen,\n tsgen,\n worldgen,\n setVersion,\n testV2,\n];\n"],"mappings":"yCAAA,OAAOA,MAAW,QAClB,OAAS,YAAAC,OAAgB,MACzB,OAAS,gBAAAC,GAAc,mBAAAC,OAAuB,uBAC9C,OAAS,yBAAAC,OAA6B,qBACtC,OAAS,YAAAC,OAAgB,qBAElB,SAASC,EAASC,EAAgB,CACvC,GAAIA,aAAiBJ,GACnB,QAAQ,IAAIH,EAAM,UAAUO,EAAM,OAAO,CAAC,UACjCA,aAAiBN,GAAU,CAGpC,IAAM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GAAiD,CACrD,QAAS,UAET,SAAU,gCAEV,QAAQC,EAAO,CACb,OAAOA,EAAM,QAAQ,CACnB,GAAGC,GACH,KAAM,CAAE,KAAM,SAAU,YAAa,gDAAiD,QAAS,IAAK,EACpG,aAAc,CACZ,KAAM,SACN,YACE,8IACJ,EACA,aAAc,CAAE,KAAM,SAAU,YAAa,+BAAgC,CAC/E,CAAC,CACH,EAEA,MAAM,QAAQC,EAAM,CAElB,GAAI,CAACA,EAAK,aAAc,CACtB,IAAMC,EAAY,CAAC,2BAA4B,IAAK,SAAU,OAAOD,EAAK,IAAI,CAAC,EAC/EV,GAAMW,CAAS,EAGjB,IAAMC,EAAUF,EAAK,aAAe,MAAMR,GAAUQ,EAAK,OAAO,EAAI,oBAAoBA,EAAK,OAEvFG,EACJH,EAAK,eAEH,MAAMI,GAAc,CAClB,GAAGJ,EACH,eAAgB,GAChB,IAAKE,CACP,CAAC,GACD,aAEJ,QAAQ,IAAIT,GAAM,KAAK,gBAAiBU,CAAY,CAAC,EAGrDR,GAAcC,GAAoBO,CAAY,EAE9C,IAAME,EAAcL,EAAK,cAAc,WAAW,KAAM,EAAE,EAAE,MAAM,GAAG,GAAK,CAAC,EAC3E,GAAI,CACF,IAAMM,EAAa,MAAMf,GAAM,CAAC,OAAQ,aAAcW,EAAS,GAAGG,CAAW,EAAG,CAC9E,QAASL,EAAK,OAChB,CAAC,EACD,QAAQ,IAAIM,CAAU,CACxB,OAASC,EAAP,CACA,QAAQ,MAAMA,CAAC,CACjB,CAEAb,GAAOE,EAAkB,EAEzB,QAAQ,KAAK,CAAC,CAChB,CACF,EAEOY,GAAQX,GCtDR,IAAMY,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EACF","names":["chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError","rmSync","homedir","path","execa","execLog","command","options","keccak256Bytes","toUtf8Bytes","readFileSync","IDregex","extractIdFromFile","path","content","regexResult","keccak256","data","readFile","writeFile","ejs","path","contractsDirectory","stubLibDeploy","generateLibDeploy","configPath","out","systems","config","systemsArray","system","LibDeploy","libDeployPath","resetLibDeploy","constants","Wallet","findLog","deployLogLines","log","logLine","runTypeChain","typechainGlob","glob","rmSync","writeFileSync","path","execa","copyFileSync","mkdirSync","readdirSync","rmSync","path","getOutDirectory","forgeBuild","options","out","getContractsInDirectory","dir","exclude","item","copyAbi","inDir","outDir","contract","filterAbi","abiIn","abiOut","include","contracts","getOutDirectory","getSrcDirectory","systemsDir","componentsDir","generateAbiTypes","inputDir","outputDir","options","rmSync","cwd","allFiles","typechainGlob","result","runTypeChain","generateSystemTypes","path","abis","systems","ids","typePaths","srcDir","getSrcDirectory","systemsPath","systemsDir","matches","glob","fragments","index","id","extractIdFromFile","system","SystemMappings","SystemTypes","SystemAbis","writeFileSync","generateTypes","abiDir","buildOutput","getOutDirectory","forgeBuild","filterAbi","execa","StaticJsonRpcProvider","path","contractsDirectory","deploy","deployerPrivateKey","rpc","worldAddress","reuseComponents","gasPrice","address","Wallet","constants","child","data","lines","deployedWorldAddress","findLog","initialBlockNumber","generateAndDeploy","args","libDeployPath","generateLibDeploy","generateTypes","result","resetLibDeploy","chokidar","readFileSync","ImportsRegex","extractImports","path","match","findDependencies","file","dependencyGraph","visited","dependencies","subDependencies","d","hsr","root","replaceSystems","systems","event","changedFile","imports","importedFile","changedSystems","f","commandModule","yargs","blocktime","userHomeDir","homedir","rmSync","path","child","execLog","devnode_default","FaucetServiceDefinition","createChannel","createClient","chalk","NodeHttpTransport","createFaucetService","url","commandModule","yargs","dripDev","faucetUrl","address","faucet","faucet_default","readFileSync","writeFileSync","rmSync","execa","chalk","table","getBorderCharacters","tempFileSuffix","commandModule","yargs","files","save","compare","validFiles","file","tempFiles","createGasReport","gasReport","runGasReport","compareGasReport","entry","prevEntry","e","printGasReport","saveGasReport","gas_report_default","filename","fileContents","newFile","functionRegex","functionMatch","functionSignature","regex","match","name","functionCall","tempFileName","logs","error","gasReportRegex","gasReportMatch","source","gasUsed","a","b","headers","values","diff","diffEntry","compareColumns","gasUsedEntry","rows","path","commandModule","yargs","name","greeting","hello_default","path","loadConfig","tablegen","getSrcDirectory","commandModule","yargs","configPath","config","srcDir","tablegen_default","loadConfig","commandModule","yargs","args","configPath","out","config","loadConfig","tsgen","tsgen_default","chalk","glob","path","basename","loadConfig","MUDError","existsSync","readFileSync","path","chalk","ethers","abi","getOutDirectory","getScriptDirectory","cast","forge","resolveWithContext","MUDError","encodeSchema","resolveAbiOrUserType","resolveWorldConfig","WorldData","IBaseWorldData","CoreModuleData","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","deploy","mudConfig","existingContracts","deployConfig","resolvedConfig","startTime","worldContractName","namespace","postDeployScript","profile","rpc","privateKey","priorityFeeMultiplier","debug","worldAddress","forgeOutDirectory","provider","signer","nonce","maxPriorityFeePerGas","maxFeePerGas","setInternalFeePerGas","promises","blockNumber","worldPromise","deployContractByName","deployContract","systemPromises","acc","systemName","defaultModules","modulePromises","module","contractPromises","WorldContract","fastTxExecute","toBytes16","tableIds","tableName","name","schema","primaryKeys","toResourceSelector","schemaTypes","abiOrUserType","schemaType","keyTypes","openAccess","registerFunctionSelectors","functionSignatures","loadFunctionSignatures","isRoot","functionName","functionArgs","functionSignature","worldFunctionSelector","toFunctionSelector","systemFunctionSelector","accessListAddresses","accessListSystems","resourceSelector","address","granteeSystem","resolvedArgs","arg","values","types","moduleAddress","postDeployPath","contractName","bytecode","getContractData","retryCount","factory","deployPromise","error","item","parseComponents","params","param","contract","func","args","confirmations","gasLimit","txPromise","tx","data","contractDataPath","multiplier","feeData","input","result","i","file","namespaceBytes","fileBytes","sigHash","signature","forge","getRpcUrl","getSrcDirectory","mkdirSync","writeFileSync","ethers","getChainId","rpc","chainId","yDeployOptions","deployHandler","args","configPath","printConfig","profile","clean","rpc","getRpcUrl","chalk","forge","srcDir","getSrcDirectory","existingContracts","glob","path","basename","mudConfig","loadConfig","privateKey","MUDError","deploymentInfo","deploy","chainId","getChainId","outputDir","mkdirSync","writeFileSync","error","logError","commandModule","yargs","deploy_v2_default","loadConfig","worldgen","getSrcDirectory","glob","path","basename","rmSync","commandModule","yargs","args","configPath","clean","srcDir","existingContracts","mudConfig","outputBaseDirectory","worldgen_default","chalk","existsSync","readFileSync","rmSync","writeFileSync","path","MUDError","package_default","BACKUP_FILE","MUD_PREFIX","commandModule","yargs","options","MUDError","getCanaryVersion","package_default","rootPath","workspaces","updatePackageJson","workspace","filePath","path","e","logError","restore","force","link","backup","mudVersion","backupFilePath","backupFileExists","existsSync","packageJson","readPackageJson","backupJson","mudDependencies","key","mudDevDependencies","writeFileSync","chalk","resolveMudVersion","logComparison","rmSync","type","resolveLinkPath","jsonString","readFileSync","pkg","canary","prev","curr","packageJsonPath","mudLinkPath","pkgName","packageJsonToRootPath","set_version_default","anvil","forge","getRpcUrl","chalk","rmSync","writeFileSync","WORLD_ADDRESS_FILE","commandModule","yargs","yDeployOptions","args","anvilArgs","forkRpc","worldAddress","deployHandler","userOptions","testResult","e","test_v2_default","commands","deploy_v2_default","devnode_default","faucet_default","gas_report_default","hello_default","tablegen_default","tsgen_default","worldgen_default","set_version_default","test_v2_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/errors.ts","../src/commands/devnode.ts","../src/utils/deprecated/exec.ts","../src/utils/deprecated/ids.ts","../src/utils/deprecated/codegen.ts","../src/utils/deprecated/deploy.ts","../src/utils/deprecated/findLog.ts","../src/utils/deprecated/typegen.ts","../src/utils/deprecated/build.ts","../src/utils/deprecated/constants.ts","../src/utils/deprecated/hsr.ts","../src/commands/faucet.ts","../src/commands/gas-report.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/commands/tsgen.ts","../src/commands/deploy-v2.ts","../src/utils/deploy-v2.ts","../src/utils/getChainId.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../package.json","../src/commands/test-v2.ts","../src/commands/index.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/config\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n","import { rmSync } from \"fs\";\nimport { homedir } from \"os\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { execLog } from \"../utils/deprecated\";\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 const child = execLog(\"anvil\", [\"-b\", String(blocktime), \"--block-base-fee-per-gas\", \"0\"]);\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 { execa } from \"execa\";\n\n/**\n * Wrapper for execa that logs the full command.\n * @param command - The program/script to execute.\n * @param options - Arguments to pass to `command` on execution.\n * @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.\n */\nexport function execLog(command: string, options: string[]) {\n console.log(\"Cmd:\");\n console.log([command, ...options].join(\" \"));\n\n // TODO piping outputs and doing custom logging would be better for readability\n // (see https://github.com/latticexyz/mud/issues/446)\n return execa(command, options, {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n}\n","import { keccak256 as keccak256Bytes, toUtf8Bytes } from \"ethers/lib/utils.js\";\nimport { readFileSync } from \"fs\";\n\nexport const IDregex = new RegExp(/(?<=uint256 constant ID = uint256\\(keccak256\\(\")(.*)(?=\"\\))/);\n\nexport function extractIdFromFile(path: string): string | null {\n const content = readFileSync(path).toString();\n const regexResult = IDregex.exec(content);\n return regexResult && regexResult[0];\n}\n\nexport function keccak256(data: string) {\n return keccak256Bytes(toUtf8Bytes(data));\n}\n","import { readFile, writeFile } from \"fs/promises\";\nimport ejs from \"ejs\";\nimport path from \"path\";\n\nconst contractsDirectory = new URL(\"../src/contracts\", import.meta.url).pathname;\n\nconst stubLibDeploy = readFile(path.join(contractsDirectory, \"LibDeployStub.sol\"));\n\n/**\n * Generate LibDeploy.sol from deploy.json\n * @param configPath path to deploy.json\n * @param out output directory for LibDeploy.sol\n * @param systems optional, only generate deploy code for the given systems\n * @returns path to generated LibDeploy.sol\n */\nexport async function generateLibDeploy(configPath: string, out: string, systems?: string | string[]) {\n // Parse config\n const config = JSON.parse(await readFile(configPath, { encoding: \"utf8\" }));\n\n // Initializers are optional\n config.initializers ??= [];\n\n // Filter systems\n if (systems) {\n const systemsArray = Array.isArray(systems) ? systems : [systems];\n config.systems = config.systems.filter((system: { name: string }) => systemsArray.includes(system.name));\n }\n\n console.log(`Deploy config: \\n`, JSON.stringify(config, null, 2));\n\n // Generate LibDeploy\n console.log(\"Generating deployment script\");\n const LibDeploy = await ejs.renderFile(path.join(contractsDirectory, \"LibDeploy.ejs\"), config, { async: true });\n const libDeployPath = path.join(out, \"LibDeploy.sol\");\n await writeFile(libDeployPath, LibDeploy);\n\n return libDeployPath;\n}\n\nexport async function resetLibDeploy(out: string) {\n await writeFile(path.join(out, \"LibDeploy.sol\"), await stubLibDeploy);\n}\n","import { constants, Wallet } from \"ethers\";\nimport { generateLibDeploy, resetLibDeploy } from \"./codegen\";\nimport { findLog } from \"./findLog\";\nimport { generateTypes } from \"./typegen\";\nimport { execa } from \"execa\";\nimport { StaticJsonRpcProvider } from \"@ethersproject/providers\";\nimport path from \"path\";\n\nconst contractsDirectory = new URL(\"../src/contracts\", import.meta.url).pathname;\n\n/**\n * Deploy world, components and systems from deploy.json\n * @param deployerPrivateKey private key of deployer\n * @param rpc rpc url\n * @param worldAddress optional, address of existing world\n * @param reuseComponents optional, reuse existing components\n * @returns address of deployed world\n */\nexport async function deploy(\n deployerPrivateKey?: string,\n rpc = \"http://localhost:8545\",\n worldAddress?: string,\n reuseComponents?: boolean,\n gasPrice?: number\n) {\n const address = deployerPrivateKey ? new Wallet(deployerPrivateKey).address : constants.AddressZero;\n\n if (gasPrice == null) {\n try {\n console.log(\"Fetching gas price...\");\n const provider = new StaticJsonRpcProvider(rpc, { name: \"AnyNetwork\", chainId: 1234 });\n gasPrice = (await provider.getGasPrice()).toNumber() * 1.3; // 30% multiplier for faster inclusion\n console.log(\"Gas price:\", gasPrice);\n } catch (e) {\n console.log(\"Could not fetch gas price\");\n }\n }\n\n const child = execa(\n \"forge\",\n [\n \"script\",\n path.join(contractsDirectory, \"/Deploy.sol\"),\n \"--target-contract\",\n \"Deploy\",\n \"-vvv\",\n ...(!deployerPrivateKey ? [] : [\"--broadcast\", \"--private-keys\", deployerPrivateKey]),\n \"--sig\",\n \"broadcastDeploy(address,address,bool)\",\n address, // Deployer\n worldAddress || constants.AddressZero, // World address (0 = deploy a new world)\n reuseComponents ? \"true\" : \"false\", // Reuse components?\n \"--fork-url\",\n rpc,\n ...(gasPrice != null ? [\"--with-gas-price\", String(Math.round(gasPrice))] : []),\n ],\n { stdio: [\"inherit\", \"pipe\", \"pipe\"] }\n );\n\n child.stderr?.on(\"data\", (data) => console.log(\"stderr:\", data.toString()));\n child.stdout?.on(\"data\", (data) => console.log(data.toString()));\n\n // Extract world address from deploy script\n const lines = (await child).stdout?.split(\"\\n\");\n const deployedWorldAddress = findLog(lines, \"world: address\");\n const initialBlockNumber = findLog(lines, \"initialBlockNumber: uint256\");\n\n return { child: await child, deployedWorldAddress, initialBlockNumber };\n}\n\nexport type DeployOptions = {\n config: string;\n deployerPrivateKey?: string;\n worldAddress?: string;\n rpc: string;\n systems?: string | string[];\n reuseComponents?: boolean;\n clear?: boolean;\n gasPrice?: number;\n};\n\nexport async function generateAndDeploy(args: DeployOptions) {\n let libDeployPath: string | undefined;\n let deployedWorldAddress: string | undefined;\n let initialBlockNumber: string | undefined;\n\n try {\n // Generate LibDeploy\n libDeployPath = await generateLibDeploy(args.config, contractsDirectory, args.systems);\n\n // Build and generate fresh types\n await generateTypes(undefined, \"./types\", { clear: args.clear });\n\n // Call deploy script\n const result = await deploy(\n args.deployerPrivateKey,\n args.rpc,\n args.worldAddress,\n Boolean(args.reuseComponents),\n args.gasPrice\n );\n deployedWorldAddress = result.deployedWorldAddress;\n initialBlockNumber = result.initialBlockNumber;\n } finally {\n // Remove generated LibDeploy\n console.log(\"Cleaning up deployment script\");\n if (libDeployPath) await resetLibDeploy(contractsDirectory);\n }\n\n return { deployedWorldAddress, initialBlockNumber };\n}\n","export function findLog(deployLogLines: string[], log: string): string {\n for (const logLine of deployLogLines) {\n if (logLine.includes(log)) {\n return logLine.split(log)[1].trim();\n }\n }\n throw new Error(\"Can not find log\");\n}\n","import { runTypeChain, glob as typechainGlob } from \"typechain\";\nimport glob from \"glob\";\nimport { extractIdFromFile } from \"./ids\";\nimport { rmSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport { filterAbi, forgeBuild } from \"./build\";\nimport { getOutDirectory, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { systemsDir } from \"./constants\";\n\nexport async function generateAbiTypes(\n inputDir: string,\n outputDir: string,\n options?: { clear?: boolean; cwd?: string }\n) {\n if (options?.clear) {\n console.log(\"Clearing typechain output directory\", outputDir);\n rmSync(outputDir, { recursive: true, force: true });\n }\n\n const cwd = options?.cwd ?? process.cwd();\n\n const allFiles = typechainGlob(cwd, [`${inputDir}/**/+([a-zA-Z0-9_]).json`]);\n\n const result = await runTypeChain({\n cwd,\n filesToProcess: allFiles,\n allFiles,\n outDir: outputDir,\n target: \"ethers-v5\",\n });\n\n console.log(`Successfully generated ${result.filesGenerated} files`);\n}\n\nexport async function generateSystemTypes(outputDir: string, options?: { clear?: boolean }) {\n if (options?.clear) {\n console.log(\"Clearing system type output files\", outputDir);\n rmSync(path.join(outputDir, \"/SystemTypes.ts\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemAbis.mts\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemAbis.mjs\"), { force: true });\n rmSync(path.join(outputDir, \"/SystemMappings.ts\"), { force: true });\n }\n\n let abis: string[] = [];\n let systems: string[] = [];\n let ids: string[] = [];\n let typePaths: string[] = [];\n\n const srcDir = await getSrcDirectory();\n const systemsPath = path.join(srcDir, systemsDir, \"*.sol\");\n\n const matches = glob.sync(systemsPath);\n\n systems = matches.map((path) => {\n const fragments = path.split(\"/\");\n return fragments[fragments.length - 1].split(\".sol\")[0];\n });\n\n ids = matches.map((path, index) => {\n const id = extractIdFromFile(path);\n if (!id) {\n console.log(\"Path:\", path);\n console.log(\"ID:\", id);\n throw new Error(\n \"No ID found for\" +\n matches[index] +\n \". Make sure your system source file includes a ID definition (uint256 constant ID = uint256(keccak256(<ID>));)\"\n );\n }\n return id;\n });\n\n abis = systems.map((system) => `../abi/${system}.json`);\n\n typePaths = systems.map((system) => `./ethers-contracts/${system}.ts`);\n\n console.log(\"Matches\", systems);\n console.log(\"Solidity\", ids);\n console.log(\"Type paths\", typePaths);\n console.log(\"ABIs\", abis);\n\n const SystemMappings = `// Autogenerated using mud system-types\nexport const systemToId = {\n${systems.map((system, index) => ` ${system}: \"${ids[index]}\",`).join(\"\\n\")}\n};\n\nexport const idToSystem = {\n${ids.map((id, index) => ` \"${id}\": \"${systems[index]}\",`).join(\"\\n\")}\n};\n `;\n\n const SystemTypes = `// Autogenerated using mud system-types\n${typePaths.map((path, index) => `import { ${systems[index]} } from \"${path.replace(\".ts\", \"\")}\";`).join(\"\\n\")}\n \nexport type SystemTypes = {\n${systems.map((system, index) => ` \"${ids[index]}\": ${system};`).join(\"\\n\")}\n};\n`;\n\n const SystemAbis = `// Autogenerated using mud system-types\n${abis.map((path, index) => `import ${systems[index]} from \"${path}\";`).join(\"\\n\")}\n\nexport const SystemAbis = {\n${systems.map((system, index) => ` \"${ids[index]}\": ${system}.abi,`).join(\"\\n\")}\n};\n`;\n\n console.log(\"Generating files:\");\n console.log(\"SystemTypes.ts\", SystemTypes);\n console.log(\"SystemAbis.mts\", SystemAbis);\n console.log(\"SystemMappings.ts\", SystemMappings);\n\n writeFileSync(`${outputDir}/SystemTypes.ts`, SystemTypes);\n writeFileSync(`${outputDir}/SystemAbis.mts`, SystemAbis);\n writeFileSync(`${outputDir}/SystemAbis.mjs`, SystemAbis);\n writeFileSync(`${outputDir}/SystemMappings.ts`, SystemMappings);\n}\n\n/**\n * @param abiDir If not provided, the contracts are built and abis are exported to ./abi\n */\nexport async function generateTypes(abiDir?: string, outputDir = \"./types\", options?: { clear?: boolean }) {\n if (!abiDir) {\n console.log(\"Compiling contracts\");\n const buildOutput = await getOutDirectory();\n abiDir = \"./abi\";\n await forgeBuild(options);\n filterAbi(buildOutput, abiDir);\n }\n\n await generateAbiTypes(abiDir, path.join(outputDir, \"ethers-contracts\"), options);\n await generateSystemTypes(outputDir, options);\n}\n","import { execa } from \"execa\";\nimport { copyFileSync, mkdirSync, readdirSync, rmSync } from \"fs\";\nimport path from \"path\";\nimport { getOutDirectory } from \"@latticexyz/common/foundry\";\n\nexport async function forgeBuild(options?: { clear?: boolean }) {\n if (options?.clear) {\n const out = await getOutDirectory();\n console.log(\"Clearing forge build output directory\", out);\n rmSync(out, { recursive: true, force: true });\n }\n\n console.log(\"Running forge build\");\n const child = execa(\"forge\", [\"build\"], {\n stdio: [\"inherit\", \"pipe\", \"inherit\"],\n });\n\n return (await child).stdout;\n}\n\nfunction getContractsInDirectory(dir: string, exclude?: string[]) {\n return readdirSync(dir)\n .filter((item) => item.includes(\".sol\"))\n .map((item) => item.replace(\".sol\", \"\"))\n .filter((item) => !exclude?.includes(item));\n}\n\nfunction copyAbi(inDir: string, outDir: string, contract: string) {\n try {\n return copyFileSync(path.join(inDir, contract + \".sol\", contract + \".json\"), path.join(outDir, contract + \".json\"));\n } catch (e) {\n console.log(\"Skipping\", contract);\n }\n}\n\nexport function filterAbi(abiIn = \"./out\", abiOut = \"./abi\", exclude: string[] = [\"Component\", \"IComponent\"]) {\n // Clean our dir\n console.log(`Cleaning output directory (${abiOut}})`);\n rmSync(abiOut, { recursive: true, force: true });\n mkdirSync(abiOut);\n\n // Only include World, LibQuery, *Component, *System\n const include = [\"Component\", \"System\", \"World\", \"LibQuery\"];\n const contracts = getContractsInDirectory(abiIn, exclude).filter((item) => include.find((i) => item.includes(i)));\n\n console.log(\"Selected ABIs: \", contracts);\n\n // Move selected ABIs to ./abi\n for (const contract of contracts) {\n if (contract.includes(\".t\")) continue;\n copyAbi(abiIn, abiOut, contract);\n }\n\n console.log(\"Successfully moved selected ABIs to ./abi\");\n}\n","export const systemsDir = \"systems\";\nexport const componentsDir = \"components\";\n","import chokidar from \"chokidar\";\nimport { readFileSync } from \"fs\";\n\nconst ImportsRegex = new RegExp(/(?<=import \").*(?=\";)|(?<=from \").*(?=\";)/g);\n\n/**\n * Extract file imports from a given file\n * @param path File to extracts imports from\n * @returns Array of imported filenames\n */\nfunction extractImports(path: string): string[] {\n const content = readFileSync(path).toString();\n const regexResult = [...content.matchAll(ImportsRegex)]\n .map((match) => match[0])\n .map((path) => path.split(\"/\").at(-1)!);\n return regexResult;\n}\n\nfunction findDependencies(\n file: string,\n dependencyGraph: { [file: string]: string[] },\n visited: string[] = []\n): string[] {\n const dependencies = dependencyGraph[file] ?? [];\n const subDependencies = dependencies.flatMap((d) => {\n if (visited.includes(d)) {\n console.warn(\"Circular dependency detected: \", d, dependencyGraph[d]);\n return [];\n }\n return findDependencies(d, dependencyGraph, [...visited, d]);\n });\n return [...new Set([...dependencies, ...subDependencies])];\n}\n\n// Hot System Replacement\nexport function hsr(root: string, replaceSystems: (systems: string[]) => Promise<unknown>) {\n const dependencyGraph: { [file: string]: string[] } = {};\n const systems = new Set<string>();\n\n console.log(\"Watching system file changes...\");\n\n chokidar.watch(root).on(\"all\", async (event, path) => {\n console.log(`[${event}]: ${path}`);\n\n // Find changed file\n const changedFile = path.split(\"/\").at(-1)!;\n\n if ([\"add\", \"change\"].includes(event)) {\n // Construct dependency graph based in file imports\n const imports = extractImports(path);\n for (const importedFile of imports) {\n dependencyGraph[importedFile] ??= [];\n dependencyGraph[importedFile].push(changedFile);\n }\n\n // Track system files\n if (path.includes(\"systems\") && path.includes(\".sol\")) systems.add(changedFile);\n }\n\n if (event === \"change\") {\n // Find all files depending on the changed file\n const dependencies = findDependencies(changedFile, dependencyGraph);\n const changedSystems = [\n ...new Set([changedFile, ...dependencies].filter((f) => systems.has(f)).map((f) => f.replace(\".sol\", \"\"))),\n ];\n console.log(\"Systems to replace\", changedSystems);\n if (changedSystems.length > 0) await replaceSystems(changedSystems);\n console.log(\"Watching system file changes...\");\n }\n });\n}\n","import type { CommandModule } from \"yargs\";\nimport { FaucetServiceDefinition } from \"@latticexyz/services/faucet\";\nimport { createChannel, createClient } from \"nice-grpc-web\";\nimport chalk from \"chalk\";\nimport { NodeHttpTransport } from \"@improbable-eng/grpc-web-node-http-transport\";\n\ntype Options = {\n dripDev?: boolean;\n faucetUrl: string;\n address: string;\n};\n\n/**\n * Create a FaucetServiceClient\n * @param url FaucetService URL\n * @returns FaucetServiceClient\n */\nfunction createFaucetService(url: string) {\n return createClient(FaucetServiceDefinition, createChannel(url, NodeHttpTransport()));\n}\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"faucet\",\n\n describe: \"Interact with a MUD faucet\",\n\n builder(yargs) {\n return yargs.options({\n dripDev: {\n type: \"boolean\",\n desc: \"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)\",\n default: true,\n },\n faucetUrl: {\n type: \"string\",\n desc: \"URL of the MUD faucet\",\n default: \"https://faucet.testnet-mud-services.linfra.xyz\",\n },\n address: {\n type: \"string\",\n desc: \"Ethereum address to fund\",\n required: true,\n },\n });\n },\n\n async handler({ dripDev, faucetUrl, address }) {\n const faucet = createFaucetService(faucetUrl);\n\n if (dripDev) {\n console.log(chalk.yellow(\"Dripping to\", address));\n await faucet.dripDev({ address });\n console.log(chalk.yellow(\"Success\"));\n }\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { readFileSync, writeFileSync, rmSync } from \"fs\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { table, getBorderCharacters } from \"table\";\n\n/**\n * Print the gas report to the console, save it to a file and compare it to a previous gas report if provided.\n * Requires forge to be installed, and gas test files including `// !gasreport` comments, like this:\n *\n * ```solidity\n * contract GasTest is DSTestPlus {\n * function testBuffer() public pure {\n * // !gasreport allocate a buffer\n * Buffer buffer = Buffer_.allocate(32);\n *\n * bytes32 value = keccak256(\"some data\");\n *\n * // !gasreport append 32 bytes to a buffer\n * buffer.append(value);\n * }\n * }\n * ```\n */\n\ntype Options = {\n path: string[];\n save?: string;\n compare?: string;\n};\n\ntype GasReportEntry = {\n source: string;\n name: string;\n functionCall: string;\n gasUsed: number;\n prevGasUsed?: number;\n};\n\ntype GasReport = GasReportEntry[];\n\nconst tempFileSuffix = \"MudGasReport\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"gas-report\",\n\n describe: \"Create a gas report\",\n\n builder(yargs) {\n return yargs.options({\n path: { type: \"array\", string: true, default: [\"Gas.t.sol\"], desc: \"File containing the gas tests\" },\n save: { type: \"string\", desc: \"Save the gas report to a file\" },\n compare: { type: \"string\", desc: \"Compare to an existing gas report\" },\n });\n },\n\n async handler({ path: files, save, compare }) {\n const validFiles = files.filter((file) => file.endsWith(\".t.sol\"));\n const tempFiles = await Promise.all(validFiles.map((file) => createGasReport(file)));\n\n process.once(\"SIGINT\", () => {\n console.log(\"caught sigint, deleting temp files\");\n tempFiles.forEach((file) => rmSync(file));\n });\n\n let gasReport: GasReport;\n try {\n gasReport = await runGasReport();\n } catch {\n setTimeout(() => process.exit());\n return;\n } finally {\n // Delete the temporary files\n tempFiles.forEach((file) => rmSync(file));\n }\n\n // If this gas report should be compared to an existing one, load the existing one\n if (compare) {\n try {\n const compareGasReport: GasReport = JSON.parse(readFileSync(compare, \"utf8\"));\n // Merge the previous gas report with the new one\n gasReport = gasReport.map((entry) => {\n const prevEntry = compareGasReport.find(\n (e) => e.name === entry.name && e.functionCall === entry.functionCall\n );\n return { ...entry, prevGasUsed: prevEntry?.gasUsed };\n });\n } catch {\n console.log(chalk.red(`Gas report to compare not found: ${compare}`));\n compare = undefined;\n }\n }\n\n // Print gas report\n printGasReport(gasReport, compare);\n\n // Save gas report to file if requested\n if (save) saveGasReport(gasReport, save);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n\nasync function createGasReport(filename: string): Promise<string> {\n console.log(\"Creating gas report for\", chalk.bold(filename));\n\n // Parse the given test file, and add gas reporting wherever requested by a `// !gasreport` comment\n const fileContents = readFileSync(filename, \"utf8\");\n let newFile = fileContents;\n\n // Use a regex to find first line of each function\n const functionRegex = new RegExp(/function (.*){/g);\n // Insert a line to declare the _gasreport variable at the start of each function\n let functionMatch;\n while ((functionMatch = functionRegex.exec(fileContents)) !== null) {\n const functionSignature = functionMatch[0];\n newFile = newFile.replace(functionSignature, `${functionSignature}\\nuint256 _gasreport;`);\n }\n\n // A gasreport comment has a name (written after the comment) and a function call (written on the next line)\n // Create a regex to extract both the name and the function call\n const regex = new RegExp(/\\/\\/ !gasreport (.*)\\n(.*)/g);\n\n // Apply the regex and loop through the matches,\n // and create a new file with the gasreport comments replaced by the gas report\n let match;\n while ((match = regex.exec(fileContents)) !== null) {\n const name = match[1];\n const functionCall = match[2].trim();\n\n newFile = newFile.replace(\n match[0],\n `\n_gasreport = gasleft();\n${functionCall}\n_gasreport = _gasreport - gasleft();\nconsole.log(\"GAS REPORT(${filename}): ${name} [${functionCall.replaceAll('\"', '\\\\\"')}]:\", _gasreport);`\n );\n }\n\n // Remove all occurrences of `pure` with `view`\n newFile = newFile.replace(/pure/g, \"view\");\n\n // Write the new file to disk (temporarily)\n // Create the temp file by replacing the previous file name with MudGasReport\n const tempFileName = filename.replace(/\\.t\\.sol$/, `${tempFileSuffix}.t.sol`);\n writeFileSync(tempFileName, newFile);\n\n return tempFileName;\n}\n\nasync function runGasReport(): Promise<GasReport> {\n console.log(\"Running gas report\");\n const gasReport: GasReport = [];\n\n // Extract the logs from the child process\n let logs = \"\";\n try {\n // Run the generated file using forge\n const child = execa(\"forge\", [\"test\", \"--match-path\", `*${tempFileSuffix}*`, \"-vvv\"], {\n stdio: [\"inherit\", \"pipe\", \"inherit\"],\n });\n logs = (await child).stdout;\n } catch (error: any) {\n console.log(error.stdout ?? error);\n console.log(chalk.red(\"\\n-----------\\nError while running the gas report (see above)\"));\n throw error;\n }\n\n // Extract the gas reports from the logs\n\n // Create a regex to find all lines starting with `GAS REPORT:` and extract the name, function call and gas used\n const gasReportRegex = new RegExp(/GAS REPORT\\((.*)\\): (.*) \\[(.*)\\]: (.*)/g);\n\n // Loop through the matches and print the gas report\n let gasReportMatch;\n while ((gasReportMatch = gasReportRegex.exec(logs)) !== null) {\n const source = gasReportMatch[1];\n const name = gasReportMatch[2];\n const functionCall = gasReportMatch[3].replace(\";\", \"\");\n const gasUsed = parseInt(gasReportMatch[4]);\n gasReport.push({ source, name, functionCall, gasUsed });\n }\n\n gasReport.sort((a, b) => a.source.localeCompare(b.source));\n\n return gasReport;\n}\n\nfunction printGasReport(gasReport: GasReport, compare?: string) {\n if (compare) console.log(chalk.bold(`Gas report compared to ${compare}`));\n\n const headers = [\n chalk.bold(\"Source\"),\n chalk.bold(\"Name\"),\n chalk.bold(\"Function call\"),\n chalk.bold(\"Gas used\"),\n ...(compare ? [chalk.bold(\"Prev gas used\"), chalk.bold(\"Difference\")] : []),\n ];\n\n const values = gasReport.map((entry) => {\n const diff = entry.prevGasUsed ? entry.gasUsed - entry.prevGasUsed : 0;\n const diffEntry = diff > 0 ? chalk.red(`+${diff}`) : diff < 0 ? chalk.green(`${diff}`) : diff;\n const compareColumns = compare ? [entry.prevGasUsed ?? \"n/a\", diffEntry] : [];\n const gasUsedEntry = diff > 0 ? chalk.red(entry.gasUsed) : diff < 0 ? chalk.green(entry.gasUsed) : entry.gasUsed;\n return [entry.source, entry.name, entry.functionCall, gasUsedEntry, ...compareColumns];\n });\n\n const rows = [headers, ...values];\n\n console.log(table(rows, { border: getBorderCharacters(\"norc\") }));\n}\n\nfunction saveGasReport(gasReport: GasReport, path: string) {\n console.log(chalk.bold(`Saving gas report to ${path}`));\n writeFileSync(path, `${JSON.stringify(gasReport, null, 2)}\\n`);\n}\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 path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig, tablegen } from \"@latticexyz/store\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\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 config file\" },\n });\n },\n\n async handler({ configPath }) {\n const config = (await loadConfig(configPath)) as StoreConfig;\n const srcDir = await getSrcDirectory();\n\n await tablegen(config, path.join(srcDir, config.codegenDirectory));\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { tsgen } from \"../render-ts/tsgen\";\n\ntype Options = {\n configPath: string;\n out: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"tsgen\",\n\n describe: \"Autogenerate MUD typescript definitions based on the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", demandOption: true, desc: \"Path to the config file\" },\n out: { type: \"string\", demandOption: true, desc: \"Directory to output MUD typescript definition files\" },\n });\n },\n\n async handler(args) {\n const { configPath, out } = args;\n\n const config = (await loadConfig(configPath)) as StoreConfig;\n\n await tsgen(config, out);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport glob from \"glob\";\nimport path, { basename } from \"path\";\nimport type { CommandModule, Options } from \"yargs\";\nimport { loadConfig, MUDError } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { deploy } from \"../utils/deploy-v2\";\nimport { logError } from \"../utils/errors\";\nimport { forge, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { mkdirSync, writeFileSync } from \"fs\";\nimport { getChainId } from \"../utils/getChainId\";\n\nexport type DeployOptions = {\n configPath?: string;\n printConfig?: boolean;\n profile?: string;\n priorityFeeMultiplier: number;\n clean?: boolean;\n debug?: boolean;\n saveDeployment?: boolean;\n rpc?: string;\n worldAddress?: string;\n srcDir?: string;\n};\n\nexport const yDeployOptions = {\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n clean: { type: \"boolean\", desc: \"Remove the build forge artifacts and cache directories before building\" },\n printConfig: { type: \"boolean\", desc: \"Print the resolved config\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n debug: { type: \"boolean\", desc: \"Print debug logs, like full error messages\" },\n priorityFeeMultiplier: {\n type: \"number\",\n desc: \"Multiply the estimated priority fee by the provided factor\",\n default: 1,\n },\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 worldAddress: { type: \"string\", desc: \"Deploy to an existing World at the given address\" },\n srcDir: { type: \"string\", desc: \"Source directory. Defaults to foundry src directory.\" },\n} satisfies Record<keyof DeployOptions, Options>;\n\nexport async function deployHandler(args: Parameters<(typeof commandModule)[\"handler\"]>[0]) {\n args.profile = args.profile ?? process.env.FOUNDRY_PROFILE;\n const { configPath, printConfig, profile, clean } = args;\n\n const rpc = args.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Deploying MUD v2 contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`)\n )\n );\n\n if (clean) await forge([\"clean\"], { profile });\n\n // Run forge build\n await forge([\"build\"], { profile });\n\n // Get a list of all contract names\n const srcDir = args?.srcDir ?? (await getSrcDirectory());\n const existingContracts = glob\n .sync(`${srcDir}/**/*.sol`)\n // Get the basename of the file\n .map((path) => basename(path, \".sol\"));\n\n // Load the config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n if (printConfig) console.log(chalk.green(\"\\nResolved config:\\n\"), JSON.stringify(mudConfig, null, 2));\n\n try {\n const privateKey = process.env.PRIVATE_KEY;\n if (!privateKey) throw new MUDError(\"Missing PRIVATE_KEY environment variable\");\n const deploymentInfo = await deploy(mudConfig, existingContracts, { ...args, rpc, privateKey });\n\n if (args.saveDeployment) {\n // Write deployment result to file (latest and timestamp)\n const chainId = await getChainId(rpc);\n const outputDir = path.join(mudConfig.deploysDirectory, chainId.toString());\n mkdirSync(outputDir, { recursive: true });\n writeFileSync(path.join(outputDir, \"latest.json\"), JSON.stringify(deploymentInfo, null, 2));\n writeFileSync(path.join(outputDir, Date.now() + \".json\"), JSON.stringify(deploymentInfo, null, 2));\n\n console.log(chalk.bgGreen(chalk.whiteBright(`\\n Deployment result (written to ${outputDir}): \\n`)));\n }\n\n console.log(deploymentInfo);\n return deploymentInfo;\n } catch (error: any) {\n logError(error);\n process.exit(1);\n }\n}\n\nconst commandModule: CommandModule<DeployOptions, DeployOptions> = {\n command: \"deploy-v2\",\n\n describe: \"Deploy MUD v2 contracts\",\n\n builder(yargs) {\n return yargs.options(yDeployOptions);\n },\n\n async handler(args) {\n await deployHandler(args);\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { existsSync, readFileSync } from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { BigNumber, ContractInterface, ethers } from \"ethers\";\nimport { defaultAbiCoder as abi, Fragment, ParamType } from \"ethers/lib/utils.js\";\n\nimport { getOutDirectory, getScriptDirectory, cast, forge } from \"@latticexyz/common/foundry\";\nimport { resolveWithContext } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/config\";\nimport { encodeSchema } from \"@latticexyz/schema-type\";\nimport { StoreConfig, resolveAbiOrUserType } from \"@latticexyz/store\";\nimport { WorldConfig, resolveWorldConfig } from \"@latticexyz/world\";\nimport { IBaseWorld } from \"@latticexyz/world/types/ethers-contracts/IBaseWorld\";\n\nimport WorldData from \"@latticexyz/world/abi/World.sol/World.json\" assert { type: \"json\" };\nimport IBaseWorldData from \"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json\" assert { type: \"json\" };\nimport CoreModuleData from \"@latticexyz/world/abi/CoreModule.sol/CoreModule.json\" assert { type: \"json\" };\nimport KeysWithValueModuleData from \"@latticexyz/world/abi/KeysWithValueModule.sol/KeysWithValueModule.json\" assert { type: \"json\" };\nimport KeysInTableModuleData from \"@latticexyz/world/abi/KeysInTableModule.sol/KeysInTableModule.json\" assert { type: \"json\" };\nimport UniqueEntityModuleData from \"@latticexyz/world/abi/UniqueEntityModule.sol/UniqueEntityModule.json\" assert { type: \"json\" };\n\nexport interface DeployConfig {\n profile?: string;\n rpc: string;\n privateKey: string;\n priorityFeeMultiplier: number;\n debug?: boolean;\n worldAddress?: string;\n}\n\nexport interface DeploymentInfo {\n blockNumber: number;\n worldAddress: string;\n}\n\nexport async function deploy(\n mudConfig: StoreConfig & WorldConfig,\n existingContracts: string[],\n deployConfig: DeployConfig\n): Promise<DeploymentInfo> {\n const resolvedConfig = resolveWorldConfig(mudConfig, existingContracts);\n\n const startTime = Date.now();\n const { worldContractName, namespace, postDeployScript } = mudConfig;\n const { profile, rpc, privateKey, priorityFeeMultiplier, debug, worldAddress } = deployConfig;\n const forgeOutDirectory = await getOutDirectory(profile);\n\n // Set up signer for deployment\n const provider = new ethers.providers.StaticJsonRpcProvider(rpc);\n const signer = new ethers.Wallet(privateKey, provider);\n\n // Manual nonce handling to allow for faster sending of transactions without waiting for previous transactions\n let nonce = await signer.getTransactionCount();\n console.log(\"Initial nonce\", nonce);\n\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n let maxPriorityFeePerGas: number;\n let maxFeePerGas: BigNumber;\n setInternalFeePerGas(priorityFeeMultiplier);\n\n // Catch all to await any promises before exiting the script\n let promises: Promise<unknown>[] = [];\n\n // Get block number before deploying\n const blockNumber = Number(await cast([\"block-number\", \"--rpc-url\", rpc], { profile }));\n console.log(\"Start deployment at block\", blockNumber);\n\n // Deploy World\n const worldPromise = {\n World: worldAddress\n ? Promise.resolve(worldAddress)\n : worldContractName\n ? deployContractByName(worldContractName)\n : deployContract(IBaseWorldData.abi, WorldData.bytecode, \"World\"),\n };\n\n // Deploy Systems\n const systemPromises = Object.keys(resolvedConfig.systems).reduce<Record<string, Promise<string>>>(\n (acc, systemName) => {\n acc[systemName] = deployContractByName(systemName);\n return acc;\n },\n {}\n );\n\n // Deploy default World modules\n const defaultModules: Record<string, Promise<string>> = {\n // TODO: these only need to be deployed once per chain, add a check if they exist already\n CoreModule: deployContract(CoreModuleData.abi, CoreModuleData.bytecode, \"CoreModule\"),\n KeysWithValueModule: deployContract(\n KeysWithValueModuleData.abi,\n KeysWithValueModuleData.bytecode,\n \"KeysWithValueModule\"\n ),\n KeysInTableModule: deployContract(KeysInTableModuleData.abi, KeysInTableModuleData.bytecode, \"KeysInTableModule\"),\n UniqueEntityModule: deployContract(\n UniqueEntityModuleData.abi,\n UniqueEntityModuleData.bytecode,\n \"UniqueEntityModule\"\n ),\n };\n\n // Deploy user Modules\n const modulePromises = mudConfig.modules\n .filter((module) => !defaultModules[module.name]) // Only deploy user modules here, not default modules\n .reduce<Record<string, Promise<string>>>((acc, module) => {\n acc[module.name] = deployContractByName(module.name);\n return acc;\n }, defaultModules);\n\n // Combine all contracts into one object\n const contractPromises: Record<string, Promise<string>> = { ...worldPromise, ...systemPromises, ...modulePromises };\n\n // Create World contract instance from deployed address\n const WorldContract = new ethers.Contract(await contractPromises.World, IBaseWorldData.abi, signer) as IBaseWorld;\n\n // Install core Modules\n if (!worldAddress) {\n console.log(chalk.blue(\"Installing core World modules\"));\n await fastTxExecute(WorldContract, \"installRootModule\", [await modulePromises.CoreModule, \"0x\"]);\n console.log(chalk.green(\"Installed core World modules\"));\n }\n\n // Register namespace\n if (namespace) await fastTxExecute(WorldContract, \"registerNamespace\", [toBytes16(namespace)]);\n\n // Register tables\n const tableIds: { [tableName: string]: Uint8Array } = {};\n promises = [\n ...promises,\n ...Object.entries(mudConfig.tables).map(async ([tableName, { name, schema, primaryKeys }]) => {\n console.log(chalk.blue(`Registering table ${tableName} at ${namespace}/${name}`));\n\n // Store the tableId for later use\n tableIds[tableName] = toResourceSelector(namespace, name);\n\n // Register table\n const schemaTypes = Object.values(schema).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);\n return schemaType;\n });\n\n const keyTypes = Object.values(primaryKeys).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);\n return schemaType;\n });\n\n await fastTxExecute(WorldContract, \"registerTable\", [\n toBytes16(namespace),\n toBytes16(name),\n encodeSchema(schemaTypes),\n encodeSchema(keyTypes),\n ]);\n\n // Register table metadata\n await fastTxExecute(WorldContract, \"setMetadata(bytes16,bytes16,string,string[])\", [\n toBytes16(namespace),\n toBytes16(name),\n tableName,\n Object.keys(schema),\n ]);\n\n console.log(chalk.green(`Registered table ${tableName} at ${name}`));\n }),\n ];\n\n // Register systems (using forEach instead of for..of to avoid blocking on async calls)\n promises = [\n ...promises,\n ...Object.entries(resolvedConfig.systems).map(\n async ([systemName, { name, openAccess, registerFunctionSelectors }]) => {\n // Register system at route\n console.log(chalk.blue(`Registering system ${systemName} at ${namespace}/${name}`));\n await fastTxExecute(WorldContract, \"registerSystem\", [\n toBytes16(namespace),\n toBytes16(name),\n await contractPromises[systemName],\n openAccess,\n ]);\n console.log(chalk.green(`Registered system ${systemName} at ${namespace}/${name}`));\n\n // Register function selectors for the system\n if (registerFunctionSelectors) {\n const functionSignatures: FunctionSignature[] = await loadFunctionSignatures(systemName);\n const isRoot = namespace === \"\";\n // Using Promise.all to avoid blocking on async calls\n await Promise.all(\n functionSignatures.map(async ({ functionName, functionArgs }) => {\n const functionSignature = isRoot\n ? functionName + functionArgs\n : `${namespace}_${name}_${functionName}${functionArgs}`;\n\n console.log(chalk.blue(`Registering function \"${functionSignature}\"`));\n if (isRoot) {\n const worldFunctionSelector = toFunctionSelector(\n functionSignature === \"\"\n ? { functionName: systemName, functionArgs } // Register the system's fallback function as `<systemName>(<args>)`\n : { functionName, functionArgs }\n );\n const systemFunctionSelector = toFunctionSelector({ functionName, functionArgs });\n await fastTxExecute(WorldContract, \"registerRootFunctionSelector\", [\n toBytes16(namespace),\n toBytes16(name),\n worldFunctionSelector,\n systemFunctionSelector,\n ]);\n } else {\n await fastTxExecute(WorldContract, \"registerFunctionSelector\", [\n toBytes16(namespace),\n toBytes16(name),\n functionName,\n functionArgs,\n ]);\n }\n console.log(chalk.green(`Registered function \"${functionSignature}\"`));\n })\n );\n }\n }\n ),\n ];\n\n // Wait for resources to be registered before granting access to them\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Grant access to systems\n for (const [systemName, { name, accessListAddresses, accessListSystems }] of Object.entries(resolvedConfig.systems)) {\n const resourceSelector = `${namespace}/${name}`;\n\n // Grant access to addresses\n promises = [\n ...promises,\n ...accessListAddresses.map(async (address) => {\n console.log(chalk.blue(`Grant ${address} access to ${systemName} (${resourceSelector})`));\n await fastTxExecute(WorldContract, \"grantAccess\", [toBytes16(namespace), toBytes16(name), address]);\n console.log(chalk.green(`Granted ${address} access to ${systemName} (${namespace}/${name})`));\n }),\n ];\n\n // Grant access to other systems\n promises = [\n ...promises,\n ...accessListSystems.map(async (granteeSystem) => {\n console.log(chalk.blue(`Grant ${granteeSystem} access to ${systemName} (${resourceSelector})`));\n await fastTxExecute(WorldContract, \"grantAccess\", [\n toBytes16(namespace),\n toBytes16(name),\n await contractPromises[granteeSystem],\n ]);\n console.log(chalk.green(`Granted ${granteeSystem} access to ${systemName} (${resourceSelector})`));\n }),\n ];\n }\n\n // Wait for access to be granted before installing modules\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Install modules\n promises = [\n ...promises,\n ...mudConfig.modules.map(async (module) => {\n console.log(chalk.blue(`Installing${module.root ? \" root \" : \" \"}module ${module.name}`));\n // Resolve arguments\n const resolvedArgs = await Promise.all(\n module.args.map((arg) => resolveWithContext(arg, { tableIds, systemAddresses: contractPromises }))\n );\n const values = resolvedArgs.map((arg) => arg.value);\n const types = resolvedArgs.map((arg) => arg.type);\n const moduleAddress = await contractPromises[module.name];\n if (!moduleAddress) throw new Error(`Module ${module.name} not found`);\n\n // Send transaction to install module\n await fastTxExecute(WorldContract, module.root ? \"installRootModule\" : \"installModule\", [\n moduleAddress,\n abi.encode(types, values),\n ]);\n\n console.log(chalk.green(`Installed${module.root ? \" root \" : \" \"}module ${module.name}`));\n }),\n ];\n\n // Await all promises before executing PostDeploy script\n await Promise.all(promises); // ----------------------------------------------------------------------------------------------\n promises = [];\n\n // Execute postDeploy forge script\n const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + \".s.sol\");\n if (existsSync(postDeployPath)) {\n console.log(chalk.blue(`Executing post deploy script at ${postDeployPath}`));\n await forge(\n [\n \"script\",\n postDeployScript,\n \"--sig\",\n \"run(address)\",\n await contractPromises.World,\n \"--broadcast\",\n \"--rpc-url\",\n rpc,\n \"-vvv\",\n ],\n {\n profile,\n }\n );\n } else {\n console.log(`No script at ${postDeployPath}, skipping post deploy hook`);\n }\n\n console.log(chalk.green(\"Deployment completed in\", (Date.now() - startTime) / 1000, \"seconds\"));\n\n return { worldAddress: await contractPromises.World, blockNumber };\n\n // ------------------- INTERNAL FUNCTIONS -------------------\n // (Inlined to avoid having to pass around nonce, signer and forgeOutDir)\n\n /**\n * Deploy a contract and return the address\n * @param contractName Name of the contract to deploy (must exist in the file system)\n * @returns Address of the deployed contract\n */\n async function deployContractByName(contractName: string): Promise<string> {\n console.log(chalk.blue(\"Deploying\", contractName));\n\n const { abi, bytecode } = await getContractData(contractName);\n return deployContract(abi, bytecode, contractName);\n }\n\n /**\n * Deploy a contract and return the address\n * @param abi The contract interface\n * @param bytecode The contract bytecode\n * @param contractName The contract name (optional, used for logs)\n * @returns Address of the deployed contract\n */\n async function deployContract(\n abi: ContractInterface,\n bytecode: string | { object: string },\n contractName?: string,\n retryCount = 0\n ): Promise<string> {\n try {\n const factory = new ethers.ContractFactory(abi, bytecode, signer);\n console.log(chalk.gray(`executing deployment of ${contractName} with nonce ${nonce}`));\n const deployPromise = factory.deploy({\n nonce: nonce++,\n maxPriorityFeePerGas,\n maxFeePerGas,\n });\n promises.push(deployPromise);\n const { address } = await deployPromise;\n\n console.log(chalk.green(\"Deployed\", contractName, \"to\", address));\n return address;\n } catch (error: any) {\n if (debug) console.error(error);\n if (retryCount === 0 && error?.message.includes(\"transaction already imported\")) {\n // If the deployment failed because the transaction was already imported,\n // retry with a higher priority fee\n setInternalFeePerGas(priorityFeeMultiplier * 1.1);\n return deployContract(abi, bytecode, contractName, retryCount++);\n } else if (error?.message.includes(\"invalid bytecode\")) {\n throw new MUDError(\n `Error deploying ${contractName}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use \"external\" functions.`\n );\n } else if (error?.message.includes(\"CreateContractLimit\")) {\n throw new MUDError(`Error deploying ${contractName}: CreateContractLimit exceeded.`);\n } else throw error;\n }\n }\n\n /**\n * Deploy a contract and return the address\n * @param contractName Name of the contract to deploy (must exist in the file system)\n * @returns Address of the deployed contract\n *\n * NOTE: Forge deploy seems to be slightly slower than ethers\n * (probably due to the extra overhead spawning a child process to run forge),\n * so we mostly use ethersDeployContract here.\n * However, for contracts not in the user directory (eg. the vanilla World contract),\n * using forge is more convenient because it automatically finds the contract in the @latticexyz/world package.\n */\n // async function forgeDeployContract(contractName: string): Promise<string> {\n // console.log(chalk.blue(\"Deploying\", contractName));\n\n // const { deployedTo } = JSON.parse(\n // await forge(\n // [\"create\", contractName, \"--rpc-url\", rpc, \"--private-key\", privateKey, \"--json\", \"--nonce\", String(nonce++)],\n // { profile, silent: true }\n // )\n // );\n // return deployedTo;\n // }\n\n async function loadFunctionSignatures(contractName: string): Promise<FunctionSignature[]> {\n const { abi } = await getContractData(contractName);\n\n return abi\n .filter((item) => [\"fallback\", \"function\"].includes(item.type))\n .map((item) => {\n if (item.type === \"fallback\") return { functionName: \"\", functionArgs: \"\" };\n\n return {\n functionName: item.name,\n functionArgs: parseComponents(item.inputs),\n };\n });\n }\n\n /**\n * Recursively turn (nested) structs in signatures into tuples\n */\n function parseComponents(params: ParamType[]): string {\n const components = params.map((param) => (param.type === \"tuple\" ? parseComponents(param.components) : param.type));\n return `(${components})`;\n }\n\n /**\n * Only await gas estimation (for speed), only execute if gas estimation succeeds (for safety)\n */\n async function fastTxExecute<C extends { estimateGas: any; [key: string]: any }, F extends keyof C>(\n contract: C,\n func: F,\n args: Parameters<C[F]>,\n retryCount = 0,\n confirmations = 1\n ): Promise<Awaited<ReturnType<Awaited<ReturnType<C[F]>>[\"wait\"]>>> {\n const functionName = `${func as string}(${args.map((arg) => `'${arg}'`).join(\",\")})`;\n try {\n const gasLimit = await contract.estimateGas[func].apply(null, args);\n console.log(chalk.gray(`executing transaction: ${functionName} with nonce ${nonce}`));\n const txPromise = contract[func]\n .apply(null, [...args, { gasLimit, nonce: nonce++, maxPriorityFeePerGas, maxFeePerGas }])\n .then((tx: any) => tx.wait(confirmations));\n promises.push(txPromise);\n return txPromise;\n } catch (error: any) {\n if (debug) console.error(error);\n if (retryCount === 0 && error?.message.includes(\"transaction already imported\")) {\n // If the deployment failed because the transaction was already imported,\n // retry with a higher priority fee\n setInternalFeePerGas(priorityFeeMultiplier * 1.1);\n return fastTxExecute(contract, func, args, retryCount++, confirmations);\n } else throw new MUDError(`Gas estimation error for ${functionName}: ${error?.reason}`);\n }\n }\n\n /**\n * Load the contract's abi and bytecode from the file system\n * @param contractName: Name of the contract to load\n */\n async function getContractData(contractName: string): Promise<{ bytecode: string; abi: Fragment[] }> {\n let data: any;\n const contractDataPath = path.join(forgeOutDirectory, contractName + \".sol\", contractName + \".json\");\n try {\n data = JSON.parse(readFileSync(contractDataPath, \"utf8\"));\n } catch (error: any) {\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 abi = data?.abi;\n if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);\n\n return { abi, bytecode };\n }\n\n /**\n * Set the maxFeePerGas and maxPriorityFeePerGas based on the current base fee and the given multiplier.\n * The multiplier is used to allow replacing pending transactions.\n * @param multiplier Multiplier to apply to the base fee\n */\n async function setInternalFeePerGas(multiplier: number) {\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n const feeData = await provider.getFeeData();\n if (!feeData.lastBaseFeePerGas) throw new MUDError(\"Can not fetch lastBaseFeePerGas from RPC\");\n\n // Set the priority fee to 0 for development chains with no base fee, to allow transactions from unfunded wallets\n maxPriorityFeePerGas = feeData.lastBaseFeePerGas.eq(0) ? 0 : Math.floor(1_500_000_000 * multiplier);\n maxFeePerGas = feeData.lastBaseFeePerGas.mul(2).add(maxPriorityFeePerGas);\n }\n}\n\n// TODO: use stringToBytes16 from utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toBytes16(input: string) {\n if (input.length > 16) throw new Error(\"String does not fit into 16 bytes\");\n\n const result = new Uint8Array(16);\n // Set ascii bytes\n for (let i = 0; i < input.length; i++) {\n result[i] = input.charCodeAt(i);\n }\n // Set the remaining bytes to 0\n for (let i = input.length; i < 16; i++) {\n result[i] = 0;\n }\n return result;\n}\n\n// TODO: use TableId from utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toResourceSelector(namespace: string, file: string): Uint8Array {\n const namespaceBytes = toBytes16(namespace);\n const fileBytes = toBytes16(file);\n const result = new Uint8Array(32);\n result.set(namespaceBytes);\n result.set(fileBytes, 16);\n return result;\n}\n\ninterface FunctionSignature {\n functionName: string;\n functionArgs: string;\n}\n\n// TODO: move this to utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction toFunctionSelector({ functionName, functionArgs }: FunctionSignature): string {\n const functionSignature = functionName + functionArgs;\n if (functionSignature === \"\") return \"0x\";\n return sigHash(functionSignature);\n}\n\n// TODO: move this to utils as soon as utils are usable inside cli\n// (see https://github.com/latticexyz/mud/issues/499)\nfunction sigHash(signature: string) {\n return ethers.utils.hexDataSlice(ethers.utils.keccak256(ethers.utils.toUtf8Bytes(signature)), 0, 4);\n}\n","import { ethers } from \"ethers\";\n\n// TODO: Use viem's getChainId\nexport async function getChainId(rpc: string) {\n const { result: chainId } = await ethers.utils.fetchJson(\n rpc,\n '{ \"id\": 42, \"jsonrpc\": \"2.0\", \"method\": \"eth_chainId\", \"params\": [ ] }'\n );\n return Number(chainId);\n}\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig, worldgen } from \"@latticexyz/world\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport glob from \"glob\";\nimport path, { basename } from \"path\";\nimport { rmSync } from \"fs\";\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 config file\" },\n clean: { type: \"boolean\", desc: \"Clear the worldgen directory before generating new interfaces\" },\n });\n },\n\n async handler(args) {\n const { configPath, clean } = args;\n const srcDir = await getSrcDirectory();\n\n // Get a list of all contract names\n const existingContracts = glob.sync(`${srcDir}/**/*.sol`).map((path) => ({\n path,\n basename: basename(path, \".sol\"),\n }));\n\n // Load the config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n const outputBaseDirectory = path.join(srcDir, mudConfig.codegenDirectory);\n\n // clear the worldgen directory\n if (clean) rmSync(path.join(outputBaseDirectory, mudConfig.worldgenDirectory), { recursive: true, force: true });\n\n // generate new interfaces\n await worldgen(mudConfig, existingContracts, outputBaseDirectory);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { MUDError } from \"@latticexyz/config\";\nimport { logError } from \"../utils/errors\";\nimport localPackageJson from \"../../package.json\" assert { type: \"json\" };\n\ntype Options = {\n backup?: boolean;\n force?: boolean;\n restore?: boolean;\n mudVersion?: string;\n link?: string;\n};\n\nconst BACKUP_FILE = \".mudbackup\";\nconst MUD_PREFIX = \"@latticexyz\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"set-version\",\n\n describe: \"Install a custom MUD version and optionally backup the previously installed version\",\n\n builder(yargs) {\n return yargs.options({\n backup: { type: \"boolean\", description: `Back up the current MUD versions to \"${BACKUP_FILE}\"` },\n force: {\n type: \"boolean\",\n description: `Backup fails if a \"${BACKUP_FILE}\" file is found, unless --force is provided`,\n },\n restore: { type: \"boolean\", description: `Restore the previous MUD versions from \"${BACKUP_FILE}\"` },\n mudVersion: { alias: \"v\", type: \"string\", description: \"The MUD version to install\" },\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 if (!options.mudVersion && !options.link && !options.restore) {\n throw new MUDError(\"`--mudVersion` or `--link` is required unless --restore is provided.\");\n }\n\n // `link` and `mudVersion` are mutually exclusive\n if (options.link && options.mudVersion) {\n throw new MUDError(\"Options `--link` and `--mudVersion` are mutually exclusive\");\n }\n\n // Resolve the `canary` version number if needed\n options.mudVersion =\n options.mudVersion === \"canary\" ? await getCanaryVersion(localPackageJson.name) : options.mudVersion;\n\n // Read the current package.json\n const rootPath = \"./package.json\";\n const { workspaces } = updatePackageJson(rootPath, options);\n\n // Load the package.json of each workspace\n if (workspaces) {\n for (const workspace of workspaces) {\n const filePath = path.join(workspace, \"/package.json\");\n updatePackageJson(filePath, options);\n }\n }\n } catch (e) {\n logError(e);\n } finally {\n process.exit(0);\n }\n },\n};\n\nfunction updatePackageJson(filePath: string, options: Options): { workspaces?: string[] } {\n const { restore, force, link } = options;\n let { backup, mudVersion } = options;\n\n const backupFilePath = path.join(path.dirname(filePath), BACKUP_FILE);\n const backupFileExists = existsSync(backupFilePath);\n\n // Create a backup file for previous MUD versions by default if linking to local MUD\n if (link && !backupFileExists) backup = true;\n\n // If `backup` is true and force not set, check if a backup file already exists and throw an error if it does\n if (backup && !force && backupFileExists) {\n throw new MUDError(\n `A backup file already exists at ${backupFilePath}.\\nUse --force to overwrite it or --restore to restore it.`\n );\n }\n\n const packageJson = readPackageJson(filePath);\n\n // Load .mudbackup if `restore` is true\n const backupJson = restore ? readPackageJson(backupFilePath) : undefined;\n\n // Find all MUD dependencies\n const mudDependencies: Record<string, string> = {};\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDependencies[key] = packageJson.dependencies[key];\n }\n }\n\n // Find all MUD devDependencies\n const mudDevDependencies: Record<string, string> = {};\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDevDependencies[key] = packageJson.devDependencies[key];\n }\n }\n\n // Back up the current dependencies if `backup` is true\n if (backup) {\n writeFileSync(\n backupFilePath,\n JSON.stringify({ dependencies: mudDependencies, devDependencies: mudDevDependencies }, null, 2)\n );\n console.log(chalk.green(`Backed up MUD dependencies from ${filePath} to ${backupFilePath}`));\n }\n\n // Update the dependencies\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.dependencies[key] = resolveMudVersion(key, \"dependencies\");\n }\n }\n\n // Update the devDependencies\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.devDependencies[key] = resolveMudVersion(key, \"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 // Remove the backup file if `restore` is true and `backup` is false\n // because the old backup file is no longer needed\n if (restore && !backup) {\n rmSync(backupFilePath);\n console.log(chalk.green(`Cleaned up ${backupFilePath}`));\n }\n\n return packageJson;\n\n function resolveMudVersion(key: string, type: \"dependencies\" | \"devDependencies\") {\n if (restore && backupJson) return backupJson[type][key];\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\nasync function getCanaryVersion(pkg: string) {\n try {\n console.log(chalk.blue(\"fetching MUD canary version...\"));\n const result = await (await fetch(`https://registry.npmjs.org/${pkg}`)).json();\n const canary = result[\"dist-tags\"].canary;\n console.log(chalk.green(\"MUD canary version:\", canary));\n return canary;\n } catch (e) {\n throw new MUDError(`Could not fetch canary version of ${pkg}`);\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, pkg: string) {\n const pkgName = pkg.replace(MUD_PREFIX, \"\");\n const packageJsonToRootPath = path.relative(path.dirname(packageJsonPath), process.cwd());\n const linkPath = path.join(packageJsonToRootPath, mudLinkPath, \"packages\", pkgName);\n return \"link:\" + linkPath;\n}\n\nexport default commandModule;\n","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"1.42.0\",\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 \"types\": \"src/index.ts\",\n \"bin\": {\n \"mud\": \"./dist/mud.js\",\n \"mud2\": \"./dist/mud2.js\"\n },\n \"scripts\": {\n \"build\": \"pnpm run build:js\",\n \"build:js\": \"tsup && chmod +x ./dist/mud.js ./dist/mud2.js\",\n \"clean\": \"pnpm run clean:js\",\n \"clean:js\": \"rimraf dist\",\n \"dev\": \"tsup --watch\",\n \"generate-test-tables\": \"tsx ./scripts/generate-test-tables.ts\",\n \"lint\": \"eslint . --ext .ts\",\n \"test\": \"tsc --noEmit && pnpm run generate-test-tables && forge test\"\n },\n \"dependencies\": {\n \"@ethersproject/abi\": \"^5.7.0\",\n \"@ethersproject/providers\": \"^5.7.2\",\n \"@improbable-eng/grpc-web\": \"^0.15.0\",\n \"@improbable-eng/grpc-web-node-http-transport\": \"^0.15.0\",\n \"@latticexyz/common\": \"workspace:*\",\n \"@latticexyz/config\": \"workspace:*\",\n \"@latticexyz/schema-type\": \"workspace:*\",\n \"@latticexyz/services\": \"workspace:*\",\n \"@latticexyz/solecs\": \"workspace:*\",\n \"@latticexyz/std-contracts\": \"workspace:*\",\n \"@latticexyz/store\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"@typechain/ethers-v5\": \"^10.2.0\",\n \"chalk\": \"^5.0.1\",\n \"chokidar\": \"^3.5.3\",\n \"dotenv\": \"^16.0.3\",\n \"ds-test\": \"https://github.com/dapphub/ds-test.git#c9ce3f25bde29fc5eb9901842bf02850dfd2d084\",\n \"ejs\": \"^3.1.8\",\n \"ethers\": \"^5.7.2\",\n \"execa\": \"^7.0.0\",\n \"forge-std\": \"https://github.com/foundry-rs/forge-std.git#b4f121555729b3afb3c5ffccb62ff4b6e2818fd3\",\n \"glob\": \"^8.0.3\",\n \"nice-grpc-web\": \"^2.0.1\",\n \"openurl\": \"^1.1.1\",\n \"path\": \"^0.12.7\",\n \"table\": \"^6.8.1\",\n \"typechain\": \"^8.1.1\",\n \"typescript\": \"^4.9.5\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"^3.21.4\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/ejs\": \"^3.1.1\",\n \"@types/glob\": \"^7.2.0\",\n \"@types/node\": \"^18.15.11\",\n \"@types/openurl\": \"^1.0.0\",\n \"@types/yargs\": \"^17.0.10\",\n \"tsup\": \"^6.7.0\",\n \"tsx\": \"^3.12.6\",\n \"vitest\": \"0.30.1\"\n },\n \"gitHead\": \"914a1e0ae4a573d685841ca2ea921435057deb8f\"\n}\n","import type { CommandModule } from \"yargs\";\nimport { deployHandler, DeployOptions, yDeployOptions } from \"./deploy-v2\";\nimport { anvil, forge, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { rmSync, writeFileSync } from \"fs\";\n\ntype Options = DeployOptions & { port?: number; worldAddress?: string; forgeOptions?: string };\n\nconst WORLD_ADDRESS_FILE = \".mudtest\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"test-v2\",\n\n describe: \"Run tests in MUD v2 contracts\",\n\n builder(yargs) {\n return yargs.options({\n ...yDeployOptions,\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 });\n },\n\n async handler(args) {\n // Start an internal anvil process if no world address is provided\n if (!args.worldAddress) {\n const anvilArgs = [\"--block-base-fee-per-gas\", \"0\", \"--port\", String(args.port)];\n anvil(anvilArgs);\n }\n\n const forkRpc = args.worldAddress ? await getRpcUrl(args.profile) : `http://127.0.0.1:${args.port}`;\n\n const worldAddress =\n args.worldAddress ??\n (\n await deployHandler({\n ...args,\n saveDeployment: false,\n rpc: forkRpc,\n })\n ).worldAddress;\n\n console.log(chalk.blue(\"World address\", worldAddress));\n\n // Create a temporary file to pass the world address to the tests\n writeFileSync(WORLD_ADDRESS_FILE, worldAddress);\n\n const userOptions = args.forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n try {\n const testResult = await forge([\"test\", \"--fork-url\", forkRpc, ...userOptions], {\n profile: args.profile,\n });\n console.log(testResult);\n } catch (e) {\n console.error(e);\n }\n\n rmSync(WORLD_ADDRESS_FILE);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import { CommandModule } from \"yargs\";\n\nimport devnode from \"./devnode\";\nimport faucet from \"./faucet\";\nimport gasReport from \"./gas-report\";\nimport hello from \"./hello\";\nimport tablegen from \"./tablegen\";\nimport tsgen from \"./tsgen\";\nimport deployV2 from \"./deploy-v2\";\nimport worldgen from \"./worldgen\";\nimport setVersion from \"./set-version\";\nimport testV2 from \"./test-v2\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each command has different options\nexport const commands: CommandModule<any, any>[] = [\n deployV2,\n devnode,\n faucet,\n gasReport,\n hello,\n tablegen,\n tsgen,\n worldgen,\n setVersion,\n testV2,\n];\n"],"mappings":"yCAAA,OAAOA,MAAW,QAClB,OAAS,YAAAC,OAAgB,MACzB,OAAS,gBAAAC,GAAc,mBAAAC,OAAuB,uBAC9C,OAAS,yBAAAC,OAA6B,qBACtC,OAAS,YAAAC,OAAgB,qBAElB,SAASC,EAASC,EAAgB,CACvC,GAAIA,aAAiBJ,GACnB,QAAQ,IAAIH,EAAM,UAAUO,EAAM,OAAO,CAAC,UACjCA,aAAiBN,GAAU,CAGpC,IAAMO,EAAkBN,GAAaK,EAAO,CAC1C,gBAAiB;AAAA,IACjB,eAAgB;AAAA,GAClB,CAAC,EACD,QAAQ,IAAIP,EAAM,UAAUQ,EAAgB,OAAO,CAAC,OAC3CD,aAAiBH,IAC1B,QAAQ,IAAIJ,EAAM,IAAIO,EAAM,OAAO,CAAC,EACpC,QAAQ,IAAI,EAAE,EAGd,QAAQ,IAAIP,EAAM,KAAK,qFAAqF,CAAC,GACpGO,aAAiBF,GAC1B,QAAQ,IAAIL,EAA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,2BAA4B,IAAK,SAAU,OAAOD,EAAK,IAAI,CAAC,EAC/EV,GAAMW,CAAS,EAGjB,IAAMC,EAAUF,EAAK,aAAe,MAAMR,GAAUQ,EAAK,OAAO,EAAI,oBAAoBA,EAAK,OAEvFG,EACJH,EAAK,eAEH,MAAMI,GAAc,CAClB,GAAGJ,EACH,eAAgB,GAChB,IAAKE,CACP,CAAC,GACD,aAEJ,QAAQ,IAAIT,GAAM,KAAK,gBAAiBU,CAAY,CAAC,EAGrDR,GAAcC,GAAoBO,CAAY,EAE9C,IAAME,EAAcL,EAAK,cAAc,WAAW,KAAM,EAAE,EAAE,MAAM,GAAG,GAAK,CAAC,EAC3E,GAAI,CACF,IAAMM,EAAa,MAAMf,GAAM,CAAC,OAAQ,aAAcW,EAAS,GAAGG,CAAW,EAAG,CAC9E,QAASL,EAAK,OAChB,CAAC,EACD,QAAQ,IAAIM,CAAU,CACxB,OAASC,EAAP,CACA,QAAQ,MAAMA,CAAC,CACjB,CAEAb,GAAOE,EAAkB,EAEzB,QAAQ,KAAK,CAAC,CAChB,CACF,EAEOY,GAAQX,GCtDR,IAAMY,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EACF","names":["chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError","rmSync","homedir","path","execa","execLog","command","options","keccak256Bytes","toUtf8Bytes","readFileSync","IDregex","extractIdFromFile","path","content","regexResult","keccak256","data","readFile","writeFile","ejs","path","contractsDirectory","stubLibDeploy","generateLibDeploy","configPath","out","systems","config","systemsArray","system","LibDeploy","libDeployPath","resetLibDeploy","constants","Wallet","findLog","deployLogLines","log","logLine","runTypeChain","typechainGlob","glob","rmSync","writeFileSync","path","execa","copyFileSync","mkdirSync","readdirSync","rmSync","path","getOutDirectory","forgeBuild","options","out","getContractsInDirectory","dir","exclude","item","copyAbi","inDir","outDir","contract","filterAbi","abiIn","abiOut","include","contracts","getOutDirectory","getSrcDirectory","systemsDir","componentsDir","generateAbiTypes","inputDir","outputDir","options","rmSync","cwd","allFiles","typechainGlob","result","runTypeChain","generateSystemTypes","path","abis","systems","ids","typePaths","srcDir","getSrcDirectory","systemsPath","systemsDir","matches","glob","fragments","index","id","extractIdFromFile","system","SystemMappings","SystemTypes","SystemAbis","writeFileSync","generateTypes","abiDir","buildOutput","getOutDirectory","forgeBuild","filterAbi","execa","StaticJsonRpcProvider","path","contractsDirectory","deploy","deployerPrivateKey","rpc","worldAddress","reuseComponents","gasPrice","address","Wallet","constants","child","data","lines","deployedWorldAddress","findLog","initialBlockNumber","generateAndDeploy","args","libDeployPath","generateLibDeploy","generateTypes","result","resetLibDeploy","chokidar","readFileSync","ImportsRegex","extractImports","path","match","findDependencies","file","dependencyGraph","visited","dependencies","subDependencies","d","hsr","root","replaceSystems","systems","event","changedFile","imports","importedFile","changedSystems","f","commandModule","yargs","blocktime","userHomeDir","homedir","rmSync","path","child","execLog","devnode_default","FaucetServiceDefinition","createChannel","createClient","chalk","NodeHttpTransport","createFaucetService","url","commandModule","yargs","dripDev","faucetUrl","address","faucet","faucet_default","readFileSync","writeFileSync","rmSync","execa","chalk","table","getBorderCharacters","tempFileSuffix","commandModule","yargs","files","save","compare","validFiles","file","tempFiles","createGasReport","gasReport","runGasReport","compareGasReport","entry","prevEntry","e","printGasReport","saveGasReport","gas_report_default","filename","fileContents","newFile","functionRegex","functionMatch","functionSignature","regex","match","name","functionCall","tempFileName","logs","error","gasReportRegex","gasReportMatch","source","gasUsed","a","b","headers","values","diff","diffEntry","compareColumns","gasUsedEntry","rows","path","commandModule","yargs","name","greeting","hello_default","path","loadConfig","tablegen","getSrcDirectory","commandModule","yargs","configPath","config","srcDir","tablegen_default","loadConfig","commandModule","yargs","args","configPath","out","config","loadConfig","tsgen","tsgen_default","chalk","glob","path","basename","loadConfig","MUDError","existsSync","readFileSync","path","chalk","ethers","abi","getOutDirectory","getScriptDirectory","cast","forge","resolveWithContext","MUDError","encodeSchema","resolveAbiOrUserType","resolveWorldConfig","WorldData","IBaseWorldData","CoreModuleData","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","deploy","mudConfig","existingContracts","deployConfig","resolvedConfig","startTime","worldContractName","namespace","postDeployScript","profile","rpc","privateKey","priorityFeeMultiplier","debug","worldAddress","forgeOutDirectory","provider","signer","nonce","maxPriorityFeePerGas","maxFeePerGas","setInternalFeePerGas","promises","blockNumber","worldPromise","deployContractByName","deployContract","systemPromises","acc","systemName","defaultModules","modulePromises","module","contractPromises","WorldContract","fastTxExecute","toBytes16","tableIds","tableName","name","schema","primaryKeys","toResourceSelector","schemaTypes","abiOrUserType","schemaType","keyTypes","openAccess","registerFunctionSelectors","functionSignatures","loadFunctionSignatures","isRoot","functionName","functionArgs","functionSignature","worldFunctionSelector","toFunctionSelector","systemFunctionSelector","accessListAddresses","accessListSystems","resourceSelector","address","granteeSystem","resolvedArgs","arg","values","types","moduleAddress","postDeployPath","contractName","bytecode","getContractData","retryCount","factory","deployPromise","error","item","parseComponents","params","param","contract","func","args","confirmations","gasLimit","txPromise","tx","data","contractDataPath","multiplier","feeData","input","result","i","file","namespaceBytes","fileBytes","sigHash","signature","forge","getRpcUrl","getSrcDirectory","mkdirSync","writeFileSync","ethers","getChainId","rpc","chainId","yDeployOptions","deployHandler","args","configPath","printConfig","profile","clean","rpc","getRpcUrl","chalk","forge","srcDir","getSrcDirectory","existingContracts","glob","path","basename","mudConfig","loadConfig","privateKey","MUDError","deploymentInfo","deploy","chainId","getChainId","outputDir","mkdirSync","writeFileSync","error","logError","commandModule","yargs","deploy_v2_default","loadConfig","worldgen","getSrcDirectory","glob","path","basename","rmSync","commandModule","yargs","args","configPath","clean","srcDir","existingContracts","mudConfig","outputBaseDirectory","worldgen_default","chalk","existsSync","readFileSync","rmSync","writeFileSync","path","MUDError","package_default","BACKUP_FILE","MUD_PREFIX","commandModule","yargs","options","MUDError","getCanaryVersion","package_default","rootPath","workspaces","updatePackageJson","workspace","filePath","path","e","logError","restore","force","link","backup","mudVersion","backupFilePath","backupFileExists","existsSync","packageJson","readPackageJson","backupJson","mudDependencies","key","mudDevDependencies","writeFileSync","chalk","resolveMudVersion","logComparison","rmSync","type","resolveLinkPath","jsonString","readFileSync","pkg","canary","prev","curr","packageJsonPath","mudLinkPath","pkgName","packageJsonToRootPath","set_version_default","anvil","forge","getRpcUrl","chalk","rmSync","writeFileSync","WORLD_ADDRESS_FILE","commandModule","yargs","yDeployOptions","args","anvilArgs","forkRpc","worldAddress","deployHandler","userOptions","testResult","e","test_v2_default","commands","deploy_v2_default","devnode_default","faucet_default","gas_report_default","hello_default","tablegen_default","tsgen_default","worldgen_default","set_version_default","test_v2_default"]}
|
package/dist/mud.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as y,b as v,c as x,d as b,e as M,f as h,g as S,h as L,i as I,j as A,k as R,l as U,m as j}from"./chunk-
|
|
2
|
+
import{a as y,b as v,c as x,d as b,e as M,f as h,g as S,h as L,i as I,j as A,k as R,l as U,m as j}from"./chunk-4AVGUQ7C.js";import"./chunk-YGEQVVUG.js";import ye from"yargs";import{hideBin as ge}from"yargs/helpers";import{execa as z}from"execa";import H from"path";var V=new URL("../src/contracts",import.meta.url).pathname,Q={command:"bulkupload",describe:"Uploads the provided ECS state to the provided World",builder(e){return e.options({statePath:{type:"string",demandOption:!0,desc:"Path to the ECS state to upload"},worldAddress:{type:"string",demandOption:!0,desc:"Contract address of the World to upload to"},rpc:{type:"string",demandOption:!0,desc:"JSON RPC endpoint"}})},async handler({statePath:e,worldAddress:t,rpc:o}){console.log("Uploading state at ",e,"to",t,"on",o);let r=H.join(V,"BulkUpload.sol");console.log("Using BulkUpload script from",r);try{await z("forge",["script","--sig",'"run(string, address)"',"--rpc-url",o,`${r}:BulkUpload`,e,t])}catch(s){console.error(s)}process.exit(0)}},P=Q;import{getTestDirectory as X}from"@latticexyz/common/foundry";import{defaultAbiCoder as Y}from"ethers/lib/utils.js";import Z from"path";var _={command:"call-system",describe:"Execute a mud system",builder(e){return e.options({rpc:{type:"string",description:"json rpc endpoint, defaults to http://localhost:8545"},caller:{type:"string",description:"caller address"},world:{type:"string",required:!0,description:"world contract address"},systemId:{type:"string",description:"system id preimage (eg mud.system.Move)"},systemAddress:{type:"string",description:"system address (alternative to system id)"},argTypes:{type:"array",string:!0,description:"system argument types for abi encoding"},args:{type:"array",description:"system arguments"},calldata:{type:"string",description:"abi encoded system arguments (instead of args/argTypes)"},broadcast:{type:"boolean",description:"send txs to the chain"},callerPrivateKey:{type:"string",description:"must be set if broadcast is set, must correspond to caller address"},debug:{type:"boolean",description:"open debugger"}})},async handler({rpc:e,caller:t,world:o,systemId:r,argTypes:s,args:d,calldata:p,broadcast:c,callerPrivateKey:a,debug:m}){let l=p??(s&&d&&Y.encode(s,d))??"",n=await X();await y("forge",["script","--fork-url",e??"http://localhost:8545","--sig","debug(address,address,string,bytes,bool)",Z.join(n,"utils/Debug.sol"),t??"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",o,r||"",l,c?"true":"false","-vvvvv",c?"--broadcast":"",a?`--private-key ${a}`:"",m?"--debug":""]),process.exit(0)}},T=_;var K={command:"codegen-libdeploy",describe:"Generate LibDeploy.sol from given deploy config",builder(e){return e.options({config:{type:"string",default:"./deploy.json",desc:"Component and system deployment configuration"},out:{type:"string",default:".",desc:"Output directory for LibDeploy.sol"},systems:{type:"string",desc:"Only generate deploy code for the given systems"}})},async handler({config:e,out:t,systems:o}){await b(e,t,o),process.exit(0)}},W=K;import ee from"openurl";import k from"chalk";import{getSrcDirectory as te}from"@latticexyz/common/foundry";var oe={command:"deploy-contracts",describe:"Deploy mud contracts",builder(e){return e.options({config:{type:"string",default:"./deploy.json",desc:"Component and system deployment configuration"},deployerPrivateKey:{type:"string",desc:"Deployer private key. If omitted, deployment is not broadcasted."},worldAddress:{type:"string",desc:"World address to deploy to. If omitted, a new World is deployed."},rpc:{type:"string",default:"http://localhost:8545",desc:"RPC URL of the network to deploy to."},systems:{type:"string",desc:"Only upgrade the given systems. Requires World address."},reuseComponents:{type:"boolean",desc:"Skip deploying components and initialization."},watch:{type:"boolean",desc:"Automatically redeploy changed systems"},dev:{type:"boolean",desc:"Automatically use funded dev private key for local development"},openUrl:{type:"string",desc:"Opens a browser at the provided url with the worldAddress url param prefilled"},gasPrice:{type:"number",desc:"Gas price to set for deploy transactions"}})},async handler({config:e,deployerPrivateKey:t,worldAddress:o,rpc:r,systems:s,reuseComponents:d,watch:p,dev:c,openUrl:a,gasPrice:m}){s!=null&&!o&&(console.error("Error: Upgrading systems requires a World address."),process.exit(1)),t=t??(c?"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80":void 0);let l;try{l=await A({config:e,deployerPrivateKey:t,worldAddress:o,rpc:r,systems:s,reuseComponents:d,clear:!0,gasPrice:m})}catch(i){i.stderr||console.log(i),console.log(k.red(`
|
|
3
3
|
-----------
|
|
4
4
|
Error during generateAndDeploy (see above)`)),process.exit()}let{deployedWorldAddress:n,initialBlockNumber:w}=l;if(console.log("World deployed at",o,"at block",w),n&&a){let i=new URL(a);i.searchParams.set("worldAddress",n),console.log(""),console.log(k.cyan("Opening client URL to",i.toString())),console.log(""),ee.open(i.toString())}if(p){let i=await te();R(i,async O=>{try{return await A({config:e,deployerPrivateKey:t,worldAddress:o,rpc:r,systems:O,gasPrice:m,reuseComponents:!0})}catch(f){f.stderr||console.log(f),console.log(k.red(`
|
|
5
5
|
-----------
|
package/dist/mud2.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{l as o,m as r}from"./chunk-
|
|
2
|
+
import{l as o,m as r}from"./chunk-4AVGUQ7C.js";import"./chunk-YGEQVVUG.js";import i from"yargs";import{hideBin as a}from"yargs/helpers";import*as m from"dotenv";m.config();i(a(process.argv)).scriptName("mud").command(r).strict().fail((e,s)=>{console.log(""),o(s),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
|
3
3
|
//# sourceMappingURL=mud2.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latticexyz/cli",
|
|
3
|
-
"version": "2.0.0-alpha.1.
|
|
3
|
+
"version": "2.0.0-alpha.1.78+3079e4de",
|
|
4
4
|
"description": "Command line interface for mud",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -25,7 +25,6 @@
|
|
|
25
25
|
"dev": "tsup --watch",
|
|
26
26
|
"generate-test-tables": "tsx ./scripts/generate-test-tables.ts",
|
|
27
27
|
"lint": "eslint . --ext .ts",
|
|
28
|
-
"release": "npm publish --access=public",
|
|
29
28
|
"test": "tsc --noEmit && pnpm run generate-test-tables && forge test"
|
|
30
29
|
},
|
|
31
30
|
"dependencies": {
|
|
@@ -33,14 +32,14 @@
|
|
|
33
32
|
"@ethersproject/providers": "^5.7.2",
|
|
34
33
|
"@improbable-eng/grpc-web": "^0.15.0",
|
|
35
34
|
"@improbable-eng/grpc-web-node-http-transport": "^0.15.0",
|
|
36
|
-
"@latticexyz/common": "2.0.0-alpha.1.
|
|
37
|
-
"@latticexyz/config": "2.0.0-alpha.1.
|
|
38
|
-
"@latticexyz/schema-type": "2.0.0-alpha.1.
|
|
39
|
-
"@latticexyz/services": "2.0.0-alpha.1.
|
|
40
|
-
"@latticexyz/solecs": "2.0.0-alpha.1.
|
|
41
|
-
"@latticexyz/std-contracts": "2.0.0-alpha.1.
|
|
42
|
-
"@latticexyz/store": "2.0.0-alpha.1.
|
|
43
|
-
"@latticexyz/world": "2.0.0-alpha.1.
|
|
35
|
+
"@latticexyz/common": "2.0.0-alpha.1.78+3079e4de",
|
|
36
|
+
"@latticexyz/config": "2.0.0-alpha.1.78+3079e4de",
|
|
37
|
+
"@latticexyz/schema-type": "2.0.0-alpha.1.78+3079e4de",
|
|
38
|
+
"@latticexyz/services": "2.0.0-alpha.1.78+3079e4de",
|
|
39
|
+
"@latticexyz/solecs": "2.0.0-alpha.1.78+3079e4de",
|
|
40
|
+
"@latticexyz/std-contracts": "2.0.0-alpha.1.78+3079e4de",
|
|
41
|
+
"@latticexyz/store": "2.0.0-alpha.1.78+3079e4de",
|
|
42
|
+
"@latticexyz/world": "2.0.0-alpha.1.78+3079e4de",
|
|
44
43
|
"@typechain/ethers-v5": "^10.2.0",
|
|
45
44
|
"chalk": "^5.0.1",
|
|
46
45
|
"chokidar": "^3.5.3",
|
|
@@ -71,5 +70,5 @@
|
|
|
71
70
|
"tsx": "^3.12.6",
|
|
72
71
|
"vitest": "0.30.1"
|
|
73
72
|
},
|
|
74
|
-
"gitHead": "
|
|
73
|
+
"gitHead": "3079e4de73039f54accb227c3e2d3f538cdbceb5"
|
|
75
74
|
}
|