@latticexyz/cli 2.0.0-next.1 → 2.0.0-next.11
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-TW3YGZ4D.js +11 -0
- package/dist/chunk-TW3YGZ4D.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/mud.js +11 -7
- package/dist/mud.js.map +1 -1
- package/package.json +17 -15
- package/src/commands/deploy.ts +1 -1
- package/src/commands/dev-contracts.ts +17 -16
- package/src/commands/index.ts +2 -2
- package/src/commands/set-version.ts +19 -60
- package/src/commands/tablegen.ts +3 -2
- package/src/commands/test.ts +3 -2
- package/src/commands/trace.ts +17 -9
- package/src/commands/worldgen.ts +1 -1
- package/src/common.ts +1 -0
- package/src/index.ts +0 -1
- package/src/mud.ts +5 -2
- package/src/mudPackages.ts +24 -0
- package/src/utils/deploy.ts +189 -554
- package/src/utils/deployHandler.ts +9 -3
- package/src/utils/modules/constants.ts +23 -0
- package/src/utils/modules/getInstallModuleCallData.ts +27 -0
- package/src/utils/modules/getUserModules.ts +5 -0
- package/src/utils/modules/types.ts +14 -0
- package/src/utils/systems/getGrantAccessCallData.ts +29 -0
- package/src/utils/systems/getRegisterFunctionSelectorsCallData.ts +57 -0
- package/src/utils/systems/getRegisterSystemCallData.ts +17 -0
- package/src/utils/systems/types.ts +9 -0
- package/src/utils/systems/utils.ts +42 -0
- package/src/utils/tables/getRegisterTableCallData.ts +49 -0
- package/src/utils/tables/getTableIds.ts +18 -0
- package/src/utils/tables/types.ts +12 -0
- package/src/utils/utils/confirmNonce.ts +24 -0
- package/src/utils/utils/deployContract.ts +33 -0
- package/src/utils/utils/fastTxExecute.ts +56 -0
- package/src/utils/utils/getContractData.ts +29 -0
- package/src/utils/utils/postDeploy.ts +25 -0
- package/src/utils/utils/setInternalFeePerGas.ts +49 -0
- package/src/utils/utils/types.ts +21 -0
- package/src/utils/world.ts +28 -0
- 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
- package/src/utils/index.ts +0 -7
- package/src/utils/worldtypes.ts +0 -21
- /package/src/utils/{getChainId.ts → utils/getChainId.ts} +0 -0
@@ -0,0 +1,11 @@
|
|
1
|
+
import S from"chalk";import $ from"path";import{MUDError as it}from"@latticexyz/common/errors";import{loadConfig as ct}from"@latticexyz/config/node";import u from"chalk";import ze from"path";import{ethers as A}from"ethers";import{getOutDirectory as Qe,cast as Xe,getSrcDirectory as Ze,getRemappings as et}from"@latticexyz/common/foundry";import{resolveWorldConfig as tt}from"@latticexyz/world";import Fe from"chalk";import Ie from"@latticexyz/world/out/World.sol/World.json"assert{type:"json"};import Me from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import G from"chalk";import{ethers as Pe}from"ethers";import{MUDError as U}from"@latticexyz/common/errors";async function I(e){let{signer:t,nonce:r,maxPriorityFeePerGas:o,maxFeePerGas:n,debug:a,gasPrice:l,confirmations:p,contract:m}=e;try{let i=new Pe.ContractFactory(m.abi,m.bytecode,t);console.log(G.gray(`executing deployment of ${m.name} with nonce ${r}`));let g=i.deploy({nonce:r,maxPriorityFeePerGas:o,maxFeePerGas:n,gasPrice:l}).then(s=>p?s:s.deployed()),{address:f}=await g;return console.log(G.green("Deployed",m.name,"to",f)),f}catch(i){throw a&&console.error(i),i?.message.includes("invalid bytecode")?new U(`Error deploying ${m.name}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use "external" functions.`):i?.message.includes("CreateContractLimit")?new U(`Error deploying ${m.name}: CreateContractLimit exceeded.`):i}}import{readFileSync as Se}from"fs";import Te from"path";import{MUDError as N}from"@latticexyz/common/errors";function w(e,t){let r,o=Te.join(t,e+".sol",e+".json");try{r=JSON.parse(Se(o,"utf8"))}catch{throw new N(`Error reading file at ${o}`)}let n=r?.bytecode?.object;if(!n)throw new N(`No bytecode found in ${o}`);let a=r?.abi;if(!a)throw new N(`No ABI found in ${o}`);return{abi:a,bytecode:n}}async function K(e){console.log(Fe.blue("Deploying World"));let t=e.worldContractName?{name:"World",...w(e.worldContractName,e.forgeOutDirectory)}:{abi:Me,bytecode:Ie.bytecode,name:"World"};return I({...e,nonce:e.nonce,contract:t})}import ot from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import ce from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import L from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import H from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import J from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var R=[{name:"KeysWithValueModule",abi:L.abi,bytecode:L.bytecode},{name:"KeysInTableModule",abi:H.abi,bytecode:H.bytecode},{name:"UniqueEntityModule",abi:J.abi,bytecode:J.bytecode}];import{defaultAbiCoder as ve}from"ethers/lib/utils.js";import{resolveWithContext as Ne}from"@latticexyz/config";async function _(e,t,r){let o=await e[t.name];if(!o)throw new Error(`Module ${t.name} not found`);let n=t.args.map(p=>Ne(p,{tableIds:r})),a=n.map(p=>p.value),l=n.map(p=>p.type);return{func:t.root?"installRootModule":"installModule",args:[o,ve.encode(l,a)]}}function q(e,t){return t.filter(r=>!e.some(o=>o.name===r.name))}import{resourceIdToHex as Re}from"@latticexyz/common";async function Y(e){let{systems:t,namespace:r,systemContracts:o}=e,n=[];for(let{name:a,accessListAddresses:l,accessListSystems:p}of t)l.map(async m=>n.push(V(a,r,m))),p.map(async m=>n.push(V(a,r,await o[m])));return n}function V(e,t,r){return{func:"grantAccess",args:[Re({type:"system",namespace:t,name:e}),r]}}import{resourceIdToHex as X}from"@latticexyz/common";import{ethers as k}from"ethers";function O(e,t){let{abi:r}=w(e,t);return r.filter(o=>["fallback","function"].includes(o.type)).map(o=>`${o.name}${Q(o.inputs)}`)}function z(e){return ke(e)}function Q(e){return`(${e.map(r=>{let o=r.type.match(/tuple(.*)/);return o?Q(r.components)+o[1]:r.type})})`}function ke(e){return k.utils.hexDataSlice(k.utils.keccak256(k.utils.toUtf8Bytes(e)),0,4)}function Z(e){let t=[],{systemContractName:r,namespace:o,forgeOutDirectory:n,system:a}=e;if(a.registerFunctionSelectors){let l=O("System",n),p=O(r,n).filter(i=>r==="System"||!l.includes(i)),m=o==="";for(let i of p)t.push(Oe({namespace:o,name:a.name,systemFunctionSignature:i,isRoot:m}))}return t}function Oe(e){let{namespace:t,name:r,systemFunctionSignature:o,isRoot:n}=e;if(n){let a=z(o);return{func:"registerRootFunctionSelector",args:[X({type:"system",namespace:t,name:r}),o,a]}}else return{func:"registerFunctionSelector",args:[X({type:"system",namespace:t,name:r}),o]}}import{resourceIdToHex as je}from"@latticexyz/common";async function ee(e){let{namespace:t,systemContracts:r,systemKey:o,system:n}=e,a=await r[o];return{func:"registerSystem",args:[je({type:"system",namespace:t,name:n.name}),a,n.openAccess]}}import{encodeSchema as te,getStaticByteLength as Ae}from"@latticexyz/schema-type/deprecated";import{resolveAbiOrUserType as oe}from"@latticexyz/store/codegen";import{resourceIdToHex as $e}from"@latticexyz/common";import{fieldLayoutToHex as We}from"@latticexyz/protocol-parser";import{loadAndExtractUserTypes as Ee}from"@latticexyz/common/codegen";function re(e,t,r,o){let{name:n,valueSchema:a,keySchema:l}=e;if(!n)throw Error("Table missing name");let p=Ee(t.userTypes,r,o),m=Object.values(a).map(s=>{let{schemaType:d}=oe(s,t,p);return d}),i=m.map(s=>Ae(s)),g={staticFieldLengths:i.filter(s=>s>0),numDynamicFields:i.filter(s=>s===0).length},f=Object.values(l).map(s=>{let{schemaType:d}=oe(s,t,p);return d});return{func:"registerTable",args:[$e({type:e.offchainOnly?"offchainTable":"table",namespace:t.namespace,name:n}),We(g),te(f),te(m),Object.keys(l),Object.keys(a)]}}import{resourceIdToHex as Be}from"@latticexyz/common";import{hexToBytes as Ge}from"viem";function ne(e){let t={};for(let[r,{name:o,offchainOnly:n}]of Object.entries(e.tables))t[r]=Ge(Be({type:n?"offchainTable":"table",namespace:e.namespace,name:o}));return t}import Ue from"chalk";import{MUDError as Ke}from"@latticexyz/common/errors";async function ae(e,t,r){let o=await e.getTransactionCount(),n=0,a=100;for(;o!==t&&n<a;)console.log(Ue.gray(`Waiting for transactions to be included before executing postDeployScript (local nonce: ${t}, remote nonce: ${o}, retry number ${n}/${a})`)),await new Promise(l=>setTimeout(l,r)),n++,o=await e.getTransactionCount();if(o!==t)throw new Ke("Remote nonce doesn't match local nonce, indicating that not all deploy transactions were included.")}import Le from"chalk";import{MUDError as He}from"@latticexyz/common/errors";async function h(e){let{func:t,args:r,contract:o,signer:n,nonce:a,maxPriorityFeePerGas:l,maxFeePerGas:p,gasPrice:m,confirmations:i=1,debug:g}=e,f=`${t}(${r.map(s=>`'${s}'`).join(",")})`;try{let s=o.connect(n),d=await s.estimateGas[t].apply(null,r);return console.log(Le.gray(`executing transaction: ${f} with nonce ${a}`)),s[t].apply(null,[...r,{gasLimit:d,nonce:a,maxPriorityFeePerGas:l,maxFeePerGas:p,gasPrice:m}]).then(D=>i===0?D:D.wait(i))}catch(s){throw g&&console.error(s),new He(`Gas estimation error for ${f}: ${s?.reason}`)}}import{existsSync as Je}from"fs";import _e from"path";import qe from"chalk";import{getScriptDirectory as Ve,forge as Ye}from"@latticexyz/common/foundry";async function se(e,t,r,o){let n=_e.join(await Ve(),e+".s.sol");Je(n)?(console.log(qe.blue(`Executing post deploy script at ${n}`)),await Ye(["script",e,"--sig","run(address)",t,"--broadcast","--rpc-url",r,"-vvv"],{profile:o})):console.log(`No script at ${n}, skipping post deploy hook`)}import{MUDError as j}from"@latticexyz/common/errors";async function ie(e,t){let r=await e.provider.getFeeData(),o,n,a;if(r.lastBaseFeePerGas){if(!r.lastBaseFeePerGas.eq(0)&&(await e.getBalance()).eq(0))throw new j(`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 e.getAddress()}'`);o=r.lastBaseFeePerGas.eq(0)?0:Math.floor(15e8*t),n=r.lastBaseFeePerGas.mul(2).add(o)}else if(r.gasPrice){if(!r.gasPrice.eq(0)&&(await e.getBalance()).eq(0))throw new j("Attempting to deploy to a chain with non-zero gas price with an account that has no balance.");a=r.gasPrice}else throw new j("Can not fetch fee data from RPC");return{maxPriorityFeePerGas:o,maxFeePerGas:n,gasPrice:a}}import{resourceIdToHex as rt}from"@latticexyz/common";async function le(e,t,r){let o=Date.now(),{profile:n,rpc:a,privateKey:l,priorityFeeMultiplier:p,debug:m,worldAddress:i,disableTxWait:g,pollInterval:f}=r,s=tt(e,t),d=await Qe(n),D=await et(n),T=ze.join(await Ze(n),e.codegenDirectory),E=new A.providers.StaticJsonRpcProvider(a);E.pollingInterval=f;let P=new A.Wallet(l,E);console.log("Deploying from",P.address);let y=await P.getTransactionCount();console.log("Initial nonce",y);let C={...await ie(P,p),signer:P,debug:!!m,disableTxWait:g,confirmations:g?0:1},B=Number(await Xe(["block-number","--rpc-url",a],{profile:n}));console.log("Start deployment at block",B);let de=i?Promise.resolve(i):K({...C,nonce:y++,worldContractName:e.worldContractName,forgeOutDirectory:d}),ue=q(R,e.modules),ge=Object.keys(ue).map(c=>{let{abi:b,bytecode:v}=w(c,d);return{name:c,abi:b,bytecode:v}}),ye=Object.keys(s.systems).map(c=>{let{abi:b,bytecode:v}=w(c,d);return{name:c,abi:b,bytecode:v}}),F=[{name:"CoreModule",abi:ce.abi,bytecode:ce.bytecode},...R,...ge,...ye].reduce((c,b)=>(c[b.name]=I({...C,nonce:y++,contract:b}),c),{}),M=await de,x=new A.Contract(M,ot);i||(console.log(u.blue("Installing CoreModule")),await h({...C,nonce:y++,contract:x,func:"initialize",args:[await F.CoreModule]}),console.log(u.green("Installed CoreModule"))),e.namespace&&(console.log(u.blue("Registering Namespace")),await h({...C,nonce:y++,contract:x,func:"registerNamespace",args:[rt({type:"namespace",namespace:e.namespace,name:""})]}),console.log(u.green("Namespace registered")));let be=ne(e),Ce=Object.values(e.tables).map(c=>re(c,e,T,D));console.log(u.blue("Registering tables")),await Promise.all(Ce.map(c=>h({...C,nonce:y++,contract:x,...c}))),console.log(u.green("Tables registered")),console.log(u.blue("Registering Systems and Functions"));let we=await Promise.all(Object.entries(s.systems).map(([c,b])=>ee({systemContracts:F,systemKey:c,system:b,namespace:e.namespace}))),he=Object.entries(s.systems).flatMap(([c,b])=>Z({systemContractName:c,system:b,namespace:e.namespace,forgeOutDirectory:d}));await Promise.all([...we,...he].map(c=>h({...C,nonce:y++,contract:x,...c}))),console.log(u.green("Systems and Functions registered"));let De=await Y({systems:Object.values(s.systems),systemContracts:F,namespace:e.namespace});console.log(u.blue("Granting Access")),await Promise.all(De.map(c=>h({...C,nonce:y++,contract:x,...c}))),console.log(u.green("Access granted"));let xe=await Promise.all(e.modules.map(c=>_(F,c,be)));return console.log(u.blue("Installing User Modules")),await Promise.all(xe.map(c=>h({...C,nonce:y++,contract:x,...c}))),console.log(u.green("User Modules Installed")),await ae(P,y,f),await se(e.postDeployScript,M,a,n),console.log(u.green("Deployment completed in",(Date.now()-o)/1e3,"seconds")),{worldAddress:M,blockNumber:B}}import{forge as fe,getRpcUrl as lt,getSrcDirectory as mt}from"@latticexyz/common/foundry";import{existsSync as pt,mkdirSync as ft,readFileSync as dt,writeFileSync as W}from"fs";import nt from"glob";import{basename as at}from"path";function me(e){return nt.sync(`${e}/**/*.sol`).map(t=>({path:t,basename:at(t,".sol")}))}import{execa as ut}from"execa";import{ethers as st}from"ethers";async function pe(e){let{result:t}=await st.utils.fetchJson(e,'{ "id": 42, "jsonrpc": "2.0", "method": "eth_chainId", "params": [ ] }');return Number(t)}async function nr(e){e.profile??=process.env.FOUNDRY_PROFILE;let{configPath:t,printConfig:r,profile:o,clean:n,skipBuild:a}=e,l=e.rpc??await lt(o);console.log(S.bgBlue(S.whiteBright(`
|
3
|
+
Deploying MUD contracts${o?" with profile "+o:""} to RPC ${l}
|
4
|
+
`))),n&&await fe(["clean"],{profile:o}),a||(await fe(["build","--skip","test","script"],{profile:o}),await ut("mud",["abi-ts"],{stdio:"inherit"}));let p=e?.srcDir??await mt(),m=me(p).map(({basename:s})=>s),i=await ct(t);r&&console.log(S.green(`
|
5
|
+
Resolved config:
|
6
|
+
`),JSON.stringify(i,null,2));let g=process.env.PRIVATE_KEY;if(!g)throw new it(`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 f=await le(i,m,{...e,rpc:l,privateKey:g});if(e.saveDeployment){let s=await pe(l),d=$.join(i.deploysDirectory,s.toString());ft(d,{recursive:!0}),W($.join(d,"latest.json"),JSON.stringify(f,null,2)),W($.join(d,Date.now()+".json"),JSON.stringify(f,null,2));let D=[1337,31337],T=pt(i.worldsFile)?JSON.parse(dt(i.worldsFile,"utf-8")):{};T[s]={address:f.worldAddress,blockNumber:D.includes(s)?void 0:f.blockNumber},W(i.worldsFile,JSON.stringify(T,null,2)),console.log(S.bgGreen(S.whiteBright(`
|
9
|
+
Deployment result (written to ${i.worldsFile} and ${d}):
|
10
|
+
`)))}return console.log(f),f}export{me as a,pe as b,nr as c};
|
11
|
+
//# sourceMappingURL=chunk-TW3YGZ4D.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/utils/deployHandler.ts","../src/utils/deploy.ts","../src/utils/world.ts","../src/utils/utils/deployContract.ts","../src/utils/utils/getContractData.ts","../src/utils/modules/constants.ts","../src/utils/modules/getInstallModuleCallData.ts","../src/utils/modules/getUserModules.ts","../src/utils/systems/getGrantAccessCallData.ts","../src/utils/systems/getRegisterFunctionSelectorsCallData.ts","../src/utils/systems/utils.ts","../src/utils/systems/getRegisterSystemCallData.ts","../src/utils/tables/getRegisterTableCallData.ts","../src/utils/tables/getTableIds.ts","../src/utils/utils/confirmNonce.ts","../src/utils/utils/fastTxExecute.ts","../src/utils/utils/postDeploy.ts","../src/utils/utils/setInternalFeePerGas.ts","../src/utils/getExistingContracts.ts","../src/utils/utils/getChainId.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 { getExistingContracts } from \"./getExistingContracts\";\nimport { execa } from \"execa\";\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 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) {\n await forge([\"clean\"], { profile });\n }\n\n // Run forge build\n if (!skipBuild) {\n await forge([\"build\", \"--skip\", \"test\", \"script\"], { profile });\n await execa(\"mud\", [\"abi-ts\"], { stdio: \"inherit\" });\n }\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 chalk from \"chalk\";\nimport path from \"path\";\nimport { ethers } from \"ethers\";\nimport { getOutDirectory, cast, getSrcDirectory, getRemappings } from \"@latticexyz/common/foundry\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig, resolveWorldConfig } from \"@latticexyz/world\";\nimport { deployWorldContract } from \"./world\";\nimport IBaseWorldAbi from \"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json\" assert { type: \"json\" };\nimport CoreModuleData from \"@latticexyz/world/out/CoreModule.sol/CoreModule.json\" assert { type: \"json\" };\nimport { defaultModuleContracts } from \"./modules/constants\";\nimport { getInstallModuleCallData } from \"./modules/getInstallModuleCallData\";\nimport { getUserModules } from \"./modules/getUserModules\";\nimport { getGrantAccessCallData } from \"./systems/getGrantAccessCallData\";\nimport { getRegisterFunctionSelectorsCallData } from \"./systems/getRegisterFunctionSelectorsCallData\";\nimport { getRegisterSystemCallData } from \"./systems/getRegisterSystemCallData\";\nimport { getRegisterTableCallData } from \"./tables/getRegisterTableCallData\";\nimport { getTableIds } from \"./tables/getTableIds\";\nimport { confirmNonce } from \"./utils/confirmNonce\";\nimport { deployContract } from \"./utils/deployContract\";\nimport { fastTxExecute } from \"./utils/fastTxExecute\";\nimport { getContractData } from \"./utils/getContractData\";\nimport { postDeploy } from \"./utils/postDeploy\";\nimport { setInternalFeePerGas } from \"./utils/setInternalFeePerGas\";\nimport { ContractCode } from \"./utils/types\";\nimport { resourceIdToHex } from \"@latticexyz/common\";\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 startTime = Date.now();\n const { profile, rpc, privateKey, priorityFeeMultiplier, debug, worldAddress, disableTxWait, pollInterval } =\n deployConfig;\n const resolvedConfig = resolveWorldConfig(mudConfig, existingContractNames);\n const forgeOutDirectory = await getOutDirectory(profile);\n const remappings = await getRemappings(profile);\n const outputBaseDirectory = path.join(await getSrcDirectory(profile), mudConfig.codegenDirectory);\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 let nonce = await signer.getTransactionCount();\n console.log(\"Initial nonce\", nonce);\n\n const txParams = await setInternalFeePerGas(signer, priorityFeeMultiplier);\n\n const txConfig = {\n ...txParams,\n signer,\n debug: Boolean(debug),\n disableTxWait,\n confirmations: disableTxWait ? 0 : 1,\n };\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 the World contract. Non-blocking.\n const worldPromise: Promise<string> = worldAddress\n ? Promise.resolve(worldAddress)\n : deployWorldContract({\n ...txConfig,\n nonce: nonce++,\n worldContractName: mudConfig.worldContractName,\n forgeOutDirectory,\n });\n\n // Filters any default modules from config\n const userModules = getUserModules(defaultModuleContracts, mudConfig.modules);\n const userModuleContracts = Object.keys(userModules).map((name) => {\n const { abi, bytecode } = getContractData(name, forgeOutDirectory);\n return {\n name,\n abi,\n bytecode,\n } as ContractCode;\n });\n\n const systemContracts = Object.keys(resolvedConfig.systems).map((name) => {\n const { abi, bytecode } = getContractData(name, forgeOutDirectory);\n return {\n name,\n abi,\n bytecode,\n } as ContractCode;\n });\n\n const contracts: ContractCode[] = [\n {\n name: \"CoreModule\",\n abi: CoreModuleData.abi,\n bytecode: CoreModuleData.bytecode,\n },\n ...defaultModuleContracts,\n ...userModuleContracts,\n ...systemContracts,\n ];\n\n // Deploy the System and Module contracts\n const deployedContracts = contracts.reduce<Record<string, Promise<string>>>((acc, contract) => {\n acc[contract.name] = deployContract({\n ...txConfig,\n nonce: nonce++,\n contract,\n });\n return acc;\n }, {});\n\n // Wait for world to be deployed\n const deployedWorldAddress = await worldPromise;\n const worldContract = new ethers.Contract(deployedWorldAddress, IBaseWorldAbi);\n\n // If an existing World is passed assume its coreModule is already installed - blocking to install if not\n if (!worldAddress) {\n console.log(chalk.blue(\"Installing CoreModule\"));\n await fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n func: \"initialize\",\n args: [await deployedContracts[\"CoreModule\"]],\n });\n console.log(chalk.green(\"Installed CoreModule\"));\n }\n\n if (mudConfig.namespace) {\n console.log(chalk.blue(\"Registering Namespace\"));\n await fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n func: \"registerNamespace\",\n args: [resourceIdToHex({ type: \"namespace\", namespace: mudConfig.namespace, name: \"\" })],\n });\n console.log(chalk.green(\"Namespace registered\"));\n }\n\n const tableIds = getTableIds(mudConfig);\n\n const registerTableCalls = Object.values(mudConfig.tables).map((table) =>\n getRegisterTableCallData(table, mudConfig, outputBaseDirectory, remappings)\n );\n\n console.log(chalk.blue(\"Registering tables\"));\n await Promise.all(\n registerTableCalls.map((call) =>\n fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n ...call,\n })\n )\n );\n console.log(chalk.green(`Tables registered`));\n\n console.log(chalk.blue(\"Registering Systems and Functions\"));\n const systemCalls = await Promise.all(\n Object.entries(resolvedConfig.systems).map(([systemKey, system]) =>\n getRegisterSystemCallData({\n systemContracts: deployedContracts,\n systemKey,\n system,\n namespace: mudConfig.namespace,\n })\n )\n );\n const functionCalls = Object.entries(resolvedConfig.systems).flatMap(([systemKey, system]) =>\n getRegisterFunctionSelectorsCallData({\n systemContractName: systemKey,\n system,\n namespace: mudConfig.namespace,\n forgeOutDirectory,\n })\n );\n await Promise.all(\n [...systemCalls, ...functionCalls].map((call) =>\n fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n ...call,\n })\n )\n );\n console.log(chalk.green(`Systems and Functions registered`));\n\n // Wait for System access to be granted before installing modules\n const grantCalls = await getGrantAccessCallData({\n systems: Object.values(resolvedConfig.systems),\n systemContracts: deployedContracts,\n namespace: mudConfig.namespace,\n });\n\n console.log(chalk.blue(\"Granting Access\"));\n await Promise.all(\n grantCalls.map((call) =>\n fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n ...call,\n })\n )\n );\n console.log(chalk.green(`Access granted`));\n\n const moduleCalls = await Promise.all(\n mudConfig.modules.map((m) => getInstallModuleCallData(deployedContracts, m, tableIds))\n );\n\n console.log(chalk.blue(\"Installing User Modules\"));\n await Promise.all(\n moduleCalls.map((call) =>\n fastTxExecute({\n ...txConfig,\n nonce: nonce++,\n contract: worldContract,\n ...call,\n })\n )\n );\n console.log(chalk.green(`User Modules Installed`));\n\n // Double check that all transactions have been included by confirming the current nonce is the expected nonce\n await confirmNonce(signer, nonce, pollInterval);\n\n await postDeploy(mudConfig.postDeployScript, deployedWorldAddress, rpc, profile);\n\n console.log(chalk.green(\"Deployment completed in\", (Date.now() - startTime) / 1000, \"seconds\"));\n\n return { worldAddress: deployedWorldAddress, blockNumber };\n}\n","import chalk from \"chalk\";\n\nimport WorldData from \"@latticexyz/world/out/World.sol/World.json\" assert { type: \"json\" };\nimport IBaseWorldAbi from \"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json\" assert { type: \"json\" };\nimport { deployContract } from \"./utils/deployContract\";\nimport { getContractData } from \"./utils/getContractData\";\nimport { TxConfig } from \"./utils/types\";\n\nexport async function deployWorldContract(\n ip: TxConfig & {\n nonce: number;\n worldContractName: string | undefined;\n forgeOutDirectory: string;\n }\n): Promise<string> {\n console.log(chalk.blue(`Deploying World`));\n const contractData = ip.worldContractName\n ? {\n name: \"World\",\n ...getContractData(ip.worldContractName, ip.forgeOutDirectory),\n }\n : { abi: IBaseWorldAbi, bytecode: WorldData.bytecode, name: \"World\" };\n return deployContract({\n ...ip,\n nonce: ip.nonce,\n contract: contractData,\n });\n}\n","import chalk from \"chalk\";\nimport { ethers } from \"ethers\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { TxConfig, ContractCode } from \"./types\";\n\nexport async function deployContract(input: TxConfig & { nonce: number; contract: ContractCode }): Promise<string> {\n const { signer, nonce, maxPriorityFeePerGas, maxFeePerGas, debug, gasPrice, confirmations, contract } = input;\n\n try {\n const factory = new ethers.ContractFactory(contract.abi, contract.bytecode, signer);\n console.log(chalk.gray(`executing deployment of ${contract.name} with nonce ${nonce}`));\n const deployPromise = factory\n .deploy({\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gasPrice,\n })\n .then((c) => (confirmations ? c : c.deployed()));\n const { address } = await deployPromise;\n console.log(chalk.green(\"Deployed\", contract.name, \"to\", address));\n return address;\n } catch (error: any) {\n if (debug) console.error(error);\n if (error?.message.includes(\"invalid bytecode\")) {\n throw new MUDError(\n `Error deploying ${contract.name}: 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 ${contract.name}: CreateContractLimit exceeded.`);\n } else throw error;\n }\n}\n","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { Fragment } from \"ethers/lib/utils.js\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\n/**\n * Load the contract's abi and bytecode from the file system\n * @param contractName: Name of the contract to load\n */\nexport function getContractData(\n contractName: string,\n forgeOutDirectory: string\n): { 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","import KeysWithValueModuleData from \"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json\" assert { type: \"json\" };\nimport KeysInTableModuleData from \"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json\" assert { type: \"json\" };\nimport UniqueEntityModuleData from \"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json\" assert { type: \"json\" };\nimport { ContractCode } from \"../utils/types\";\n\n// These modules are always deployed\nexport const defaultModuleContracts: ContractCode[] = [\n {\n name: \"KeysWithValueModule\",\n abi: KeysWithValueModuleData.abi,\n bytecode: KeysWithValueModuleData.bytecode,\n },\n {\n name: \"KeysInTableModule\",\n abi: KeysInTableModuleData.abi,\n bytecode: KeysInTableModuleData.bytecode,\n },\n {\n name: \"UniqueEntityModule\",\n abi: UniqueEntityModuleData.abi,\n bytecode: UniqueEntityModuleData.bytecode,\n },\n];\n","import { defaultAbiCoder } from \"ethers/lib/utils.js\";\nimport { resolveWithContext } from \"@latticexyz/config\";\nimport { Module } from \"./types\";\nimport { CallData } from \"../utils/types\";\nimport { TableIds } from \"../tables/types\";\n\nexport async function getInstallModuleCallData(\n moduleContracts: Record<string, Promise<string>>,\n module: Module,\n tableIds: TableIds\n): Promise<CallData> {\n const moduleAddress = await moduleContracts[module.name];\n if (!moduleAddress) throw new Error(`Module ${module.name} not found`);\n // Resolve arguments\n const resolvedArgs = module.args.map((arg) =>\n resolveWithContext(arg, {\n tableIds,\n })\n );\n const values = resolvedArgs.map((arg) => arg.value);\n const types = resolvedArgs.map((arg) => arg.type);\n\n return {\n func: module.root ? \"installRootModule\" : \"installModule\",\n args: [moduleAddress, defaultAbiCoder.encode(types, values)],\n };\n}\n","import { Module } from \"./types\";\n\nexport function getUserModules(defaultModules: { name: string }[], configModules: Module[]): Omit<Module, \"address\">[] {\n return configModules.filter((module) => !defaultModules.some((m) => m.name === module.name));\n}\n","import { System } from \"./types\";\nimport { CallData } from \"../utils/types\";\nimport { resourceIdToHex } from \"@latticexyz/common\";\n\nexport async function getGrantAccessCallData(input: {\n systems: System[];\n systemContracts: Record<string, Promise<string>>;\n namespace: string;\n}): Promise<CallData[]> {\n const { systems, namespace, systemContracts } = input;\n const calls: CallData[] = [];\n for (const { name, accessListAddresses, accessListSystems } of systems) {\n // Grant access to addresses\n accessListAddresses.map(async (address) => calls.push(getGrantSystemAccessCallData(name, namespace, address)));\n\n // Grant access to other systems\n accessListSystems.map(async (granteeSystem) =>\n calls.push(getGrantSystemAccessCallData(name, namespace, await systemContracts[granteeSystem]))\n );\n }\n return calls;\n}\n\nfunction getGrantSystemAccessCallData(name: string, namespace: string, address: string): CallData {\n return {\n func: \"grantAccess\",\n args: [resourceIdToHex({ type: \"system\", namespace, name }), address],\n };\n}\n","import { resourceIdToHex } from \"@latticexyz/common\";\nimport { System } from \"./types\";\nimport { loadFunctionSignatures, toFunctionSelector } from \"./utils\";\nimport { CallData } from \"../utils/types\";\n\nexport function getRegisterFunctionSelectorsCallData(input: {\n systemContractName: string;\n system: System;\n namespace: string;\n forgeOutDirectory: string;\n}): CallData[] {\n // Register system at route\n const callData: CallData[] = [];\n const { systemContractName, namespace, forgeOutDirectory, system } = input;\n\n if (system.registerFunctionSelectors) {\n const baseSystemFunctionSignatures = loadFunctionSignatures(\"System\", forgeOutDirectory);\n const systemFunctionSignatures = loadFunctionSignatures(systemContractName, forgeOutDirectory).filter(\n (functionSignature) =>\n systemContractName === \"System\" || !baseSystemFunctionSignatures.includes(functionSignature)\n );\n const isRoot = namespace === \"\";\n for (const systemFunctionSignature of systemFunctionSignatures) {\n callData.push(\n getRegisterFunctionSelectorCallData({\n namespace,\n name: system.name,\n systemFunctionSignature,\n isRoot,\n })\n );\n }\n }\n return callData;\n}\n\nfunction getRegisterFunctionSelectorCallData(input: {\n namespace: string;\n name: string;\n systemFunctionSignature: string;\n isRoot: boolean;\n}): CallData {\n const { namespace, name, systemFunctionSignature, isRoot } = input;\n\n if (isRoot) {\n const functionSelector = toFunctionSelector(systemFunctionSignature);\n return {\n func: \"registerRootFunctionSelector\",\n args: [resourceIdToHex({ type: \"system\", namespace, name }), systemFunctionSignature, functionSelector],\n };\n } else {\n return {\n func: \"registerFunctionSelector\",\n args: [resourceIdToHex({ type: \"system\", namespace, name }), systemFunctionSignature],\n };\n }\n}\n","import { ethers } from \"ethers\";\nimport { ParamType } from \"ethers/lib/utils.js\";\nimport { getContractData } from \"../utils/getContractData\";\n\nexport function loadFunctionSignatures(contractName: string, forgeOutDirectory: string): string[] {\n const { abi } = getContractData(contractName, forgeOutDirectory);\n\n return abi\n .filter((item) => [\"fallback\", \"function\"].includes(item.type))\n .map((item) => {\n return `${item.name}${parseComponents(item.inputs)}`;\n });\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)\nexport function toFunctionSelector(functionSignature: string): string {\n return sigHash(functionSignature);\n}\n\n/**\n * Recursively turn (nested) structs in signatures into tuples\n */\nfunction 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// 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 { resourceIdToHex } from \"@latticexyz/common\";\nimport { System } from \"./types\";\nimport { CallData } from \"../utils/types\";\n\nexport async function getRegisterSystemCallData(input: {\n systemContracts: Record<string, Promise<string>>;\n systemKey: string;\n system: System;\n namespace: string;\n}): Promise<CallData> {\n const { namespace, systemContracts, systemKey, system } = input;\n const systemAddress = await systemContracts[systemKey];\n return {\n func: \"registerSystem\",\n args: [resourceIdToHex({ type: \"system\", namespace, name: system.name }), systemAddress, system.openAccess],\n };\n}\n","import { encodeSchema, getStaticByteLength } from \"@latticexyz/schema-type/deprecated\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { resolveAbiOrUserType } from \"@latticexyz/store/codegen\";\nimport { resourceIdToHex } from \"@latticexyz/common\";\nimport { Table } from \"./types\";\nimport { fieldLayoutToHex } from \"@latticexyz/protocol-parser\";\nimport { CallData } from \"../utils/types\";\nimport { loadAndExtractUserTypes } from \"@latticexyz/common/codegen\";\n\nexport function getRegisterTableCallData(\n table: Table,\n storeConfig: StoreConfig,\n outputBaseDirectory: string,\n remappings: [string, string][]\n): CallData {\n const { name, valueSchema, keySchema } = table;\n if (!name) throw Error(\"Table missing name\");\n\n const solidityUserTypes = loadAndExtractUserTypes(storeConfig.userTypes, outputBaseDirectory, remappings);\n\n const schemaTypes = Object.values(valueSchema).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, storeConfig, solidityUserTypes);\n return schemaType;\n });\n\n const schemaTypeLengths = schemaTypes.map((schemaType) => getStaticByteLength(schemaType));\n const fieldLayout = {\n staticFieldLengths: schemaTypeLengths.filter((schemaTypeLength) => schemaTypeLength > 0),\n numDynamicFields: schemaTypeLengths.filter((schemaTypeLength) => schemaTypeLength === 0).length,\n };\n\n const keyTypes = Object.values(keySchema).map((abiOrUserType) => {\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, storeConfig, solidityUserTypes);\n return schemaType;\n });\n\n return {\n func: \"registerTable\",\n args: [\n // TODO: add support for table namespaces (https://github.com/latticexyz/mud/issues/994)\n resourceIdToHex({ type: table.offchainOnly ? \"offchainTable\" : \"table\", namespace: storeConfig.namespace, name }),\n fieldLayoutToHex(fieldLayout),\n encodeSchema(keyTypes),\n encodeSchema(schemaTypes),\n Object.keys(keySchema),\n Object.keys(valueSchema),\n ],\n };\n}\n","import { StoreConfig } from \"@latticexyz/store\";\nimport { TableIds } from \"./types\";\nimport { resourceIdToHex } from \"@latticexyz/common\";\nimport { hexToBytes } from \"viem\";\n\nexport function getTableIds(storeConfig: StoreConfig): TableIds {\n const tableIds: TableIds = {};\n for (const [tableName, { name, offchainOnly }] of Object.entries(storeConfig.tables)) {\n tableIds[tableName] = hexToBytes(\n resourceIdToHex({\n type: offchainOnly ? \"offchainTable\" : \"table\",\n namespace: storeConfig.namespace,\n name,\n })\n );\n }\n return tableIds;\n}\n","import chalk from \"chalk\";\nimport { Wallet } from \"ethers\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\nexport async function confirmNonce(signer: Wallet, nonce: number, pollInterval: number): Promise<void> {\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","import chalk from \"chalk\";\nimport { TransactionReceipt, TransactionResponse } from \"@ethersproject/providers\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { TxConfig } from \"./types\";\n\n/**\n * Only await gas estimation (for speed), only execute if gas estimation succeeds (for safety)\n */\nexport async function fastTxExecute<\n C extends { connect: any; estimateGas: any; [key: string]: any },\n F extends keyof C\n>(\n input: TxConfig & {\n nonce: number;\n contract: C;\n func: F;\n args: Parameters<C[F]>;\n confirmations: number;\n }\n): Promise<TransactionResponse | TransactionReceipt> {\n const {\n func,\n args,\n contract,\n signer,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gasPrice,\n confirmations = 1,\n debug,\n } = input;\n const functionName = `${func as string}(${args.map((arg) => `'${arg}'`).join(\",\")})`;\n try {\n const contractWithSigner = contract.connect(signer);\n const gasLimit = await contractWithSigner.estimateGas[func].apply(null, args);\n console.log(chalk.gray(`executing transaction: ${functionName} with nonce ${nonce}`));\n return contractWithSigner[func]\n .apply(null, [\n ...args,\n {\n gasLimit,\n nonce: nonce,\n maxPriorityFeePerGas: maxPriorityFeePerGas,\n maxFeePerGas: maxFeePerGas,\n gasPrice: gasPrice,\n },\n ])\n .then((tx: TransactionResponse) => {\n return confirmations === 0 ? tx : tx.wait(confirmations);\n });\n } catch (error: any) {\n if (debug) console.error(error);\n throw new MUDError(`Gas estimation error for ${functionName}: ${error?.reason}`);\n }\n}\n","import { existsSync } from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getScriptDirectory, forge } from \"@latticexyz/common/foundry\";\n\nexport async function postDeploy(\n postDeployScript: string,\n worldAddress: string,\n rpc: string,\n profile: string | undefined\n): Promise<void> {\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 [\"script\", postDeployScript, \"--sig\", \"run(address)\", worldAddress, \"--broadcast\", \"--rpc-url\", rpc, \"-vvv\"],\n {\n profile: profile,\n }\n );\n } else {\n console.log(`No script at ${postDeployPath}, skipping post deploy hook`);\n }\n}\n","import { BigNumber, Wallet } from \"ethers\";\nimport { MUDError } from \"@latticexyz/common/errors\";\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 */\nexport async function setInternalFeePerGas(\n signer: Wallet,\n multiplier: number\n): Promise<{\n maxPriorityFeePerGas: number | undefined;\n maxFeePerGas: BigNumber | undefined;\n gasPrice: BigNumber | undefined;\n}> {\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n const feeData = await signer.provider.getFeeData();\n let maxPriorityFeePerGas: number | undefined;\n let maxFeePerGas: BigNumber | undefined;\n let gasPrice: BigNumber | undefined;\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 return {\n maxPriorityFeePerGas,\n maxFeePerGas,\n gasPrice,\n };\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","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"],"mappings":"AAAA,OAAOA,MAAW,QAClB,OAAOC,MAAU,OACjB,OAAS,YAAAC,OAAgB,4BACzB,OAAS,cAAAC,OAAkB,0BCH3B,OAAOC,MAAW,QAClB,OAAOC,OAAU,OACjB,OAAS,UAAAC,MAAc,SACvB,OAAS,mBAAAC,GAAiB,QAAAC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QAAQA,EAAM,YAAY;AAAA,iCAAoCQ,EAAU,kBAAkBQ;AAAA,CAAgB,CAAC,CACnH,EAGF,eAAQ,IAAIJ,CAAc,EACnBA,CACT","names":["chalk","path","MUDError","loadConfig","chalk","path","ethers","getOutDirectory","cast","getSrcDirectory","getRemappings","resolveWorldConfig","chalk","WorldData","IBaseWorldAbi","chalk","ethers","MUDError","deployContract","input","signer","nonce","maxPriorityFeePerGas","maxFeePerGas","debug","gasPrice","confirmations","contract","factory","deployPromise","c","address","error","readFileSync","path","MUDError","getContractData","contractName","forgeOutDirectory","data","contractDataPath","bytecode","abi","deployWorldContract","ip","chalk","contractData","getContractData","IBaseWorldAbi","WorldData","deployContract","IBaseWorldAbi","CoreModuleData","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","defaultModuleContracts","defaultAbiCoder","resolveWithContext","getInstallModuleCallData","moduleContracts","module","tableIds","moduleAddress","resolvedArgs","arg","values","types","getUserModules","defaultModules","configModules","module","m","resourceIdToHex","getGrantAccessCallData","input","systems","namespace","systemContracts","calls","name","accessListAddresses","accessListSystems","address","getGrantSystemAccessCallData","granteeSystem","resourceIdToHex","ethers","loadFunctionSignatures","contractName","forgeOutDirectory","abi","getContractData","item","parseComponents","toFunctionSelector","functionSignature","sigHash","params","param","tupleMatch","signature","ethers","getRegisterFunctionSelectorsCallData","input","callData","systemContractName","namespace","forgeOutDirectory","system","baseSystemFunctionSignatures","loadFunctionSignatures","systemFunctionSignatures","functionSignature","isRoot","systemFunctionSignature","getRegisterFunctionSelectorCallData","name","functionSelector","toFunctionSelector","resourceIdToHex","resourceIdToHex","getRegisterSystemCallData","input","namespace","systemContracts","systemKey","system","systemAddress","encodeSchema","getStaticByteLength","resolveAbiOrUserType","resourceIdToHex","fieldLayoutToHex","loadAndExtractUserTypes","getRegisterTableCallData","table","storeConfig","outputBaseDirectory","remappings","name","valueSchema","keySchema","solidityUserTypes","schemaTypes","abiOrUserType","schemaType","schemaTypeLengths","fieldLayout","schemaTypeLength","keyTypes","resourceIdToHex","hexToBytes","getTableIds","storeConfig","tableIds","tableName","name","offchainOnly","chalk","MUDError","confirmNonce","signer","nonce","pollInterval","remoteNonce","retryCount","maxRetries","resolve","chalk","MUDError","fastTxExecute","input","func","args","contract","signer","nonce","maxPriorityFeePerGas","maxFeePerGas","gasPrice","confirmations","debug","functionName","arg","contractWithSigner","gasLimit","tx","error","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","postDeployPath","MUDError","setInternalFeePerGas","signer","multiplier","feeData","maxPriorityFeePerGas","maxFeePerGas","gasPrice","resourceIdToHex","deploy","mudConfig","existingContractNames","deployConfig","startTime","profile","rpc","privateKey","priorityFeeMultiplier","debug","worldAddress","disableTxWait","pollInterval","resolvedConfig","resolveWorldConfig","forgeOutDirectory","getOutDirectory","remappings","getRemappings","outputBaseDirectory","path","getSrcDirectory","provider","ethers","signer","nonce","txConfig","setInternalFeePerGas","blockNumber","cast","worldPromise","deployWorldContract","userModules","getUserModules","defaultModuleContracts","userModuleContracts","name","abi","bytecode","getContractData","systemContracts","deployedContracts","CoreModuleData","acc","contract","deployContract","deployedWorldAddress","worldContract","IBaseWorldAbi","chalk","fastTxExecute","tableIds","getTableIds","registerTableCalls","table","getRegisterTableCallData","call","systemCalls","systemKey","system","getRegisterSystemCallData","functionCalls","getRegisterFunctionSelectorsCallData","grantCalls","getGrantAccessCallData","moduleCalls","m","getInstallModuleCallData","confirmNonce","postDeploy","forge","getRpcUrl","getSrcDirectory","existsSync","mkdirSync","readFileSync","writeFileSync","glob","basename","getExistingContracts","srcDir","path","execa","ethers","getChainId","rpc","chainId","deployHandler","args","configPath","printConfig","profile","clean","skipBuild","rpc","getRpcUrl","chalk","forge","execa","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-TW3YGZ4D.js";export{o as deployHandler};
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/mud.js
CHANGED
@@ -1,16 +1,20 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{
|
3
|
-
gracefully shutting down from SIGINT (Crtl-C)`),
|
2
|
+
import{a as k,b as R,c as y}from"./chunk-TW3YGZ4D.js";import Oo from"yargs";import{hideBin as Po}from"yargs/helpers";import Mo from"@latticexyz/gas-report";import So from"@latticexyz/abi-ts";import{rmSync as ae}from"fs";import{homedir as ce}from"os";import de from"path";import{execa as le}from"execa";var pe={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=ce();ae(de.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=le("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}},A=pe;import{FaucetServiceDefinition as me}from"@latticexyz/services/faucet";import{createChannel as fe,createClient as ge}from"nice-grpc-web";import E from"chalk";import{NodeHttpTransport as ue}from"@improbable-eng/grpc-web-node-http-transport";function ye(e){return ge(me,fe(e,ue()))}var he={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=ye(o);e&&(console.log(E.yellow("Dripping to",t)),await n.dripDev({address:t}),console.log(E.yellow("Success"))),process.exit(0)}},W=he;var be={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)}},$=be;import we from"path";import{loadConfig as ve}from"@latticexyz/config/node";import{tablegen as De}from"@latticexyz/store/codegen";import{getRemappings as Ce,getSrcDirectory as ke}from"@latticexyz/common/foundry";var xe={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 ve(e),t=await ke(),n=await Ce();await De(o,we.join(t,o.codegenDirectory),n),process.exit(0)}},I=xe;import w from"chalk";import{ZodError as Me}from"zod";import{fromZodError as Se,ValidationError as Oe}from"zod-validation-error";import{NotInsideProjectError as Pe}from"@latticexyz/config";import{MUDError as je}from"@latticexyz/common/errors";function f(e){if(e instanceof Oe)console.log(w.redBright(e.message));else if(e instanceof Me){let o=Se(e,{prefixSeparator:`
|
4
4
|
- `,issueSeparator:`
|
5
|
-
- `});console.log(
|
5
|
+
- `});console.log(w.redBright(o.message))}else e instanceof Pe?(console.log(w.red(e.message)),console.log(""),console.log(w.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof je?console.log(w.red(e)):console.log(e)}var S={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"}},Ue={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(S)},async handler(e){try{await y(e)}catch(o){f(o),process.exit(1)}process.exit(0)}},z=Ue;import{loadConfig as Re}from"@latticexyz/config/node";import{worldgen as Ae}from"@latticexyz/world/node";import{getSrcDirectory as Ee}from"@latticexyz/common/foundry";import T from"path";import{rmSync as We}from"fs";var $e={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 O(e),process.exit(0)}};async function O(e){let o=e.srcDir??await Ee(),t=k(o),n=e.config??await Re(e.configPath),r=T.join(o,n.codegenDirectory);e.clean&&We(T.join(r,n.worldgenDirectory),{recursive:!0,force:!0}),await Ae(n,t,r)}var F=$e;import v from"chalk";import{readFileSync as Ne,writeFileSync as _e}from"fs";import j from"path";import{MUDError as h}from"@latticexyz/common/errors";var N={name:"@latticexyz/cli",version:"2.0.0-next.11",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 && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run 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/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",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",typescript:"5.1.6",viem:"1.14.0",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 Je from"glob";import{ZodError as ze,z as _}from"zod";var Te=_.object({MUD_PACKAGES:_.string().transform(e=>JSON.parse(e))});function Fe(){try{return Te.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/noise":{"localPath":"packages/noise"},"@latticexyz/phaserx":{"localPath":"packages/phaserx"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"@latticexyz/services":{"localPath":"packages/services"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof ze){let{_errors:o,...t}=e.format();console.error(`
|
6
|
+
Missing or invalid environment variables:
|
7
|
+
|
8
|
+
${Object.keys(t).join(`
|
9
|
+
`)}
|
10
|
+
`),process.exit(1)}throw e}}var P=Fe().MUD_PACKAGES;var Ve={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({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((r,c)=>e[c]?r+1:r,0);if(t===0)throw new h(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new h(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await He(e);let n=Je.sync("**/package.json").filter(r=>!r.includes("node_modules"));for(let r of n)Le(r,e)}catch(o){f(o)}finally{process.exit(0)}}};async function He(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(v.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${N.name}`)).json()}catch{throw new h("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new h(`Could not find npm version with tag "${e.tag}"`);return console.log(v.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(r=>r.includes(t));if(!n)throw new h(`Could not find npm version based on commit "${e.commit}"`);return console.log(v.green(`Version from commit ${e.commit}: ${n}`)),n}return e.mudVersion}function Le(e,o){let{link:t}=o,{mudVersion:n}=o,r=Ge(e),c=Object.keys(P),l={};for(let i in r.dependencies)c.includes(i)&&(l[i]=r.dependencies[i]);let s={};for(let i in r.devDependencies)c.includes(i)&&(s[i]=r.devDependencies[i]);for(let i in r.dependencies)c.includes(i)&&(r.dependencies[i]=p(i,"dependencies"));for(let i in r.devDependencies)c.includes(i)&&(r.devDependencies[i]=p(i,"devDependencies"));return _e(e,JSON.stringify(r,null,2)+`
|
11
|
+
`),console.log(`Updating ${e}`),J(l,r.dependencies),J(s,r.devDependencies),r;function p(i,g){return t&&(n=Be(e,t,i)),n||r[g][i]}}function Ge(e){try{let o=Ne(e,"utf8");return JSON.parse(o)}catch{throw new h("Could not read JSON at "+e)}}function J(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${v.red(e[t])} -> ${v.green(o[t])}`)}function Be(e,o,t){let n=j.relative(j.dirname(e),process.cwd());return"link:"+j.join(n,o,P[t].localPath)}var V=Ve;import{anvil as qe,forge as Ke,getRpcUrl as Ze}from"@latticexyz/common/foundry";import Ye from"chalk";import{rmSync as H,writeFileSync as Qe}from"fs";var U=".mudtest",Xe={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options({...S,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 r=["--block-base-fee-per-gas","0","--port",String(e.port)];qe(r)}let o=e.worldAddress?await Ze(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await y({...e,saveDeployment:!1,rpc:o})).worldAddress;console.log(Ye.blue("World address",t)),Qe(U,t);let n=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{let r=await Ke(["test","--fork-url",o,...n],{profile:e.profile});console.log(r)}catch(r){console.error(r),H(U),process.exit(1)}H(U),process.exit(0)}},L=Xe;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 B}from"@latticexyz/common/errors";import{cast as ro,getRpcUrl as no,getSrcDirectory as io}from"@latticexyz/common/foundry";import{resolveWorldConfig as so}from"@latticexyz/world";import ao from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import q from"@latticexyz/world/mud.config.js";import{resourceIdToHex as Z}from"@latticexyz/common";var K=Z({type:"system",namespace:q.namespace,name:q.tables.Systems.name}),co={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:r,rpc:c}=e,l=k(r),s=await to(n),p=so(s,l.map(({basename:m})=>m)),i=e.worldAddress??await lo(s.worldsFile,c),g=new G.providers.StaticJsonRpcProvider(c),b=new G.Contract(i,ao,g),C=s.namespace,x=Object.values(p.systems).map(({name:m})=>m),d=await b.getFieldLayout(K),a=[];for(let m of x){let M=Z({type:"system",namespace:C,name:m}),se=await b.getField(K,[M],0,d);a.push({name:m,address:se})}let u=await ro(["run","--label",`${i}:World`,...a.map(({name:m,address:M})=>["--label",`${M}:${m}`]).flat(),`${t}`]);console.log(u),process.exit(0)}},Y=co;async function lo(e,o){if(eo(e)){let t=await R(o),n=JSON.parse(oo(e,"utf-8"));if(!n[t])throw new B(`chainId ${t} is missing in worldsFile "${e}"`);return n[t].address}else throw new B("worldAddress is not specified and worldsFile is missing")}import{anvil as mo,forge as X,getRemappings as fo,getRpcUrl as go,getScriptDirectory as uo,getSrcDirectory as yo}from"@latticexyz/common/foundry";import D from"chalk";import ho from"chokidar";import{loadConfig as ee,resolveConfigPath as bo}from"@latticexyz/config/node";import{tablegen as wo}from"@latticexyz/store/codegen";import oe from"path";import{debounce as vo}from"throttle-debounce";import{homedir as Do}from"os";import{rmSync as Co}from"fs";import{execa as ko}from"execa";import po from"chalk";function Q(){console.log(po.yellow(`
|
6
12
|
.------..------..------.
|
7
13
|
|M.--. ||U.--. ||D.--. |
|
8
14
|
| (\\/) || (\\/) || :/\\: |
|
9
15
|
| :\\/: || :\\/: || (__) |
|
10
16
|
| '--'M|| '--'U|| '--'D|
|
11
17
|
'------''------''------'
|
12
|
-
`))}
|
13
|
-
|
14
|
-
`),console.log(`Updating ${e}`),L(m,s.dependencies),L(y,s.devDependencies),t&&!d&&(_e(a),console.log(h.green(`Cleaned up ${a}`))),s;function c(n,p){return t&&u?u[p][n]:(i&&(l=Ze(e,i,n)),l||s[p][n])}}function _(e){try{let o=Ve(e,"utf8");return JSON.parse(o)}catch{throw new b("Could not read JSON at "+e)}}function L(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${h.red(e[t])} -> ${h.green(o[t])}`)}function Ze(e,o,t){let r=t.replace(C,""),i=x.relative(x.dirname(e),process.cwd());return"link:"+x.join(i,o,"packages",r)}var q=qe;import{anvil as Ke,forge as Xe,getRpcUrl as Qe}from"@latticexyz/common/foundry";import eo from"chalk";import{rmSync as oo,writeFileSync as to}from"fs";var G=".mudtest",ro={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options({...P,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)];Ke(i)}let o=e.worldAddress?await Qe(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await w({...e,saveDeployment:!1,rpc:o})).worldAddress;console.log(eo.blue("World address",t)),to(G,t);let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{let i=await Xe(["test","--fork-url",o,...r],{profile:e.profile});console.log(i)}catch(i){console.error(i)}oo(G),process.exit(0)}},Y=ro;import{existsSync as no,readFileSync as io}from"fs";import{ethers as Z}from"ethers";import{loadConfig as so}from"@latticexyz/config/node";import{MUDError as K}from"@latticexyz/common/errors";import{cast as ao,getRpcUrl as co,getSrcDirectory as lo}from"@latticexyz/common/foundry";import{TableId as X}from"@latticexyz/common/deprecated";import{resolveWorldConfig as po}from"@latticexyz/world";import mo from"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json"assert{type:"json"};var fo=new X("","Systems"),go={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 lo(o),e.rpc??=await co(o);let{tx:t,configPath:r,srcDir:i,rpc:d}=e,l=O(i),a=await so(r),v=po(a,l.map(({basename:f})=>f)),s=e.worldAddress??await uo(a.worldsFile,d),u=new Z.providers.StaticJsonRpcProvider(d),m=new Z.Contract(s,mo.abi,u),y=a.namespace,c=Object.values(v.systems).map(({name:f})=>f),n=[];for(let f of c){let U=new X(y,f),ae=await m.getField(fo.toHex(),[U.toHex()],0);n.push({name:f,address:ae})}let p=await ao(["run","--label",`${s}:World`,...n.map(({name:f,address:U})=>["--label",`${U}:${f}`]).flat(),`${t}`]);console.log(p),process.exit(0)}},Q=go;async function uo(e,o){if(no(e)){let t=await W(o),r=JSON.parse(io(e,"utf-8"));if(!r[t])throw new K(`chainId ${t} is missing in worldsFile "${e}"`);return r[t].address}else throw new K("worldAddress is not specified and worldsFile is missing")}import{anvil as yo,forge as ee,getRpcUrl as ho,getScriptDirectory as bo,getSrcDirectory as wo}from"@latticexyz/common/foundry";import k from"chalk";import vo from"chokidar";import{loadConfig as oe,resolveConfigPath as Do}from"@latticexyz/config/node";import{tablegen as Co}from"@latticexyz/store/codegen";import te from"path";import{debounce as xo}from"throttle-debounce";import{homedir as ko}from"os";import{rmSync as Mo}from"fs";var Oo={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"},tsgenOutput:{type:"string",demandOption:!0,desc:"Directory to output MUD typescript definition files"}})},async handler(e){e.tsgenOutputDir||console.error("No output provided"),await ee(["clean"]);let o=e.rpc??await ho(),t=e.configPath??await Do(e.configPath),r=await wo(),i=await bo(),d=await oe(t);if(await u(d),await m(d),!e.rpc){console.log(k.gray("Cleaning devnode cache"));let c=ko();Mo(te.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),yo(["--block-time","1","--block-base-fee-per-gas","0"])}let l={config:!1,contracts:!1},a={current:!1};vo.watch([t,r]).on("all",async(c,n)=>{if(n.includes(t)&&(l.config=!0,l.contracts=!0),n.includes(r)||n.includes(i)){if(n.includes(d.codegenDirectory))return;l.contracts=!0}s()});let s=xo(100,async()=>{if(a.current)return;a.current=!0;let{config:c,contracts:n}=l;l.config=!1,l.contracts=!1;try{let p=await oe(t);c&&await u(p),n&&await m(p),await y()}catch(p){console.error(k.red(`MUD dev-contracts watcher failed to deploy config or contracts changes
|
15
|
-
`)),g(p)}a.current=!1,(l.config||l.contracts)&&(console.log("Detected change while handling the previous change"),s()),T(),console.log("MUD watching for changes...")});async function u(c){console.log(k.blue("mud.config.ts changed - regenerating tables and recs types"));let n=te.join(r,c.codegenDirectory);await Co(c,n),await M(c,e.tsgenOutput)}async function m(c){console.log(k.blue("contracts changed - regenerating interfaces and contract types")),await j({config:c,clean:!0,srcDir:r}),await ee(["build"]),await z()}async function y(){console.log(k.blue("redeploying World")),await w({configPath:t,skipBuild:!0,priorityFeeMultiplier:1,disableTxWait:!0,pollInterval:1e3,saveDeployment:!0,srcDir:r,rpc:o})}}},re=Oo;var ne=[J,R,$,So,A,E,F,H,q,Y,Q,re];import*as se from"dotenv";import ie from"chalk";se.config();Uo(Po(process.argv)).scriptName("mud").command(ne).strict().fail((e,o)=>{console.error(ie.red(e)),e.includes("Missing required argument")&&console.log(ie.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;
|
18
|
+
`))}var xo={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 go(),t=e.configPath??await bo(e.configPath),n=await yo(),r=await uo(),c=await fo(),l=await ee(t);if(await b(l),await C(l),!e.rpc){console.log(D.gray("Cleaning devnode cache"));let d=Do();Co(oe.join(d,".foundry","anvil","tmp"),{recursive:!0,force:!0}),mo(["--block-time","1","--block-base-fee-per-gas","0"])}let s={config:!1,contracts:!1},p={current:!1};ho.watch([t,n]).on("all",async(d,a)=>{if(a.includes(t)&&(s.config=!0,s.contracts=!0),a.includes(n)||a.includes(r)){if(a.includes(l.codegenDirectory))return;s.contracts=!0}g()});let g=vo(100,async()=>{if(p.current)return;p.current=!0;let{config:d,contracts:a}=s;s.config=!1,s.contracts=!1;try{let u=await ee(t);d&&await b(u),a&&await C(u),await x()}catch(u){console.error(D.red(`MUD dev-contracts watcher failed to deploy config or contracts changes
|
19
|
+
`)),f(u)}p.current=!1,(s.config||s.contracts)&&(console.log("Detected change while handling the previous change"),g()),Q(),console.log("MUD watching for changes...")});async function b(d){console.log(D.blue("mud.config.ts changed - regenerating tables and recs types"));let a=oe.join(n,d.codegenDirectory);await wo(d,a,c)}async function C(d){console.log(D.blue("contracts changed - regenerating interfaces and contract types")),await O({config:d,clean:!0,srcDir:n}),await X(["build","--skip","test","script"]),await ko("mud",["abi-ts"],{stdio:"inherit"})}async function x(){console.log(D.blue("redeploying World")),await y({configPath:t,skipBuild:!0,priorityFeeMultiplier:1,disableTxWait:!0,pollInterval:1e3,saveDeployment:!0,srcDir:n,rpc:o})}}},te=xo;var re=[z,A,W,Mo,$,I,F,V,L,Y,te,So];import*as ie from"dotenv";import ne from"chalk";ie.config();Oo(Po(process.argv)).scriptName("mud").command(re).strict().fail((e,o)=>{console.error(ne.red(e)),e.includes("Missing required argument")&&console.log(ne.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(f(o),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
|
16
20
|
//# sourceMappingURL=mud.js.map
|