@latticexyz/cli 0.0.0-main-20230704121617

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Lattice Labs Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # cli
2
+
3
+ docs coming soon
@@ -0,0 +1,30 @@
1
+ import{SchemaType as e}from"@latticexyz/schema-type/deprecated";var re={[e.UINT8]:"RecsType.Number",[e.UINT16]:"RecsType.Number",[e.UINT24]:"RecsType.Number",[e.UINT32]:"RecsType.Number",[e.UINT40]:"RecsType.Number",[e.UINT48]:"RecsType.Number",[e.UINT56]:"RecsType.BigInt",[e.UINT64]:"RecsType.BigInt",[e.UINT72]:"RecsType.BigInt",[e.UINT80]:"RecsType.BigInt",[e.UINT88]:"RecsType.BigInt",[e.UINT96]:"RecsType.BigInt",[e.UINT104]:"RecsType.BigInt",[e.UINT112]:"RecsType.BigInt",[e.UINT120]:"RecsType.BigInt",[e.UINT128]:"RecsType.BigInt",[e.UINT136]:"RecsType.BigInt",[e.UINT144]:"RecsType.BigInt",[e.UINT152]:"RecsType.BigInt",[e.UINT160]:"RecsType.BigInt",[e.UINT168]:"RecsType.BigInt",[e.UINT176]:"RecsType.BigInt",[e.UINT184]:"RecsType.BigInt",[e.UINT192]:"RecsType.BigInt",[e.UINT200]:"RecsType.BigInt",[e.UINT208]:"RecsType.BigInt",[e.UINT216]:"RecsType.BigInt",[e.UINT224]:"RecsType.BigInt",[e.UINT232]:"RecsType.BigInt",[e.UINT240]:"RecsType.BigInt",[e.UINT248]:"RecsType.BigInt",[e.UINT256]:"RecsType.BigInt",[e.INT8]:"RecsType.Number",[e.INT16]:"RecsType.Number",[e.INT24]:"RecsType.Number",[e.INT32]:"RecsType.Number",[e.INT40]:"RecsType.Number",[e.INT48]:"RecsType.Number",[e.INT56]:"RecsType.BigInt",[e.INT64]:"RecsType.BigInt",[e.INT72]:"RecsType.BigInt",[e.INT80]:"RecsType.BigInt",[e.INT88]:"RecsType.BigInt",[e.INT96]:"RecsType.BigInt",[e.INT104]:"RecsType.BigInt",[e.INT112]:"RecsType.BigInt",[e.INT120]:"RecsType.BigInt",[e.INT128]:"RecsType.BigInt",[e.INT136]:"RecsType.BigInt",[e.INT144]:"RecsType.BigInt",[e.INT152]:"RecsType.BigInt",[e.INT160]:"RecsType.BigInt",[e.INT168]:"RecsType.BigInt",[e.INT176]:"RecsType.BigInt",[e.INT184]:"RecsType.BigInt",[e.INT192]:"RecsType.BigInt",[e.INT200]:"RecsType.BigInt",[e.INT208]:"RecsType.BigInt",[e.INT216]:"RecsType.BigInt",[e.INT224]:"RecsType.BigInt",[e.INT232]:"RecsType.BigInt",[e.INT240]:"RecsType.BigInt",[e.INT248]:"RecsType.BigInt",[e.INT256]:"RecsType.BigInt",[e.BYTES1]:"RecsType.String",[e.BYTES2]:"RecsType.String",[e.BYTES3]:"RecsType.String",[e.BYTES4]:"RecsType.String",[e.BYTES5]:"RecsType.String",[e.BYTES6]:"RecsType.String",[e.BYTES7]:"RecsType.String",[e.BYTES8]:"RecsType.String",[e.BYTES9]:"RecsType.String",[e.BYTES10]:"RecsType.String",[e.BYTES11]:"RecsType.String",[e.BYTES12]:"RecsType.String",[e.BYTES13]:"RecsType.String",[e.BYTES14]:"RecsType.String",[e.BYTES15]:"RecsType.String",[e.BYTES16]:"RecsType.String",[e.BYTES17]:"RecsType.String",[e.BYTES18]:"RecsType.String",[e.BYTES19]:"RecsType.String",[e.BYTES20]:"RecsType.String",[e.BYTES21]:"RecsType.String",[e.BYTES22]:"RecsType.String",[e.BYTES23]:"RecsType.String",[e.BYTES24]:"RecsType.String",[e.BYTES25]:"RecsType.String",[e.BYTES26]:"RecsType.String",[e.BYTES27]:"RecsType.String",[e.BYTES28]:"RecsType.String",[e.BYTES29]:"RecsType.String",[e.BYTES30]:"RecsType.String",[e.BYTES31]:"RecsType.String",[e.BYTES32]:"RecsType.String",[e.BOOL]:"RecsType.Boolean",[e.ADDRESS]:"RecsType.String",[e.UINT8_ARRAY]:"RecsType.NumberArray",[e.UINT16_ARRAY]:"RecsType.NumberArray",[e.UINT24_ARRAY]:"RecsType.NumberArray",[e.UINT32_ARRAY]:"RecsType.NumberArray",[e.UINT40_ARRAY]:"RecsType.NumberArray",[e.UINT48_ARRAY]:"RecsType.NumberArray",[e.UINT56_ARRAY]:"RecsType.BigIntArray",[e.UINT64_ARRAY]:"RecsType.BigIntArray",[e.UINT72_ARRAY]:"RecsType.BigIntArray",[e.UINT80_ARRAY]:"RecsType.BigIntArray",[e.UINT88_ARRAY]:"RecsType.BigIntArray",[e.UINT96_ARRAY]:"RecsType.BigIntArray",[e.UINT104_ARRAY]:"RecsType.BigIntArray",[e.UINT112_ARRAY]:"RecsType.BigIntArray",[e.UINT120_ARRAY]:"RecsType.BigIntArray",[e.UINT128_ARRAY]:"RecsType.BigIntArray",[e.UINT136_ARRAY]:"RecsType.BigIntArray",[e.UINT144_ARRAY]:"RecsType.BigIntArray",[e.UINT152_ARRAY]:"RecsType.BigIntArray",[e.UINT160_ARRAY]:"RecsType.BigIntArray",[e.UINT168_ARRAY]:"RecsType.BigIntArray",[e.UINT176_ARRAY]:"RecsType.BigIntArray",[e.UINT184_ARRAY]:"RecsType.BigIntArray",[e.UINT192_ARRAY]:"RecsType.BigIntArray",[e.UINT200_ARRAY]:"RecsType.BigIntArray",[e.UINT208_ARRAY]:"RecsType.BigIntArray",[e.UINT216_ARRAY]:"RecsType.BigIntArray",[e.UINT224_ARRAY]:"RecsType.BigIntArray",[e.UINT232_ARRAY]:"RecsType.BigIntArray",[e.UINT240_ARRAY]:"RecsType.BigIntArray",[e.UINT248_ARRAY]:"RecsType.BigIntArray",[e.UINT256_ARRAY]:"RecsType.BigIntArray",[e.INT8_ARRAY]:"RecsType.NumberArray",[e.INT16_ARRAY]:"RecsType.NumberArray",[e.INT24_ARRAY]:"RecsType.NumberArray",[e.INT32_ARRAY]:"RecsType.NumberArray",[e.INT40_ARRAY]:"RecsType.NumberArray",[e.INT48_ARRAY]:"RecsType.NumberArray",[e.INT56_ARRAY]:"RecsType.BigIntArray",[e.INT64_ARRAY]:"RecsType.BigIntArray",[e.INT72_ARRAY]:"RecsType.BigIntArray",[e.INT80_ARRAY]:"RecsType.BigIntArray",[e.INT88_ARRAY]:"RecsType.BigIntArray",[e.INT96_ARRAY]:"RecsType.BigIntArray",[e.INT104_ARRAY]:"RecsType.BigIntArray",[e.INT112_ARRAY]:"RecsType.BigIntArray",[e.INT120_ARRAY]:"RecsType.BigIntArray",[e.INT128_ARRAY]:"RecsType.BigIntArray",[e.INT136_ARRAY]:"RecsType.BigIntArray",[e.INT144_ARRAY]:"RecsType.BigIntArray",[e.INT152_ARRAY]:"RecsType.BigIntArray",[e.INT160_ARRAY]:"RecsType.BigIntArray",[e.INT168_ARRAY]:"RecsType.BigIntArray",[e.INT176_ARRAY]:"RecsType.BigIntArray",[e.INT184_ARRAY]:"RecsType.BigIntArray",[e.INT192_ARRAY]:"RecsType.BigIntArray",[e.INT200_ARRAY]:"RecsType.BigIntArray",[e.INT208_ARRAY]:"RecsType.BigIntArray",[e.INT216_ARRAY]:"RecsType.BigIntArray",[e.INT224_ARRAY]:"RecsType.BigIntArray",[e.INT232_ARRAY]:"RecsType.BigIntArray",[e.INT240_ARRAY]:"RecsType.BigIntArray",[e.INT248_ARRAY]:"RecsType.BigIntArray",[e.INT256_ARRAY]:"RecsType.BigIntArray",[e.BYTES1_ARRAY]:"RecsType.StringArray",[e.BYTES2_ARRAY]:"RecsType.StringArray",[e.BYTES3_ARRAY]:"RecsType.StringArray",[e.BYTES4_ARRAY]:"RecsType.StringArray",[e.BYTES5_ARRAY]:"RecsType.StringArray",[e.BYTES6_ARRAY]:"RecsType.StringArray",[e.BYTES7_ARRAY]:"RecsType.StringArray",[e.BYTES8_ARRAY]:"RecsType.StringArray",[e.BYTES9_ARRAY]:"RecsType.StringArray",[e.BYTES10_ARRAY]:"RecsType.StringArray",[e.BYTES11_ARRAY]:"RecsType.StringArray",[e.BYTES12_ARRAY]:"RecsType.StringArray",[e.BYTES13_ARRAY]:"RecsType.StringArray",[e.BYTES14_ARRAY]:"RecsType.StringArray",[e.BYTES15_ARRAY]:"RecsType.StringArray",[e.BYTES16_ARRAY]:"RecsType.StringArray",[e.BYTES17_ARRAY]:"RecsType.StringArray",[e.BYTES18_ARRAY]:"RecsType.StringArray",[e.BYTES19_ARRAY]:"RecsType.StringArray",[e.BYTES20_ARRAY]:"RecsType.StringArray",[e.BYTES21_ARRAY]:"RecsType.StringArray",[e.BYTES22_ARRAY]:"RecsType.StringArray",[e.BYTES23_ARRAY]:"RecsType.StringArray",[e.BYTES24_ARRAY]:"RecsType.StringArray",[e.BYTES25_ARRAY]:"RecsType.StringArray",[e.BYTES26_ARRAY]:"RecsType.StringArray",[e.BYTES27_ARRAY]:"RecsType.StringArray",[e.BYTES28_ARRAY]:"RecsType.StringArray",[e.BYTES29_ARRAY]:"RecsType.StringArray",[e.BYTES30_ARRAY]:"RecsType.StringArray",[e.BYTES31_ARRAY]:"RecsType.StringArray",[e.BYTES32_ARRAY]:"RecsType.StringArray",[e.BOOL_ARRAY]:"RecsType.T",[e.ADDRESS_ARRAY]:"RecsType.StringArray",[e.BYTES]:"RecsType.String",[e.STRING]:"RecsType.String"};import{resolveAbiOrUserType as Ye}from"@latticexyz/store/codegen";function ne(n){let a=[];for(let i of Object.keys(n.tables)){let T=n.tables[i],m=Object.keys(T.schema).map(y=>{let U=T.schema[y],{schemaType:$}=Ye(U,n);return{recsTypeString:re[$],name:y}});if(T.tableIdArgument)continue;let x={namespace:n.namespace,name:T.name};a.push({tableName:i,fields:m,staticResourceData:x})}return{tables:a}}function oe(n){let{tables:a}=n;return`/* Autogenerated file. Do not edit manually. */
2
+
3
+ import { TableId } from "@latticexyz/common";
4
+ import { defineComponent, Type as RecsType, World } from "@latticexyz/recs";
5
+
6
+ export function defineContractComponents(world: World) {
7
+ return {
8
+ ${a.map(i=>`${i.tableName}: ${we(i)},`).join("")}
9
+ }
10
+ }
11
+ `}function we(n){let{namespace:a,name:i}=n.staticResourceData;return`
12
+ (() => {
13
+ const tableId = new TableId("${a}", "${i}");
14
+ return defineComponent(world, {
15
+ ${n.fields.map(({name:T,recsTypeString:m})=>`${T}: ${m},`).join("")}
16
+ }, {
17
+ metadata: { contractId: tableId.toHex(), tableId: tableId.toString() },
18
+ });
19
+ })()
20
+ `}import _e from"path";import{formatAndWriteTypescript as Ee}from"@latticexyz/common/codegen";async function at(n,a){let i=_e.join(a,"contractComponents.ts"),T=ne(n),m=oe(T);Ee(m,i,"Generated ts definition files")}import v from"chalk";import J from"path";import{MUDError as Ve}from"@latticexyz/common/errors";import{loadConfig as Ke}from"@latticexyz/config/node";import{existsSync as he,readFileSync as Ue}from"fs";import se from"path";import p from"chalk";import{ethers as P}from"ethers";import{defaultAbiCoder as $e}from"ethers/lib/utils.js";import{getOutDirectory as Ce,getScriptDirectory as De,cast as Pe,forge as xe}from"@latticexyz/common/foundry";import{resolveWithContext as Fe}from"@latticexyz/config";import{MUDError as Y}from"@latticexyz/common/errors";import{encodeSchema as ie}from"@latticexyz/schema-type/deprecated";import{resolveAbiOrUserType as ae}from"@latticexyz/store/codegen";import{resolveWorldConfig as ve}from"@latticexyz/world";import Oe from"@latticexyz/world/abi/World.sol/World.json"assert{type:"json"};import ce from"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json"assert{type:"json"};import ye from"@latticexyz/world/abi/CoreModule.sol/CoreModule.json"assert{type:"json"};import pe from"@latticexyz/world/abi/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import Te from"@latticexyz/world/abi/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Re from"@latticexyz/world/abi/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import le from"@latticexyz/world/abi/SnapSyncModule.sol/SnapSyncModule.json"assert{type:"json"};async function Ae(n,a,i){let T=ve(n,a),m=Date.now(),{worldContractName:x,namespace:y,postDeployScript:U}=n,{profile:$,rpc:u,privateKey:O,priorityFeeMultiplier:S,debug:w,worldAddress:_,disableTxWait:d,pollInterval:F}=i,de=await Ce($),k=new P.providers.StaticJsonRpcProvider(u);k.pollingInterval=F;let C=new P.Wallet(O,k),E=await C.getTransactionCount();console.log("Initial nonce",E);let j,W;await L(S);let g=[],z=Number(await Pe(["block-number","--rpc-url",u],{profile:$}));console.log("Start deployment at block",z);let fe={World:_?Promise.resolve(_):x?K(x,d):h(ce.abi,Oe.bytecode,d,"World")},Se=Object.keys(T.systems).reduce((t,r)=>(t[r]=K(r,d),t),{}),H={CoreModule:h(ye.abi,ye.bytecode,d,"CoreModule"),KeysWithValueModule:h(pe.abi,pe.bytecode,d,"KeysWithValueModule"),KeysInTableModule:h(Te.abi,Te.bytecode,d,"KeysInTableModule"),UniqueEntityModule:h(Re.abi,Re.bytecode,d,"UniqueEntityModule"),SnapSyncModule:h(le.abi,le.bytecode,d,"SnapSyncModule")},Q=n.modules.filter(t=>!H[t.name]).reduce((t,r)=>(t[r.name]=K(r.name,d),t),H),D={...fe,...Se,...Q},B=new P.Contract(await D.World,ce.abi,C),b=d?0:1;_||(console.log(p.blue("Installing core World modules")),await f(B,"installRootModule",[await Q.CoreModule,"0x"],b),console.log(p.green("Installed core World modules"))),y&&await f(B,"registerNamespace",[A(y)],b);let X={};g=[...g,...Object.entries(n.tables).map(async([t,{name:r,schema:o,keySchema:c}])=>{console.log(p.blue(`Registering table ${t} at ${y}/${r}`)),X[t]=je(y,r);let l=Object.values(o).map(R=>{let{schemaType:I}=ae(R,n);return I}),s=Object.values(c).map(R=>{let{schemaType:I}=ae(R,n);return I});await f(B,"registerTable",[A(y),A(r),ie(l),ie(s)],b),await f(B,"setMetadata(bytes16,bytes16,string,string[])",[A(y),A(r),t,Object.keys(o)],b),console.log(p.green(`Registered table ${t} at ${r}`))})],g=[...g,...Object.entries(T.systems).map(async([t,{name:r,openAccess:o,registerFunctionSelectors:c}])=>{if(console.log(p.blue(`Registering system ${t} at ${y}/${r}`)),await f(B,"registerSystem",[A(y),A(r),await D[t],o],b),console.log(p.green(`Registered system ${t} at ${y}/${r}`)),c){let l=await Be(t),s=y==="";await Promise.all(l.map(async({functionName:R,functionArgs:I})=>{let N=s?R+I:`${y}_${r}_${R}${I}`;if(console.log(p.blue(`Registering function "${N}"`)),s){let be=ge(N===""?{functionName:t,functionArgs:I}:{functionName:R,functionArgs:I}),Ne=ge({functionName:R,functionArgs:I});await f(B,"registerRootFunctionSelector",[A(y),A(r),be,Ne],b)}else await f(B,"registerFunctionSelector",[A(y),A(r),R,I],b);console.log(p.green(`Registered function "${N}"`))}))}})],await Promise.all(g),g=[];for(let[t,{name:r,accessListAddresses:o,accessListSystems:c}]of Object.entries(T.systems)){let l=`${y}/${r}`;g=[...g,...o.map(async s=>{console.log(p.blue(`Grant ${s} access to ${t} (${l})`)),await f(B,"grantAccess",[A(y),A(r),s],b),console.log(p.green(`Granted ${s} access to ${t} (${y}/${r})`))})],g=[...g,...c.map(async s=>{console.log(p.blue(`Grant ${s} access to ${t} (${l})`)),await f(B,"grantAccess",[A(y),A(r),await D[s]],b),console.log(p.green(`Granted ${s} access to ${t} (${l})`))})]}await Promise.all(g),g=[],g=[...g,...n.modules.map(async t=>{console.log(p.blue(`Installing${t.root?" root ":" "}module ${t.name}`));let r=await Promise.all(t.args.map(s=>Fe(s,{tableIds:X,systemAddresses:D}))),o=r.map(s=>s.value),c=r.map(s=>s.type),l=await D[t.name];if(!l)throw new Error(`Module ${t.name} not found`);await f(B,t.root?"installRootModule":"installModule",[l,$e.encode(c,o)],b),console.log(p.green(`Installed${t.root?" root ":" "}module ${t.name}`))})],await Promise.all(g);let M=await C.getTransactionCount(),G=0,Z=100;for(;M!==E&&G<Z;)console.log(p.gray(`Waiting for transactions to be included before executing ${U} (local nonce: ${E}, remote nonce: ${M}, retry number ${G}/${Z})`)),await new Promise(t=>setTimeout(t,F)),G++,M=await C.getTransactionCount();if(M!==E)throw new Y("Remote nonce doesn't match local nonce, indicating that not all deploy transactions were included.");g=[];let V=se.join(await De(),U+".s.sol");return he(V)?(console.log(p.blue(`Executing post deploy script at ${V}`)),await xe(["script",U,"--sig","run(address)",await D.World,"--broadcast","--rpc-url",u,"-vvv"],{profile:$})):console.log(`No script at ${V}, skipping post deploy hook`),console.log(p.green("Deployment completed in",(Date.now()-m)/1e3,"seconds")),{worldAddress:await D.World,blockNumber:z};async function K(t,r){console.log(p.blue("Deploying",t));let{abi:o,bytecode:c}=await te(t);return h(o,c,r,t)}async function h(t,r,o,c,l=0){try{let s=new P.ContractFactory(t,r,C);console.log(p.gray(`executing deployment of ${c} with nonce ${E}`));let R=s.deploy({nonce:E++,maxPriorityFeePerGas:j,maxFeePerGas:W}).then(N=>o?N:N.deployed());g.push(R);let{address:I}=await R;return console.log(p.green("Deployed",c,"to",I)),I}catch(s){if(w&&console.error(s),l===0&&s?.message.includes("transaction already imported"))return L(S*1.1),h(t,r,o,c,l++);throw s?.message.includes("invalid bytecode")?new Y(`Error deploying ${c}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use "external" functions.`):s?.message.includes("CreateContractLimit")?new Y(`Error deploying ${c}: CreateContractLimit exceeded.`):s}}async function Be(t){let{abi:r}=await te(t);return r.filter(o=>["fallback","function"].includes(o.type)).map(o=>o.type==="fallback"?{functionName:"",functionArgs:""}:{functionName:o.name,functionArgs:ee(o.inputs)})}function ee(t){return`(${t.map(o=>{let c=o.type.match(/tuple(.*)/);return c?ee(o.components)+c[1]:o.type})})`}async function f(t,r,o,c=1,l=0){let s=`${r}(${o.map(R=>`'${R}'`).join(",")})`;try{let R=await t.estimateGas[r].apply(null,o);console.log(p.gray(`executing transaction: ${s} with nonce ${E}`));let I=t[r].apply(null,[...o,{gasLimit:R,nonce:E++,maxPriorityFeePerGas:j,maxFeePerGas:W}]).then(N=>c===0?N:N.wait(c));return g.push(I),I}catch(R){if(w&&console.error(R),l===0&&R?.message.includes("transaction already imported"))return L(S*1.1),f(t,r,o,c,l++);throw new Y(`Gas estimation error for ${s}: ${R?.reason}`)}}async function te(t){let r,o=se.join(de,t+".sol",t+".json");try{r=JSON.parse(Ue(o,"utf8"))}catch{throw new Y(`Error reading file at ${o}`)}let c=r?.bytecode?.object;if(!c)throw new Y(`No bytecode found in ${o}`);let l=r?.abi;if(!l)throw new Y(`No ABI found in ${o}`);return{abi:l,bytecode:c}}async function L(t){let r=await k.getFeeData();if(!r.lastBaseFeePerGas)throw new Y("Can not fetch lastBaseFeePerGas from RPC");if(!r.lastBaseFeePerGas.eq(0)&&(await C.getBalance()).eq(0))throw new Y(`Attempting to deploy to a chain with non-zero base fee with an account that has no balance.
21
+ If you're deploying to the Lattice testnet, you can fund your account by running 'pnpm mud faucet --address ${await C.getAddress()}'`);j=r.lastBaseFeePerGas.eq(0)?0:Math.floor(15e8*t),W=r.lastBaseFeePerGas.mul(2).add(j)}}function A(n){if(n.length>16)throw new Error("String does not fit into 16 bytes");let a=new Uint8Array(16);for(let i=0;i<n.length;i++)a[i]=n.charCodeAt(i);for(let i=n.length;i<16;i++)a[i]=0;return a}function je(n,a){let i=A(n),T=A(a),m=new Uint8Array(32);return m.set(i),m.set(T,16),m}function ge({functionName:n,functionArgs:a}){let i=n+a;return i===""?"0x":Me(i)}function Me(n){return P.utils.hexDataSlice(P.utils.keccak256(P.utils.toUtf8Bytes(n)),0,4)}import{forge as ue,getRpcUrl as Le,getSrcDirectory as Je}from"@latticexyz/common/foundry";import{existsSync as qe,mkdirSync as ze,readFileSync as He,writeFileSync as q}from"fs";import{ethers as ke}from"ethers";async function Ie(n){let{result:a}=await ke.utils.fetchJson(n,'{ "id": 42, "jsonrpc": "2.0", "method": "eth_chainId", "params": [ ] }');return Number(a)}import We from"glob";import{basename as Ge}from"path";function me(n){return We.sync(`${n}/**/*.sol`).map(a=>({path:a,basename:Ge(a,".sol")}))}async function Zt(n){n.profile??=process.env.FOUNDRY_PROFILE;let{configPath:a,printConfig:i,profile:T,clean:m,skipBuild:x}=n,y=n.rpc??await Le(T);console.log(v.bgBlue(v.whiteBright(`
22
+ Deploying MUD contracts${T?" with profile "+T:""} to RPC ${y}
23
+ `))),m&&await ue(["clean"],{profile:T}),x||await ue(["build"],{profile:T});let U=n?.srcDir??await Je(),$=me(U).map(({basename:w})=>w),u=await Ke(a);i&&console.log(v.green(`
24
+ Resolved config:
25
+ `),JSON.stringify(u,null,2));let O=process.env.PRIVATE_KEY;if(!O)throw new Ve(`Missing PRIVATE_KEY environment variable.
26
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
27
+ in your contracts directory to use the default anvil private key.`);let S=await Ae(u,$,{...n,rpc:y,privateKey:O});if(n.saveDeployment){let w=await Ie(y),_=J.join(u.deploysDirectory,w.toString());ze(_,{recursive:!0}),q(J.join(_,"latest.json"),JSON.stringify(S,null,2)),q(J.join(_,Date.now()+".json"),JSON.stringify(S,null,2));let d=[1337,31337],F=qe(u.worldsFile)?JSON.parse(He(u.worldsFile,"utf-8")):{};F[w]={address:S.worldAddress,blockNumber:d.includes(w)?void 0:S.blockNumber},q(u.worldsFile,JSON.stringify(F,null,2)),console.log(v.bgGreen(v.whiteBright(`
28
+ Deployment result (written to ${u.worldsFile} and ${_}):
29
+ `)))}return console.log(S),S}export{re as a,ne as b,oe as c,at as d,Ie as e,me as f,Zt as g};
30
+ //# sourceMappingURL=chunk-LFIOIY67.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/render-ts/schemaTypesToRecsTypeStrings.ts","../src/render-ts/recsV1TableOptions.ts","../src/render-ts/renderRecsV1Tables.ts","../src/render-ts/tsgen.ts","../src/utils/deployHandler.ts","../src/utils/deploy.ts","../src/utils/getChainId.ts","../src/utils/getExistingContracts.ts"],"sourcesContent":["import { SchemaType } from \"@latticexyz/schema-type/deprecated\";\n\nexport const schemaTypesToRecsTypeStrings: Record<SchemaType, string> = {\n [SchemaType.UINT8]: \"RecsType.Number\",\n [SchemaType.UINT16]: \"RecsType.Number\",\n [SchemaType.UINT24]: \"RecsType.Number\",\n [SchemaType.UINT32]: \"RecsType.Number\",\n [SchemaType.UINT40]: \"RecsType.Number\",\n [SchemaType.UINT48]: \"RecsType.Number\",\n [SchemaType.UINT56]: \"RecsType.BigInt\",\n [SchemaType.UINT64]: \"RecsType.BigInt\",\n [SchemaType.UINT72]: \"RecsType.BigInt\",\n [SchemaType.UINT80]: \"RecsType.BigInt\",\n [SchemaType.UINT88]: \"RecsType.BigInt\",\n [SchemaType.UINT96]: \"RecsType.BigInt\",\n [SchemaType.UINT104]: \"RecsType.BigInt\",\n [SchemaType.UINT112]: \"RecsType.BigInt\",\n [SchemaType.UINT120]: \"RecsType.BigInt\",\n [SchemaType.UINT128]: \"RecsType.BigInt\",\n [SchemaType.UINT136]: \"RecsType.BigInt\",\n [SchemaType.UINT144]: \"RecsType.BigInt\",\n [SchemaType.UINT152]: \"RecsType.BigInt\",\n [SchemaType.UINT160]: \"RecsType.BigInt\",\n [SchemaType.UINT168]: \"RecsType.BigInt\",\n [SchemaType.UINT176]: \"RecsType.BigInt\",\n [SchemaType.UINT184]: \"RecsType.BigInt\",\n [SchemaType.UINT192]: \"RecsType.BigInt\",\n [SchemaType.UINT200]: \"RecsType.BigInt\",\n [SchemaType.UINT208]: \"RecsType.BigInt\",\n [SchemaType.UINT216]: \"RecsType.BigInt\",\n [SchemaType.UINT224]: \"RecsType.BigInt\",\n [SchemaType.UINT232]: \"RecsType.BigInt\",\n [SchemaType.UINT240]: \"RecsType.BigInt\",\n [SchemaType.UINT248]: \"RecsType.BigInt\",\n [SchemaType.UINT256]: \"RecsType.BigInt\",\n [SchemaType.INT8]: \"RecsType.Number\",\n [SchemaType.INT16]: \"RecsType.Number\",\n [SchemaType.INT24]: \"RecsType.Number\",\n [SchemaType.INT32]: \"RecsType.Number\",\n [SchemaType.INT40]: \"RecsType.Number\",\n [SchemaType.INT48]: \"RecsType.Number\",\n [SchemaType.INT56]: \"RecsType.BigInt\",\n [SchemaType.INT64]: \"RecsType.BigInt\",\n [SchemaType.INT72]: \"RecsType.BigInt\",\n [SchemaType.INT80]: \"RecsType.BigInt\",\n [SchemaType.INT88]: \"RecsType.BigInt\",\n [SchemaType.INT96]: \"RecsType.BigInt\",\n [SchemaType.INT104]: \"RecsType.BigInt\",\n [SchemaType.INT112]: \"RecsType.BigInt\",\n [SchemaType.INT120]: \"RecsType.BigInt\",\n [SchemaType.INT128]: \"RecsType.BigInt\",\n [SchemaType.INT136]: \"RecsType.BigInt\",\n [SchemaType.INT144]: \"RecsType.BigInt\",\n [SchemaType.INT152]: \"RecsType.BigInt\",\n [SchemaType.INT160]: \"RecsType.BigInt\",\n [SchemaType.INT168]: \"RecsType.BigInt\",\n [SchemaType.INT176]: \"RecsType.BigInt\",\n [SchemaType.INT184]: \"RecsType.BigInt\",\n [SchemaType.INT192]: \"RecsType.BigInt\",\n [SchemaType.INT200]: \"RecsType.BigInt\",\n [SchemaType.INT208]: \"RecsType.BigInt\",\n [SchemaType.INT216]: \"RecsType.BigInt\",\n [SchemaType.INT224]: \"RecsType.BigInt\",\n [SchemaType.INT232]: \"RecsType.BigInt\",\n [SchemaType.INT240]: \"RecsType.BigInt\",\n [SchemaType.INT248]: \"RecsType.BigInt\",\n [SchemaType.INT256]: \"RecsType.BigInt\",\n [SchemaType.BYTES1]: \"RecsType.String\",\n [SchemaType.BYTES2]: \"RecsType.String\",\n [SchemaType.BYTES3]: \"RecsType.String\",\n [SchemaType.BYTES4]: \"RecsType.String\",\n [SchemaType.BYTES5]: \"RecsType.String\",\n [SchemaType.BYTES6]: \"RecsType.String\",\n [SchemaType.BYTES7]: \"RecsType.String\",\n [SchemaType.BYTES8]: \"RecsType.String\",\n [SchemaType.BYTES9]: \"RecsType.String\",\n [SchemaType.BYTES10]: \"RecsType.String\",\n [SchemaType.BYTES11]: \"RecsType.String\",\n [SchemaType.BYTES12]: \"RecsType.String\",\n [SchemaType.BYTES13]: \"RecsType.String\",\n [SchemaType.BYTES14]: \"RecsType.String\",\n [SchemaType.BYTES15]: \"RecsType.String\",\n [SchemaType.BYTES16]: \"RecsType.String\",\n [SchemaType.BYTES17]: \"RecsType.String\",\n [SchemaType.BYTES18]: \"RecsType.String\",\n [SchemaType.BYTES19]: \"RecsType.String\",\n [SchemaType.BYTES20]: \"RecsType.String\",\n [SchemaType.BYTES21]: \"RecsType.String\",\n [SchemaType.BYTES22]: \"RecsType.String\",\n [SchemaType.BYTES23]: \"RecsType.String\",\n [SchemaType.BYTES24]: \"RecsType.String\",\n [SchemaType.BYTES25]: \"RecsType.String\",\n [SchemaType.BYTES26]: \"RecsType.String\",\n [SchemaType.BYTES27]: \"RecsType.String\",\n [SchemaType.BYTES28]: \"RecsType.String\",\n [SchemaType.BYTES29]: \"RecsType.String\",\n [SchemaType.BYTES30]: \"RecsType.String\",\n [SchemaType.BYTES31]: \"RecsType.String\",\n [SchemaType.BYTES32]: \"RecsType.String\",\n [SchemaType.BOOL]: \"RecsType.Boolean\",\n [SchemaType.ADDRESS]: \"RecsType.String\",\n [SchemaType.UINT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES1_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES2_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES3_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES4_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES5_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES6_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES7_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES8_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES9_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES10_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES11_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES12_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES13_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES14_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES15_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES16_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES17_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES18_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES19_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES20_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES21_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES22_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES23_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES24_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES25_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES26_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES27_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES28_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES29_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES30_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES31_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES32_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BOOL_ARRAY]: \"RecsType.T\", // no boolean array\n [SchemaType.ADDRESS_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES]: \"RecsType.String\",\n [SchemaType.STRING]: \"RecsType.String\",\n};\n","import { StoreConfig } from \"@latticexyz/store\";\nimport { resolveAbiOrUserType } from \"@latticexyz/store/codegen\";\nimport { schemaTypesToRecsTypeStrings } from \"./schemaTypesToRecsTypeStrings\";\nimport { RecsV1TableOptions } from \"./types\";\n\nexport function getRecsV1TableOptions(config: StoreConfig): RecsV1TableOptions {\n const tableOptions = [];\n for (const tableName of Object.keys(config.tables)) {\n const tableData = config.tables[tableName];\n\n const fields = Object.keys(tableData.schema).map((name) => {\n const abiOrUserType = tableData.schema[name];\n const { schemaType } = resolveAbiOrUserType(abiOrUserType, config);\n\n const recsTypeString = schemaTypesToRecsTypeStrings[schemaType];\n\n return {\n recsTypeString,\n name,\n };\n });\n\n // WARNING: skip tables without a static tableId\n if (tableData.tableIdArgument) continue;\n const staticResourceData = {\n namespace: config.namespace,\n name: tableData.name,\n };\n\n tableOptions.push({\n tableName,\n fields,\n staticResourceData,\n });\n }\n return {\n tables: tableOptions,\n };\n}\n","import { RecsV1TableOptions } from \"./types\";\n\nexport function renderRecsV1Tables(options: RecsV1TableOptions) {\n const { tables } = options;\n\n return `/* Autogenerated file. Do not edit manually. */\n\nimport { TableId } from \"@latticexyz/common\";\nimport { defineComponent, Type as RecsType, World } from \"@latticexyz/recs\";\n\nexport function defineContractComponents(world: World) {\n return {\n ${tables.map((table) => `${table.tableName}: ${renderDefineComponent(table)},`).join(\"\")}\n }\n}\n`;\n}\n\nfunction renderDefineComponent(table: RecsV1TableOptions[\"tables\"][number]) {\n const { namespace, name } = table.staticResourceData;\n return `\n (() => {\n const tableId = new TableId(\"${namespace}\", \"${name}\");\n return defineComponent(world, {\n ${table.fields.map(({ name, recsTypeString }) => `${name}: ${recsTypeString},`).join(\"\")}\n }, {\n metadata: { contractId: tableId.toHex(), tableId: tableId.toString() },\n });\n })()\n `;\n}\n","import path from \"path\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { formatAndWriteTypescript } from \"@latticexyz/common/codegen\";\nimport { getRecsV1TableOptions } from \"../render-ts/recsV1TableOptions\";\nimport { renderRecsV1Tables } from \"../render-ts/renderRecsV1Tables\";\n\nexport async function tsgen(config: StoreConfig, outDirectory: string) {\n const fullOutputPath = path.join(outDirectory, `contractComponents.ts`);\n const options = getRecsV1TableOptions(config);\n const output = renderRecsV1Tables(options);\n formatAndWriteTypescript(output, fullOutputPath, \"Generated ts definition files\");\n}\n","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\n // Manual nonce handling to allow for faster sending of transactions without waiting for previous transactions\n let nonce = await signer.getTransactionCount();\n console.log(\"Initial nonce\", nonce);\n\n // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions\n let maxPriorityFeePerGas: number;\n let maxFeePerGas: BigNumber;\n 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 })\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 }])\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 if (!feeData.lastBaseFeePerGas) throw new MUDError(\"Can not fetch lastBaseFeePerGas from RPC\");\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.\nIf 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 }\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,OAAS,cAAAA,MAAkB,qCAEpB,IAAMC,GAA2D,CACtE,CAACD,EAAW,KAAK,EAAG,kBACpB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,MAAM,EAAG,kBACrB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO,EAAG,kBACtB,CAACA,EAAW,OAAO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,IAAIM,EAAM,MAAM;AAAA;AAAA,CAAsB,EAAG,KAAK,UAAUO,EAAW,KAAM,CAAC,CAAC,EAEpG,IAAME,EAAa,QAAQ,IAAI,YAC/B,GAAI,CAACA,EACH,MAAM,IAAIC,GACR;AAAA;AAAA,kEAGF,EACF,IAAMC,EAAiB,MAAMC,GAAOL,EAAWH,EAAuB,CAAE,GAAGZ,EAAM,IAAAM,EAAK,WAAAW,CAAW,CAAC,EAElG,GAAIjB,EAAK,eAAgB,CAEvB,IAAMqB,EAAU,MAAMC,GAAWhB,CAAG,EAC9BiB,EAAYC,EAAK,KAAKT,EAAU,iBAAkBM,EAAQ,SAAS,CAAC,EAC1EI,GAAUF,EAAW,CAAE,UAAW,EAAK,CAAC,EACxCG,EAAcF,EAAK,KAAKD,EAAW,aAAa,EAAG,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":["SchemaType","schemaTypesToRecsTypeStrings","resolveAbiOrUserType","getRecsV1TableOptions","config","tableOptions","tableName","tableData","fields","name","abiOrUserType","schemaType","resolveAbiOrUserType","schemaTypesToRecsTypeStrings","staticResourceData","renderRecsV1Tables","options","tables","table","renderDefineComponent","namespace","name","recsTypeString","path","formatAndWriteTypescript","tsgen","config","outDirectory","fullOutputPath","path","options","getRecsV1TableOptions","output","renderRecsV1Tables","formatAndWriteTypescript","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","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","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 ADDED
@@ -0,0 +1,2 @@
1
+ import{a as o,b as r,c as e,d as f,g as m}from"./chunk-LFIOIY67.js";export{m as deployHandler,r as getRecsV1TableOptions,e as renderRecsV1Tables,o as schemaTypesToRecsTypeStrings,f as tsgen};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/mud.js ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import{d as O,e as I,f as S,g as w}from"./chunk-LFIOIY67.js";import Fo from"yargs";import{hideBin as To}from"yargs/helpers";import{rmSync as pe}from"fs";import{homedir as fe}from"os";import me from"path";import{execa as ge}from"execa";var ue={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=fe();pe(me.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 r=ge("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
3
+ gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},W=ue;import{FaucetServiceDefinition as ye}from"@latticexyz/services/faucet";import{createChannel as he,createClient as be}from"nice-grpc-web";import j from"chalk";import{NodeHttpTransport as we}from"@improbable-eng/grpc-web-node-http-transport";function ve(e){return be(ye,he(e,we()))}var De={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 r=ve(o);e&&(console.log(j.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(j.yellow("Success"))),process.exit(0)}},A=De;import{readFileSync as Ce,writeFileSync as xe}from"fs";import{execa as ke}from"execa";import f from"chalk";import{table as Me,getBorderCharacters as Oe}from"table";import Se from"strip-ansi";var Re={command:"gas-report",describe:"Create a gas report",builder(e){return e.options({save:{type:"string",desc:"Save the gas report to a file"},compare:{type:"string",desc:"Compare to an existing gas report"}})},async handler({save:e,compare:o}){let t;try{t=await Ue()}catch(r){console.error(r),setTimeout(()=>process.exit());return}if(o)try{let r=JSON.parse(Ce(o,"utf8"));t=t.map(i=>{let a=r.find(c=>c.file===i.file&&c.name===i.name);return{...i,prevGasUsed:a?.gasUsed}})}catch{console.log(f.red(`Gas report to compare not found: ${o}`)),o=void 0}Pe(t,o),e&&Ee(t,e),process.exit(0)}},$=Re;async function Ue(){console.log("Running gas report");let e=[],o;try{o=(await ke("forge",["test","-vvv"],{stdio:["inherit","pipe","inherit"],env:{GAS_REPORTER_ENABLED:"true"}})).stdout}catch(s){throw console.log(s.stdout??s),console.log(f.red(`
4
+ -----------
5
+ Error while running the gas report (see above)`)),s}let t=o.split(`
6
+ `).map(Se),r=/^\s*GAS REPORT: (\d+) (.*)$/,i=/^\[(?:PASS|FAIL).*\] (\w+)\(\)/,a=/^Running \d+ tests? for (.*):(.*)$/;function c(s,p=t.length-1){for(let d=p;d>=0;d--){let g=t[d];if(s.test(g))return d}return-1}for(let s=0;s<t.length;s++){let p=t[s].match(r);if(!p)continue;let d=parseInt(p[1]),g=p[2],m=c(i,s);if(m===-1)throw new Error("Could not find nearest test function, did `forge test` output change?");let y=c(a,m);if(y===-1)throw new Error("Could not find nearest test filename, did `forge test` output change?");let l=t[m].match(i);if(!l)throw new Error("Could not parse test function name, did `forge test` output change?");let n=t[y].match(a);if(!n)throw new Error("Could not parse test filename, did `forge test` output change?");let u=l[1],h=n[1];e.push({file:h,test:u,name:g,gasUsed:d})}return e.sort((s,p)=>s.file.localeCompare(p.file)),e}function Pe(e,o){o&&console.log(f.bold(`Gas report compared to ${o}`));let t=[f.bold("File"),f.bold("Test"),f.bold("Name"),f.bold("Gas used"),...o?[f.bold("Prev gas used"),f.bold("Difference")]:[]],r=e.map(a=>{let c=a.prevGasUsed?a.gasUsed-a.prevGasUsed:0,s=c>0?f.red(`+${c}`):c<0?f.green(`${c}`):c,p=o?[a.prevGasUsed??"n/a",s]:[],d=c>0?f.red(a.gasUsed):c<0?f.green(a.gasUsed):a.gasUsed;return[a.file,a.test,a.name,d,...p]}),i=[t,...r];console.log(Me(i,{border:Oe("norc")}))}function Ee(e,o){console.log(f.bold(`Saving gas report to ${o}`)),xe(o,`${JSON.stringify(e,null,2)}
7
+ `)}var Ie={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)}},G=Ie;import We from"path";import{loadConfig as je}from"@latticexyz/config/node";import{tablegen as Ae}from"@latticexyz/store/codegen";import{getSrcDirectory as $e}from"@latticexyz/common/foundry";var Ge={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 je(e),t=await $e();await Ae(o,We.join(t,o.codegenDirectory)),process.exit(0)}},F=Ge;import{loadConfig as Fe}from"@latticexyz/config/node";var Te={command:"tsgen",describe:"Autogenerate MUD typescript definitions based on the config file",builder(e){return e.options({configPath:{type:"string",demandOption:!0,desc:"Path to the config file"},out:{type:"string",demandOption:!0,desc:"Directory to output MUD typescript definition files"}})},async handler(e){let{configPath:o,out:t}=e,r=await Fe(o);await O(r,t),process.exit(0)}},T=Te;import C from"chalk";import{ZodError as Ne}from"zod";import{fromZodError as ze,ValidationError as Be}from"zod-validation-error";import{NotInsideProjectError as Je}from"@latticexyz/config";import{MUDError as Ve}from"@latticexyz/common/errors";function b(e){if(e instanceof Be)console.log(C.redBright(e.message));else if(e instanceof Ne){let o=ze(e,{prefixSeparator:`
8
+ - `,issueSeparator:`
9
+ - `});console.log(C.redBright(o.message))}else e instanceof Je?(console.log(C.red(e.message)),console.log(""),console.log(C.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Ve?console.log(C.red(e)):console.log(e)}import He from"chalk";function N(){console.log(He.yellow(`
10
+ .------..------..------.
11
+ |M.--. ||U.--. ||D.--. |
12
+ | (\\/) || (\\/) || :/\\: |
13
+ | :\\/: || :\\/: || (__) |
14
+ | '--'M|| '--'U|| '--'D|
15
+ '------''------''------'
16
+ `))}import{getOutDirectory as Le}from"@latticexyz/common/foundry";import _e from"path";import{runTypeChain as qe}from"typechain";async function z(){let e=process.cwd(),o=await Le(),t=_e.join(process.cwd(),o,"IWorld.sol/IWorld.json");await qe({cwd:e,filesToProcess:[t],allFiles:[t],target:"ethers-v5"}),console.log("Typechain generated IWorld interface")}var P={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"}},Ze={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(P)},async handler(e){try{await w(e)}catch(o){b(o),process.exit(1)}process.exit(0)}},B=Ze;import{loadConfig as Ke}from"@latticexyz/config/node";import{worldgen as Xe}from"@latticexyz/world/node";import{getSrcDirectory as Ye}from"@latticexyz/common/foundry";import J from"path";import{rmSync as Qe}from"fs";var eo={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 E(e),process.exit(0)}};async function E(e){let o=e.srcDir??await Ye(),t=S(o),r=e.config??await Ke(e.configPath),i=J.join(o,r.codegenDirectory);e.clean&&Qe(J.join(i,r.worldgenDirectory),{recursive:!0,force:!0}),await Xe(r,t,i)}var V=eo;import D from"chalk";import{existsSync as to,readFileSync as ro,rmSync as no,writeFileSync as L}from"fs";import v from"path";import{MUDError as k}from"@latticexyz/common/errors";var H={name:"@latticexyz/cli",version:"0.0.0-main-20230704121617",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","build:js":"tsup && chmod +x ./dist/mud.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch","generate-test-tables":"tsx ./scripts/generate-test-tables.ts",lint:"eslint . --ext .ts",test:"tsc --noEmit && pnpm run generate-test-tables && forge test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/solecs":"workspace:*","@latticexyz/std-contracts":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/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","strip-ansi":"^7.1.0",table:"^6.8.1","throttle-debounce":"^5.0.0",typechain:"^8.1.1",typescript:"^4.9.5",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#c9ce3f25bde29fc5eb9901842bf02850dfd2d084","forge-std":"https://github.com/foundry-rs/forge-std.git#b4f121555729b3afb3c5ffccb62ff4b6e2818fd3",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};var R=".mudbackup",x="@latticexyz",so={command:"set-version",describe:"Install a custom MUD version and optionally backup the previously installed version",builder(e){return e.options({backup:{type:"boolean",description:`Back up the current MUD versions to "${R}"`},force:{type:"boolean",description:`Backup fails if a "${R}" file is found, unless --force is provided`},restore:{type:"boolean",description:`Restore the previous MUD versions from "${R}"`},mudVersion:{alias:"v",type:"string",description:"The MUD version to install"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{if(!e.mudVersion&&!e.link&&!e.restore)throw new k("`--mudVersion` or `--link` is required unless --restore is provided.");if(e.link&&e.mudVersion)throw new k("Options `--link` and `--mudVersion` are mutually exclusive");e.mudVersion=e.mudVersion==="canary"?await io(H.name):e.mudVersion;let o="./package.json",{workspaces:t}=_(o,e);if(t)for(let r of t){let i=v.join(r,"/package.json");_(i,e)}}catch(o){b(o)}finally{process.exit(0)}}};function _(e,o){let{restore:t,force:r,link:i}=o,{backup:a,mudVersion:c}=o,s=v.join(v.dirname(e),R),p=to(s);if(i&&!p&&(a=!0),a&&!r&&p)throw new k(`A backup file already exists at ${s}.
17
+ Use --force to overwrite it or --restore to restore it.`);let d=q(e),g=t?q(s):void 0,m={};for(let n in d.dependencies)n.startsWith(x)&&(m[n]=d.dependencies[n]);let y={};for(let n in d.devDependencies)n.startsWith(x)&&(y[n]=d.devDependencies[n]);a&&(L(s,JSON.stringify({dependencies:m,devDependencies:y},null,2)),console.log(D.green(`Backed up MUD dependencies from ${e} to ${s}`)));for(let n in d.dependencies)n.startsWith(x)&&(d.dependencies[n]=l(n,"dependencies"));for(let n in d.devDependencies)n.startsWith(x)&&(d.devDependencies[n]=l(n,"devDependencies"));return L(e,JSON.stringify(d,null,2)+`
18
+ `),console.log(`Updating ${e}`),Z(m,d.dependencies),Z(y,d.devDependencies),t&&!a&&(no(s),console.log(D.green(`Cleaned up ${s}`))),d;function l(n,u){return t&&g?g[u][n]:(i&&(c=ao(e,i,n)),c||d[u][n])}}function q(e){try{let o=ro(e,"utf8");return JSON.parse(o)}catch{throw new k("Could not read JSON at "+e)}}async function io(e){try{console.log(D.blue("fetching MUD canary version..."));let t=(await(await fetch(`https://registry.npmjs.org/${e}`)).json())["dist-tags"].canary;return console.log(D.green("MUD canary version:",t)),t}catch{throw new k(`Could not fetch canary version of ${e}`)}}function Z(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${D.red(e[t])} -> ${D.green(o[t])}`)}function ao(e,o,t){let r=t.replace(x,""),i=v.relative(v.dirname(e),process.cwd());return"link:"+v.join(i,o,"packages",r)}var K=so;import{anvil as co,forge as lo,getRpcUrl as po}from"@latticexyz/common/foundry";import fo from"chalk";import{rmSync as mo,writeFileSync as go}from"fs";var X=".mudtest",uo={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)];co(i)}let o=e.worldAddress?await po(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await w({...e,saveDeployment:!1,rpc:o})).worldAddress;console.log(fo.blue("World address",t)),go(X,t);let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{let i=await lo(["test","--fork-url",o,...r],{profile:e.profile});console.log(i)}catch(i){console.error(i)}mo(X),process.exit(0)}},Y=uo;import{existsSync as yo,readFileSync as ho}from"fs";import{ethers as Q}from"ethers";import{loadConfig as bo}from"@latticexyz/config/node";import{MUDError as ee}from"@latticexyz/common/errors";import{cast as wo,getRpcUrl as vo,getSrcDirectory as Do}from"@latticexyz/common/foundry";import{TableId as oe}from"@latticexyz/common";import{resolveWorldConfig as Co}from"@latticexyz/world";import xo from"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json"assert{type:"json"};var ko=new oe("","Systems"),Mo={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 Do(o),e.rpc??=await vo(o);let{tx:t,configPath:r,srcDir:i,rpc:a}=e,c=S(i),s=await bo(r),p=Co(s,c.map(({basename:h})=>h)),d=e.worldAddress??await Oo(s.worldsFile,a),g=new Q.providers.StaticJsonRpcProvider(a),m=new Q.Contract(d,xo.abi,g),y=s.namespace,l=Object.values(p.systems).map(({name:h})=>h),n=[];for(let h of l){let U=new oe(y,h),le=await m.getField(ko.toHex(),[U.toHex()],0);n.push({name:h,address:le})}let u=await wo(["run","--label",`${d}:World`,...n.map(({name:h,address:U})=>["--label",`${U}:${h}`]).flat(),`${t}`]);console.log(u),process.exit(0)}},te=Mo;async function Oo(e,o){if(yo(e)){let t=await I(o),r=JSON.parse(ho(e,"utf-8"));if(!r[t])throw new ee(`chainId ${t} is missing in worldsFile "${e}"`);return r[t].address}else throw new ee("worldAddress is not specified and worldsFile is missing")}import{anvil as So,forge as re,getRpcUrl as Ro,getScriptDirectory as Uo,getSrcDirectory as Po}from"@latticexyz/common/foundry";import M from"chalk";import Eo from"chokidar";import{loadConfig as ne,resolveConfigPath as Io}from"@latticexyz/config/node";import{tablegen as Wo}from"@latticexyz/store/codegen";import se from"path";import{debounce as jo}from"throttle-debounce";import{homedir as Ao}from"os";import{rmSync as $o}from"fs";var Go={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 re(["clean"]);let o=e.rpc??await Ro(),t=e.configPath??await Io(e.configPath),r=await Po(),i=await Uo(),a=await ne(t);if(await g(a),await m(a),!e.rpc){console.log(M.gray("Cleaning devnode cache"));let l=Ao();$o(se.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),So(["--block-time","1","--block-base-fee-per-gas","0"])}let c={config:!1,contracts:!1},s={current:!1};Eo.watch([t,r]).on("all",async(l,n)=>{if(n.includes(t)&&(c.config=!0,c.contracts=!0),n.includes(r)||n.includes(i)){if(n.includes(a.codegenDirectory))return;c.contracts=!0}d()});let d=jo(100,async()=>{if(s.current)return;s.current=!0;let{config:l,contracts:n}=c;c.config=!1,c.contracts=!1;try{let u=await ne(t);l&&await g(u),n&&await m(u),await y()}catch(u){console.error(M.red(`MUD dev-contracts watcher failed to deploy config or contracts changes
19
+ `)),b(u)}s.current=!1,(c.config||c.contracts)&&(console.log("Detected change while handling the previous change"),d()),N(),console.log("MUD watching for changes...")});async function g(l){console.log(M.blue("mud.config.ts changed - regenerating tables and recs types"));let n=se.join(r,l.codegenDirectory);await Wo(l,n),await O(l,e.tsgenOutput)}async function m(l){console.log(M.blue("contracts changed - regenerating interfaces and contract types")),await E({config:l,clean:!0,srcDir:r}),await re(["build"]),await z()}async function y(){console.log(M.blue("redeploying World")),await w({configPath:t,skipBuild:!0,priorityFeeMultiplier:1,disableTxWait:!0,pollInterval:1e3,saveDeployment:!0,srcDir:r,rpc:o})}}},ie=Go;var ae=[B,W,A,$,G,F,T,V,K,Y,te,ie];import*as de from"dotenv";import ce from"chalk";de.config();Fo(To(process.argv)).scriptName("mud").command(ae).strict().fail((e,o)=>{console.error(ce.red(e)),e.includes("Missing required argument")&&console.log(ce.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),b(o),console.log(""),process.exit(1)}).alias({h:"help"}).argv;
20
+ //# sourceMappingURL=mud.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mud.ts","../src/commands/devnode.ts","../src/commands/faucet.ts","../src/commands/gas-report.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/commands/tsgen.ts","../src/utils/errors.ts","../src/utils/printMUD.ts","../src/utils/worldtypes.ts","../src/commands/deploy.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../package.json","../src/commands/test.ts","../src/commands/trace.ts","../src/commands/dev-contracts.ts","../src/commands/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { commands } from \"./commands\";\nimport { logError } from \"./utils/errors\";\n\n// Load .env file into process.env\nimport * as dotenv from \"dotenv\";\nimport chalk from \"chalk\";\ndotenv.config();\n\nyargs(hideBin(process.argv))\n // Explicit name to display in help (by default it's the entry file, which may not be \"mud\" for e.g. ts-node)\n .scriptName(\"mud\")\n // Use the commands directory to scaffold\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy\n .command(commands as any)\n // Enable strict mode.\n .strict()\n // Custom error handler\n .fail((msg, err) => {\n console.error(chalk.red(msg));\n if (msg.includes(\"Missing required argument\")) {\n console.log(\n chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)\n );\n }\n console.log(\"\");\n logError(err);\n console.log(\"\");\n\n process.exit(1);\n })\n // Useful aliases.\n .alias({ h: \"help\" }).argv;\n","import { rmSync } from \"fs\";\nimport { homedir } from \"os\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { execa } from \"execa\";\n\ntype Options = {\n blocktime: number;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"devnode\",\n\n describe: \"Start a local Ethereum node for development\",\n\n builder(yargs) {\n return yargs.options({\n blocktime: { type: \"number\", default: 1, decs: \"Interval in which new blocks are produced\" },\n });\n },\n\n async handler({ blocktime }) {\n console.log(\"Clearing devnode history\");\n const userHomeDir = homedir();\n rmSync(path.join(userHomeDir, \".foundry\", \"anvil\", \"tmp\"), { recursive: true, force: true });\n\n const anvilArgs = [\"-b\", String(blocktime), \"--block-base-fee-per-gas\", \"0\"];\n console.log(`Running: anvil ${anvilArgs.join(\" \")}`);\n const child = execa(\"anvil\", anvilArgs, {\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n\n process.on(\"SIGINT\", () => {\n console.log(\"\\ngracefully shutting down from SIGINT (Crtl-C)\");\n child.kill();\n process.exit();\n });\n await child;\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { FaucetServiceDefinition } from \"@latticexyz/services/faucet\";\nimport { createChannel, createClient } from \"nice-grpc-web\";\nimport chalk from \"chalk\";\nimport { NodeHttpTransport } from \"@improbable-eng/grpc-web-node-http-transport\";\n\ntype Options = {\n dripDev?: boolean;\n faucetUrl: string;\n address: string;\n};\n\n/**\n * Create a FaucetServiceClient\n * @param url FaucetService URL\n * @returns FaucetServiceClient\n */\nfunction createFaucetService(url: string) {\n return createClient(FaucetServiceDefinition, createChannel(url, NodeHttpTransport()));\n}\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"faucet\",\n\n describe: \"Interact with a MUD faucet\",\n\n builder(yargs) {\n return yargs.options({\n dripDev: {\n type: \"boolean\",\n desc: \"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)\",\n default: true,\n },\n faucetUrl: {\n type: \"string\",\n desc: \"URL of the MUD faucet\",\n default: \"https://faucet.testnet-mud-services.linfra.xyz\",\n },\n address: {\n type: \"string\",\n desc: \"Ethereum address to fund\",\n required: true,\n },\n });\n },\n\n async handler({ dripDev, faucetUrl, address }) {\n const faucet = createFaucetService(faucetUrl);\n\n if (dripDev) {\n console.log(chalk.yellow(\"Dripping to\", address));\n await faucet.dripDev({ address });\n console.log(chalk.yellow(\"Success\"));\n }\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { readFileSync, writeFileSync } from \"fs\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { table, getBorderCharacters } from \"table\";\nimport stripAnsi from \"strip-ansi\";\n\n/**\n * Print the gas report to the console, save it to a file and compare it to a previous gas report if provided.\n *\n * Requires foundry to be installed. Inherit from GasReporter and use startGasReport/endGasReport to measure gas used.\n *\n * ```solidity\n * contract MyContractTest is Test, GasReporter {\n * function testBuffer() public pure {\n * startGasReport(\"allocate a buffer\");\n * Buffer buffer = Buffer_.allocate(32);\n * endGasReport();\n *\n * bytes32 value = keccak256(\"some data\");\n *\n * startGasReport(\"append 32 bytes to a buffer\");\n * buffer.append(value);\n * endGasReport();\n * }\n * }\n * ```\n */\n\ntype Options = {\n path: string[];\n save?: string;\n compare?: string;\n};\n\ntype GasReportEntry = {\n file: string;\n test: string;\n name: string;\n gasUsed: number;\n prevGasUsed?: number;\n};\n\ntype GasReport = GasReportEntry[];\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"gas-report\",\n\n describe: \"Create a gas report\",\n\n builder(yargs) {\n return yargs.options({\n save: { type: \"string\", desc: \"Save the gas report to a file\" },\n compare: { type: \"string\", desc: \"Compare to an existing gas report\" },\n });\n },\n\n async handler({ save, compare }) {\n let gasReport: GasReport;\n try {\n gasReport = await runGasReport();\n } catch (error) {\n console.error(error);\n setTimeout(() => process.exit());\n return;\n }\n\n // If this gas report should be compared to an existing one, load the existing one\n if (compare) {\n try {\n const compareGasReport: GasReport = JSON.parse(readFileSync(compare, \"utf8\"));\n // Merge the previous gas report with the new one\n gasReport = gasReport.map((entry) => {\n const prevEntry = compareGasReport.find((e) => e.file === entry.file && e.name === entry.name);\n return { ...entry, prevGasUsed: prevEntry?.gasUsed };\n });\n } catch {\n console.log(chalk.red(`Gas report to compare not found: ${compare}`));\n compare = undefined;\n }\n }\n\n // Print gas report\n printGasReport(gasReport, compare);\n\n // Save gas report to file if requested\n if (save) saveGasReport(gasReport, save);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n\nasync function runGasReport(): Promise<GasReport> {\n console.log(\"Running gas report\");\n const gasReport: GasReport = [];\n\n // Extract the logs from the child process\n let stdout: string;\n try {\n // Run the generated file using forge\n const child = execa(\"forge\", [\"test\", \"-vvv\"], {\n stdio: [\"inherit\", \"pipe\", \"inherit\"],\n env: { GAS_REPORTER_ENABLED: \"true\" },\n });\n stdout = (await child).stdout;\n } catch (error: any) {\n console.log(error.stdout ?? error);\n console.log(chalk.red(\"\\n-----------\\nError while running the gas report (see above)\"));\n throw error;\n }\n\n // Extract the gas reports from the logs\n const lines = stdout.split(\"\\n\").map(stripAnsi);\n const gasReportPattern = /^\\s*GAS REPORT: (\\d+) (.*)$/;\n const testFunctionPattern = /^\\[(?:PASS|FAIL).*\\] (\\w+)\\(\\)/;\n const testFilePattern = /^Running \\d+ tests? for (.*):(.*)$/;\n\n function nearestLine(pattern: RegExp, startIndex: number = lines.length - 1): number {\n for (let i = startIndex; i >= 0; i--) {\n const line = lines[i];\n if (pattern.test(line)) {\n return i;\n }\n }\n return -1;\n }\n\n for (let i = 0; i < lines.length; i++) {\n const matches = lines[i].match(gasReportPattern);\n if (!matches) continue;\n\n const gasUsed = parseInt(matches[1]);\n const name = matches[2];\n\n const testFunctionLineIndex = nearestLine(testFunctionPattern, i);\n if (testFunctionLineIndex === -1) {\n throw new Error(\"Could not find nearest test function, did `forge test` output change?\");\n }\n const testFileLineIndex = nearestLine(testFilePattern, testFunctionLineIndex);\n if (testFileLineIndex === -1) {\n throw new Error(\"Could not find nearest test filename, did `forge test` output change?\");\n }\n\n const functionMatches = lines[testFunctionLineIndex].match(testFunctionPattern);\n if (!functionMatches) {\n throw new Error(\"Could not parse test function name, did `forge test` output change?\");\n }\n const fileMatches = lines[testFileLineIndex].match(testFilePattern);\n if (!fileMatches) {\n throw new Error(\"Could not parse test filename, did `forge test` output change?\");\n }\n\n const test = functionMatches[1];\n const file = fileMatches[1];\n\n gasReport.push({ file, test, name, gasUsed });\n }\n\n gasReport.sort((a, b) => a.file.localeCompare(b.file));\n\n return gasReport;\n}\n\nfunction printGasReport(gasReport: GasReport, compare?: string) {\n if (compare) console.log(chalk.bold(`Gas report compared to ${compare}`));\n\n const headers = [\n chalk.bold(\"File\"),\n chalk.bold(\"Test\"),\n chalk.bold(\"Name\"),\n chalk.bold(\"Gas used\"),\n ...(compare ? [chalk.bold(\"Prev gas used\"), chalk.bold(\"Difference\")] : []),\n ];\n\n const values = gasReport.map((entry) => {\n const diff = entry.prevGasUsed ? entry.gasUsed - entry.prevGasUsed : 0;\n const diffEntry = diff > 0 ? chalk.red(`+${diff}`) : diff < 0 ? chalk.green(`${diff}`) : diff;\n const compareColumns = compare ? [entry.prevGasUsed ?? \"n/a\", diffEntry] : [];\n const gasUsedEntry = diff > 0 ? chalk.red(entry.gasUsed) : diff < 0 ? chalk.green(entry.gasUsed) : entry.gasUsed;\n return [entry.file, entry.test, entry.name, gasUsedEntry, ...compareColumns];\n });\n\n const rows = [headers, ...values];\n\n console.log(table(rows, { border: getBorderCharacters(\"norc\") }));\n}\n\nfunction saveGasReport(gasReport: GasReport, path: string) {\n console.log(chalk.bold(`Saving gas report to ${path}`));\n writeFileSync(path, `${JSON.stringify(gasReport, null, 2)}\\n`);\n}\n","import type { CommandModule } from \"yargs\";\n\ntype Options = {\n name: string;\n upper: boolean | undefined;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"hello <name>\",\n\n describe: \"Greet <name> with Hello\",\n\n builder(yargs) {\n return yargs\n .options({\n upper: { type: \"boolean\" },\n })\n .positional(\"name\", { type: \"string\", demandOption: true });\n },\n\n handler({ name }) {\n const greeting = `Gm, ${name}!`;\n console.log(greeting);\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { tablegen } from \"@latticexyz/store/codegen\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\n\ntype Options = {\n configPath?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"tablegen\",\n\n describe: \"Autogenerate MUD Store table libraries based on the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n });\n },\n\n async handler({ configPath }) {\n const config = (await loadConfig(configPath)) as StoreConfig;\n const srcDir = await getSrcDirectory();\n\n await tablegen(config, path.join(srcDir, config.codegenDirectory));\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { tsgen } from \"../render-ts/tsgen\";\n\ntype Options = {\n configPath: string;\n out: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"tsgen\",\n\n describe: \"Autogenerate MUD typescript definitions based on the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", demandOption: true, desc: \"Path to the config file\" },\n out: { type: \"string\", demandOption: true, desc: \"Directory to output MUD typescript definition files\" },\n });\n },\n\n async handler(args) {\n const { configPath, out } = args;\n\n const config = (await loadConfig(configPath)) as StoreConfig;\n\n await tsgen(config, out);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n","import chalk from \"chalk\";\n\nexport function printMUD() {\n console.log(\n chalk.yellow(`\n.------..------..------.\n|M.--. ||U.--. ||D.--. |\n| (\\\\/) || (\\\\/) || :/\\\\: |\n| :\\\\/: || :\\\\/: || (__) |\n| '--'M|| '--'U|| '--'D|\n'------''------''------'\n`)\n );\n}\n","import { getOutDirectory } from \"@latticexyz/common/foundry\";\nimport path from \"path\";\nimport { runTypeChain } from \"typechain\";\n\n/**\n * Generate IWorld typescript bindings\n */\nexport async function worldtypes() {\n const cwd = process.cwd();\n const forgeOurDir = await getOutDirectory();\n const IWorldPath = path.join(process.cwd(), forgeOurDir, \"IWorld.sol/IWorld.json\");\n\n await runTypeChain({\n cwd,\n filesToProcess: [IWorldPath],\n allFiles: [IWorldPath],\n target: \"ethers-v5\",\n });\n\n console.log(\"Typechain generated IWorld interface\");\n}\n","import type { CommandModule, Options } from \"yargs\";\nimport { logError } from \"../utils/errors\";\nimport { deployHandler, DeployOptions } from \"../utils\";\n\nexport const yDeployOptions = {\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n clean: { type: \"boolean\", desc: \"Remove the build forge artifacts and cache directories before building\" },\n printConfig: { type: \"boolean\", desc: \"Print the resolved config\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n debug: { type: \"boolean\", desc: \"Print debug logs, like full error messages\" },\n priorityFeeMultiplier: {\n type: \"number\",\n desc: \"Multiply the estimated priority fee by the provided factor\",\n default: 1,\n },\n saveDeployment: { type: \"boolean\", desc: \"Save the deployment info to a file\", default: true },\n rpc: { type: \"string\", desc: \"The RPC URL to use. Defaults to the RPC url from the local foundry.toml\" },\n worldAddress: { type: \"string\", desc: \"Deploy to an existing World at the given address\" },\n srcDir: { type: \"string\", desc: \"Source directory. Defaults to foundry src directory.\" },\n disableTxWait: { type: \"boolean\", desc: \"Disable waiting for transactions to be confirmed.\", default: false },\n pollInterval: {\n type: \"number\",\n desc: \"Interval in miliseconds to use to poll for transaction receipts / block inclusion\",\n default: 1000,\n },\n skipBuild: { type: \"boolean\", desc: \"Skip rebuilding the contracts before deploying\" },\n} satisfies Record<keyof DeployOptions, Options>;\n\nconst commandModule: CommandModule<DeployOptions, DeployOptions> = {\n command: \"deploy\",\n\n describe: \"Deploy MUD contracts\",\n\n builder(yargs) {\n return yargs.options(yDeployOptions);\n },\n\n async handler(args) {\n try {\n await deployHandler(args);\n } catch (error: any) {\n logError(error);\n process.exit(1);\n }\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { worldgen } from \"@latticexyz/world/node\";\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport path from \"path\";\nimport { rmSync } from \"fs\";\nimport { getExistingContracts } from \"../utils\";\n\ntype Options = {\n configPath?: string;\n clean?: boolean;\n srcDir?: string;\n config?: StoreConfig & WorldConfig;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"worldgen\",\n\n describe: \"Autogenerate interfaces for Systems and World based on existing contracts and the config file\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n clean: {\n type: \"boolean\",\n desc: \"Clear the worldgen directory before generating new interfaces (defaults to true)\",\n default: true,\n },\n });\n },\n\n async handler(args) {\n await worldgenHandler(args);\n process.exit(0);\n },\n};\n\nexport async function worldgenHandler(args: Options) {\n const srcDir = args.srcDir ?? (await getSrcDirectory());\n\n const existingContracts = getExistingContracts(srcDir);\n\n // Load the config\n const mudConfig = args.config ?? ((await loadConfig(args.configPath)) as StoreConfig & WorldConfig);\n\n const outputBaseDirectory = path.join(srcDir, mudConfig.codegenDirectory);\n\n // clear the worldgen directory\n if (args.clean) rmSync(path.join(outputBaseDirectory, mudConfig.worldgenDirectory), { recursive: true, force: true });\n\n // generate new interfaces\n await worldgen(mudConfig, existingContracts, outputBaseDirectory);\n}\n\nexport default commandModule;\n","import chalk from \"chalk\";\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { logError } from \"../utils/errors\";\nimport localPackageJson from \"../../package.json\" assert { type: \"json\" };\n\ntype Options = {\n backup?: boolean;\n force?: boolean;\n restore?: boolean;\n mudVersion?: string;\n link?: string;\n};\n\nconst BACKUP_FILE = \".mudbackup\";\nconst MUD_PREFIX = \"@latticexyz\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"set-version\",\n\n describe: \"Install a custom MUD version and optionally backup the previously installed version\",\n\n builder(yargs) {\n return yargs.options({\n backup: { type: \"boolean\", description: `Back up the current MUD versions to \"${BACKUP_FILE}\"` },\n force: {\n type: \"boolean\",\n description: `Backup fails if a \"${BACKUP_FILE}\" file is found, unless --force is provided`,\n },\n restore: { type: \"boolean\", description: `Restore the previous MUD versions from \"${BACKUP_FILE}\"` },\n mudVersion: { alias: \"v\", type: \"string\", description: \"The MUD version to install\" },\n link: { alias: \"l\", type: \"string\", description: \"Relative path to the local MUD root directory to link\" },\n });\n },\n\n async handler(options) {\n try {\n if (!options.mudVersion && !options.link && !options.restore) {\n throw new MUDError(\"`--mudVersion` or `--link` is required unless --restore is provided.\");\n }\n\n // `link` and `mudVersion` are mutually exclusive\n if (options.link && options.mudVersion) {\n throw new MUDError(\"Options `--link` and `--mudVersion` are mutually exclusive\");\n }\n\n // Resolve the `canary` version number if needed\n options.mudVersion =\n options.mudVersion === \"canary\" ? await getCanaryVersion(localPackageJson.name) : options.mudVersion;\n\n // Read the current package.json\n const rootPath = \"./package.json\";\n const { workspaces } = updatePackageJson(rootPath, options);\n\n // Load the package.json of each workspace\n if (workspaces) {\n for (const workspace of workspaces) {\n const filePath = path.join(workspace, \"/package.json\");\n updatePackageJson(filePath, options);\n }\n }\n } catch (e) {\n logError(e);\n } finally {\n process.exit(0);\n }\n },\n};\n\nfunction updatePackageJson(filePath: string, options: Options): { workspaces?: string[] } {\n const { restore, force, link } = options;\n let { backup, mudVersion } = options;\n\n const backupFilePath = path.join(path.dirname(filePath), BACKUP_FILE);\n const backupFileExists = existsSync(backupFilePath);\n\n // Create a backup file for previous MUD versions by default if linking to local MUD\n if (link && !backupFileExists) backup = true;\n\n // If `backup` is true and force not set, check if a backup file already exists and throw an error if it does\n if (backup && !force && backupFileExists) {\n throw new MUDError(\n `A backup file already exists at ${backupFilePath}.\\nUse --force to overwrite it or --restore to restore it.`\n );\n }\n\n const packageJson = readPackageJson(filePath);\n\n // Load .mudbackup if `restore` is true\n const backupJson = restore ? readPackageJson(backupFilePath) : undefined;\n\n // Find all MUD dependencies\n const mudDependencies: Record<string, string> = {};\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDependencies[key] = packageJson.dependencies[key];\n }\n }\n\n // Find all MUD devDependencies\n const mudDevDependencies: Record<string, string> = {};\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n mudDevDependencies[key] = packageJson.devDependencies[key];\n }\n }\n\n // Back up the current dependencies if `backup` is true\n if (backup) {\n writeFileSync(\n backupFilePath,\n JSON.stringify({ dependencies: mudDependencies, devDependencies: mudDevDependencies }, null, 2)\n );\n console.log(chalk.green(`Backed up MUD dependencies from ${filePath} to ${backupFilePath}`));\n }\n\n // Update the dependencies\n for (const key in packageJson.dependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.dependencies[key] = resolveMudVersion(key, \"dependencies\");\n }\n }\n\n // Update the devDependencies\n for (const key in packageJson.devDependencies) {\n if (key.startsWith(MUD_PREFIX)) {\n packageJson.devDependencies[key] = resolveMudVersion(key, \"devDependencies\");\n }\n }\n\n // Write the updated package.json\n writeFileSync(filePath, JSON.stringify(packageJson, null, 2) + \"\\n\");\n\n console.log(`Updating ${filePath}`);\n logComparison(mudDependencies, packageJson.dependencies);\n logComparison(mudDevDependencies, packageJson.devDependencies);\n\n // Remove the backup file if `restore` is true and `backup` is false\n // because the old backup file is no longer needed\n if (restore && !backup) {\n rmSync(backupFilePath);\n console.log(chalk.green(`Cleaned up ${backupFilePath}`));\n }\n\n return packageJson;\n\n function resolveMudVersion(key: string, type: \"dependencies\" | \"devDependencies\") {\n if (restore && backupJson) return backupJson[type][key];\n if (link) mudVersion = resolveLinkPath(filePath, link, key);\n if (!mudVersion) return packageJson[type][key];\n return mudVersion;\n }\n}\n\nfunction readPackageJson(path: string): {\n workspaces?: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n} {\n try {\n const jsonString = readFileSync(path, \"utf8\");\n return JSON.parse(jsonString);\n } catch {\n throw new MUDError(\"Could not read JSON at \" + path);\n }\n}\n\nasync function getCanaryVersion(pkg: string) {\n try {\n console.log(chalk.blue(\"fetching MUD canary version...\"));\n const result = await (await fetch(`https://registry.npmjs.org/${pkg}`)).json();\n const canary = result[\"dist-tags\"].canary;\n console.log(chalk.green(\"MUD canary version:\", canary));\n return canary;\n } catch (e) {\n throw new MUDError(`Could not fetch canary version of ${pkg}`);\n }\n}\n\nfunction logComparison(prev: Record<string, string>, curr: Record<string, string>) {\n for (const key in prev) {\n if (prev[key] !== curr[key]) {\n console.log(`${key}: ${chalk.red(prev[key])} -> ${chalk.green(curr[key])}`);\n }\n }\n}\n\n/**\n * Returns path of the package to link, given a path to a local MUD clone and a package\n */\nfunction resolveLinkPath(packageJsonPath: string, mudLinkPath: string, pkg: string) {\n const pkgName = pkg.replace(MUD_PREFIX, \"\");\n const packageJsonToRootPath = path.relative(path.dirname(packageJsonPath), process.cwd());\n const linkPath = path.join(packageJsonToRootPath, mudLinkPath, \"packages\", pkgName);\n return \"link:\" + linkPath;\n}\n\nexport default commandModule;\n","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"0.0.0-main-20230704121617\",\n \"description\": \"Command line interface for mud\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/latticexyz/mud.git\",\n \"directory\": \"packages/cli\"\n },\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"src/index.ts\",\n \"bin\": {\n \"mud\": \"./dist/mud.js\"\n },\n \"scripts\": {\n \"build\": \"pnpm run build:js\",\n \"build:js\": \"tsup && chmod +x ./dist/mud.js\",\n \"clean\": \"pnpm run clean:js\",\n \"clean:js\": \"rimraf dist\",\n \"dev\": \"tsup --watch\",\n \"generate-test-tables\": \"tsx ./scripts/generate-test-tables.ts\",\n \"lint\": \"eslint . --ext .ts\",\n \"test\": \"tsc --noEmit && pnpm run generate-test-tables && forge test\"\n },\n \"dependencies\": {\n \"@ethersproject/abi\": \"^5.7.0\",\n \"@ethersproject/providers\": \"^5.7.2\",\n \"@improbable-eng/grpc-web\": \"^0.15.0\",\n \"@improbable-eng/grpc-web-node-http-transport\": \"^0.15.0\",\n \"@latticexyz/common\": \"workspace:*\",\n \"@latticexyz/config\": \"workspace:*\",\n \"@latticexyz/schema-type\": \"workspace:*\",\n \"@latticexyz/services\": \"workspace:*\",\n \"@latticexyz/solecs\": \"workspace:*\",\n \"@latticexyz/std-contracts\": \"workspace:*\",\n \"@latticexyz/store\": \"workspace:*\",\n \"@latticexyz/utils\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"@typechain/ethers-v5\": \"^10.2.0\",\n \"chalk\": \"^5.0.1\",\n \"chokidar\": \"^3.5.3\",\n \"dotenv\": \"^16.0.3\",\n \"ejs\": \"^3.1.8\",\n \"ethers\": \"^5.7.2\",\n \"execa\": \"^7.0.0\",\n \"glob\": \"^8.0.3\",\n \"nice-grpc-web\": \"^2.0.1\",\n \"openurl\": \"^1.1.1\",\n \"path\": \"^0.12.7\",\n \"strip-ansi\": \"^7.1.0\",\n \"table\": \"^6.8.1\",\n \"throttle-debounce\": \"^5.0.0\",\n \"typechain\": \"^8.1.1\",\n \"typescript\": \"^4.9.5\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"^3.21.4\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/ejs\": \"^3.1.1\",\n \"@types/glob\": \"^7.2.0\",\n \"@types/node\": \"^18.15.11\",\n \"@types/openurl\": \"^1.0.0\",\n \"@types/throttle-debounce\": \"^5.0.0\",\n \"@types/yargs\": \"^17.0.10\",\n \"ds-test\": \"https://github.com/dapphub/ds-test.git#c9ce3f25bde29fc5eb9901842bf02850dfd2d084\",\n \"forge-std\": \"https://github.com/foundry-rs/forge-std.git#b4f121555729b3afb3c5ffccb62ff4b6e2818fd3\",\n \"tsup\": \"^6.7.0\",\n \"tsx\": \"^3.12.6\",\n \"vitest\": \"0.31.4\"\n },\n \"gitHead\": \"914a1e0ae4a573d685841ca2ea921435057deb8f\"\n}\n","import type { CommandModule } from \"yargs\";\nimport { anvil, forge, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { rmSync, writeFileSync } from \"fs\";\nimport { yDeployOptions } from \"./deploy\";\nimport { deployHandler, DeployOptions } from \"../utils\";\n\ntype Options = DeployOptions & { port?: number; worldAddress?: string; forgeOptions?: string };\n\nconst WORLD_ADDRESS_FILE = \".mudtest\";\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"test\",\n\n describe: \"Run tests in MUD contracts\",\n\n builder(yargs) {\n return yargs.options({\n ...yDeployOptions,\n port: { type: \"number\", description: \"Port to run internal node for fork testing on\", default: 4242 },\n worldAddress: {\n type: \"string\",\n description:\n \"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing.\",\n },\n forgeOptions: { type: \"string\", description: \"Options to pass to forge test\" },\n });\n },\n\n async handler(args) {\n // Start an internal anvil process if no world address is provided\n if (!args.worldAddress) {\n const anvilArgs = [\"--block-base-fee-per-gas\", \"0\", \"--port\", String(args.port)];\n anvil(anvilArgs);\n }\n\n const forkRpc = args.worldAddress ? await getRpcUrl(args.profile) : `http://127.0.0.1:${args.port}`;\n\n const worldAddress =\n args.worldAddress ??\n (\n await deployHandler({\n ...args,\n saveDeployment: false,\n rpc: forkRpc,\n })\n ).worldAddress;\n\n console.log(chalk.blue(\"World address\", worldAddress));\n\n // Create a temporary file to pass the world address to the tests\n writeFileSync(WORLD_ADDRESS_FILE, worldAddress);\n\n const userOptions = args.forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n try {\n const testResult = await forge([\"test\", \"--fork-url\", forkRpc, ...userOptions], {\n profile: args.profile,\n });\n console.log(testResult);\n } catch (e) {\n console.error(e);\n }\n\n rmSync(WORLD_ADDRESS_FILE);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import { existsSync, readFileSync } from \"fs\";\nimport type { CommandModule } from \"yargs\";\nimport { ethers } from \"ethers\";\n\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { cast, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { TableId } from \"@latticexyz/common\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { resolveWorldConfig, WorldConfig } from \"@latticexyz/world\";\nimport { IBaseWorld } from \"@latticexyz/world/types/ethers-contracts/IBaseWorld\";\nimport IBaseWorldData from \"@latticexyz/world/abi/IBaseWorld.sol/IBaseWorld.json\" assert { type: \"json\" };\nimport { getChainId, getExistingContracts } from \"../utils\";\n\nconst systemsTableId = new TableId(\"\", \"Systems\");\n\ntype Options = {\n tx: string;\n worldAddress?: string;\n configPath?: string;\n profile?: string;\n srcDir?: string;\n rpc?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"trace\",\n\n describe: \"Display the trace of a transaction\",\n\n builder(yargs) {\n return yargs.options({\n tx: { type: \"string\", required: true, description: \"Transaction hash to replay\" },\n worldAddress: {\n type: \"string\",\n description: \"World contract address. Defaults to the value from worlds.json, based on rpc's chainId\",\n },\n configPath: { type: \"string\", description: \"Path to the config file\" },\n profile: { type: \"string\", description: \"The foundry profile to use\" },\n srcDir: { type: \"string\", description: \"Source directory. Defaults to foundry src directory.\" },\n rpc: { type: \"string\", description: \"json rpc endpoint. Defaults to foundry's configured eth_rpc_url\" },\n });\n },\n\n async handler(args) {\n args.profile ??= process.env.FOUNDRY_PROFILE;\n const { profile } = args;\n args.srcDir ??= await getSrcDirectory(profile);\n args.rpc ??= await getRpcUrl(profile);\n const { tx, configPath, srcDir, rpc } = args;\n\n const existingContracts = getExistingContracts(srcDir);\n\n // Load the config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n const resolvedConfig = resolveWorldConfig(\n mudConfig,\n existingContracts.map(({ basename }) => basename)\n );\n\n // Get worldAddress either from args or from worldsFile\n const worldAddress = args.worldAddress ?? (await getWorldAddress(mudConfig.worldsFile, rpc));\n\n // Create World contract instance from deployed address\n const provider = new ethers.providers.StaticJsonRpcProvider(rpc);\n const WorldContract = new ethers.Contract(worldAddress, IBaseWorldData.abi, provider) as IBaseWorld;\n\n // TODO account for multiple namespaces (https://github.com/latticexyz/mud/issues/994)\n const namespace = mudConfig.namespace;\n const names = Object.values(resolvedConfig.systems).map(({ name }) => name);\n\n const labels: { name: string; address: string }[] = [];\n for (const name of names) {\n const systemSelector = new TableId(namespace, name);\n // Get the first field of `Systems` table (the table maps system name to its address and other data)\n const address = await WorldContract.getField(systemsTableId.toHex(), [systemSelector.toHex()], 0);\n labels.push({ name, address });\n }\n\n const result = await cast([\n \"run\",\n \"--label\",\n `${worldAddress}:World`,\n ...labels.map(({ name, address }) => [\"--label\", `${address}:${name}`]).flat(),\n `${tx}`,\n ]);\n console.log(result);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n\nasync function getWorldAddress(worldsFile: string, rpc: string) {\n if (existsSync(worldsFile)) {\n const chainId = await getChainId(rpc);\n const deploys = JSON.parse(readFileSync(worldsFile, \"utf-8\"));\n\n if (!deploys[chainId]) {\n throw new MUDError(`chainId ${chainId} is missing in worldsFile \"${worldsFile}\"`);\n }\n return deploys[chainId].address as string;\n } else {\n throw new MUDError(\"worldAddress is not specified and worldsFile is missing\");\n }\n}\n","import type { CommandModule } from \"yargs\";\nimport { anvil, forge, getRpcUrl, getScriptDirectory, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport chokidar from \"chokidar\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { tablegen } from \"@latticexyz/store/codegen\";\nimport path from \"path\";\nimport { tsgen } from \"../render-ts\";\nimport { debounce } from \"throttle-debounce\";\nimport { worldgenHandler } from \"./worldgen\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { deployHandler, logError, printMUD, worldtypes } from \"../utils\";\nimport { homedir } from \"os\";\nimport { rmSync } from \"fs\";\n\ntype Options = {\n rpc?: string;\n configPath?: string;\n tsgenOutput: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"dev-contracts\",\n\n describe: \"Start a development server for MUD contracts\",\n\n builder(yargs) {\n return yargs.options({\n rpc: {\n type: \"string\",\n decs: \"RPC endpoint of the development node. If none is provided, an anvil instance is spawned in the background on port 8545.\",\n },\n configPath: {\n type: \"string\",\n decs: \"Path to MUD config\",\n },\n tsgenOutput: { type: \"string\", demandOption: true, desc: \"Directory to output MUD typescript definition files\" },\n });\n },\n\n async handler(args) {\n if (!args.tsgenOutputDir) {\n console.error(\"No output provided\");\n }\n\n // Initial cleanup\n await forge([\"clean\"]);\n\n const rpc = args.rpc ?? (await getRpcUrl());\n const configPath = args.configPath ?? (await resolveConfigPath(args.configPath));\n const srcDirectory = await getSrcDirectory();\n const scriptDirectory = await getScriptDirectory();\n const initialConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n // Initial run of all codegen steps before starting anvil\n // (so clients can wait for everything to be ready before starting)\n await handleConfigChange(initialConfig);\n await handleContractsChange(initialConfig);\n\n // Start an anvil instance in the background if no RPC url is provided\n if (!args.rpc) {\n console.log(chalk.gray(\"Cleaning devnode cache\"));\n const userHomeDir = homedir();\n rmSync(path.join(userHomeDir, \".foundry\", \"anvil\", \"tmp\"), { recursive: true, force: true });\n\n const anvilArgs = [\"--block-time\", \"1\", \"--block-base-fee-per-gas\", \"0\"];\n anvil(anvilArgs);\n }\n\n const changedSinceLastHandled = {\n config: false,\n contracts: false,\n };\n\n const changeInProgress = {\n current: false,\n };\n\n // Watch for changes\n const configWatcher = chokidar.watch([configPath, srcDirectory]);\n configWatcher.on(\"all\", async (_, updatePath) => {\n if (updatePath.includes(configPath)) {\n changedSinceLastHandled.config = true;\n // We trigger contract changes if the config changed here instead of\n // listening to changes in the codegen directory to avoid an infinite loop\n changedSinceLastHandled.contracts = true;\n }\n\n if (updatePath.includes(srcDirectory) || updatePath.includes(scriptDirectory)) {\n // Ignore changes to codegen files to avoid an infinite loop\n if (updatePath.includes(initialConfig.codegenDirectory)) return;\n changedSinceLastHandled.contracts = true;\n }\n\n // Trigger debounced onChange\n handleChange();\n });\n\n const handleChange = debounce(100, async () => {\n // Avoid handling changes multiple times in parallel\n if (changeInProgress.current) return;\n changeInProgress.current = true;\n\n // Reset dirty flags\n const { config, contracts } = changedSinceLastHandled;\n changedSinceLastHandled.config = false;\n changedSinceLastHandled.contracts = false;\n\n try {\n // Load latest config\n const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n // Handle changes\n if (config) await handleConfigChange(mudConfig);\n if (contracts) await handleContractsChange(mudConfig);\n\n await deploy();\n } catch (error) {\n console.error(chalk.red(\"MUD dev-contracts watcher failed to deploy config or contracts changes\\n\"));\n logError(error);\n }\n\n changeInProgress.current = false;\n if (changedSinceLastHandled.config || changedSinceLastHandled.contracts) {\n console.log(\"Detected change while handling the previous change\");\n handleChange();\n }\n\n printMUD();\n console.log(\"MUD watching for changes...\");\n });\n\n /** Codegen to run if config changes */\n async function handleConfigChange(config: StoreConfig & WorldConfig) {\n console.log(chalk.blue(\"mud.config.ts changed - regenerating tables and recs types\"));\n // Run tablegen to generate tables based on the config\n const outPath = path.join(srcDirectory, config.codegenDirectory);\n await tablegen(config, outPath);\n\n // Run tsgen to regenerate recs types based on the mud config\n await tsgen(config, args.tsgenOutput);\n }\n\n /** Codegen to run if contracts changed */\n async function handleContractsChange(config: StoreConfig & WorldConfig) {\n console.log(chalk.blue(\"contracts changed - regenerating interfaces and contract types\"));\n\n // Run worldgen to generate interfaces based on the systems\n await worldgenHandler({ config, clean: true, srcDir: srcDirectory });\n\n // Build the contracts\n await forge([\"build\"]);\n\n // Run typechain to rebuild typescript types for the contracts\n await worldtypes();\n }\n\n /** Run after codegen if either mud config or contracts changed */\n async function deploy() {\n console.log(chalk.blue(\"redeploying World\"));\n await deployHandler({\n configPath,\n skipBuild: true,\n priorityFeeMultiplier: 1,\n disableTxWait: true,\n pollInterval: 1000,\n saveDeployment: true,\n srcDir: srcDirectory,\n rpc,\n });\n }\n },\n};\n\nexport default commandModule;\n","import { CommandModule } from \"yargs\";\n\nimport devnode from \"./devnode\";\nimport faucet from \"./faucet\";\nimport gasReport from \"./gas-report\";\nimport hello from \"./hello\";\nimport tablegen from \"./tablegen\";\nimport tsgen from \"./tsgen\";\nimport deploy from \"./deploy\";\nimport worldgen from \"./worldgen\";\nimport setVersion from \"./set-version\";\nimport test from \"./test\";\nimport trace from \"./trace\";\nimport devContracts from \"./dev-contracts\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each command has different options\nexport const commands: CommandModule<any, any>[] = [\n deploy,\n devnode,\n faucet,\n gasReport,\n hello,\n tablegen,\n tsgen,\n worldgen,\n setVersion,\n test,\n trace,\n devContracts,\n];\n"],"mappings":";6DAEA,OAAOA,OAAW,QAClB,OAAS,WAAAC,OAAe,gBCHxB,OAAS,UAAAC,OAAc,KACvB,OAAS,WAAAC,OAAe,KACxB,OAAOC,OAAU,OAEjB,OAAS,SAAAC,OAAa,QAMtB,IAAMC,GAAiD,CACrD,QAAS,UAET,SAAU,8CAEV,QAAQC,EAAO,CACb,OAAOA,EAAM,QAAQ,CACnB,UAAW,CAAE,KAAM,SAAU,QAAS,EAAG,KAAM,2CAA4C,CAC7F,CAAC,CACH,EAEA,MAAM,QAAQ,CAAE,UAAAC,CAAU,EAAG,CAC3B,QAAQ,IAAI,0BAA0B,EACtC,IAAMC,EAAcN,GAAQ,EAC5BD,GAAOE,GAAK,KAAKK,EAAa,WAAY,QAAS,KAAK,EAAG,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAE3F,IAAMC,EAAY,CAAC,KAAM,OAAOF,CAAS,EAAG,2B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,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,GACAC,EACF,EjBrBA,UAAYC,OAAY,SACxB,OAAOC,OAAW,QACX,UAAO,EAEdC,GAAMC,GAAQ,QAAQ,IAAI,CAAC,EAExB,WAAW,KAAK,EAGhB,QAAQC,EAAe,EAEvB,OAAO,EAEP,KAAK,CAACC,EAAKC,IAAQ,CAClB,QAAQ,MAAML,GAAM,IAAII,CAAG,CAAC,EACxBA,EAAI,SAAS,2BAA2B,GAC1C,QAAQ,IACNJ,GAAM,OAAO,iBAAiB,QAAQ,KAAK,CAAC,2DAA2D,CACzG,EAEF,QAAQ,IAAI,EAAE,EACdM,EAASD,CAAG,EACZ,QAAQ,IAAI,EAAE,EAEd,QAAQ,KAAK,CAAC,CAChB,CAAC,EAEA,MAAM,CAAE,EAAG,MAAO,CAAC,EAAE","names":["yargs","hideBin","rmSync","homedir","path","execa","commandModule","yargs","blocktime","userHomeDir","anvilArgs","child","devnode_default","FaucetServiceDefinition","createChannel","createClient","chalk","NodeHttpTransport","createFaucetService","url","commandModule","yargs","dripDev","faucetUrl","address","faucet","faucet_default","readFileSync","writeFileSync","execa","chalk","table","getBorderCharacters","stripAnsi","commandModule","yargs","save","compare","gasReport","runGasReport","error","compareGasReport","entry","prevEntry","e","printGasReport","saveGasReport","gas_report_default","stdout","lines","gasReportPattern","testFunctionPattern","testFilePattern","nearestLine","pattern","startIndex","i","line","matches","gasUsed","name","testFunctionLineIndex","testFileLineIndex","functionMatches","fileMatches","test","file","a","b","headers","values","diff","diffEntry","compareColumns","gasUsedEntry","rows","path","commandModule","yargs","name","greeting","hello_default","path","loadConfig","tablegen","getSrcDirectory","commandModule","yargs","configPath","config","srcDir","tablegen_default","loadConfig","commandModule","yargs","args","configPath","out","config","loadConfig","tsgen","tsgen_default","chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError","chalk","printMUD","getOutDirectory","path","runTypeChain","worldtypes","cwd","forgeOurDir","IWorldPath","yDeployOptions","commandModule","yargs","args","deployHandler","error","logError","deploy_default","loadConfig","worldgen","getSrcDirectory","path","rmSync","commandModule","yargs","args","worldgenHandler","srcDir","getSrcDirectory","existingContracts","getExistingContracts","mudConfig","loadConfig","outputBaseDirectory","path","rmSync","worldgen","worldgen_default","chalk","existsSync","readFileSync","rmSync","writeFileSync","path","MUDError","package_default","BACKUP_FILE","MUD_PREFIX","commandModule","yargs","options","MUDError","getCanaryVersion","package_default","rootPath","workspaces","updatePackageJson","workspace","filePath","path","e","logError","restore","force","link","backup","mudVersion","backupFilePath","backupFileExists","existsSync","packageJson","readPackageJson","backupJson","mudDependencies","key","mudDevDependencies","writeFileSync","chalk","resolveMudVersion","logComparison","rmSync","type","resolveLinkPath","jsonString","readFileSync","pkg","canary","prev","curr","packageJsonPath","mudLinkPath","pkgName","packageJsonToRootPath","set_version_default","anvil","forge","getRpcUrl","chalk","rmSync","writeFileSync","WORLD_ADDRESS_FILE","commandModule","yargs","yDeployOptions","args","anvilArgs","anvil","forkRpc","getRpcUrl","worldAddress","deployHandler","chalk","writeFileSync","userOptions","testResult","forge","e","rmSync","test_default","existsSync","readFileSync","ethers","loadConfig","MUDError","cast","getRpcUrl","getSrcDirectory","TableId","resolveWorldConfig","IBaseWorldData","systemsTableId","TableId","commandModule","yargs","args","profile","getSrcDirectory","getRpcUrl","tx","configPath","srcDir","rpc","existingContracts","getExistingContracts","mudConfig","loadConfig","resolvedConfig","resolveWorldConfig","basename","worldAddress","getWorldAddress","provider","ethers","WorldContract","IBaseWorldData","namespace","names","name","labels","systemSelector","address","result","cast","trace_default","worldsFile","existsSync","chainId","getChainId","deploys","readFileSync","MUDError","anvil","forge","getRpcUrl","getScriptDirectory","getSrcDirectory","chalk","chokidar","loadConfig","resolveConfigPath","tablegen","path","debounce","homedir","rmSync","commandModule","yargs","args","forge","rpc","getRpcUrl","configPath","resolveConfigPath","srcDirectory","getSrcDirectory","scriptDirectory","getScriptDirectory","initialConfig","loadConfig","handleConfigChange","handleContractsChange","chalk","userHomeDir","path","anvil","changedSinceLastHandled","changeInProgress","chokidar","_","updatePath","handleChange","debounce","config","contracts","mudConfig","deploy","error","logError","printMUD","outPath","tablegen","tsgen","worldgenHandler","worldtypes","deployHandler","dev_contracts_default","commands","deploy_default","devnode_default","faucet_default","gas_report_default","hello_default","tablegen_default","tsgen_default","worldgen_default","set_version_default","test_default","trace_default","dev_contracts_default","dotenv","chalk","yargs","hideBin","commands","msg","err","logError"]}