@latticexyz/cli 2.0.0-next.1 → 2.0.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-KN3UEKI6.js +11 -0
- package/dist/chunk-KN3UEKI6.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/mud.js +7 -7
- package/dist/mud.js.map +1 -1
- package/package.json +11 -11
- package/src/commands/dev-contracts.ts +0 -10
- package/src/commands/index.ts +0 -2
- package/src/index.ts +0 -1
- package/dist/chunk-P7JIR52V.js +0 -32
- package/dist/chunk-P7JIR52V.js.map +0 -1
- package/src/commands/tsgen.ts +0 -34
- package/src/render-ts/index.ts +0 -5
- package/src/render-ts/recsV1TableOptions.ts +0 -57
- package/src/render-ts/renderRecsV1Tables.ts +0 -35
- package/src/render-ts/schemaTypesToRecsTypeStrings.ts +0 -202
- package/src/render-ts/tsgen.ts +0 -12
- package/src/render-ts/types.ts +0 -17
@@ -0,0 +1,11 @@
|
|
1
|
+
import T from"chalk";import V from"path";import{MUDError as Ee}from"@latticexyz/common/errors";import{loadConfig as Oe}from"@latticexyz/config/node";import{existsSync as Ce,readFileSync as Se}from"fs";import oe from"path";import a from"chalk";import{ethers as j}from"ethers";import{defaultAbiCoder as De}from"ethers/lib/utils.js";import{getOutDirectory as Fe,getScriptDirectory as ve,cast as Ie,forge as xe}from"@latticexyz/common/foundry";import{resolveWithContext as Me}from"@latticexyz/config";import{MUDError as C}from"@latticexyz/common/errors";import{encodeSchema as ne}from"@latticexyz/schema-type/deprecated";import{resolveAbiOrUserType as re}from"@latticexyz/store/codegen";import{resolveWorldConfig as Re}from"@latticexyz/world";import je from"@latticexyz/world/abi/World.sol/World.json"assert{type:"json"};import se from"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json"assert{type:"json"};import ie from"@latticexyz/world/abi/CoreModule.sol/CoreModule.json"assert{type:"json"};import ae from"@latticexyz/world/abi/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import le from"@latticexyz/world/abi/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import ce from"@latticexyz/world/abi/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import de from"@latticexyz/world/abi/SnapSyncModule.sol/SnapSyncModule.json"assert{type:"json"};async function pe(r,g,u){let f=Re(r,g),M=Date.now(),{worldContractName:B,namespace:i,postDeployScript:k}=r,{profile:A,rpc:b,privateKey:E,priorityFeeMultiplier:h,debug:F,worldAddress:v,disableTxWait:y,pollInterval:W}=u,fe=await Fe(A),U=new j.providers.StaticJsonRpcProvider(b);U.pollingInterval=W;let S=new j.Wallet(E,U);console.log("Deploying from",S.address);let I=await S.getTransactionCount();console.log("Initial nonce",I);let O,N,K;await L(h);let d=[],z=Number(await Ie(["block-number","--rpc-url",b],{profile:A}));console.log("Start deployment at block",z);let be={World:v?Promise.resolve(v):B?J(B,y):x(se.abi,je.bytecode,y,"World")},we=Object.keys(f.systems).reduce((e,t)=>(e[t]=J(t,y),e),{}),H={CoreModule:x(ie.abi,ie.bytecode,y,"CoreModule"),KeysWithValueModule:x(ae.abi,ae.bytecode,y,"KeysWithValueModule"),KeysInTableModule:x(le.abi,le.bytecode,y,"KeysInTableModule"),UniqueEntityModule:x(ce.abi,ce.bytecode,y,"UniqueEntityModule"),SnapSyncModule:x(de.abi,de.bytecode,y,"SnapSyncModule")},Q=r.modules.filter(e=>!H[e.name]).reduce((e,t)=>(e[t.name]=J(t.name,y),e),H),R={...be,...we,...Q},$=new j.Contract(await R.World,se.abi,S),P=y?0:1;v||(console.log(a.blue("Installing core World modules")),await w($,"installRootModule",[await Q.CoreModule,"0x"],P),console.log(a.green("Installed core World modules"))),i&&await w($,"registerNamespace",[p(i)],P);let X={};d=[...d,...Object.entries(r.tables).map(async([e,{name:t,schema:o,keySchema:s}])=>{console.log(a.blue(`Registering table ${e} at ${i}/${t}`)),X[e]=ke(i,t);let c=Object.values(o).map(l=>{let{schemaType:m}=re(l,r);return m}),n=Object.values(s).map(l=>{let{schemaType:m}=re(l,r);return m});await w($,"registerTable",[p(i),p(t),ne(c),ne(n)],P),await w($,"setMetadata(bytes16,bytes16,string,string[])",[p(i),p(t),e,Object.keys(o)],P),console.log(a.green(`Registered table ${e} at ${t}`))})],d=[...d,...Object.entries(f.systems).map(async([e,{name:t,openAccess:o,registerFunctionSelectors:s}])=>{if(console.log(a.blue(`Registering system ${e} at ${i}/${t}`)),await w($,"registerSystem",[p(i),p(t),await R[e],o],P),console.log(a.green(`Registered system ${e} at ${i}/${t}`)),s){let c=await he(e),n=i==="";await Promise.all(c.map(async({functionName:l,functionArgs:m})=>{let D=n?l+m:`${i}_${t}_${l}${m}`;if(console.log(a.blue(`Registering function "${D}"`)),n){let $e=ue(D===""?{functionName:e,functionArgs:m}:{functionName:l,functionArgs:m}),Pe=ue({functionName:l,functionArgs:m});await w($,"registerRootFunctionSelector",[p(i),p(t),$e,Pe],P)}else await w($,"registerFunctionSelector",[p(i),p(t),l,m],P);console.log(a.green(`Registered function "${D}"`))}))}})],await Promise.all(d),d=[];for(let[e,{name:t,accessListAddresses:o,accessListSystems:s}]of Object.entries(f.systems)){let c=`${i}/${t}`;d=[...d,...o.map(async n=>{console.log(a.blue(`Grant ${n} access to ${e} (${c})`)),await w($,"grantAccess",[p(i),p(t),n],P),console.log(a.green(`Granted ${n} access to ${e} (${i}/${t})`))})],d=[...d,...s.map(async n=>{console.log(a.blue(`Grant ${n} access to ${e} (${c})`)),await w($,"grantAccess",[p(i),p(t),await R[n]],P),console.log(a.green(`Granted ${n} access to ${e} (${c})`))})]}await Promise.all(d),d=[],d=[...d,...r.modules.map(async e=>{console.log(a.blue(`Installing${e.root?" root ":" "}module ${e.name}`));let t=await Promise.all(e.args.map(n=>Me(n,{tableIds:X,systemAddresses:R}))),o=t.map(n=>n.value),s=t.map(n=>n.type),c=await R[e.name];if(!c)throw new Error(`Module ${e.name} not found`);await w($,e.root?"installRootModule":"installModule",[c,De.encode(s,o)],P),console.log(a.green(`Installed${e.root?" root ":" "}module ${e.name}`))})],await Promise.all(d);let G=await S.getTransactionCount(),_=0,Z=100;for(;G!==I&&_<Z;)console.log(a.gray(`Waiting for transactions to be included before executing ${k} (local nonce: ${I}, remote nonce: ${G}, retry number ${_}/${Z})`)),await new Promise(e=>setTimeout(e,W)),_++,G=await S.getTransactionCount();if(G!==I)throw new C("Remote nonce doesn't match local nonce, indicating that not all deploy transactions were included.");d=[];let q=oe.join(await ve(),k+".s.sol");return Ce(q)?(console.log(a.blue(`Executing post deploy script at ${q}`)),await xe(["script",k,"--sig","run(address)",await R.World,"--broadcast","--rpc-url",b,"-vvv"],{profile:A})):console.log(`No script at ${q}, skipping post deploy hook`),console.log(a.green("Deployment completed in",(Date.now()-M)/1e3,"seconds")),{worldAddress:await R.World,blockNumber:z};async function J(e,t){console.log(a.blue("Deploying",e));let{abi:o,bytecode:s}=await te(e);return x(o,s,t,e)}async function x(e,t,o,s,c=0){try{let n=new j.ContractFactory(e,t,S);console.log(a.gray(`executing deployment of ${s} with nonce ${I}`));let l=n.deploy({nonce:I++,maxPriorityFeePerGas:O,maxFeePerGas:N,gasPrice:K}).then(D=>o?D:D.deployed());d.push(l);let{address:m}=await l;return console.log(a.green("Deployed",s,"to",m)),m}catch(n){if(F&&console.error(n),c===0&&n?.message.includes("transaction already imported"))return L(h*1.1),x(e,t,o,s,c++);throw n?.message.includes("invalid bytecode")?new C(`Error deploying ${s}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use "external" functions.`):n?.message.includes("CreateContractLimit")?new C(`Error deploying ${s}: CreateContractLimit exceeded.`):n}}async function he(e){let{abi:t}=await te(e);return t.filter(o=>["fallback","function"].includes(o.type)).map(o=>o.type==="fallback"?{functionName:"",functionArgs:""}:{functionName:o.name,functionArgs:ee(o.inputs)})}function ee(e){return`(${e.map(o=>{let s=o.type.match(/tuple(.*)/);return s?ee(o.components)+s[1]:o.type})})`}async function w(e,t,o,s=1,c=0){let n=`${t}(${o.map(l=>`'${l}'`).join(",")})`;try{let l=await e.estimateGas[t].apply(null,o);console.log(a.gray(`executing transaction: ${n} with nonce ${I}`));let m=e[t].apply(null,[...o,{gasLimit:l,nonce:I++,maxPriorityFeePerGas:O,maxFeePerGas:N,gasPrice:K}]).then(D=>s===0?D:D.wait(s));return d.push(m),m}catch(l){if(F&&console.error(l),c===0&&l?.message.includes("transaction already imported"))return L(h*1.1),w(e,t,o,s,c++);throw new C(`Gas estimation error for ${n}: ${l?.reason}`)}}async function te(e){let t,o=oe.join(fe,e+".sol",e+".json");try{t=JSON.parse(Se(o,"utf8"))}catch{throw new C(`Error reading file at ${o}`)}let s=t?.bytecode?.object;if(!s)throw new C(`No bytecode found in ${o}`);let c=t?.abi;if(!c)throw new C(`No ABI found in ${o}`);return{abi:c,bytecode:s}}async function L(e){let t=await U.getFeeData();if(t.lastBaseFeePerGas){if(!t.lastBaseFeePerGas.eq(0)&&(await S.getBalance()).eq(0))throw new C(`Attempting to deploy to a chain with non-zero base fee with an account that has no balance.
|
2
|
+
If you're deploying to the Lattice testnet, you can fund your account by running 'pnpm mud faucet --address ${await S.getAddress()}'`);O=t.lastBaseFeePerGas.eq(0)?0:Math.floor(15e8*e),N=t.lastBaseFeePerGas.mul(2).add(O)}else if(t.gasPrice){if(!t.gasPrice.eq(0)&&(await S.getBalance()).eq(0))throw new C("Attempting to deploy to a chain with non-zero gas price with an account that has no balance.");K=t.gasPrice}else throw new C("Can not fetch fee data from RPC")}}function p(r){if(r.length>16)throw new Error("String does not fit into 16 bytes");let g=new Uint8Array(16);for(let u=0;u<r.length;u++)g[u]=r.charCodeAt(u);for(let u=r.length;u<16;u++)g[u]=0;return g}function ke(r,g){let u=p(r),f=p(g),M=new Uint8Array(32);return M.set(u),M.set(f,16),M}function ue({functionName:r,functionArgs:g}){let u=r+g;return u===""?"0x":Ae(u)}function Ae(r){return j.utils.hexDataSlice(j.utils.keccak256(j.utils.toUtf8Bytes(r)),0,4)}import{forge as ye,getRpcUrl as Ge,getSrcDirectory as Ue}from"@latticexyz/common/foundry";import{existsSync as Ne,mkdirSync as Ke,readFileSync as _e,writeFileSync as Y}from"fs";import{ethers as We}from"ethers";async function ge(r){let{result:g}=await We.utils.fetchJson(r,'{ "id": 42, "jsonrpc": "2.0", "method": "eth_chainId", "params": [ ] }');return Number(g)}import Te from"glob";import{basename as Be}from"path";function me(r){return Te.sync(`${r}/**/*.sol`).map(g=>({path:g,basename:Be(g,".sol")}))}async function xt(r){r.profile??=process.env.FOUNDRY_PROFILE;let{configPath:g,printConfig:u,profile:f,clean:M,skipBuild:B}=r,i=r.rpc??await Ge(f);console.log(T.bgBlue(T.whiteBright(`
|
3
|
+
Deploying MUD contracts${f?" with profile "+f:""} to RPC ${i}
|
4
|
+
`))),M&&await ye(["clean"],{profile:f}),B||await ye(["build"],{profile:f});let k=r?.srcDir??await Ue(),A=me(k).map(({basename:F})=>F),b=await Oe(g);u&&console.log(T.green(`
|
5
|
+
Resolved config:
|
6
|
+
`),JSON.stringify(b,null,2));let E=process.env.PRIVATE_KEY;if(!E)throw new Ee(`Missing PRIVATE_KEY environment variable.
|
7
|
+
Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
|
8
|
+
in your contracts directory to use the default anvil private key.`);let h=await pe(b,A,{...r,rpc:i,privateKey:E});if(r.saveDeployment){let F=await ge(i),v=V.join(b.deploysDirectory,F.toString());Ke(v,{recursive:!0}),Y(V.join(v,"latest.json"),JSON.stringify(h,null,2)),Y(V.join(v,Date.now()+".json"),JSON.stringify(h,null,2));let y=[1337,31337],W=Ne(b.worldsFile)?JSON.parse(_e(b.worldsFile,"utf-8")):{};W[F]={address:h.worldAddress,blockNumber:y.includes(F)?void 0:h.blockNumber},Y(b.worldsFile,JSON.stringify(W,null,2)),console.log(T.bgGreen(T.whiteBright(`
|
9
|
+
Deployment result (written to ${b.worldsFile} and ${v}):
|
10
|
+
`)))}return console.log(h),h}export{ge as a,me as b,xt as c};
|
11
|
+
//# sourceMappingURL=chunk-KN3UEKI6.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/utils/deployHandler.ts","../src/utils/deploy.ts","../src/utils/getChainId.ts","../src/utils/getExistingContracts.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport path from \"path\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { deploy } from \"../utils/deploy\";\nimport { forge, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { getChainId } from \"../utils/getChainId\";\nimport { getExistingContracts } from \"./getExistingContracts\";\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 disableTxWait: boolean;\n pollInterval: number;\n skipBuild?: boolean;\n};\n\nexport async function deployHandler(args: DeployOptions) {\n args.profile ??= process.env.FOUNDRY_PROFILE;\n const { configPath, printConfig, profile, clean, skipBuild } = args;\n\n const rpc = args.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Deploying MUD contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`)\n )\n );\n\n if (clean) await forge([\"clean\"], { profile });\n\n // Run forge build\n if (!skipBuild) await forge([\"build\"], { profile });\n\n // Get a list of all contract names\n const srcDir = args?.srcDir ?? (await getSrcDirectory());\n const existingContractNames = getExistingContracts(srcDir).map(({ basename }) => basename);\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 const privateKey = process.env.PRIVATE_KEY;\n if (!privateKey)\n throw new MUDError(\n `Missing PRIVATE_KEY environment variable.\nRun 'echo \"PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80\" > .env'\nin your contracts directory to use the default anvil private key.`\n );\n const deploymentInfo = await deploy(mudConfig, existingContractNames, { ...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 const localChains = [1337, 31337];\n const deploys = existsSync(mudConfig.worldsFile) ? JSON.parse(readFileSync(mudConfig.worldsFile, \"utf-8\")) : {};\n deploys[chainId] = {\n address: deploymentInfo.worldAddress,\n // We expect the worlds file to be committed and since local deployments are often a consistent address but different block number, we'll ignore the block number.\n blockNumber: localChains.includes(chainId) ? undefined : deploymentInfo.blockNumber,\n };\n writeFileSync(mudConfig.worldsFile, JSON.stringify(deploys, null, 2));\n\n console.log(\n chalk.bgGreen(chalk.whiteBright(`\\n Deployment result (written to ${mudConfig.worldsFile} and ${outputDir}): \\n`))\n );\n }\n\n console.log(deploymentInfo);\n return deploymentInfo;\n}\n","import { 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/common/errors\";\nimport { encodeSchema } from \"@latticexyz/schema-type/deprecated\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { resolveAbiOrUserType } from \"@latticexyz/store/codegen\";\nimport { WorldConfig, resolveWorldConfig } from \"@latticexyz/world\";\nimport { IBaseWorld } from \"@latticexyz/world/types/ethers-contracts/IBaseWorld\";\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\" };\nimport SnapSyncModuleData from \"@latticexyz/world/abi/SnapSyncModule.sol/SnapSyncModule.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 disableTxWait: boolean;\n pollInterval: number;\n}\n\nexport interface DeploymentInfo {\n blockNumber: number;\n worldAddress: string;\n}\n\nexport async function deploy(\n mudConfig: StoreConfig & WorldConfig,\n existingContractNames: string[],\n deployConfig: DeployConfig\n): Promise<DeploymentInfo> {\n const resolvedConfig = resolveWorldConfig(mudConfig, existingContractNames);\n\n const startTime = Date.now();\n const { worldContractName, namespace, postDeployScript } = mudConfig;\n const { profile, rpc, privateKey, priorityFeeMultiplier, debug, worldAddress, disableTxWait, pollInterval } =\n deployConfig;\n const forgeOutDirectory = await getOutDirectory(profile);\n\n // Set up signer for deployment\n const provider = new ethers.providers.StaticJsonRpcProvider(rpc);\n provider.pollingInterval = pollInterval;\n const signer = new ethers.Wallet(privateKey, provider);\n console.log(\"Deploying from\", signer.address);\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 | undefined;\n let maxFeePerGas: BigNumber | undefined;\n let gasPrice: BigNumber | undefined;\n\n await 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, disableTxWait)\n : deployContract(IBaseWorldData.abi, WorldData.bytecode, disableTxWait, \"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, disableTxWait);\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, disableTxWait, \"CoreModule\"),\n KeysWithValueModule: deployContract(\n KeysWithValueModuleData.abi,\n KeysWithValueModuleData.bytecode,\n disableTxWait,\n \"KeysWithValueModule\"\n ),\n KeysInTableModule: deployContract(\n KeysInTableModuleData.abi,\n KeysInTableModuleData.bytecode,\n disableTxWait,\n \"KeysInTableModule\"\n ),\n UniqueEntityModule: deployContract(\n UniqueEntityModuleData.abi,\n UniqueEntityModuleData.bytecode,\n disableTxWait,\n \"UniqueEntityModule\"\n ),\n SnapSyncModule: deployContract(\n SnapSyncModuleData.abi,\n SnapSyncModuleData.bytecode,\n disableTxWait,\n \"SnapSyncModule\"\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, disableTxWait);\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 const confirmations = disableTxWait ? 0 : 1;\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\"], confirmations);\n console.log(chalk.green(\"Installed core World modules\"));\n }\n\n // Register namespace\n if (namespace) await fastTxExecute(WorldContract, \"registerNamespace\", [toBytes16(namespace)], confirmations);\n\n // Register tables\n const tableIds: { [tableName: string]: Uint8Array } = {};\n promises = [\n ...promises,\n ...Object.entries(mudConfig.tables).map(async ([tableName, { name, schema, keySchema }]) => {\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(keySchema).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);\n return schemaType;\n });\n\n await fastTxExecute(\n WorldContract,\n \"registerTable\",\n [toBytes16(namespace), toBytes16(name), encodeSchema(schemaTypes), encodeSchema(keyTypes)],\n confirmations\n );\n\n // Register table metadata\n await fastTxExecute(\n WorldContract,\n \"setMetadata(bytes16,bytes16,string,string[])\",\n [toBytes16(namespace), toBytes16(name), tableName, Object.keys(schema)],\n confirmations\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(\n WorldContract,\n \"registerSystem\",\n [toBytes16(namespace), toBytes16(name), await contractPromises[systemName], openAccess],\n confirmations\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(\n WorldContract,\n \"registerRootFunctionSelector\",\n [toBytes16(namespace), toBytes16(name), worldFunctionSelector, systemFunctionSelector],\n confirmations\n );\n } else {\n await fastTxExecute(\n WorldContract,\n \"registerFunctionSelector\",\n [toBytes16(namespace), toBytes16(name), functionName, functionArgs],\n confirmations\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(\n WorldContract,\n \"grantAccess\",\n [toBytes16(namespace), toBytes16(name), address],\n confirmations\n );\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(\n WorldContract,\n \"grantAccess\",\n [toBytes16(namespace), toBytes16(name), await contractPromises[granteeSystem]],\n confirmations\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(\n WorldContract,\n module.root ? \"installRootModule\" : \"installModule\",\n [moduleAddress, abi.encode(types, values)],\n confirmations\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\n // Confirm the current nonce is the expected nonce to make sure all transactions have been included\n let remoteNonce = await signer.getTransactionCount();\n let retryCount = 0;\n const maxRetries = 100;\n while (remoteNonce !== nonce && retryCount < maxRetries) {\n console.log(\n chalk.gray(\n `Waiting for transactions to be included before executing ${postDeployScript} (local nonce: ${nonce}, remote nonce: ${remoteNonce}, retry number ${retryCount}/${maxRetries})`\n )\n );\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n retryCount++;\n remoteNonce = await signer.getTransactionCount();\n }\n if (remoteNonce !== nonce) {\n throw new MUDError(\n \"Remote nonce doesn't match local nonce, indicating that not all deploy transactions were included.\"\n );\n }\n\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 * @param disableTxWait Disable waiting for contract deployment\n * @returns Address of the deployed contract\n */\n async function deployContractByName(contractName: string, disableTxWait: boolean): Promise<string> {\n console.log(chalk.blue(\"Deploying\", contractName));\n\n const { abi, bytecode } = await getContractData(contractName);\n return deployContract(abi, bytecode, disableTxWait, 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 disableTxWait Disable waiting for contract deployment\n * @param contractName The contract name (optional, used for logs)\n * @param retryCount\n * @returns Address of the deployed contract\n */\n async function deployContract(\n abi: ContractInterface,\n bytecode: string | { object: string },\n disableTxWait: boolean,\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\n .deploy({\n nonce: nonce++,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gasPrice,\n })\n .then((c) => (disableTxWait ? c : c.deployed()));\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, disableTxWait, 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) => {\n const tupleMatch = param.type.match(/tuple(.*)/);\n if (tupleMatch) {\n // there can be arrays of tuples,\n // `tupleMatch[1]` preserves the array brackets (or is empty string for non-arrays)\n return parseComponents(param.components) + tupleMatch[1];\n } else {\n return param.type;\n }\n });\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 confirmations = 1,\n retryCount = 0\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, gasPrice }])\n .then((tx: any) => (confirmations === 0 ? tx : 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, confirmations, retryCount++);\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\n if (feeData.lastBaseFeePerGas) {\n if (!feeData.lastBaseFeePerGas.eq(0) && (await signer.getBalance()).eq(0)) {\n throw new MUDError(`Attempting to deploy to a chain with non-zero base fee with an account that has no balance.\n If you're deploying to the Lattice testnet, you can fund your account by running 'pnpm mud faucet --address ${await signer.getAddress()}'`);\n }\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 } else if (feeData.gasPrice) {\n // Legacy chains with gasPrice instead of maxFeePerGas\n if (!feeData.gasPrice.eq(0) && (await signer.getBalance()).eq(0)) {\n throw new MUDError(\n `Attempting to deploy to a chain with non-zero gas price with an account that has no balance.`\n );\n }\n\n gasPrice = feeData.gasPrice;\n } else {\n throw new MUDError(\"Can not fetch fee data from RPC\");\n }\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 glob from \"glob\";\nimport { basename } from \"path\";\n\n/**\n * Get a list of all contract paths/names within the provided src directory\n */\nexport function getExistingContracts(srcDir: string) {\n return glob.sync(`${srcDir}/**/*.sol`).map((path) => ({\n path,\n basename: basename(path, \".sol\"),\n }));\n}\n"],"mappings":"AAAA,OAAOA,MAAW,QAClB,OAAOC,MAAU,OACjB,OAAS,YAAAC,OAAgB,4BACzB,OAAS,cAAAC,OAAkB,0BCH3B,OAAS,cAAAC,GAAY,gBAAAC,OAAoB,KACzC,OAAOC,OAAU,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KAAK,UAAUJ,EAAgB,KAAM,CAAC,CAAC,EAC1FO,EAAcF,EAAK,KAAKD,EAAW,KAAK,IAAI,EAAI,OAAO,EAAG,KAAK,UAAUJ,EAAgB,KAAM,CAAC,CAAC,EAEjG,IAAMQ,EAAc,CAAC,KAAM,KAAK,EAC1BC,EAAUC,GAAWd,EAAU,UAAU,EAAI,KAAK,MAAMe,GAAaf,EAAU,WAAY,OAAO,CAAC,EAAI,CAAC,EAC9Ga,EAAQP,CAAO,EAAI,CACjB,QAASF,EAAe,aAExB,YAAaQ,EAAY,SAASN,CAAO,EAAI,OAAYF,EAAe,WAC1E,EACAO,EAAcX,EAAU,WAAY,KAAK,UAAUa,EAAS,KAAM,CAAC,CAAC,EAEpE,QAAQ,IACNpB,EAAM,QAAQA,EAAM,YAAY;AAAA,iCAAoCO,EAAU,kBAAkBQ;AAAA,CAAgB,CAAC,CACnH,EAGF,eAAQ,IAAIJ,CAAc,EACnBA,CACT","names":["chalk","path","MUDError","loadConfig","existsSync","readFileSync","path","chalk","ethers","abi","getOutDirectory","getScriptDirectory","cast","forge","resolveWithContext","MUDError","encodeSchema","resolveAbiOrUserType","resolveWorldConfig","WorldData","IBaseWorldData","CoreModuleData","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","SnapSyncModuleData","deploy","mudConfig","existingContractNames","deployConfig","resolvedConfig","startTime","worldContractName","namespace","postDeployScript","profile","rpc","privateKey","priorityFeeMultiplier","debug","worldAddress","disableTxWait","pollInterval","forgeOutDirectory","provider","signer","nonce","maxPriorityFeePerGas","maxFeePerGas","gasPrice","setInternalFeePerGas","promises","blockNumber","worldPromise","deployContractByName","deployContract","systemPromises","acc","systemName","defaultModules","modulePromises","module","contractPromises","WorldContract","confirmations","fastTxExecute","toBytes16","tableIds","tableName","name","schema","keySchema","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","remoteNonce","retryCount","maxRetries","resolve","postDeployPath","contractName","bytecode","getContractData","factory","deployPromise","c","error","item","parseComponents","params","param","tupleMatch","contract","func","args","gasLimit","txPromise","tx","data","contractDataPath","multiplier","feeData","input","result","i","file","namespaceBytes","fileBytes","sigHash","signature","forge","getRpcUrl","getSrcDirectory","existsSync","mkdirSync","readFileSync","writeFileSync","ethers","getChainId","rpc","chainId","glob","basename","getExistingContracts","srcDir","path","deployHandler","args","configPath","printConfig","profile","clean","skipBuild","rpc","getRpcUrl","chalk","forge","srcDir","getSrcDirectory","existingContractNames","getExistingContracts","basename","mudConfig","loadConfig","privateKey","MUDError","deploymentInfo","deploy","chainId","getChainId","outputDir","path","mkdirSync","writeFileSync","localChains","deploys","existsSync","readFileSync"]}
|
package/dist/index.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
import{
|
1
|
+
import{c as o}from"./chunk-KN3UEKI6.js";export{o as deployHandler};
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/mud.js
CHANGED
@@ -1,16 +1,16 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{
|
3
|
-
gracefully shutting down from SIGINT (Crtl-C)`),
|
2
|
+
import{a as P,b as M,c as w}from"./chunk-KN3UEKI6.js";import xo from"yargs";import{hideBin as Mo}from"yargs/helpers";import ko from"@latticexyz/gas-report";import{rmSync as se}from"fs";import{homedir as ae}from"os";import ce from"path";import{execa as de}from"execa";var le={command:"devnode",describe:"Start a local Ethereum node for development",builder(e){return e.options({blocktime:{type:"number",default:1,decs:"Interval in which new blocks are produced"}})},async handler({blocktime:e}){console.log("Clearing devnode history");let o=ae();se(ce.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let n=de("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
|
3
|
+
gracefully shutting down from SIGINT (Crtl-C)`),n.kill(),process.exit()}),await n}},W=le;import{FaucetServiceDefinition as pe}from"@latticexyz/services/faucet";import{createChannel as me,createClient as fe}from"nice-grpc-web";import R from"chalk";import{NodeHttpTransport as ge}from"@improbable-eng/grpc-web-node-http-transport";function ue(e){return fe(pe,me(e,ge()))}var ye={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:t}){let n=ue(o);e&&(console.log(R.yellow("Dripping to",t)),await n.dripDev({address:t}),console.log(R.yellow("Success"))),process.exit(0)}},I=ye;var he={command:"hello <name>",describe:"Greet <name> with Hello",builder(e){return e.options({upper:{type:"boolean"}}).positional("name",{type:"string",demandOption:!0})},handler({name:e}){let o=`Gm, ${e}!`;console.log(o),process.exit(0)}},$=he;import be from"path";import{loadConfig as we}from"@latticexyz/config/node";import{tablegen as ve}from"@latticexyz/store/codegen";import{getSrcDirectory as De}from"@latticexyz/common/foundry";var Ce={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"}})},async handler({configPath:e}){let o=await we(e),t=await De();await ve(o,be.join(t,o.codegenDirectory)),process.exit(0)}},E=Ce;import D from"chalk";import{ZodError as ke}from"zod";import{fromZodError as xe,ValidationError as Me}from"zod-validation-error";import{NotInsideProjectError as Se}from"@latticexyz/config";import{MUDError as Oe}from"@latticexyz/common/errors";function g(e){if(e instanceof Me)console.log(D.redBright(e.message));else if(e instanceof ke){let o=xe(e,{prefixSeparator:`
|
4
4
|
- `,issueSeparator:`
|
5
|
-
- `});console.log(D.redBright(o.message))}else e instanceof
|
5
|
+
- `});console.log(D.redBright(o.message))}else e instanceof Se?(console.log(D.red(e.message)),console.log(""),console.log(D.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Oe?console.log(D.red(e)):console.log(e)}import Ue from"chalk";function A(){console.log(Ue.yellow(`
|
6
6
|
.------..------..------.
|
7
7
|
|M.--. ||U.--. ||D.--. |
|
8
8
|
| (\\/) || (\\/) || :/\\: |
|
9
9
|
| :\\/: || :\\/: || (__) |
|
10
10
|
| '--'M|| '--'U|| '--'D|
|
11
11
|
'------''------''------'
|
12
|
-
`))}import{getOutDirectory as
|
13
|
-
Use --force to overwrite it or --restore to restore it.`);let s=
|
14
|
-
`),console.log(`Updating ${e}`),
|
15
|
-
`)),g(p)}a.current=!1,(
|
12
|
+
`))}import{getOutDirectory as je}from"@latticexyz/common/foundry";import Pe from"path";import{runTypeChain as We}from"typechain";async function F(){let e=process.cwd(),o=await je(),t=Pe.join(process.cwd(),o,"IWorld.sol/IWorld.json");await We({cwd:e,filesToProcess:[t],allFiles:[t],target:"ethers-v5"}),console.log("Typechain generated IWorld interface")}var U={configPath:{type:"string",desc:"Path to the config file"},clean:{type:"boolean",desc:"Remove the build forge artifacts and cache directories before building"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},debug:{type:"boolean",desc:"Print debug logs, like full error messages"},priorityFeeMultiplier:{type:"number",desc:"Multiply the estimated priority fee by the provided factor",default:1},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},disableTxWait:{type:"boolean",desc:"Disable waiting for transactions to be confirmed.",default:!1},pollInterval:{type:"number",desc:"Interval in miliseconds to use to poll for transaction receipts / block inclusion",default:1e3},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"}},Re={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(U)},async handler(e){try{await w(e)}catch(o){g(o),process.exit(1)}process.exit(0)}},T=Re;import{loadConfig as Ie}from"@latticexyz/config/node";import{worldgen as $e}from"@latticexyz/world/node";import{getSrcDirectory as Ee}from"@latticexyz/common/foundry";import z from"path";import{rmSync as Ae}from"fs";var Fe={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 (defaults to true)",default:!0}})},async handler(e){await j(e),process.exit(0)}};async function j(e){let o=e.srcDir??await Ee(),t=M(o),n=e.config??await Ie(e.configPath),i=z.join(o,n.codegenDirectory);e.clean&&Ae(z.join(i,n.worldgenDirectory),{recursive:!0,force:!0}),await $e(n,t,i)}var J=Fe;import h from"chalk";import{existsSync as ze,readFileSync as Je,rmSync as Be,writeFileSync as H}from"fs";import k from"path";import{MUDError as b}from"@latticexyz/common/errors";var B={name:"@latticexyz/cli",version:"2.0.0-next.2",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"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",test:"tsc --noEmit && 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/gas-report":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/solecs":"workspace:*","@latticexyz/std-contracts":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@typechain/ethers-v5":"^10.2.0",chalk:"^5.0.1",chokidar:"^3.5.3",dotenv:"^16.0.3",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.1",path:"^0.12.7","throttle-debounce":"^5.0.0",typechain:"^8.1.1",typescript:"5.1.6",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/throttle-debounce":"^5.0.0","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};import He from"glob";var S=".mudbackup",C="@latticexyz",Ne={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({backup:{type:"boolean",description:`Back up the current MUD versions to "${S}"`},force:{type:"boolean",description:`Backup fails if a "${S}" file is found, unless --force is provided`},restore:{type:"boolean",description:`Restore the previous MUD versions from "${S}"`},mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((i,c)=>e[c]?i+1:i,0);if(t===0)throw new b(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new b(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Ve(e);let n=He.sync("**/package.json").filter(i=>!i.includes("node_modules"));for(let i of n)_e(i,e)}catch(o){g(o)}finally{process.exit(0)}}};async function Ve(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(h.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${B.name}`)).json()}catch{throw new b("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new b(`Could not find npm version with tag "${e.tag}"`);return console.log(h.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),n=Object.keys(o.versions).find(i=>i.includes(t));if(!n)throw new b(`Could not find npm version based on commit "${e.commit}"`);return console.log(h.green(`Version from commit ${e.commit}: ${n}`)),n}return e.mudVersion}function _e(e,o){let{restore:t,force:n,link:i}=o,{backup:c,mudVersion:d}=o,a=k.join(k.dirname(e),S),v=ze(a);if(i&&!v&&(c=!0),c&&!n&&v)throw new b(`A backup file already exists at ${a}.
|
13
|
+
Use --force to overwrite it or --restore to restore it.`);let s=N(e),u=t?N(a):void 0,m={};for(let r in s.dependencies)r.startsWith(C)&&(m[r]=s.dependencies[r]);let y={};for(let r in s.devDependencies)r.startsWith(C)&&(y[r]=s.devDependencies[r]);c&&(H(a,JSON.stringify({dependencies:m,devDependencies:y},null,2)),console.log(h.green(`Backed up MUD dependencies from ${e} to ${a}`)));for(let r in s.dependencies)r.startsWith(C)&&(s.dependencies[r]=l(r,"dependencies"));for(let r in s.devDependencies)r.startsWith(C)&&(s.devDependencies[r]=l(r,"devDependencies"));return H(e,JSON.stringify(s,null,2)+`
|
14
|
+
`),console.log(`Updating ${e}`),V(m,s.dependencies),V(y,s.devDependencies),t&&!c&&(Be(a),console.log(h.green(`Cleaned up ${a}`))),s;function l(r,p){return t&&u?u[p][r]:(i&&(d=Le(e,i,r)),d||s[p][r])}}function N(e){try{let o=Je(e,"utf8");return JSON.parse(o)}catch{throw new b("Could not read JSON at "+e)}}function V(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${h.red(e[t])} -> ${h.green(o[t])}`)}function Le(e,o,t){let n=t.replace(C,""),i=k.relative(k.dirname(e),process.cwd());return"link:"+k.join(i,o,"packages",n)}var _=Ne;import{anvil as qe,forge as Ge,getRpcUrl as Ye}from"@latticexyz/common/foundry";import Ze from"chalk";import{rmSync as Ke,writeFileSync as Xe}from"fs";var L=".mudtest",Qe={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options({...U,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 i=["--block-base-fee-per-gas","0","--port",String(e.port)];qe(i)}let o=e.worldAddress?await Ye(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await w({...e,saveDeployment:!1,rpc:o})).worldAddress;console.log(Ze.blue("World address",t)),Xe(L,t);let n=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{let i=await Ge(["test","--fork-url",o,...n],{profile:e.profile});console.log(i)}catch(i){console.error(i)}Ke(L),process.exit(0)}},q=Qe;import{existsSync as eo,readFileSync as oo}from"fs";import{ethers as G}from"ethers";import{loadConfig as to}from"@latticexyz/config/node";import{MUDError as Y}from"@latticexyz/common/errors";import{cast as ro,getRpcUrl as no,getSrcDirectory as io}from"@latticexyz/common/foundry";import{TableId as Z}from"@latticexyz/common/deprecated";import{resolveWorldConfig as so}from"@latticexyz/world";import ao from"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json"assert{type:"json"};var co=new Z("","Systems"),lo={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the config file"},profile:{type:"string",description:"The foundry profile to use"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await io(o),e.rpc??=await no(o);let{tx:t,configPath:n,srcDir:i,rpc:c}=e,d=M(i),a=await to(n),v=so(a,d.map(({basename:f})=>f)),s=e.worldAddress??await po(a.worldsFile,c),u=new G.providers.StaticJsonRpcProvider(c),m=new G.Contract(s,ao.abi,u),y=a.namespace,l=Object.values(v.systems).map(({name:f})=>f),r=[];for(let f of l){let O=new Z(y,f),ie=await m.getField(co.toHex(),[O.toHex()],0);r.push({name:f,address:ie})}let p=await ro(["run","--label",`${s}:World`,...r.map(({name:f,address:O})=>["--label",`${O}:${f}`]).flat(),`${t}`]);console.log(p),process.exit(0)}},K=lo;async function po(e,o){if(eo(e)){let t=await P(o),n=JSON.parse(oo(e,"utf-8"));if(!n[t])throw new Y(`chainId ${t} is missing in worldsFile "${e}"`);return n[t].address}else throw new Y("worldAddress is not specified and worldsFile is missing")}import{anvil as mo,forge as X,getRpcUrl as fo,getScriptDirectory as go,getSrcDirectory as uo}from"@latticexyz/common/foundry";import x from"chalk";import yo from"chokidar";import{loadConfig as Q,resolveConfigPath as ho}from"@latticexyz/config/node";import{tablegen as bo}from"@latticexyz/store/codegen";import ee from"path";import{debounce as wo}from"throttle-debounce";import{homedir as vo}from"os";import{rmSync as Do}from"fs";var Co={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options({rpc:{type:"string",decs:"RPC endpoint of the development node. If none is provided, an anvil instance is spawned in the background on port 8545."},configPath:{type:"string",decs:"Path to MUD config"}})},async handler(e){await X(["clean"]);let o=e.rpc??await fo(),t=e.configPath??await ho(e.configPath),n=await uo(),i=await go(),c=await Q(t);if(await u(c),await m(c),!e.rpc){console.log(x.gray("Cleaning devnode cache"));let l=vo();Do(ee.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),mo(["--block-time","1","--block-base-fee-per-gas","0"])}let d={config:!1,contracts:!1},a={current:!1};yo.watch([t,n]).on("all",async(l,r)=>{if(r.includes(t)&&(d.config=!0,d.contracts=!0),r.includes(n)||r.includes(i)){if(r.includes(c.codegenDirectory))return;d.contracts=!0}s()});let s=wo(100,async()=>{if(a.current)return;a.current=!0;let{config:l,contracts:r}=d;d.config=!1,d.contracts=!1;try{let p=await Q(t);l&&await u(p),r&&await m(p),await y()}catch(p){console.error(x.red(`MUD dev-contracts watcher failed to deploy config or contracts changes
|
15
|
+
`)),g(p)}a.current=!1,(d.config||d.contracts)&&(console.log("Detected change while handling the previous change"),s()),A(),console.log("MUD watching for changes...")});async function u(l){console.log(x.blue("mud.config.ts changed - regenerating tables and recs types"));let r=ee.join(n,l.codegenDirectory);await bo(l,r)}async function m(l){console.log(x.blue("contracts changed - regenerating interfaces and contract types")),await j({config:l,clean:!0,srcDir:n}),await X(["build"]),await F()}async function y(){console.log(x.blue("redeploying World")),await w({configPath:t,skipBuild:!0,priorityFeeMultiplier:1,disableTxWait:!0,pollInterval:1e3,saveDeployment:!0,srcDir:n,rpc:o})}}},oe=Co;var te=[T,W,I,ko,$,E,J,_,q,K,oe];import*as ne from"dotenv";import re from"chalk";ne.config();xo(Mo(process.argv)).scriptName("mud").command(te).strict().fail((e,o)=>{console.error(re.red(e)),e.includes("Missing required argument")&&console.log(re.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),g(o),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
|
16
16
|
//# sourceMappingURL=mud.js.map
|