@latticexyz/cli 2.0.0-next.14 → 2.0.0-next.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands-DSIRJZEM.js +27 -0
- package/dist/commands-DSIRJZEM.js.map +1 -0
- package/dist/mud.js +1 -1
- package/package.json +12 -12
- package/src/build.ts +44 -0
- package/src/commands/build.ts +36 -0
- package/src/commands/index.ts +2 -0
- package/src/commands/set-version.ts +4 -1
- package/src/debug.ts +7 -0
- package/src/deploy/debug.ts +7 -0
- package/src/deploy/deploy.ts +8 -3
- package/src/deploy/ensureNamespaceOwner.ts +71 -0
- package/src/deploy/ensureWorldFactory.ts +76 -3
- package/src/runDeploy.ts +3 -10
- package/dist/commands-UYAATBY6.js +0 -27
- package/dist/commands-UYAATBY6.js.map +0 -1
- package/src/deploy/assertNamespaceOwner.ts +0 -42
@@ -0,0 +1,27 @@
|
|
1
|
+
import{a as _}from"./chunk-22IIKR4S.js";import hs from"@latticexyz/gas-report";import ws from"@latticexyz/abi-ts";import{loadConfig as qo}from"@latticexyz/config/node";import{getSrcDirectory as Go}from"@latticexyz/common/foundry";import{existsSync as Ho,readFileSync as Eo,writeFileSync as No}from"node:fs";import X from"node:path";import{tablegen as zo}from"@latticexyz/store/codegen";import{worldgen as Uo}from"@latticexyz/world/node";import{forge as Vo,getForgeConfig as _o,getRemappings as Lo}from"@latticexyz/common/foundry";import Wo from"glob";import{basename as Ro}from"path";function I(e){return Wo.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:Ro(o,".sol")}))}import ye from"debug";var M=ye("mud:cli"),$o=ye("mud:cli");M.log=console.debug.bind(console);$o.log=console.error.bind(console);import{execa as Ko}from"execa";var Jo=M.extend("runDeploy");async function L({config:e,srcDir:o,foundryProfile:r=process.env.FOUNDRY_PROFILE}){let t=X.join(o,e.codegenDirectory),n=await Lo(r);await Promise.all([zo(e,t,n),Uo(e,I(o),t)]);let s=await _o(r);if(s.cache){let c=X.join(s.cache_path,"solidity-files-cache.json");if(Ho(c)){Jo("Unsetting cached content hash of IWorld.sol to force it to regenerate");let i=JSON.parse(Eo(c,"utf8")),p=X.join(t,"world","IWorld.sol");i.files[p].contentHash="",No(c,JSON.stringify(i,null,2))}}await Vo(["build"],{profile:r}),await Ko("mud",["abi-ts"],{stdio:"inherit"})}var Yo={command:"build",describe:"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler({configPath:e,profile:o}){let r=await qo(e),t=await Go();await L({config:r,srcDir:t,foundryProfile:o}),process.exit(0)}},ue=Yo;import{rmSync as Zo}from"fs";import{homedir as Qo}from"os";import Xo from"path";import{execa as et}from"execa";var ot={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=Qo();Zo(Xo.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let r=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${r.join(" ")}`);let t=et("anvil",r,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
|
2
|
+
gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},ge=ot;import{FaucetServiceDefinition as tt}from"@latticexyz/services/faucet";import{createChannel as rt,createClient as nt}from"nice-grpc-web";import be from"chalk";import{NodeHttpTransport as st}from"@improbable-eng/grpc-web-node-http-transport";function it(e){return nt(tt,rt(e,st()))}var at={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:r}){let t=it(o);e&&(console.log(be.yellow("Dripping to",r)),await t.dripDev({address:r}),console.log(be.yellow("Success"))),process.exit(0)}},he=at;var ct={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)}},we=ct;import dt from"path";import{loadConfig as lt}from"@latticexyz/config/node";import{tablegen as mt}from"@latticexyz/store/codegen";import{getRemappings as pt,getSrcDirectory as ft}from"@latticexyz/common/foundry";var yt={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 lt(e),r=await ft(),t=await pt();await mt(o,dt.join(r,o.codegenDirectory),t),process.exit(0)}},xe=yt;import de from"node:path";import{existsSync as sn,mkdirSync as an,readFileSync as cn,writeFileSync as le}from"node:fs";import{getAddress as lo}from"viem";import{getBytecode as bt,sendRawTransaction as ht,sendTransaction as wt,waitForTransactionReceipt as Se}from"viem/actions";var P={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};var d=M.extend("deploy"),gt=M.extend("deploy");d.log=console.debug.bind(console);gt.log=console.error.bind(console);var S=`0x${P.address}`;async function Ce(e){if(await bt(e,{address:S})){d("found create2 deployer at",S);return}d("sending gas for create2 deployer to signer at",P.signerAddress);let r=await wt(e,{chain:e.chain??null,to:`0x${P.signerAddress}`,value:BigInt(P.gasLimit)*BigInt(P.gasPrice)}),t=await Se(e,{hash:r});if(t.status!=="success")throw console.error("failed to send gas to deployer signer",t),new Error("failed to send gas to deployer signer");d("deploying create2 deployer at",S);let n=await ht(e,{serializedTransaction:`0x${P.transaction}`}),s=await Se(e,{hash:n});if(s.contractAddress!==S)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as Qt}from"viem/actions";import ke from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Ie from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Oe from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import je from"@latticexyz/world/out/CoreRegistrationSystem.sol/CoreRegistrationSystem.json"assert{type:"json"};import Be from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import Wt from"@latticexyz/world/out/CoreModule.sol/CoreModule.abi.json"assert{type:"json"};import Pe from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Rt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as W,encodeDeployData as R,size as $}from"viem";import{padHex as St}from"viem";import Ct from"@latticexyz/store/mud.config";import vt from"@latticexyz/world/mud.config";import Dt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Tt from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as xt}from"@latticexyz/common";import{resolveUserTypes as ve}from"@latticexyz/store";function z(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([r])=>[r,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([r,t])=>[`${e.namespace}_${r}`,{namespace:e.namespace,name:t.name,tableId:xt({type:t.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:t.name}),keySchema:ve(t.keySchema,o),valueSchema:ve(t.valueSchema,o)}]))}import{helloStoreEvent as At}from"@latticexyz/store";import{helloWorldEvent as kt}from"@latticexyz/world";var D=St("0x",{size:32}),U=parseInt("6000",16),F=z(Ct),T=z(vt),K=[At,kt],v=[...Dt,...Tt],De=["1.0.0-unaudited"],Te=["1.0.0-unaudited"];import{waitForTransactionReceipt as Ft}from"viem/actions";import{concatHex as It,getCreate2Address as Ot}from"viem";import{getBytecode as jt}from"viem/actions";import{sendTransaction as Bt}from"@latticexyz/common";import Pt from"p-retry";import{wait as Mt}from"@latticexyz/common/utils";async function Ae({client:e,bytecode:o,deployedBytecodeSize:r,label:t="contract"}){let n=Ot({from:S,salt:D,bytecode:o});return await jt(e,{address:n,blockTag:"pending"})?(d("found",t,"at",n),[]):(r>U?console.warn(`
|
3
|
+
Bytecode for ${t} (${r} bytes) is over the contract size limit (${U} bytes). Run \`forge build --sizes\` for more info.
|
4
|
+
`):r>U*.95&&console.warn(`
|
5
|
+
Bytecode for ${t} (${r} bytes) is almost over the contract size limit (${U} bytes). Run \`forge build --sizes\` for more info.
|
6
|
+
`),d("deploying",t,"at",n),[await Pt(()=>Bt(e,{chain:e.chain??null,to:S,data:It([D,o])}),{retries:3,onFailedAttempt:async c=>{let i=c.attemptNumber*500;d(`failed to deploy ${t}, retrying in ${i}ms...`),await Mt(i)}})])}async function O({client:e,contracts:o}){let r=(await Promise.all(o.map(t=>Ae({client:e,...t})))).flat();if(r.length){d("waiting for contracts");for(let t of r)await Ft(e,{hash:t})}return r}var $t=$(ke.deployedBytecode.object),Me=R({bytecode:ke.bytecode.object,abi:[]}),Ht=W({from:S,bytecode:Me,salt:D}),Et=$(Ie.deployedBytecode.object),Fe=R({bytecode:Ie.bytecode.object,abi:[]}),Nt=W({from:S,bytecode:Fe,salt:D}),zt=$(Oe.deployedBytecode.object),We=R({bytecode:Oe.bytecode.object,abi:[]}),Ut=W({from:S,bytecode:We,salt:D}),Vt=$(je.deployedBytecode.object),Re=R({bytecode:je.bytecode.object,abi:[]}),_t=W({from:S,bytecode:Re,salt:D}),Lt=$(Be.deployedBytecode.object),$e=R({bytecode:Be.bytecode.object,abi:Wt,args:[Ht,Nt,Ut,_t]}),Kt=W({from:S,bytecode:$e,salt:D}),Jt=$(Pe.deployedBytecode.object),He=R({bytecode:Pe.bytecode.object,abi:Rt,args:[Kt]}),Ee=W({from:S,bytecode:He,salt:D}),ee=[{bytecode:Me,deployedBytecodeSize:$t,label:"access management system"},{bytecode:Fe,deployedBytecodeSize:Et,label:"balance transfer system"},{bytecode:We,deployedBytecodeSize:zt,label:"batch call system"},{bytecode:Re,deployedBytecodeSize:Vt,label:"core registration system"},{bytecode:$e,deployedBytecodeSize:Lt,label:"core module"},{bytecode:He,deployedBytecodeSize:Jt,label:"world factory"}];async function Ne(e){return await O({client:e,contracts:ee})}import Xt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as er}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as qt,decodeEventLog as Gt,hexToString as ze,parseAbi as Yt,trim as Ue}from"viem";import{isDefined as Zt}from"@latticexyz/common/utils";function J(e){let o=e.map(c=>{try{return{...c,...Gt({strict:!0,abi:Yt(K),topics:c.topics,data:c.data})}}catch(i){if(i instanceof qt)return;throw i}}).filter(Zt),{address:r,deployBlock:t,worldVersion:n,storeVersion:s}=o.reduce((c,i)=>({...c,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:ze(Ue(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:ze(Ue(i.args.storeVersion,{dir:"right"}))}:null}),{});if(r==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:r,deployBlock:t,worldVersion:n,storeVersion:s}}async function Ve(e){await Ne(e),d("deploying world");let o=await er(e,{chain:e.chain??null,address:Ee,abi:Xt,functionName:"deployWorld"});d("waiting for world deploy");let r=await Qt(e,{hash:o});if(r.status!=="success")throw console.error("world deploy failed",r),new Error("world deploy failed");let t=J(r.logs.map(n=>n));return d("deployed world to",t.address,"at block",t.deployBlock),{...t,stateBlock:t.deployBlock}}import{writeContract as ar}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as dr,valueSchemaToHex as lr}from"@latticexyz/protocol-parser";function C({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as or,decodeAbiParameters as _e,parseAbiParameters as Le}from"viem";import{hexToResource as tr}from"@latticexyz/common";import{storeSetRecordEvent as rr}from"@latticexyz/store";import{getLogs as nr}from"viem/actions";import{decodeKey as sr,decodeValueArgs as ir,hexToSchema as Ke}from"@latticexyz/protocol-parser";async function Je({client:e,worldDeploy:o}){d("looking up tables for",o.address);let t=(await nr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:or(rr),args:{tableId:F.store_Tables.tableId}})).map(n=>{let{tableId:s}=sr(F.store_Tables.keySchema,n.args.keyTuple),{namespace:c,name:i}=tr(s),p=ir(F.store_Tables.valueSchema,n.args),l=Ke(p.keySchema),f=Ke(p.valueSchema),y=_e(Le("string[]"),p.abiEncodedKeyNames)[0],m=_e(Le("string[]"),p.abiEncodedFieldNames)[0],u=[...f.staticFields,...f.dynamicFields],w=Object.fromEntries(l.staticFields.map((x,a)=>[y[a],x])),b=Object.fromEntries(u.map((x,a)=>[m[a],x]));return{namespace:c,name:i,tableId:s,keySchema:w,valueSchema:b}});return d("found",t.length,"tables for",o.address),t}import mr from"p-retry";import{wait as pr}from"@latticexyz/common/utils";async function qe({client:e,worldDeploy:o,tables:r}){let n=(await Je({client:e,worldDeploy:o})).map(i=>i.tableId),s=r.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(C).join(", "));let c=r.filter(i=>!n.includes(i.tableId));return c.length?(d("registering tables",c.map(C).join(", ")),await Promise.all(c.map(i=>mr(()=>ar(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[i.tableId,cr(i.valueSchema),dr(i.keySchema),lr(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]}),{retries:3,onFailedAttempt:async p=>{let l=p.attemptNumber*500;d(`failed to register table ${C(i)}, retrying in ${l}ms...`),await pr(l)}})))):[]}import{getAddress as A}from"viem";import{writeContract as oe}from"@latticexyz/common";import{parseAbiItem as fr}from"viem";import{getLogs as yr}from"viem/actions";import{storeSpliceStaticDataEvent as ur}from"@latticexyz/store";async function q({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let t=(await yr(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:fr(ur),args:{tableId:F.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",t.length,"resource IDs for",o.address),t}import{hexToResource as jr}from"@latticexyz/common";import{decodeValueArgs as gr,encodeKey as br}from"@latticexyz/protocol-parser";import{readContract as hr}from"viem/actions";async function j({client:e,worldDeploy:o,table:r,key:t}){let[n,s,c]=await hr(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[r.tableId,br(r.keySchema,t)]});return gr(r.valueSchema,{staticData:n,encodedLengths:s,dynamicData:c})}import{getFunctionSelector as wr,parseAbiItem as xr}from"viem";import{storeSetRecordEvent as Sr}from"@latticexyz/store";import{getLogs as Cr}from"viem/actions";import{decodeValueArgs as vr}from"@latticexyz/protocol-parser";import{hexToResource as Dr}from"@latticexyz/common";async function G({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let t=(await Cr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:xr(Sr),args:{tableId:T.world_FunctionSignatures.tableId}})).map(s=>vr(T.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",t.length,"function signatures for",o.address),await Promise.all(t.map(async s=>{let c=wr(s),{systemId:i,systemFunctionSelector:p}=await j({client:e,worldDeploy:o,table:T.world_FunctionSelectors,key:{functionSelector:c}}),{namespace:l,name:f}=Dr(i),y=l===""?s:s.replace(`${l}_${f}_`,"");return{signature:s,selector:c,systemId:i,systemFunctionSignature:y,systemFunctionSelector:p}}))}import{parseAbiItem as Tr,getAddress as Ar}from"viem";import{storeSpliceStaticDataEvent as kr}from"@latticexyz/store";import{getLogs as Ir}from"viem/actions";import{decodeKey as Or}from"@latticexyz/protocol-parser";async function Y({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let t=(await Ir(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Tr(kr),args:{tableId:T.world_ResourceAccess.tableId}})).map(s=>Or(T.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(t.map(async s=>[s,await j({client:e,worldDeploy:o,table:T.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Ar(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Ge({client:e,worldDeploy:o}){let[r,t,n]=await Promise.all([q({client:e,worldDeploy:o}),G({client:e,worldDeploy:o}),Y({client:e,worldDeploy:o})]),s=r.map(jr).filter(c=>c.type==="system");return d("looking up systems",s.map(C).join(", ")),await Promise.all(s.map(async c=>{let{system:i,publicAccess:p}=await j({client:e,worldDeploy:o,table:T.world_Systems,key:{systemId:c.resourceId}}),l=t.filter(f=>f.systemId===c.resourceId);return{address:i,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:p,allowedAddresses:n.filter(({resourceId:f})=>f===c.resourceId).map(({address:f})=>f),functions:l}}))}import{uniqueBy as Br,wait as te}from"@latticexyz/common/utils";import re from"p-retry";async function Ye({client:e,worldDeploy:o,systems:r}){let[t,n]=await Promise.all([Ge({client:e,worldDeploy:o}),Y({client:e,worldDeploy:o})]),s=r.map(a=>a.systemId),c=n.filter(({resourceId:a})=>s.includes(a)),i=r.flatMap(a=>a.allowedAddresses.map(g=>({resourceId:a.systemId,address:g}))),p=i.filter(a=>!c.some(({resourceId:g,address:h})=>g===a.resourceId&&A(h)===A(a.address))),l=c.filter(a=>!i.some(({resourceId:g,address:h})=>g===a.resourceId&&A(h)===A(a.address)));l.length&&d("revoking",l.length,"access grants"),p.length&&d("adding",p.length,"access grants");let f=[...l.map(a=>re(()=>oe(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"revokeAccess",args:[a.resourceId,a.address]}),{retries:3,onFailedAttempt:async g=>{let h=g.attemptNumber*500;d(`failed to revoke access, retrying in ${h}ms...`),await te(h)}})),...p.map(a=>re(()=>oe(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"grantAccess",args:[a.resourceId,a.address]}),{retries:3,onFailedAttempt:async g=>{let h=g.attemptNumber*500;d(`failed to grant access, retrying in ${h}ms...`),await te(h)}}))],y=r.filter(a=>t.some(g=>g.systemId===a.systemId&&A(g.address)===A(a.address)));y.length&&d("existing systems",y.map(C).join(", "));let m=y.map(a=>a.systemId),u=r.filter(a=>!m.includes(a.systemId));if(!u.length)return[];let w=u.filter(a=>t.some(g=>g.systemId===a.systemId&&A(g.address)!==A(a.address)));w.length&&d("upgrading systems",w.map(C).join(", "));let b=u.filter(a=>!t.some(g=>g.systemId===a.systemId));b.length&&d("registering new systems",b.map(C).join(", ")),await O({client:e,contracts:Br(u,a=>A(a.address)).map(a=>({bytecode:a.bytecode,deployedBytecodeSize:a.deployedBytecodeSize,label:`${C(a)} system`}))});let x=u.map(a=>re(()=>oe(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerSystem",args:[a.systemId,a.address,a.allowAll]}),{retries:3,onFailedAttempt:async g=>{let h=g.attemptNumber*500;d(`failed to register system ${C(a)}, retrying in ${h}ms...`),await te(h)}}));return await Promise.all([...f,...x])}import{waitForTransactionReceipt as mo}from"viem/actions";import{getAddress as Pr,parseAbi as Mr}from"viem";import{getBlockNumber as Fr,getLogs as Wr}from"viem/actions";var Ze=new Map;async function Qe(e,o){let r=Pr(o),t=Ze.get(r);if(t!=null)return t;d("looking up world deploy for",r);let n=await Fr(e),s=await Wr(e,{strict:!0,address:r,events:Mr(K),fromBlock:"earliest",toBlock:n});return t={...J(s),stateBlock:n},Ze.set(r,t),d("found world deploy for",r,"at block",t.deployBlock),t}import{hexToResource as Rr,writeContract as Xe}from"@latticexyz/common";import eo from"p-retry";import{wait as oo}from"@latticexyz/common/utils";async function to({client:e,worldDeploy:o,functions:r}){let t=await G({client:e,worldDeploy:o}),n=Object.fromEntries(t.map(i=>[i.selector,i])),s=r.filter(i=>n[i.selector]),c=r.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(p=>p.signature).join(", "));let i=s.filter(p=>p.systemId!==n[p.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(p=>p.signature).join(", "))}return c.length?(d("registering functions:",c.map(i=>i.signature).join(", ")),Promise.all(c.map(i=>{let{namespace:p}=Rr(i.systemId);return p===""?eo(()=>Xe(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${f}ms...`),await oo(f)}}):eo(()=>Xe(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${f}ms...`),await oo(f)}})}))):[]}import{BaseError as $r,getAddress as Hr}from"viem";import{writeContract as ro}from"@latticexyz/common";import{isDefined as Er,uniqueBy as Nr,wait as zr}from"@latticexyz/common/utils";import Ur from"p-retry";async function no({client:e,worldDeploy:o,modules:r}){return r.length?(await O({client:e,contracts:Nr(r,t=>Hr(t.address)).map(t=>({bytecode:t.bytecode,deployedBytecodeSize:t.deployedBytecodeSize,label:`${t.name} module`}))}),d("installing modules:",r.map(t=>t.name).join(", ")),(await Promise.all(r.map(t=>Ur(async()=>{try{return t.installAsRoot?await ro(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installRootModule",args:[t.address,t.installData]}):await ro(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installModule",args:[t.address,t.installData]})}catch(n){if(n instanceof $r&&n.message.includes("Module_AlreadyInstalled")){d(`module ${t.name} already installed`);return}throw n}},{retries:3,onFailedAttempt:async n=>{let s=n.attemptNumber*500;d(`failed to install module ${t.name}, retrying in ${s}ms...`),await zr(s)}})))).filter(Er)):[]}import{getAddress as so}from"viem";import{hexToResource as io,resourceToHex as ao,writeContract as Vr}from"@latticexyz/common";async function co({client:e,worldDeploy:o,resourceIds:r}){let t=Array.from(new Set(r.map(y=>io(y).namespace))),n=await q({client:e,worldDeploy:o}),s=new Set(n.map(y=>io(y).namespace));s.size&&d("found",s.size,"existing namespaces:",Array.from(s).map(y=>y===""?"<root>":y).join(", "));let c=t.filter(y=>s.has(y)),p=(await Promise.all(c.map(async y=>{let{owner:m}=await j({client:e,worldDeploy:o,table:T.world_NamespaceOwner,key:{namespaceId:ao({type:"namespace",namespace:y,name:""})}});return[y,m]}))).filter(([,y])=>so(y)!==so(e.account.address)).map(([y])=>y);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`);let l=t.filter(y=>!s.has(y));return l.length>0&&d("registering namespaces",Array.from(l).join(", ")),Promise.all(l.map(y=>Vr(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerNamespace",args:[ao({namespace:y,type:"namespace",name:""})]})))}import{uniqueBy as po}from"@latticexyz/common/utils";async function fo({client:e,config:o,worldAddress:r}){let t=Object.values(o.tables),n=Object.values(o.systems);await Ce(e),await O({client:e,contracts:[...ee,...po(n,m=>lo(m.address)).map(m=>({bytecode:m.bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${C(m)} system`})),...po(o.modules,m=>lo(m.address)).map(m=>({bytecode:m.bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${m.name} module`}))]});let s=r?await Qe(e,r):await Ve(e);if(!De.includes(s.storeVersion))throw new Error(`Unsupported Store version: ${s.storeVersion}`);if(!Te.includes(s.worldVersion))throw new Error(`Unsupported World version: ${s.worldVersion}`);let c=await co({client:e,worldDeploy:s,resourceIds:[...t.map(m=>m.tableId),...n.map(m=>m.systemId)]});d("waiting for all namespace registration transactions to confirm");for(let m of c)await mo(e,{hash:m});let i=await qe({client:e,worldDeploy:s,tables:t}),p=await Ye({client:e,worldDeploy:s,systems:n}),l=await to({client:e,worldDeploy:s,functions:n.flatMap(m=>m.functions)}),f=await no({client:e,worldDeploy:s,modules:o.modules}),y=[...i,...p,...l,...f];d("waiting for all transactions to confirm");for(let m of y)await mo(e,{hash:m});return d("deploy complete"),s}import{createWalletClient as dn,http as ln}from"viem";import{privateKeyToAccount as mn}from"viem/accounts";import{loadConfig as pn}from"@latticexyz/config/node";import{getOutDirectory as fn,getRpcUrl as yn,getSrcDirectory as un}from"@latticexyz/common/foundry";import H from"chalk";import{MUDError as gn}from"@latticexyz/common/errors";import{resolveWorldConfig as Jr}from"@latticexyz/world";import{resourceToHex as ce,hexToResource as qr}from"@latticexyz/common";import{resolveWithContext as Gr}from"@latticexyz/config";import{encodeField as Yr}from"@latticexyz/protocol-parser";import{getFunctionSelector as uo,getCreate2Address as go,getAddress as Zr,hexToBytes as Qr,bytesToHex as Xr,getFunctionSignature as bo}from"viem";import ne from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import se from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import ie from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import{size as ae}from"viem";var yo=[{name:"KeysWithValueModule",abi:ne.abi,bytecode:ne.bytecode.object,deployedBytecodeSize:ae(ne.deployedBytecode.object)},{name:"KeysInTableModule",abi:se.abi,bytecode:se.bytecode.object,deployedBytecodeSize:ae(se.deployedBytecode.object)},{name:"UniqueEntityModule",abi:ie.abi,bytecode:ie.bytecode.object,deployedBytecodeSize:ae(ie.deployedBytecode.object)}];import{readFileSync as _r}from"fs";import Lr from"path";import{MUDError as Z}from"@latticexyz/common/errors";import{size as Kr}from"viem";function Q(e,o){let r,t=Lr.join(o,e+".sol",e+".json");try{r=JSON.parse(_r(t,"utf8"))}catch{throw new Z(`Error reading file at ${t}`)}let n=r?.bytecode?.object;if(!n)throw new Z(`No bytecode found in ${t}`);let s=r?.deployedBytecode?.object;if(!s)throw new Z(`No deployed bytecode found in ${t}`);let c=r?.abi;if(!c)throw new Z(`No ABI found in ${t}`);return{abi:c,bytecode:n,deployedBytecodeSize:Kr(s)}}function ho({config:e,forgeSourceDir:o,forgeOutDir:r}){let t=z(e),n=I(o).map(({basename:m})=>m),s=Jr(e,n),i=Q("System",r).abi.filter(m=>m.type==="function").map(bo),p=Object.entries(s.systems).map(([m,u])=>{let w=e.namespace,b=u.name,x=ce({type:"system",namespace:w,name:b}),a=Q(m,r),g=a.abi.filter(h=>h.type==="function").map(bo).filter(h=>!i.includes(h)).map(h=>{let fe=w===""?h:`${w}_${b}_${h}`;return{signature:fe,selector:uo(fe),systemId:x,systemFunctionSignature:h,systemFunctionSelector:uo(h)}});return{namespace:w,name:b,systemId:x,allowAll:u.openAccess,allowedAddresses:u.accessListAddresses,allowedSystemIds:u.accessListSystems.map(h=>ce({type:"system",namespace:w,name:s.systems[h].name})),address:go({from:S,bytecode:a.bytecode,salt:D}),bytecode:a.bytecode,deployedBytecodeSize:a.deployedBytecodeSize,abi:a.abi,functions:g}}),l=p.map(({allowedAddresses:m,allowedSystemIds:u,...w})=>{let b=u.map(x=>{let a=p.find(g=>g.systemId===x);if(!a)throw new Error(`System ${C(w)} wanted access to ${C(qr(x))}, but it wasn't found in the config.`);return a.address});return{...w,allowedAddresses:Array.from(new Set([...m,...b].map(x=>Zr(x))))}}),f={tableIds:Object.fromEntries(Object.entries(e.tables).map(([m,u])=>[m,Qr(ce({type:u.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:u.name}))]))},y=e.modules.map(m=>{let u=yo.find(b=>b.name===m.name)??Q(m.name,r),w=m.args.map(b=>Gr(b,f)).map(b=>{let x=b.value instanceof Uint8Array?Xr(b.value):b.value;return Yr(b.type,x)});if(w.length>1)throw new Error(`${m.name} module should only have 0-1 args, but had ${w.length} args.`);return{name:m.name,installAsRoot:m.root,installData:w.length===0?"0x":w[0],address:go({from:S,bytecode:u.bytecode,salt:D}),bytecode:u.bytecode,deployedBytecodeSize:u.deployedBytecodeSize,abi:u.abi}});return{tables:t,systems:l,modules:y}}import{getChainId as bn}from"viem/actions";import{existsSync as en}from"fs";import on from"path";import tn from"chalk";import{getScriptDirectory as rn,forge as nn}from"@latticexyz/common/foundry";async function wo(e,o,r,t){let n=on.join(await rn(),e+".s.sol");en(n)?(console.log(tn.blue(`Executing post deploy script at ${n}`)),await nn(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",r,"-vvv"],{profile:t})):console.log(`No script at ${n}, skipping post deploy hook`)}var k={configPath:{type:"string",desc:"Path to the config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},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."},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."}};async function E(e){let o=e.profile??process.env.FOUNDRY_PROFILE,r=await pn(e.configPath);e.printConfig&&console.log(H.green(`
|
7
|
+
Resolved config:
|
8
|
+
`),JSON.stringify(r,null,2));let t=e.srcDir??await un(o),n=await fn(o),s=e.rpc??await yn(o);console.log(H.bgBlue(H.whiteBright(`
|
9
|
+
Deploying MUD contracts${o?" with profile "+o:""} to RPC ${s}
|
10
|
+
`))),e.skipBuild||await L({config:r,srcDir:t,foundryProfile:o});let c=process.env.PRIVATE_KEY;if(!c)throw new gn(`Missing PRIVATE_KEY environment variable.
|
11
|
+
Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
|
12
|
+
in your contracts directory to use the default anvil private key.`);let i=ho({config:r,forgeSourceDir:t,forgeOutDir:n}),p=dn({transport:ln(s),account:mn(c)});console.log("Deploying from",p.account.address);let l=Date.now(),f=await fo({worldAddress:e.worldAddress,client:p,config:i});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await wo(r.postDeployScript,f.address,s,o),console.log(H.green("Deployment completed in",(Date.now()-l)/1e3,"seconds"));let y={worldAddress:f.address,blockNumber:Number(f.deployBlock)};if(e.saveDeployment){let m=await bn(p),u=de.join(r.deploysDirectory,m.toString());an(u,{recursive:!0}),le(de.join(u,"latest.json"),JSON.stringify(y,null,2)),le(de.join(u,Date.now()+".json"),JSON.stringify(y,null,2));let w=[1337,31337],b=sn(r.worldsFile)?JSON.parse(cn(r.worldsFile,"utf-8")):{};b[m]={address:y.worldAddress,blockNumber:w.includes(m)?void 0:y.blockNumber},le(r.worldsFile,JSON.stringify(b,null,2)),console.log(H.bgGreen(H.whiteBright(`
|
13
|
+
Deployment result (written to ${r.worldsFile} and ${u}):
|
14
|
+
`)))}return console.log(y),f}var hn={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(k)},async handler(e){try{await E(e)}catch(o){_(o),process.exit(1)}process.exit(0)}},xo=hn;import{loadConfig as wn}from"@latticexyz/config/node";import{worldgen as xn}from"@latticexyz/world/node";import{getSrcDirectory as Sn}from"@latticexyz/common/foundry";import So from"path";import{rmSync as Cn}from"fs";var vn={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 Dn(e),process.exit(0)}};async function Dn(e){let o=e.srcDir??await Sn(),r=I(o),t=e.config??await wn(e.configPath),n=So.join(o,t.codegenDirectory);e.clean&&Cn(So.join(n,t.worldgenDirectory),{recursive:!0,force:!0}),await xn(t,r,n)}var Co=vn;import V from"chalk";import{readFileSync as On,writeFileSync as jn}from"fs";import pe from"path";import{MUDError as N}from"@latticexyz/common/errors";var vo={name:"@latticexyz/cli",version:"2.0.0-next.16",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",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","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",typescript:"5.1.6",viem:"1.14.0",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};import Bn from"glob";import{ZodError as An,z as Do}from"zod";var kn=Do.object({MUD_PACKAGES:Do.string().transform(e=>JSON.parse(e))});function In(){try{return kn.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/noise":{"localPath":"packages/noise"},"@latticexyz/phaserx":{"localPath":"packages/phaserx"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"@latticexyz/services":{"localPath":"packages/services"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof An){let{_errors:o,...r}=e.format();console.error(`
|
15
|
+
Missing or invalid environment variables:
|
16
|
+
|
17
|
+
${Object.keys(r).join(`
|
18
|
+
`)}
|
19
|
+
`),process.exit(1)}throw e}}var me=In().MUD_PACKAGES;var Pn={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],r=o.reduce((n,s)=>e[s]?n+1:n,0);if(r===0)throw new N(`You need to provide one these options: ${o.join(", ")}`);if(r>1)throw new N(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Mn(e));let t=Bn.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of t)Fn(n,e)}catch(o){_(o)}finally{process.exit(0)}}};async function Mn(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(V.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${vo.name}`)).json()}catch{throw new N("Could not fetch available MUD versions")}if(e.tag){let r=o["dist-tags"][e.tag];if(!r)throw new N(`Could not find npm version with tag "${e.tag}"`);return console.log(V.green(`Latest version with tag ${e.tag}: ${r}`)),r}if(e.commit){let r=e.commit.substring(0,8),t=Object.keys(o.versions).find(n=>n.includes(r));if(!t)throw new N(`Could not find npm version based on commit "${e.commit}"`);return console.log(V.green(`Version from commit ${e.commit}: ${t}`)),t}return e.mudVersion}function Fn(e,o){let{link:r}=o,{mudVersion:t}=o,n=Wn(e),s=Object.keys(me),c={};for(let l in n.dependencies)s.includes(l)&&(c[l]=n.dependencies[l]);let i={};for(let l in n.devDependencies)s.includes(l)&&(i[l]=n.devDependencies[l]);for(let l in n.dependencies)s.includes(l)&&(n.dependencies[l]=p(l,"dependencies"));for(let l in n.devDependencies)s.includes(l)&&(n.devDependencies[l]=p(l,"devDependencies"));return jn(e,JSON.stringify(n,null,2)+`
|
20
|
+
`),console.log(`Updating ${e}`),To(c,n.dependencies),To(i,n.devDependencies),n;function p(l,f){return r&&(t=Rn(e,r,l)),t||n[f][l]}}function Wn(e){try{let o=On(e,"utf8");return JSON.parse(o)}catch{throw new N("Could not read JSON at "+e)}}function To(e,o){for(let r in e)e[r]!==o[r]&&console.log(`${r}: ${V.red(e[r])} -> ${V.green(o[r])}`)}function Rn(e,o,r){let t=pe.relative(pe.dirname(e),process.cwd());return"link:"+pe.join(t,o,me[r].localPath)}var Ao=Pn;import{anvil as $n,forge as Hn,getRpcUrl as En}from"@latticexyz/common/foundry";import Nn from"chalk";var zn={...k,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"}},Un={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(zn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];$n(n)}let o=e.worldAddress?await En(e.profile):`http://127.0.0.1:${e.port}`,r=e.worldAddress??(await E({...e,saveDeployment:!1,rpc:o})).address;console.log(Nn.blue("World address",r));let t=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Hn(["test","--fork-url",o,...t],{profile:e.profile,env:{WORLD_ADDRESS:r}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ko=Un;import{existsSync as Vn,readFileSync as _n}from"fs";import{ethers as Io}from"ethers";import{loadConfig as Ln}from"@latticexyz/config/node";import{MUDError as Oo}from"@latticexyz/common/errors";import{cast as Kn,getRpcUrl as Jn,getSrcDirectory as qn}from"@latticexyz/common/foundry";import{resolveWorldConfig as Gn}from"@latticexyz/world";import Yn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import jo from"@latticexyz/world/mud.config";import{resourceToHex as Po}from"@latticexyz/common";import{createClient as Zn,http as Qn}from"viem";import{getChainId as Xn}from"viem/actions";var Bo=Po({type:"system",namespace:jo.namespace,name:jo.tables.Systems.name}),es={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 qn(o),e.rpc??=await Jn(o);let{tx:r,configPath:t,srcDir:n,rpc:s}=e,c=I(n),i=await Ln(t),p=Gn(i,c.map(({basename:a})=>a)),l=e.worldAddress??await os(i.worldsFile,s),f=new Io.providers.StaticJsonRpcProvider(s),y=new Io.Contract(l,Yn,f),m=i.namespace,u=Object.values(p.systems).map(({name:a})=>a),w=await y.getFieldLayout(Bo),b=[];for(let a of u){let g=Po({type:"system",namespace:m,name:a}),h=await y.getField(Bo,[g],0,w);b.push({name:a,address:h})}let x=await Kn(["run","--label",`${l}:World`,...b.map(({name:a,address:g})=>["--label",`${g}:${a}`]).flat(),`${r}`]);console.log(x),process.exit(0)}},Mo=es;async function os(e,o){if(Vn(e)){let r=Zn({transport:Qn(o)}),t=await Xn(r),n=JSON.parse(_n(e,"utf-8"));if(!n[t])throw new Oo(`chainId ${t} is missing in worldsFile "${e}"`);return n[t].address}else throw new Oo("worldAddress is not specified and worldsFile is missing")}import{anvil as ts,getScriptDirectory as rs,getSrcDirectory as ns}from"@latticexyz/common/foundry";import B from"chalk";import ss from"chokidar";import{loadConfig as is,resolveConfigPath as as}from"@latticexyz/config/node";import cs from"path";import{homedir as ds}from"os";import{rmSync as ls}from"fs";import{BehaviorSubject as ms,debounceTime as ps,exhaustMap as fs,filter as ys}from"rxjs";import{isDefined as us}from"@latticexyz/common/utils";var gs={rpc:k.rpc,configPath:k.configPath,alwaysRunPostDeploy:k.alwaysRunPostDeploy,worldAddress:k.worldAddress},bs={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(gs)},async handler(e){let o=e.rpc,r=e.configPath??await as(e.configPath),t=await ns(),n=await rs(),s=await is(r);if(!e.rpc){console.log(B.gray("Cleaning devnode cache"));let l=ds();ls(cs.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),ts(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let c=new ms(Date.now());ss.watch([r,t,n],{ignoreInitial:!0}).on("all",async(l,f)=>{f.includes(r)&&(console.log(B.blue("Config changed, queuing deploy\u2026")),c.next(Date.now())),(f.includes(t)||f.includes(n))&&(f.includes(s.codegenDirectory)||(console.log(B.blue("Contracts changed, queuing deploy\u2026")),c.next(Date.now())))});let i=e.worldAddress;c.pipe(ps(200),fs(async l=>{i&&console.log(B.blue("Rebuilding and upgrading world\u2026"));try{let f=await E({...e,configPath:r,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:t});return i=f.address,l<c.value?c.next(c.value):console.log(B.gray(`
|
21
|
+
Waiting for file changes\u2026
|
22
|
+
`)),f}catch(f){console.error(B.bgRed(B.whiteBright(`
|
23
|
+
Error while attempting deploy
|
24
|
+
`))),console.error(f),console.log(B.gray(`
|
25
|
+
Waiting for file changes\u2026
|
26
|
+
`))}}),ys(us)).subscribe()}},Fo=bs;var Pp=[ue,xo,ge,he,hs,we,xe,Co,Ao,ko,Mo,Fo,ws];export{Pp as commands};
|
27
|
+
//# sourceMappingURL=commands-DSIRJZEM.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/commands/index.ts","../src/commands/build.ts","../src/build.ts","../src/utils/getExistingContracts.ts","../src/debug.ts","../src/commands/devnode.ts","../src/commands/faucet.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/runDeploy.ts","../src/deploy/deploy.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/deploy/debug.ts","../src/deploy/deployWorld.ts","../src/deploy/ensureWorldFactory.ts","../src/deploy/common.ts","../src/deploy/configToTables.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureContract.ts","../src/deploy/logsToWorldDeploy.ts","../src/deploy/ensureTables.ts","../src/deploy/resourceLabel.ts","../src/deploy/getTables.ts","../src/deploy/ensureSystems.ts","../src/deploy/getResourceIds.ts","../src/deploy/getSystems.ts","../src/deploy/getTableValue.ts","../src/deploy/getFunctions.ts","../src/deploy/getResourceAccess.ts","../src/deploy/getWorldDeploy.ts","../src/deploy/ensureFunctions.ts","../src/deploy/ensureModules.ts","../src/deploy/ensureNamespaceOwner.ts","../src/deploy/resolveConfig.ts","../src/utils/modules/constants.ts","../src/utils/utils/getContractData.ts","../src/utils/utils/postDeploy.ts","../src/commands/deploy.ts","../src/commands/worldgen.ts","../src/commands/set-version.ts","../package.json","../src/mudPackages.ts","../src/commands/test.ts","../src/commands/trace.ts","../src/commands/dev-contracts.ts"],"sourcesContent":["import { CommandModule } from \"yargs\";\n\nimport gasReport from \"@latticexyz/gas-report\";\nimport abiTs from \"@latticexyz/abi-ts\";\n\nimport build from \"./build\";\nimport devnode from \"./devnode\";\nimport faucet from \"./faucet\";\nimport hello from \"./hello\";\nimport tablegen from \"./tablegen\";\nimport deploy from \"./deploy\";\nimport worldgen from \"./worldgen\";\nimport setVersion from \"./set-version\";\nimport test from \"./test\";\nimport trace from \"./trace\";\nimport devContracts from \"./dev-contracts\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each command has different options\nexport const commands: CommandModule<any, any>[] = [\n build,\n deploy,\n devnode,\n faucet,\n gasReport as CommandModule,\n hello,\n tablegen,\n worldgen,\n setVersion,\n test,\n trace,\n devContracts,\n abiTs,\n];\n","import type { CommandModule } from \"yargs\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\n\nimport { getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport { build } from \"../build\";\n\ntype Options = {\n configPath?: string;\n profile?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"build\",\n\n describe: \"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)\",\n\n builder(yargs) {\n return yargs.options({\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n });\n },\n\n async handler({ configPath, profile }) {\n const config = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n const srcDir = await getSrcDirectory();\n\n await build({ config, srcDir, foundryProfile: profile });\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { tablegen } from \"@latticexyz/store/codegen\";\nimport { worldgen } from \"@latticexyz/world/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { forge, getForgeConfig, getRemappings } from \"@latticexyz/common/foundry\";\nimport { getExistingContracts } from \"./utils/getExistingContracts\";\nimport { debug as parentDebug } from \"./debug\";\nimport { execa } from \"execa\";\n\nconst debug = parentDebug.extend(\"runDeploy\");\n\ntype BuildOptions = {\n foundryProfile?: string;\n srcDir: string;\n config: StoreConfig & WorldConfig;\n};\n\nexport async function build({\n config,\n srcDir,\n foundryProfile = process.env.FOUNDRY_PROFILE,\n}: BuildOptions): Promise<void> {\n const outPath = path.join(srcDir, config.codegenDirectory);\n const remappings = await getRemappings(foundryProfile);\n await Promise.all([tablegen(config, outPath, remappings), worldgen(config, getExistingContracts(srcDir), outPath)]);\n\n // TODO remove when https://github.com/foundry-rs/foundry/issues/6241 is resolved\n const forgeConfig = await getForgeConfig(foundryProfile);\n if (forgeConfig.cache) {\n const cacheFilePath = path.join(forgeConfig.cache_path, \"solidity-files-cache.json\");\n if (existsSync(cacheFilePath)) {\n debug(\"Unsetting cached content hash of IWorld.sol to force it to regenerate\");\n const solidityFilesCache = JSON.parse(readFileSync(cacheFilePath, \"utf8\"));\n const worldInterfacePath = path.join(outPath, \"world\", \"IWorld.sol\");\n solidityFilesCache[\"files\"][worldInterfacePath][\"contentHash\"] = \"\";\n writeFileSync(cacheFilePath, JSON.stringify(solidityFilesCache, null, 2));\n }\n }\n\n await forge([\"build\"], { profile: foundryProfile });\n await execa(\"mud\", [\"abi-ts\"], { stdio: \"inherit\" });\n}\n","import glob from \"glob\";\nimport { basename } from \"path\";\n\n/**\n * Get a list of all contract paths/names within the provided src directory\n */\nexport function getExistingContracts(srcDir: string) {\n return glob.sync(`${srcDir}/**/*.sol`).map((path) => ({\n path,\n basename: basename(path, \".sol\"),\n }));\n}\n","import createDebug from \"debug\";\n\nexport const debug = createDebug(\"mud:cli\");\nexport const error = createDebug(\"mud:cli\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { 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\";\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 { getRemappings, 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 const remappings = await getRemappings();\n\n await tablegen(config, path.join(srcDir, config.codegenDirectory), remappings);\n\n process.exit(0);\n },\n};\n\nexport default commandModule;\n","import path from \"node:path\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { InferredOptionTypes, Options } from \"yargs\";\nimport { deploy } from \"./deploy/deploy\";\nimport { createWalletClient, http, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { loadConfig } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { getOutDirectory, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { resolveConfig } from \"./deploy/resolveConfig\";\nimport { getChainId } from \"viem/actions\";\nimport { postDeploy } from \"./utils/utils/postDeploy\";\nimport { WorldDeploy } from \"./deploy/common\";\nimport { build } from \"./build\";\n\nexport const deployOptions = {\n configPath: { type: \"string\", desc: \"Path to the config file\" },\n printConfig: { type: \"boolean\", desc: \"Print the resolved config\" },\n profile: { type: \"string\", desc: \"The foundry profile to use\" },\n saveDeployment: { type: \"boolean\", desc: \"Save the deployment info to a file\", default: true },\n rpc: { type: \"string\", desc: \"The RPC URL to use. Defaults to the RPC url from the local foundry.toml\" },\n 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 skipBuild: { type: \"boolean\", desc: \"Skip rebuilding the contracts before deploying\" },\n alwaysRunPostDeploy: {\n type: \"boolean\",\n desc: \"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed.\",\n },\n} as const satisfies Record<string, Options>;\n\nexport type DeployOptions = InferredOptionTypes<typeof deployOptions>;\n\n/**\n * Given some CLI arguments, finds and resolves a MUD config, foundry profile, and runs a deploy.\n * This is used by the deploy, test, and dev-contracts CLI commands.\n */\nexport async function runDeploy(opts: DeployOptions): Promise<WorldDeploy> {\n const profile = opts.profile ?? process.env.FOUNDRY_PROFILE;\n\n const config = (await loadConfig(opts.configPath)) as StoreConfig & WorldConfig;\n if (opts.printConfig) {\n console.log(chalk.green(\"\\nResolved config:\\n\"), JSON.stringify(config, null, 2));\n }\n\n const srcDir = opts.srcDir ?? (await getSrcDirectory(profile));\n const outDir = await getOutDirectory(profile);\n\n const rpc = opts.rpc ?? (await getRpcUrl(profile));\n console.log(\n chalk.bgBlue(\n chalk.whiteBright(`\\n Deploying MUD contracts${profile ? \" with profile \" + profile : \"\"} to RPC ${rpc} \\n`)\n )\n );\n\n // Run build\n if (!opts.skipBuild) {\n await build({ config, srcDir, foundryProfile: profile });\n }\n\n const privateKey = process.env.PRIVATE_KEY as Hex;\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 }\n\n const resolvedConfig = resolveConfig({ config, forgeSourceDir: srcDir, forgeOutDir: outDir });\n\n const client = createWalletClient({\n transport: http(rpc),\n account: privateKeyToAccount(privateKey),\n });\n console.log(\"Deploying from\", client.account.address);\n\n const startTime = Date.now();\n const worldDeploy = await deploy({\n worldAddress: opts.worldAddress as Hex | undefined,\n client,\n config: resolvedConfig,\n });\n if (opts.worldAddress == null || opts.alwaysRunPostDeploy) {\n await postDeploy(config.postDeployScript, worldDeploy.address, rpc, profile);\n }\n console.log(chalk.green(\"Deployment completed in\", (Date.now() - startTime) / 1000, \"seconds\"));\n\n const deploymentInfo = {\n worldAddress: worldDeploy.address,\n blockNumber: Number(worldDeploy.deployBlock),\n };\n\n if (opts.saveDeployment) {\n const chainId = await getChainId(client);\n const deploysDir = path.join(config.deploysDirectory, chainId.toString());\n mkdirSync(deploysDir, { recursive: true });\n writeFileSync(path.join(deploysDir, \"latest.json\"), JSON.stringify(deploymentInfo, null, 2));\n writeFileSync(path.join(deploysDir, Date.now() + \".json\"), JSON.stringify(deploymentInfo, null, 2));\n\n const localChains = [1337, 31337];\n const deploys = existsSync(config.worldsFile) ? JSON.parse(readFileSync(config.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\n // a consistent address but different block number, we'll ignore the block number.\n blockNumber: localChains.includes(chainId) ? undefined : deploymentInfo.blockNumber,\n };\n writeFileSync(config.worldsFile, JSON.stringify(deploys, null, 2));\n\n console.log(\n chalk.bgGreen(chalk.whiteBright(`\\n Deployment result (written to ${config.worldsFile} and ${deploysDir}): \\n`))\n );\n }\n\n console.log(deploymentInfo);\n\n return worldDeploy;\n}\n","import { Account, Address, Chain, Client, Transport, getAddress } from \"viem\";\nimport { ensureDeployer } from \"./ensureDeployer\";\nimport { deployWorld } from \"./deployWorld\";\nimport { ensureTables } from \"./ensureTables\";\nimport { Config, ConfigInput, WorldDeploy, supportedStoreVersions, supportedWorldVersions } from \"./common\";\nimport { ensureSystems } from \"./ensureSystems\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { getWorldDeploy } from \"./getWorldDeploy\";\nimport { ensureFunctions } from \"./ensureFunctions\";\nimport { ensureModules } from \"./ensureModules\";\nimport { Table } from \"./configToTables\";\nimport { ensureNamespaceOwner } from \"./ensureNamespaceOwner\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\nimport { worldFactoryContracts } from \"./ensureWorldFactory\";\n\ntype DeployOptions<configInput extends ConfigInput> = {\n client: Client<Transport, Chain | undefined, Account>;\n config: Config<configInput>;\n worldAddress?: Address;\n};\n\n/**\n * Given a viem client and MUD config, we attempt to introspect the world\n * (or deploy a new one if no world address is provided) and do the minimal\n * amount of work to make the world match the config (e.g. deploy new tables,\n * replace systems, etc.)\n */\nexport async function deploy<configInput extends ConfigInput>({\n client,\n config,\n worldAddress: existingWorldAddress,\n}: DeployOptions<configInput>): Promise<WorldDeploy> {\n const tables = Object.values(config.tables) as Table[];\n const systems = Object.values(config.systems);\n\n await ensureDeployer(client);\n\n // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.\n await ensureContractsDeployed({\n client,\n contracts: [\n ...worldFactoryContracts,\n ...uniqueBy(systems, (system) => getAddress(system.address)).map((system) => ({\n bytecode: system.bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n label: `${resourceLabel(system)} system`,\n })),\n ...uniqueBy(config.modules, (mod) => getAddress(mod.address)).map((mod) => ({\n bytecode: mod.bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n label: `${mod.name} module`,\n })),\n ],\n });\n\n const worldDeploy = existingWorldAddress\n ? await getWorldDeploy(client, existingWorldAddress)\n : await deployWorld(client);\n\n if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {\n throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);\n }\n if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {\n throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);\n }\n\n const namespaceTxs = await ensureNamespaceOwner({\n client,\n worldDeploy,\n resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],\n });\n\n debug(\"waiting for all namespace registration transactions to confirm\");\n for (const tx of namespaceTxs) {\n await waitForTransactionReceipt(client, { hash: tx });\n }\n\n const tableTxs = await ensureTables({\n client,\n worldDeploy,\n tables,\n });\n const systemTxs = await ensureSystems({\n client,\n worldDeploy,\n systems,\n });\n const functionTxs = await ensureFunctions({\n client,\n worldDeploy,\n functions: systems.flatMap((system) => system.functions),\n });\n const moduleTxs = await ensureModules({\n client,\n worldDeploy,\n modules: config.modules,\n });\n\n const txs = [...tableTxs, ...systemTxs, ...functionTxs, ...moduleTxs];\n\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n debug(\"waiting for all transactions to confirm\");\n for (const tx of txs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\n\n debug(\"deploy complete\");\n return worldDeploy;\n}\n","import { Account, Chain, Client, Transport } from \"viem\";\nimport { getBytecode, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nexport const deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<void> {\n const bytecode = await getBytecode(client, { address: deployer });\n if (bytecode) {\n debug(\"found create2 deployer at\", deployer);\n return;\n }\n\n // send gas to signer\n debug(\"sending gas for create2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice),\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n\n // deploy the deployer\n debug(\"deploying create2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` });\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (deployReceipt.contractAddress !== deployer) {\n console.error(\"unexpected contract address for deployer\", deployReceipt);\n throw new Error(\"unexpected contract address for deployer\");\n }\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\"\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { Account, Chain, Client, Log, Transport } from \"viem\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { ensureWorldFactory, worldFactory } from \"./ensureWorldFactory\";\nimport WorldFactoryAbi from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json\" assert { type: \"json\" };\nimport { writeContract } from \"@latticexyz/common\";\nimport { debug } from \"./debug\";\nimport { logsToWorldDeploy } from \"./logsToWorldDeploy\";\nimport { WorldDeploy } from \"./common\";\n\nexport async function deployWorld(client: Client<Transport, Chain | undefined, Account>): Promise<WorldDeploy> {\n await ensureWorldFactory(client);\n\n debug(\"deploying world\");\n const tx = await writeContract(client, {\n chain: client.chain ?? null,\n address: worldFactory,\n abi: WorldFactoryAbi,\n functionName: \"deployWorld\",\n });\n\n debug(\"waiting for world deploy\");\n const receipt = await waitForTransactionReceipt(client, { hash: tx });\n if (receipt.status !== \"success\") {\n console.error(\"world deploy failed\", receipt);\n throw new Error(\"world deploy failed\");\n }\n\n // TODO: remove type casting once https://github.com/wagmi-dev/viem/pull/1330 is merged\n const deploy = logsToWorldDeploy(receipt.logs.map((log) => log as Log<bigint, number, false>));\n debug(\"deployed world to\", deploy.address, \"at block\", deploy.deployBlock);\n\n return { ...deploy, stateBlock: deploy.deployBlock };\n}\n","import accessManagementSystemBuild from \"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json\" assert { type: \"json\" };\nimport balanceTransferSystemBuild from \"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json\" assert { type: \"json\" };\nimport batchCallSystemBuild from \"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json\" assert { type: \"json\" };\nimport coreRegistrationSystemBuild from \"@latticexyz/world/out/CoreRegistrationSystem.sol/CoreRegistrationSystem.json\" assert { type: \"json\" };\nimport coreModuleBuild from \"@latticexyz/world/out/CoreModule.sol/CoreModule.json\" assert { type: \"json\" };\nimport coreModuleAbi from \"@latticexyz/world/out/CoreModule.sol/CoreModule.abi.json\" assert { type: \"json\" };\nimport worldFactoryBuild from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json\" assert { type: \"json\" };\nimport worldFactoryAbi from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json\" assert { type: \"json\" };\nimport { Client, Transport, Chain, Account, Hex, getCreate2Address, encodeDeployData, size } from \"viem\";\nimport { deployer } from \"./ensureDeployer\";\nimport { salt } from \"./common\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\nimport { Contract } from \"./ensureContract\";\n\nexport const accessManagementSystemDeployedBytecodeSize = size(\n accessManagementSystemBuild.deployedBytecode.object as Hex\n);\nexport const accessManagementSystemBytecode = encodeDeployData({\n bytecode: accessManagementSystemBuild.bytecode.object as Hex,\n abi: [],\n});\nexport const accessManagementSystem = getCreate2Address({\n from: deployer,\n bytecode: accessManagementSystemBytecode,\n salt,\n});\n\nexport const balanceTransferSystemDeployedBytecodeSize = size(\n balanceTransferSystemBuild.deployedBytecode.object as Hex\n);\nexport const balanceTransferSystemBytecode = encodeDeployData({\n bytecode: balanceTransferSystemBuild.bytecode.object as Hex,\n abi: [],\n});\nexport const balanceTransferSystem = getCreate2Address({\n from: deployer,\n bytecode: balanceTransferSystemBytecode,\n salt,\n});\n\nexport const batchCallSystemDeployedBytecodeSize = size(batchCallSystemBuild.deployedBytecode.object as Hex);\nexport const batchCallSystemBytecode = encodeDeployData({\n bytecode: batchCallSystemBuild.bytecode.object as Hex,\n abi: [],\n});\nexport const batchCallSystem = getCreate2Address({ from: deployer, bytecode: batchCallSystemBytecode, salt });\n\nexport const coreRegistrationSystemDeployedBytecodeSize = size(\n coreRegistrationSystemBuild.deployedBytecode.object as Hex\n);\nexport const coreRegistrationSystemBytecode = encodeDeployData({\n bytecode: coreRegistrationSystemBuild.bytecode.object as Hex,\n abi: [],\n});\nexport const coreRegistrationSystem = getCreate2Address({\n from: deployer,\n bytecode: coreRegistrationSystemBytecode,\n salt,\n});\n\nexport const coreModuleDeployedBytecodeSize = size(coreModuleBuild.deployedBytecode.object as Hex);\nexport const coreModuleBytecode = encodeDeployData({\n bytecode: coreModuleBuild.bytecode.object as Hex,\n abi: coreModuleAbi,\n args: [accessManagementSystem, balanceTransferSystem, batchCallSystem, coreRegistrationSystem],\n});\n\nexport const coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });\n\nexport const worldFactoryDeployedBytecodeSize = size(worldFactoryBuild.deployedBytecode.object as Hex);\nexport const worldFactoryBytecode = encodeDeployData({\n bytecode: worldFactoryBuild.bytecode.object as Hex,\n abi: worldFactoryAbi,\n args: [coreModule],\n});\n\nexport const worldFactory = getCreate2Address({ from: deployer, bytecode: worldFactoryBytecode, salt });\n\nexport const worldFactoryContracts: readonly Contract[] = [\n {\n bytecode: accessManagementSystemBytecode,\n deployedBytecodeSize: accessManagementSystemDeployedBytecodeSize,\n label: \"access management system\",\n },\n {\n bytecode: balanceTransferSystemBytecode,\n deployedBytecodeSize: balanceTransferSystemDeployedBytecodeSize,\n label: \"balance transfer system\",\n },\n {\n bytecode: batchCallSystemBytecode,\n deployedBytecodeSize: batchCallSystemDeployedBytecodeSize,\n label: \"batch call system\",\n },\n {\n bytecode: coreRegistrationSystemBytecode,\n deployedBytecodeSize: coreRegistrationSystemDeployedBytecodeSize,\n label: \"core registration system\",\n },\n {\n bytecode: coreModuleBytecode,\n deployedBytecodeSize: coreModuleDeployedBytecodeSize,\n label: \"core module\",\n },\n {\n bytecode: worldFactoryBytecode,\n deployedBytecodeSize: worldFactoryDeployedBytecodeSize,\n label: \"world factory\",\n },\n];\n\nexport async function ensureWorldFactory(\n client: Client<Transport, Chain | undefined, Account>\n): Promise<readonly Hex[]> {\n // WorldFactory constructor doesn't call CoreModule, only sets its address, so we can do these in parallel since the address is deterministic\n return await ensureContractsDeployed({\n client,\n contracts: worldFactoryContracts,\n });\n}\n","import { Abi, Address, Hex, padHex } from \"viem\";\nimport storeConfig from \"@latticexyz/store/mud.config\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\nimport IBaseWorldAbi from \"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json\" assert { type: \"json\" };\nimport IModuleAbi from \"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json\" assert { type: \"json\" };\nimport { Tables, configToTables } from \"./configToTables\";\nimport { StoreConfig, helloStoreEvent } from \"@latticexyz/store\";\nimport { WorldConfig, helloWorldEvent } from \"@latticexyz/world\";\n\nexport const salt = padHex(\"0x\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\n\n// TODO: add `as const` to mud config so these get more strongly typed (blocked by current config parsing not using readonly)\nexport const storeTables = configToTables(storeConfig);\nexport const worldTables = configToTables(worldConfig);\n\nexport const worldDeployEvents = [helloStoreEvent, helloWorldEvent] as const;\n\nexport const worldAbi = [...IBaseWorldAbi, ...IModuleAbi] as const;\n\n// Ideally, this should be an append-only list. Before adding more versions here, be sure to add backwards-compatible support for old Store/World versions.\nexport const supportedStoreVersions = [\"1.0.0-unaudited\"];\nexport const supportedWorldVersions = [\"1.0.0-unaudited\"];\n\nexport type WorldDeploy = {\n readonly address: Address;\n readonly worldVersion: string;\n readonly storeVersion: string;\n /** Block number where the world was deployed */\n readonly deployBlock: bigint;\n /**\n * Block number at the time of fetching world deploy.\n * We use this block number when requesting data from the chain to align chain state\n * with the same block during the introspection steps of the deploy.\n */\n readonly stateBlock: bigint;\n};\n\nexport type WorldFunction = {\n readonly signature: string;\n readonly selector: Hex;\n readonly systemId: Hex;\n readonly systemFunctionSignature: string;\n readonly systemFunctionSelector: Hex;\n};\n\nexport type DeterministicContract = {\n readonly address: Address;\n readonly bytecode: Hex;\n readonly deployedBytecodeSize: number;\n readonly abi: Abi;\n};\n\nexport type System = DeterministicContract & {\n readonly namespace: string;\n readonly name: string;\n readonly systemId: Hex;\n readonly allowAll: boolean;\n readonly allowedAddresses: readonly Hex[];\n readonly functions: readonly WorldFunction[];\n};\n\nexport type Module = DeterministicContract & {\n readonly name: string;\n readonly installAsRoot: boolean;\n readonly installData: Hex; // TODO: figure out better naming for this\n};\n\nexport type ConfigInput = StoreConfig & WorldConfig;\nexport type Config<config extends ConfigInput> = {\n readonly tables: Tables<config>;\n readonly systems: readonly System[];\n readonly modules: readonly Module[];\n};\n","import { resourceToHex } from \"@latticexyz/common\";\nimport { KeySchema, ValueSchema } from \"@latticexyz/protocol-parser\";\nimport { SchemaAbiType, StaticAbiType } from \"@latticexyz/schema-type\";\nimport { StoreConfig, resolveUserTypes } from \"@latticexyz/store\";\nimport { Hex } from \"viem\";\n\n// TODO: we shouldn't need this file once our config parsing returns nicely formed tables\n\ntype UserTypes<config extends StoreConfig = StoreConfig> = config[\"userTypes\"];\n// TODO: fix strong enum types and avoid every schema getting `{ [k: string]: \"uint8\" }`\n// type UserTypes<config extends StoreConfig = StoreConfig> = config[\"userTypes\"] & {\n// [k in keyof config[\"enums\"]]: { internalType: \"uint8\" };\n// };\n\nexport type TableKey<\n config extends StoreConfig = StoreConfig,\n table extends config[\"tables\"][keyof config[\"tables\"]] = config[\"tables\"][keyof config[\"tables\"]]\n> = `${config[\"namespace\"]}_${table[\"name\"]}`;\n\nexport type Table<\n config extends StoreConfig = StoreConfig,\n table extends config[\"tables\"][keyof config[\"tables\"]] = config[\"tables\"][keyof config[\"tables\"]]\n> = {\n readonly namespace: config[\"namespace\"];\n readonly name: table[\"name\"];\n readonly tableId: Hex;\n readonly keySchema: table[\"keySchema\"] extends KeySchema<UserTypes<config>>\n ? KeySchema & {\n readonly [k in keyof table[\"keySchema\"]]: UserTypes<config>[table[\"keySchema\"][k]][\"internalType\"] extends StaticAbiType\n ? UserTypes<config>[table[\"keySchema\"][k]][\"internalType\"]\n : table[\"keySchema\"][k];\n }\n : KeySchema;\n readonly valueSchema: table[\"valueSchema\"] extends ValueSchema<UserTypes<config>>\n ? {\n readonly [k in keyof table[\"valueSchema\"]]: UserTypes<config>[table[\"valueSchema\"][k]][\"internalType\"] extends SchemaAbiType\n ? UserTypes<config>[table[\"valueSchema\"][k]][\"internalType\"]\n : table[\"valueSchema\"][k];\n }\n : ValueSchema;\n};\n\nexport type Tables<config extends StoreConfig = StoreConfig> = {\n readonly [k in keyof config[\"tables\"] as TableKey<config, config[\"tables\"][k]>]: Table<config, config[\"tables\"][k]>;\n};\n\nexport function configToTables<config extends StoreConfig>(config: config): Tables<config> {\n const userTypes = {\n ...config.userTypes,\n ...Object.fromEntries(Object.entries(config.enums).map(([key]) => [key, { internalType: \"uint8\" }] as const)),\n };\n return Object.fromEntries(\n Object.entries(config.tables).map(([tableName, table]) => [\n `${config.namespace}_${tableName}` satisfies TableKey<config, config[\"tables\"][keyof config[\"tables\"]]>,\n {\n namespace: config.namespace,\n name: table.name,\n tableId: resourceToHex({\n type: table.offchainOnly ? \"offchainTable\" : \"table\",\n namespace: config.namespace,\n name: table.name,\n }),\n keySchema: resolveUserTypes(table.keySchema, userTypes) as any,\n valueSchema: resolveUserTypes(table.valueSchema, userTypes) as any,\n } satisfies Table<config, config[\"tables\"][keyof config[\"tables\"]]>,\n ])\n ) as Tables<config>;\n}\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\nimport { debug } from \"./debug\";\nimport { Contract, ensureContract } from \"./ensureContract\";\n\nexport async function ensureContractsDeployed({\n client,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n const txs = (await Promise.all(contracts.map((contract) => ensureContract({ client, ...contract })))).flat();\n\n if (txs.length) {\n debug(\"waiting for contracts\");\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const tx of txs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\n }\n\n return txs;\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex, size } from \"viem\";\nimport { getBytecode } from \"viem/actions\";\nimport { deployer } from \"./ensureDeployer\";\nimport { contractSizeLimit, salt } from \"./common\";\nimport { sendTransaction } from \"@latticexyz/common\";\nimport { debug } from \"./debug\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize: number;\n label?: string;\n};\n\nexport async function ensureContract({\n client,\n bytecode,\n deployedBytecodeSize,\n label = \"contract\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n} & Contract): Promise<readonly Hex[]> {\n const address = getCreate2Address({ from: deployer, salt, bytecode });\n\n const contractCode = await getBytecode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", label, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n `\\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`\n );\n }\n\n debug(\"deploying\", label, \"at\", address);\n return [\n await pRetry(\n () =>\n sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployer,\n data: concatHex([salt, bytecode]),\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to deploy ${label}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n ),\n ];\n}\n","import { AbiEventSignatureNotFoundError, Log, decodeEventLog, hexToString, parseAbi, trim } from \"viem\";\nimport { WorldDeploy, worldDeployEvents } from \"./common\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nexport function logsToWorldDeploy(logs: readonly Log<bigint, number, false>[]): Omit<WorldDeploy, \"stateBlock\"> {\n const deployLogs = logs\n .map((log) => {\n try {\n return {\n ...log,\n ...decodeEventLog({\n strict: true,\n abi: parseAbi(worldDeployEvents),\n topics: log.topics,\n data: log.data,\n }),\n };\n } catch (error: unknown) {\n if (error instanceof AbiEventSignatureNotFoundError) {\n return;\n }\n throw error;\n }\n })\n .filter(isDefined);\n\n // TODO: should this test for/validate that only one of each of these events is present? and that the address/block number don't change between each?\n const { address, deployBlock, worldVersion, storeVersion } = deployLogs.reduce<Partial<WorldDeploy>>(\n (deploy, log) => ({\n ...deploy,\n address: log.address,\n deployBlock: log.blockNumber,\n ...(log.eventName === \"HelloWorld\"\n ? { worldVersion: hexToString(trim(log.args.worldVersion, { dir: \"right\" })) }\n : null),\n ...(log.eventName === \"HelloStore\"\n ? { storeVersion: hexToString(trim(log.args.storeVersion, { dir: \"right\" })) }\n : null),\n }),\n {}\n );\n\n if (address == null) throw new Error(\"could not find world address\");\n if (deployBlock == null) throw new Error(\"could not find world deploy block number\");\n if (worldVersion == null) throw new Error(\"could not find world version\");\n if (storeVersion == null) throw new Error(\"could not find store version\");\n\n return { address, deployBlock, worldVersion, storeVersion };\n}\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { Table } from \"./configToTables\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport { valueSchemaToFieldLayoutHex, keySchemaToHex, valueSchemaToHex } from \"@latticexyz/protocol-parser\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { getTables } from \"./getTables\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\n\nexport async function ensureTables({\n client,\n worldDeploy,\n tables,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly tables: readonly Table[];\n}): Promise<readonly Hex[]> {\n const worldTables = await getTables({ client, worldDeploy });\n const worldTableIds = worldTables.map((table) => table.tableId);\n\n const existingTables = tables.filter((table) => worldTableIds.includes(table.tableId));\n if (existingTables.length) {\n debug(\"existing tables\", existingTables.map(resourceLabel).join(\", \"));\n }\n\n const missingTables = tables.filter((table) => !worldTableIds.includes(table.tableId));\n if (missingTables.length) {\n debug(\"registering tables\", missingTables.map(resourceLabel).join(\", \"));\n return await Promise.all(\n missingTables.map((table) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerTable\",\n args: [\n table.tableId,\n valueSchemaToFieldLayoutHex(table.valueSchema),\n keySchemaToHex(table.keySchema),\n valueSchemaToHex(table.valueSchema),\n Object.keys(table.keySchema),\n Object.keys(table.valueSchema),\n ],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register table ${resourceLabel(table)}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\n )\n );\n }\n\n return [];\n}\n","export function resourceLabel({ namespace, name }: { readonly namespace: string; readonly name: string }): string {\n return `${namespace}:${name}`;\n}\n","import { Client, parseAbiItem, decodeAbiParameters, parseAbiParameters } from \"viem\";\nimport { Table } from \"./configToTables\";\nimport { hexToResource } from \"@latticexyz/common\";\nimport { WorldDeploy, storeTables } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSetRecordEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport { KeySchema, ValueSchema, decodeKey, decodeValueArgs, hexToSchema } from \"@latticexyz/protocol-parser\";\n\nexport async function getTables({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly Table[]> {\n // This assumes we only use `Tables._set(...)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n // TODO: consider moving this to a batched getRecord for Tables table\n\n debug(\"looking up tables for\", worldDeploy.address);\n const logs = await getLogs(client, {\n strict: true,\n // this may fail for certain RPC providers with block range limits\n // if so, could potentially use our fetchLogs helper (which does pagination)\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n event: parseAbiItem(storeSetRecordEvent),\n args: { tableId: storeTables.store_Tables.tableId },\n });\n\n // TODO: combine with store-sync logToTable and export from somewhere\n const tables = logs.map((log) => {\n const { tableId } = decodeKey(storeTables.store_Tables.keySchema, log.args.keyTuple);\n const { namespace, name } = hexToResource(tableId);\n const value = decodeValueArgs(storeTables.store_Tables.valueSchema, log.args);\n\n // TODO: migrate to better helper\n const keySchemaFields = hexToSchema(value.keySchema);\n const valueSchemaFields = hexToSchema(value.valueSchema);\n const keyNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), value.abiEncodedKeyNames)[0];\n const fieldNames = decodeAbiParameters(parseAbiParameters(\"string[]\"), value.abiEncodedFieldNames)[0];\n\n const valueAbiTypes = [...valueSchemaFields.staticFields, ...valueSchemaFields.dynamicFields];\n\n const keySchema = Object.fromEntries(\n keySchemaFields.staticFields.map((abiType, i) => [keyNames[i], abiType])\n ) as KeySchema;\n const valueSchema = Object.fromEntries(valueAbiTypes.map((abiType, i) => [fieldNames[i], abiType])) as ValueSchema;\n\n return { namespace, name, tableId, keySchema, valueSchema } as const;\n });\n // TODO: filter/detect duplicates?\n\n debug(\"found\", tables.length, \"tables for\", worldDeploy.address);\n\n return tables;\n}\n","import { Client, Transport, Chain, Account, Hex, getAddress } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { System, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { getSystems } from \"./getSystems\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport { uniqueBy, wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\n\nexport async function ensureSystems({\n client,\n worldDeploy,\n systems,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly systems: readonly System[];\n}): Promise<readonly Hex[]> {\n const [worldSystems, worldAccess] = await Promise.all([\n getSystems({ client, worldDeploy }),\n getResourceAccess({ client, worldDeploy }),\n ]);\n const systemIds = systems.map((system) => system.systemId);\n const currentAccess = worldAccess.filter(({ resourceId }) => systemIds.includes(resourceId));\n const desiredAccess = systems.flatMap((system) =>\n system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address }))\n );\n\n const accessToAdd = desiredAccess.filter(\n (access) =>\n !currentAccess.some(\n ({ resourceId, address }) =>\n resourceId === access.resourceId && getAddress(address) === getAddress(access.address)\n )\n );\n\n const accessToRemove = currentAccess.filter(\n (access) =>\n !desiredAccess.some(\n ({ resourceId, address }) =>\n resourceId === access.resourceId && getAddress(address) === getAddress(access.address)\n )\n );\n\n // TODO: move each system access+registration to batch call to be atomic\n\n if (accessToRemove.length) {\n debug(\"revoking\", accessToRemove.length, \"access grants\");\n }\n if (accessToAdd.length) {\n debug(\"adding\", accessToAdd.length, \"access grants\");\n }\n\n const accessTxs = [\n ...accessToRemove.map((access) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"revokeAccess\",\n args: [access.resourceId, access.address],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to revoke access, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\n ),\n ...accessToAdd.map((access) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"grantAccess\",\n args: [access.resourceId, access.address],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to grant access, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\n ),\n ];\n\n const existingSystems = systems.filter((system) =>\n worldSystems.some(\n (worldSystem) =>\n worldSystem.systemId === system.systemId && getAddress(worldSystem.address) === getAddress(system.address)\n )\n );\n if (existingSystems.length) {\n debug(\"existing systems\", existingSystems.map(resourceLabel).join(\", \"));\n }\n const existingSystemIds = existingSystems.map((system) => system.systemId);\n\n const missingSystems = systems.filter((system) => !existingSystemIds.includes(system.systemId));\n if (!missingSystems.length) return [];\n\n const systemsToUpgrade = missingSystems.filter((system) =>\n worldSystems.some(\n (worldSystem) =>\n worldSystem.systemId === system.systemId && getAddress(worldSystem.address) !== getAddress(system.address)\n )\n );\n if (systemsToUpgrade.length) {\n debug(\"upgrading systems\", systemsToUpgrade.map(resourceLabel).join(\", \"));\n }\n\n const systemsToAdd = missingSystems.filter(\n (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId)\n );\n if (systemsToAdd.length) {\n debug(\"registering new systems\", systemsToAdd.map(resourceLabel).join(\", \"));\n }\n\n await ensureContractsDeployed({\n client,\n contracts: uniqueBy(missingSystems, (system) => getAddress(system.address)).map((system) => ({\n bytecode: system.bytecode,\n deployedBytecodeSize: system.deployedBytecodeSize,\n label: `${resourceLabel(system)} system`,\n })),\n });\n\n const registerTxs = missingSystems.map((system) =>\n pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerSystem\",\n args: [system.systemId, system.address, system.allowAll],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register system ${resourceLabel(system)}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\n );\n\n return await Promise.all([...accessTxs, ...registerTxs]);\n}\n","import { Client, parseAbiItem, Hex } from \"viem\";\nimport { getLogs } from \"viem/actions\";\nimport { storeSpliceStaticDataEvent } from \"@latticexyz/store\";\nimport { WorldDeploy, storeTables } from \"./common\";\nimport { debug } from \"./debug\";\n\nexport async function getResourceIds({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly Hex[]> {\n // This assumes we only use `ResourceIds._setExists(true)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n\n debug(\"looking up resource IDs for\", worldDeploy.address);\n const logs = await getLogs(client, {\n strict: true,\n address: worldDeploy.address,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n event: parseAbiItem(storeSpliceStaticDataEvent),\n args: { tableId: storeTables.store_ResourceIds.tableId },\n });\n\n const resourceIds = logs.map((log) => log.args.keyTuple[0]);\n debug(\"found\", resourceIds.length, \"resource IDs for\", worldDeploy.address);\n\n return resourceIds;\n}\n","import { System, WorldDeploy, worldTables } from \"./common\";\nimport { Client } from \"viem\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { hexToResource } from \"@latticexyz/common\";\nimport { getTableValue } from \"./getTableValue\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { getFunctions } from \"./getFunctions\";\nimport { getResourceAccess } from \"./getResourceAccess\";\n\nexport async function getSystems({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly Omit<System, \"abi\" | \"bytecode\" | \"deployedBytecodeSize\">[]> {\n const [resourceIds, functions, resourceAccess] = await Promise.all([\n getResourceIds({ client, worldDeploy }),\n getFunctions({ client, worldDeploy }),\n getResourceAccess({ client, worldDeploy }),\n ]);\n const systems = resourceIds.map(hexToResource).filter((resource) => resource.type === \"system\");\n\n debug(\"looking up systems\", systems.map(resourceLabel).join(\", \"));\n return await Promise.all(\n systems.map(async (system) => {\n const { system: address, publicAccess } = await getTableValue({\n client,\n worldDeploy,\n table: worldTables.world_Systems,\n key: { systemId: system.resourceId },\n });\n const systemFunctions = functions.filter((func) => func.systemId === system.resourceId);\n return {\n address,\n namespace: system.namespace,\n name: system.name,\n systemId: system.resourceId,\n allowAll: publicAccess,\n allowedAddresses: resourceAccess\n .filter(({ resourceId }) => resourceId === system.resourceId)\n .map(({ address }) => address),\n functions: systemFunctions,\n };\n })\n );\n}\n","import { SchemaToPrimitives, decodeValueArgs, encodeKey } from \"@latticexyz/protocol-parser\";\nimport { WorldDeploy, worldAbi } from \"./common\";\nimport { Client } from \"viem\";\nimport { readContract } from \"viem/actions\";\nimport { Table } from \"./configToTables\";\n\nexport async function getTableValue<table extends Table>({\n client,\n worldDeploy,\n table,\n key,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n readonly table: table;\n readonly key: SchemaToPrimitives<table[\"keySchema\"]>;\n}): Promise<SchemaToPrimitives<table[\"valueSchema\"]>> {\n const [staticData, encodedLengths, dynamicData] = await readContract(client, {\n blockNumber: worldDeploy.stateBlock,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"getRecord\",\n args: [table.tableId, encodeKey(table.keySchema, key)],\n });\n return decodeValueArgs(table.valueSchema, {\n staticData,\n encodedLengths,\n dynamicData,\n });\n}\n","import { Client, getFunctionSelector, parseAbiItem } from \"viem\";\nimport { WorldDeploy, WorldFunction, worldTables } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSetRecordEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport { decodeValueArgs } from \"@latticexyz/protocol-parser\";\nimport { getTableValue } from \"./getTableValue\";\nimport { hexToResource } from \"@latticexyz/common\";\n\nexport async function getFunctions({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly WorldFunction[]> {\n // This assumes we only use `FunctionSelectors._set(...)`, which is true as of this writing.\n debug(\"looking up function signatures for\", worldDeploy.address);\n const logs = await getLogs(client, {\n strict: true,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n event: parseAbiItem(storeSetRecordEvent),\n args: { tableId: worldTables.world_FunctionSignatures.tableId },\n });\n\n const signatures = logs.map((log) => {\n const value = decodeValueArgs(worldTables.world_FunctionSignatures.valueSchema, log.args);\n return value.functionSignature;\n });\n debug(\"found\", signatures.length, \"function signatures for\", worldDeploy.address);\n\n // TODO: parallelize with a bulk getRecords\n const functions = await Promise.all(\n signatures.map(async (signature) => {\n const selector = getFunctionSelector(signature);\n const { systemId, systemFunctionSelector } = await getTableValue({\n client,\n worldDeploy,\n table: worldTables.world_FunctionSelectors,\n key: { functionSelector: selector },\n });\n const { namespace, name } = hexToResource(systemId);\n // TODO: find away around undoing contract logic (https://github.com/latticexyz/mud/issues/1708)\n const systemFunctionSignature = namespace === \"\" ? signature : signature.replace(`${namespace}_${name}_`, \"\");\n return {\n signature,\n selector,\n systemId,\n systemFunctionSignature,\n systemFunctionSelector,\n };\n })\n );\n\n return functions;\n}\n","import { Client, parseAbiItem, Hex, Address, getAddress } from \"viem\";\nimport { WorldDeploy, worldTables } from \"./common\";\nimport { debug } from \"./debug\";\nimport { storeSpliceStaticDataEvent } from \"@latticexyz/store\";\nimport { getLogs } from \"viem/actions\";\nimport { decodeKey } from \"@latticexyz/protocol-parser\";\nimport { getTableValue } from \"./getTableValue\";\n\nexport async function getResourceAccess({\n client,\n worldDeploy,\n}: {\n readonly client: Client;\n readonly worldDeploy: WorldDeploy;\n}): Promise<readonly { readonly resourceId: Hex; readonly address: Address }[]> {\n // This assumes we only use `ResourceAccess._set(...)`, which is true as of this writing.\n // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state\n\n debug(\"looking up resource access for\", worldDeploy.address);\n\n const logs = await getLogs(client, {\n strict: true,\n fromBlock: worldDeploy.deployBlock,\n toBlock: worldDeploy.stateBlock,\n address: worldDeploy.address,\n // our usage of `ResourceAccess._set(...)` emits a splice instead of set record\n // TODO: https://github.com/latticexyz/mud/issues/479\n event: parseAbiItem(storeSpliceStaticDataEvent),\n args: { tableId: worldTables.world_ResourceAccess.tableId },\n });\n\n const keys = logs.map((log) => decodeKey(worldTables.world_ResourceAccess.keySchema, log.args.keyTuple));\n\n const access = (\n await Promise.all(\n keys.map(\n async (key) =>\n [key, await getTableValue({ client, worldDeploy, table: worldTables.world_ResourceAccess, key })] as const\n )\n )\n )\n .filter(([, value]) => value.access)\n .map(([key]) => ({\n resourceId: key.resourceId,\n address: getAddress(key.caller),\n }));\n\n debug(\"found\", access.length, \"resource<>address access pairs\");\n\n return access;\n}\n","import { Client, Address, getAddress, parseAbi } from \"viem\";\nimport { getBlockNumber, getLogs } from \"viem/actions\";\nimport { WorldDeploy, worldDeployEvents } from \"./common\";\nimport { debug } from \"./debug\";\nimport { logsToWorldDeploy } from \"./logsToWorldDeploy\";\n\nconst deploys = new Map<Address, WorldDeploy>();\n\nexport async function getWorldDeploy(client: Client, worldAddress: Address): Promise<WorldDeploy> {\n const address = getAddress(worldAddress);\n\n let deploy = deploys.get(address);\n if (deploy != null) {\n return deploy;\n }\n\n debug(\"looking up world deploy for\", address);\n\n const stateBlock = await getBlockNumber(client);\n const logs = await getLogs(client, {\n strict: true,\n address,\n events: parseAbi(worldDeployEvents),\n // this may fail for certain RPC providers with block range limits\n // if so, could potentially use our fetchLogs helper (which does pagination)\n fromBlock: \"earliest\",\n toBlock: stateBlock,\n });\n\n deploy = {\n ...logsToWorldDeploy(logs),\n stateBlock,\n };\n deploys.set(address, deploy);\n\n debug(\"found world deploy for\", address, \"at block\", deploy.deployBlock);\n\n return deploy;\n}\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { hexToResource, writeContract } from \"@latticexyz/common\";\nimport { WorldDeploy, WorldFunction, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { getFunctions } from \"./getFunctions\";\nimport pRetry from \"p-retry\";\nimport { wait } from \"@latticexyz/common/utils\";\n\nexport async function ensureFunctions({\n client,\n worldDeploy,\n functions,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly functions: readonly WorldFunction[];\n}): Promise<readonly Hex[]> {\n const worldFunctions = await getFunctions({ client, worldDeploy });\n const worldSelectorToFunction = Object.fromEntries(worldFunctions.map((func) => [func.selector, func]));\n\n const toSkip = functions.filter((func) => worldSelectorToFunction[func.selector]);\n const toAdd = functions.filter((func) => !toSkip.includes(func));\n\n if (toSkip.length) {\n debug(\"functions already registered:\", toSkip.map((func) => func.signature).join(\", \"));\n const wrongSystem = toSkip.filter((func) => func.systemId !== worldSelectorToFunction[func.selector]?.systemId);\n if (wrongSystem.length) {\n console.warn(\n \"found\",\n wrongSystem.length,\n \"functions already registered but pointing at a different system ID:\",\n wrongSystem.map((func) => func.signature).join(\", \")\n );\n }\n }\n\n if (!toAdd.length) return [];\n\n debug(\"registering functions:\", toAdd.map((func) => func.signature).join(\", \"));\n\n return Promise.all(\n toAdd.map((func) => {\n const { namespace } = hexToResource(func.systemId);\n if (namespace === \"\") {\n return pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerRootFunctionSelector\",\n args: [func.systemId, func.systemFunctionSignature, func.systemFunctionSelector],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n );\n }\n return pRetry(\n () =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"registerFunctionSelector\",\n args: [func.systemId, func.systemFunctionSignature],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n );\n })\n );\n}\n","import { Client, Transport, Chain, Account, Hex, BaseError, getAddress } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { isDefined, uniqueBy, wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\n\nexport async function ensureModules({\n client,\n worldDeploy,\n modules,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly modules: readonly Module[];\n}): Promise<readonly Hex[]> {\n if (!modules.length) return [];\n\n await ensureContractsDeployed({\n client,\n contracts: uniqueBy(modules, (mod) => getAddress(mod.address)).map((mod) => ({\n bytecode: mod.bytecode,\n deployedBytecodeSize: mod.deployedBytecodeSize,\n label: `${mod.name} module`,\n })),\n });\n\n debug(\"installing modules:\", modules.map((mod) => mod.name).join(\", \"));\n return (\n await Promise.all(\n modules.map((mod) =>\n pRetry(\n async () => {\n try {\n return mod.installAsRoot\n ? await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"installRootModule\",\n args: [mod.address, mod.installData],\n })\n : await writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)\n functionName: \"installModule\",\n args: [mod.address, mod.installData],\n });\n } catch (error) {\n if (error instanceof BaseError && error.message.includes(\"Module_AlreadyInstalled\")) {\n debug(`module ${mod.name} already installed`);\n return;\n }\n throw error;\n }\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\n )\n )\n ).filter(isDefined);\n}\n","import { Account, Chain, Client, Hex, Transport, getAddress } from \"viem\";\nimport { WorldDeploy, worldAbi, worldTables } from \"./common\";\nimport { hexToResource, resourceToHex, writeContract } from \"@latticexyz/common\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { getTableValue } from \"./getTableValue\";\nimport { debug } from \"./debug\";\n\nexport async function ensureNamespaceOwner({\n client,\n worldDeploy,\n resourceIds,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly worldDeploy: WorldDeploy;\n readonly resourceIds: readonly Hex[];\n}): Promise<readonly Hex[]> {\n const desiredNamespaces = Array.from(new Set(resourceIds.map((resourceId) => hexToResource(resourceId).namespace)));\n const existingResourceIds = await getResourceIds({ client, worldDeploy });\n const existingNamespaces = new Set(existingResourceIds.map((resourceId) => hexToResource(resourceId).namespace));\n if (existingNamespaces.size) {\n debug(\n \"found\",\n existingNamespaces.size,\n \"existing namespaces:\",\n Array.from(existingNamespaces)\n .map((namespace) => (namespace === \"\" ? \"<root>\" : namespace))\n .join(\", \")\n );\n }\n\n // Assert ownership of existing namespaces\n const existingDesiredNamespaces = desiredNamespaces.filter((namespace) => existingNamespaces.has(namespace));\n const namespaceOwners = await Promise.all(\n existingDesiredNamespaces.map(async (namespace) => {\n const { owner } = await getTableValue({\n client,\n worldDeploy,\n table: worldTables.world_NamespaceOwner,\n key: { namespaceId: resourceToHex({ type: \"namespace\", namespace, name: \"\" }) },\n });\n return [namespace, owner];\n })\n );\n\n const unauthorizedNamespaces = namespaceOwners\n .filter(([, owner]) => getAddress(owner) !== getAddress(client.account.address))\n .map(([namespace]) => namespace);\n\n if (unauthorizedNamespaces.length) {\n throw new Error(`You are attempting to deploy to namespaces you do not own: ${unauthorizedNamespaces.join(\", \")}`);\n }\n\n // Register missing namespaces\n const missingNamespaces = desiredNamespaces.filter((namespace) => !existingNamespaces.has(namespace));\n if (missingNamespaces.length > 0) {\n debug(\"registering namespaces\", Array.from(missingNamespaces).join(\", \"));\n }\n const registrationTxs = Promise.all(\n missingNamespaces.map((namespace) =>\n writeContract(client, {\n chain: client.chain ?? null,\n address: worldDeploy.address,\n abi: worldAbi,\n functionName: \"registerNamespace\",\n args: [resourceToHex({ namespace, type: \"namespace\", name: \"\" })],\n })\n )\n );\n\n return registrationTxs;\n}\n","import { resolveWorldConfig } from \"@latticexyz/world\";\nimport { Config, ConfigInput, WorldFunction, salt } from \"./common\";\nimport { resourceToHex, hexToResource } from \"@latticexyz/common\";\nimport { resolveWithContext } from \"@latticexyz/config\";\nimport { encodeField } from \"@latticexyz/protocol-parser\";\nimport { SchemaAbiType, SchemaAbiTypeToPrimitiveType } from \"@latticexyz/schema-type\";\nimport {\n getFunctionSelector,\n Hex,\n getCreate2Address,\n getAddress,\n hexToBytes,\n Abi,\n bytesToHex,\n getFunctionSignature,\n} from \"viem\";\nimport { getExistingContracts } from \"../utils/getExistingContracts\";\nimport { defaultModuleContracts } from \"../utils/modules/constants\";\nimport { getContractData } from \"../utils/utils/getContractData\";\nimport { configToTables } from \"./configToTables\";\nimport { deployer } from \"./ensureDeployer\";\nimport { resourceLabel } from \"./resourceLabel\";\n\n// TODO: this should be replaced by https://github.com/latticexyz/mud/issues/1668\n\nexport function resolveConfig<config extends ConfigInput>({\n config,\n forgeSourceDir,\n forgeOutDir,\n}: {\n config: config;\n forgeSourceDir: string;\n forgeOutDir: string;\n}): Config<config> {\n const tables = configToTables(config);\n\n // TODO: should the config parser/loader help with resolving systems?\n const contractNames = getExistingContracts(forgeSourceDir).map(({ basename }) => basename);\n const resolvedConfig = resolveWorldConfig(config, contractNames);\n const baseSystemContractData = getContractData(\"System\", forgeOutDir);\n const baseSystemFunctions = baseSystemContractData.abi\n .filter((item): item is typeof item & { type: \"function\" } => item.type === \"function\")\n .map(getFunctionSignature);\n\n const systems = Object.entries(resolvedConfig.systems).map(([systemName, system]) => {\n const namespace = config.namespace;\n const name = system.name;\n const systemId = resourceToHex({ type: \"system\", namespace, name });\n const contractData = getContractData(systemName, forgeOutDir);\n\n const systemFunctions = contractData.abi\n .filter((item): item is typeof item & { type: \"function\" } => item.type === \"function\")\n .map(getFunctionSignature)\n .filter((sig) => !baseSystemFunctions.includes(sig))\n .map((sig): WorldFunction => {\n // TODO: figure out how to not duplicate contract behavior (https://github.com/latticexyz/mud/issues/1708)\n const worldSignature = namespace === \"\" ? sig : `${namespace}_${name}_${sig}`;\n return {\n signature: worldSignature,\n selector: getFunctionSelector(worldSignature),\n systemId,\n systemFunctionSignature: sig,\n systemFunctionSelector: getFunctionSelector(sig),\n };\n });\n\n return {\n namespace,\n name,\n systemId,\n allowAll: system.openAccess,\n allowedAddresses: system.accessListAddresses as Hex[],\n allowedSystemIds: system.accessListSystems.map((name) =>\n resourceToHex({ type: \"system\", namespace, name: resolvedConfig.systems[name].name })\n ),\n address: getCreate2Address({ from: deployer, bytecode: contractData.bytecode, salt }),\n bytecode: contractData.bytecode,\n deployedBytecodeSize: contractData.deployedBytecodeSize,\n abi: contractData.abi,\n functions: systemFunctions,\n };\n });\n\n // resolve allowedSystemIds\n // TODO: resolve this at deploy time so we can allow for arbitrary system IDs registered in the world as the source-of-truth rather than config\n const systemsWithAccess = systems.map(({ allowedAddresses, allowedSystemIds, ...system }) => {\n const allowedSystemAddresses = allowedSystemIds.map((systemId) => {\n const targetSystem = systems.find((s) => s.systemId === systemId);\n if (!targetSystem) {\n throw new Error(\n `System ${resourceLabel(system)} wanted access to ${resourceLabel(\n hexToResource(systemId)\n )}, but it wasn't found in the config.`\n );\n }\n return targetSystem.address;\n });\n return {\n ...system,\n allowedAddresses: Array.from(\n new Set([...allowedAddresses, ...allowedSystemAddresses].map((addr) => getAddress(addr)))\n ),\n };\n });\n\n // ugh (https://github.com/latticexyz/mud/issues/1668)\n const resolveContext = {\n tableIds: Object.fromEntries(\n Object.entries(config.tables).map(([tableName, table]) => [\n tableName,\n hexToBytes(\n resourceToHex({\n type: table.offchainOnly ? \"offchainTable\" : \"table\",\n namespace: config.namespace,\n name: table.name,\n })\n ),\n ])\n ),\n };\n\n const modules = config.modules.map((mod) => {\n const contractData =\n defaultModuleContracts.find((defaultMod) => defaultMod.name === mod.name) ??\n getContractData(mod.name, forgeOutDir);\n const installArgs = mod.args\n .map((arg) => resolveWithContext(arg, resolveContext))\n .map((arg) => {\n const value = arg.value instanceof Uint8Array ? bytesToHex(arg.value) : arg.value;\n return encodeField(arg.type as SchemaAbiType, value as SchemaAbiTypeToPrimitiveType<SchemaAbiType>);\n });\n if (installArgs.length > 1) {\n throw new Error(`${mod.name} module should only have 0-1 args, but had ${installArgs.length} args.`);\n }\n return {\n name: mod.name,\n installAsRoot: mod.root,\n installData: installArgs.length === 0 ? \"0x\" : installArgs[0],\n address: getCreate2Address({ from: deployer, bytecode: contractData.bytecode, salt }),\n bytecode: contractData.bytecode,\n deployedBytecodeSize: contractData.deployedBytecodeSize,\n abi: contractData.abi,\n };\n });\n\n return {\n tables,\n systems: systemsWithAccess,\n modules,\n };\n}\n","import KeysWithValueModuleData from \"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json\" assert { type: \"json\" };\nimport KeysInTableModuleData from \"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json\" assert { type: \"json\" };\nimport UniqueEntityModuleData from \"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json\" assert { type: \"json\" };\nimport { Abi, Hex, size } from \"viem\";\n\n// These modules are always deployed\nexport const defaultModuleContracts = [\n {\n name: \"KeysWithValueModule\",\n abi: KeysWithValueModuleData.abi as Abi,\n bytecode: KeysWithValueModuleData.bytecode.object as Hex,\n deployedBytecodeSize: size(KeysWithValueModuleData.deployedBytecode.object as Hex),\n },\n {\n name: \"KeysInTableModule\",\n abi: KeysInTableModuleData.abi as Abi,\n bytecode: KeysInTableModuleData.bytecode.object as Hex,\n deployedBytecodeSize: size(KeysInTableModuleData.deployedBytecode.object as Hex),\n },\n {\n name: \"UniqueEntityModule\",\n abi: UniqueEntityModuleData.abi as Abi,\n bytecode: UniqueEntityModuleData.bytecode.object as Hex,\n deployedBytecodeSize: size(UniqueEntityModuleData.deployedBytecode.object as Hex),\n },\n];\n","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { Abi, Hex, size } from \"viem\";\n\n/**\n * Load the contract's abi and bytecode from the file system\n * @param contractName: Name of the contract to load\n */\nexport function getContractData(\n contractName: string,\n forgeOutDirectory: string\n): { bytecode: Hex; abi: Abi; deployedBytecodeSize: number } {\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 deployedBytecode = data?.deployedBytecode?.object;\n if (!deployedBytecode) throw new MUDError(`No deployed bytecode found in ${contractDataPath}`);\n\n const abi = data?.abi;\n if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);\n\n return { abi, bytecode, deployedBytecodeSize: size(deployedBytecode as Hex) };\n}\n","import { existsSync } from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getScriptDirectory, forge } from \"@latticexyz/common/foundry\";\n\nexport async function postDeploy(\n postDeployScript: string,\n worldAddress: string,\n rpc: string,\n profile: string | undefined\n): Promise<void> {\n // Execute postDeploy forge script\n const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + \".s.sol\");\n if (existsSync(postDeployPath)) {\n console.log(chalk.blue(`Executing post deploy script at ${postDeployPath}`));\n await forge(\n [\"script\", postDeployScript, \"--sig\", \"run(address)\", worldAddress, \"--broadcast\", \"--rpc-url\", rpc, \"-vvv\"],\n {\n profile: profile,\n }\n );\n } else {\n console.log(`No script at ${postDeployPath}, skipping post deploy hook`);\n }\n}\n","import type { CommandModule } from \"yargs\";\nimport { logError } from \"../utils/errors\";\nimport { DeployOptions, deployOptions, runDeploy } from \"../runDeploy\";\n\nconst commandModule: CommandModule<typeof deployOptions, DeployOptions> = {\n command: \"deploy\",\n\n describe: \"Deploy MUD contracts\",\n\n builder(yargs) {\n return yargs.options(deployOptions);\n },\n\n async handler(opts) {\n // Wrap in try/catch, because yargs seems to swallow errors\n try {\n await runDeploy(opts);\n } catch (error: 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/getExistingContracts\";\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 { readFileSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { CommandModule } from \"yargs\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { logError } from \"../utils/errors\";\nimport localPackageJson from \"../../package.json\" assert { type: \"json\" };\nimport glob from \"glob\";\nimport { mudPackages } from \"../mudPackages\";\n\ntype Options = {\n backup?: boolean;\n force?: boolean;\n restore?: boolean;\n mudVersion?: string;\n tag?: string;\n commit?: string;\n link?: string;\n};\n\nconst commandModule: CommandModule<Options, Options> = {\n command: \"set-version\",\n\n describe: \"Set MUD version in all package.json files and optionally backup the previously installed version\",\n\n builder(yargs) {\n return yargs.options({\n mudVersion: { alias: \"v\", type: \"string\", description: \"Set MUD to the given version\" },\n tag: {\n alias: \"t\",\n type: \"string\",\n description: \"Set MUD to the latest version with the given tag from npm\",\n },\n commit: {\n alias: \"c\",\n type: \"string\",\n description: \"Set MUD to the version based on a given git commit hash from npm\",\n },\n link: { alias: \"l\", type: \"string\", description: \"Relative path to the local MUD root directory to link\" },\n });\n },\n\n async handler(options) {\n try {\n const mutuallyExclusiveOptions = [\"mudVersion\", \"link\", \"tag\", \"commit\", \"restore\"];\n const numMutuallyExclusiveOptions = mutuallyExclusiveOptions.reduce(\n (acc, opt) => (options[opt] ? acc + 1 : acc),\n 0\n );\n\n if (numMutuallyExclusiveOptions === 0) {\n throw new MUDError(`You need to provide one these options: ${mutuallyExclusiveOptions.join(\", \")}`);\n }\n\n if (numMutuallyExclusiveOptions > 1) {\n throw new MUDError(`These options are mutually exclusive: ${mutuallyExclusiveOptions.join(\", \")}`);\n }\n\n // If the --link flag is not set, we call resolveVersion to get the version\n // Resolve the version number from available options like `tag` or `commit`\n if (!options.link) {\n options.mudVersion = await resolveVersion(options);\n }\n\n // Update all package.json below the current working directory (except in node_modules)\n const packageJsons = glob.sync(\"**/package.json\").filter((p) => !p.includes(\"node_modules\"));\n for (const packageJson of packageJsons) {\n updatePackageJson(packageJson, options);\n }\n } catch (e) {\n logError(e);\n } finally {\n process.exit(0);\n }\n },\n};\n\nasync function resolveVersion(options: Options) {\n // Backwards compatibility to previous behavior of this script where passing \"canary\" as the version resolved to the latest commit on main\n if (options.mudVersion === \"canary\") options.tag = \"main\";\n\n let npmResult;\n try {\n console.log(chalk.blue(`Fetching available versions`));\n npmResult = await (await fetch(`https://registry.npmjs.org/${localPackageJson.name}`)).json();\n } catch (e) {\n throw new MUDError(`Could not fetch available MUD versions`);\n }\n\n if (options.tag) {\n const version = npmResult[\"dist-tags\"][options.tag];\n if (!version) {\n throw new MUDError(`Could not find npm version with tag \"${options.tag}\"`);\n }\n console.log(chalk.green(`Latest version with tag ${options.tag}: ${version}`));\n return version;\n }\n\n if (options.commit) {\n // Find a version with this commit hash\n const commit = options.commit.substring(0, 8); // changesets uses the first 8 characters of the commit hash as version for prereleases/snapshot releases\n const version = Object.keys(npmResult[\"versions\"]).find((v) => (v as string).includes(commit));\n if (!version) {\n throw new MUDError(`Could not find npm version based on commit \"${options.commit}\"`);\n }\n console.log(chalk.green(`Version from commit ${options.commit}: ${version}`));\n return version;\n }\n\n // If neither a tag nor a commit option is given, return the `mudVersion`\n return options.mudVersion;\n}\n\nfunction updatePackageJson(filePath: string, options: Options): { workspaces?: string[] } {\n const { link } = options;\n let { mudVersion } = options;\n\n const packageJson = readPackageJson(filePath);\n const mudPackageNames = Object.keys(mudPackages);\n\n // Find all MUD dependencies\n const mudDependencies: Record<string, string> = {};\n for (const packageName in packageJson.dependencies) {\n if (mudPackageNames.includes(packageName)) {\n mudDependencies[packageName] = packageJson.dependencies[packageName];\n }\n }\n\n // Find all MUD devDependencies\n const mudDevDependencies: Record<string, string> = {};\n for (const packageName in packageJson.devDependencies) {\n if (mudPackageNames.includes(packageName)) {\n mudDevDependencies[packageName] = packageJson.devDependencies[packageName];\n }\n }\n\n // Update the dependencies\n for (const packageName in packageJson.dependencies) {\n if (mudPackageNames.includes(packageName)) {\n packageJson.dependencies[packageName] = resolveMudVersion(packageName, \"dependencies\");\n }\n }\n\n // Update the devDependencies\n for (const packageName in packageJson.devDependencies) {\n if (mudPackageNames.includes(packageName)) {\n packageJson.devDependencies[packageName] = resolveMudVersion(packageName, \"devDependencies\");\n }\n }\n\n // Write the updated package.json\n writeFileSync(filePath, JSON.stringify(packageJson, null, 2) + \"\\n\");\n\n console.log(`Updating ${filePath}`);\n logComparison(mudDependencies, packageJson.dependencies);\n logComparison(mudDevDependencies, packageJson.devDependencies);\n\n return packageJson;\n\n function resolveMudVersion(key: string, type: \"dependencies\" | \"devDependencies\") {\n if (link) mudVersion = resolveLinkPath(filePath, link, key);\n if (!mudVersion) return packageJson[type][key];\n return mudVersion;\n }\n}\n\nfunction readPackageJson(path: string): {\n workspaces?: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n} {\n try {\n const jsonString = readFileSync(path, \"utf8\");\n return JSON.parse(jsonString);\n } catch {\n throw new MUDError(\"Could not read JSON at \" + path);\n }\n}\n\nfunction logComparison(prev: Record<string, string>, curr: Record<string, string>) {\n for (const key in prev) {\n if (prev[key] !== curr[key]) {\n console.log(`${key}: ${chalk.red(prev[key])} -> ${chalk.green(curr[key])}`);\n }\n }\n}\n\n/**\n * Returns path of the package to link, given a path to a local MUD clone and a package\n */\nfunction resolveLinkPath(packageJsonPath: string, mudLinkPath: string, packageName: string) {\n const packageJsonToRootPath = path.relative(path.dirname(packageJsonPath), process.cwd());\n const linkPath = path.join(packageJsonToRootPath, mudLinkPath, mudPackages[packageName].localPath);\n return \"link:\" + linkPath;\n}\n\nexport default commandModule;\n","{\n \"name\": \"@latticexyz/cli\",\n \"version\": \"2.0.0-next.16\",\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 && pnpm run build:test-tables\",\n \"build:js\": \"tsup && chmod +x ./dist/mud.js\",\n \"build:test-tables\": \"tsx ./scripts/generate-test-tables.ts\",\n \"clean\": \"pnpm run clean:js && pnpm run clean:test-tables\",\n \"clean:js\": \"rimraf dist\",\n \"clean:test-tables\": \"rimraf src/codegen\",\n \"dev\": \"tsup --watch\",\n \"lint\": \"eslint . --ext .ts\",\n \"prepare\": \"mkdir -p ./dist && touch ./dist/mud.js\",\n \"test\": \"tsc --noEmit && forge test\",\n \"test:ci\": \"pnpm run test\"\n },\n \"dependencies\": {\n \"@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/abi-ts\": \"workspace:*\",\n \"@latticexyz/common\": \"workspace:*\",\n \"@latticexyz/config\": \"workspace:*\",\n \"@latticexyz/gas-report\": \"workspace:*\",\n \"@latticexyz/protocol-parser\": \"workspace:*\",\n \"@latticexyz/schema-type\": \"workspace:*\",\n \"@latticexyz/services\": \"workspace:*\",\n \"@latticexyz/store\": \"workspace:*\",\n \"@latticexyz/utils\": \"workspace:*\",\n \"@latticexyz/world\": \"workspace:*\",\n \"@latticexyz/world-modules\": \"workspace:*\",\n \"chalk\": \"^5.0.1\",\n \"chokidar\": \"^3.5.3\",\n \"debug\": \"^4.3.4\",\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 \"p-retry\": \"^5.1.2\",\n \"path\": \"^0.12.7\",\n \"rxjs\": \"7.5.5\",\n \"throttle-debounce\": \"^5.0.0\",\n \"typescript\": \"5.1.6\",\n \"viem\": \"1.14.0\",\n \"yargs\": \"^17.7.1\",\n \"zod\": \"^3.21.4\",\n \"zod-validation-error\": \"^1.3.0\"\n },\n \"devDependencies\": {\n \"@types/debug\": \"^4.1.7\",\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#e282159d5170298eb2455a6c05280ab5a73a4ef0\",\n \"forge-std\": \"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1\",\n \"tsup\": \"^6.7.0\",\n \"tsx\": \"^3.12.6\",\n \"vitest\": \"0.31.4\"\n },\n \"gitHead\": \"914a1e0ae4a573d685841ca2ea921435057deb8f\"\n}\n","import { ZodError, z } from \"zod\";\nimport { MudPackages } from \"./common\";\n\nconst envSchema = z.object({\n MUD_PACKAGES: z.string().transform((value) => JSON.parse(value) as MudPackages),\n});\n\nfunction parseEnv(): z.infer<typeof envSchema> {\n try {\n return envSchema.parse({\n // tsup replaces the env vars with their values at compile time\n MUD_PACKAGES: process.env.MUD_PACKAGES,\n });\n } catch (error) {\n if (error instanceof ZodError) {\n const { _errors, ...invalidEnvVars } = error.format();\n console.error(`\\nMissing or invalid environment variables:\\n\\n ${Object.keys(invalidEnvVars).join(\"\\n \")}\\n`);\n process.exit(1);\n }\n throw error;\n }\n}\n\nexport const mudPackages = parseEnv().MUD_PACKAGES;\n","import type { CommandModule, InferredOptionTypes, Options } from \"yargs\";\nimport { anvil, forge, getRpcUrl } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { deployOptions, runDeploy } from \"../runDeploy\";\n\nconst testOptions = {\n ...deployOptions,\n port: { type: \"number\", description: \"Port to run internal node for fork testing on\", default: 4242 },\n worldAddress: {\n type: \"string\",\n description:\n \"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing.\",\n },\n forgeOptions: { type: \"string\", description: \"Options to pass to forge test\" },\n} as const satisfies Record<string, Options>;\n\ntype TestOptions = InferredOptionTypes<typeof testOptions>;\n\nconst commandModule: CommandModule<typeof testOptions, TestOptions> = {\n command: \"test\",\n\n describe: \"Run tests in MUD contracts\",\n\n builder(yargs) {\n return yargs.options(testOptions);\n },\n\n async handler(opts) {\n // Start an internal anvil process if no world address is provided\n if (!opts.worldAddress) {\n const anvilArgs = [\"--block-base-fee-per-gas\", \"0\", \"--port\", String(opts.port)];\n anvil(anvilArgs);\n }\n\n const forkRpc = opts.worldAddress ? await getRpcUrl(opts.profile) : `http://127.0.0.1:${opts.port}`;\n\n const worldAddress =\n opts.worldAddress ??\n (\n await runDeploy({\n ...opts,\n saveDeployment: false,\n rpc: forkRpc,\n })\n ).address;\n\n console.log(chalk.blue(\"World address\", worldAddress));\n\n const userOptions = opts.forgeOptions?.replaceAll(\"\\\\\", \"\").split(\" \") ?? [];\n try {\n await forge([\"test\", \"--fork-url\", forkRpc, ...userOptions], {\n profile: opts.profile,\n env: {\n WORLD_ADDRESS: worldAddress,\n },\n });\n process.exit(0);\n } catch (e) {\n console.error(e);\n process.exit(1);\n }\n },\n};\n\nexport default commandModule;\n","import { 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 { StoreConfig } from \"@latticexyz/store\";\nimport { resolveWorldConfig, WorldConfig } from \"@latticexyz/world\";\nimport IBaseWorldAbi from \"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json\" assert { type: \"json\" };\nimport worldConfig from \"@latticexyz/world/mud.config\";\nimport { resourceToHex } from \"@latticexyz/common\";\nimport { getExistingContracts } from \"../utils/getExistingContracts\";\nimport { createClient, http } from \"viem\";\nimport { getChainId } from \"viem/actions\";\n\n// TODO account for multiple namespaces (https://github.com/latticexyz/mud/issues/994)\nconst systemsTableId = resourceToHex({\n type: \"system\",\n namespace: worldConfig.namespace,\n name: worldConfig.tables.Systems.name,\n});\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, IBaseWorldAbi, provider);\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 // Fetch system table field layout from chain\n const systemTableFieldLayout = await WorldContract.getFieldLayout(systemsTableId);\n const labels: { name: string; address: string }[] = [];\n for (const name of names) {\n const systemSelector = resourceToHex({ type: \"system\", 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, [systemSelector], 0, systemTableFieldLayout);\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 client = createClient({ transport: http(rpc) });\n const chainId = await getChainId(client);\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, InferredOptionTypes } from \"yargs\";\nimport { anvil, getScriptDirectory, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport chokidar from \"chokidar\";\nimport { loadConfig, resolveConfigPath } from \"@latticexyz/config/node\";\nimport { StoreConfig } from \"@latticexyz/store\";\nimport path from \"path\";\nimport { WorldConfig } from \"@latticexyz/world\";\nimport { homedir } from \"os\";\nimport { rmSync } from \"fs\";\nimport { deployOptions, runDeploy } from \"../runDeploy\";\nimport { BehaviorSubject, debounceTime, exhaustMap, filter } from \"rxjs\";\nimport { Address } from \"viem\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nconst devOptions = {\n rpc: deployOptions.rpc,\n configPath: deployOptions.configPath,\n alwaysRunPostDeploy: deployOptions.alwaysRunPostDeploy,\n worldAddress: deployOptions.worldAddress,\n};\n\nconst commandModule: CommandModule<typeof devOptions, InferredOptionTypes<typeof devOptions>> = {\n command: \"dev-contracts\",\n\n describe: \"Start a development server for MUD contracts\",\n\n builder(yargs) {\n return yargs.options(devOptions);\n },\n\n async handler(opts) {\n let rpc = opts.rpc;\n const configPath = opts.configPath ?? (await resolveConfigPath(opts.configPath));\n const srcDir = await getSrcDirectory();\n const scriptDir = await getScriptDirectory();\n const initialConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;\n\n // Start an anvil instance in the background if no RPC url is provided\n if (!opts.rpc) {\n // Clean anvil cache as 1s block times can fill up the disk\n // - https://github.com/foundry-rs/foundry/issues/3623\n // - https://github.com/foundry-rs/foundry/issues/4989\n // - https://github.com/foundry-rs/foundry/issues/3699\n // - https://github.com/foundry-rs/foundry/issues/3512\n console.log(chalk.gray(\"Cleaning devnode cache\"));\n const userHomeDir = homedir();\n rmSync(path.join(userHomeDir, \".foundry\", \"anvil\", \"tmp\"), { recursive: true, force: true });\n\n const anvilArgs = [\"--block-time\", \"1\", \"--block-base-fee-per-gas\", \"0\"];\n anvil(anvilArgs);\n rpc = \"http://127.0.0.1:8545\";\n }\n\n // Watch for changes\n const lastChange$ = new BehaviorSubject<number>(Date.now());\n chokidar.watch([configPath, srcDir, scriptDir], { ignoreInitial: true }).on(\"all\", async (_, updatePath) => {\n if (updatePath.includes(configPath)) {\n console.log(chalk.blue(\"Config changed, queuing deploy…\"));\n lastChange$.next(Date.now());\n }\n if (updatePath.includes(srcDir) || updatePath.includes(scriptDir)) {\n // Ignore changes to codegen files to avoid an infinite loop\n if (!updatePath.includes(initialConfig.codegenDirectory)) {\n console.log(chalk.blue(\"Contracts changed, queuing deploy…\"));\n lastChange$.next(Date.now());\n }\n }\n });\n\n let worldAddress = opts.worldAddress as Address | undefined;\n\n const deploys$ = lastChange$.pipe(\n // debounce so that a large batch of file changes only triggers a deploy after it settles down, rather than the first change it sees (and then redeploying immediately after)\n debounceTime(200),\n exhaustMap(async (lastChange) => {\n if (worldAddress) {\n console.log(chalk.blue(\"Rebuilding and upgrading world…\"));\n }\n\n try {\n const deploy = await runDeploy({\n ...opts,\n configPath,\n rpc,\n skipBuild: false,\n printConfig: false,\n profile: undefined,\n saveDeployment: true,\n worldAddress,\n srcDir,\n });\n worldAddress = deploy.address;\n // if there were changes while we were deploying, trigger it again\n if (lastChange < lastChange$.value) {\n lastChange$.next(lastChange$.value);\n } else {\n console.log(chalk.gray(\"\\nWaiting for file changes…\\n\"));\n }\n return deploy;\n } catch (error) {\n console.error(chalk.bgRed(chalk.whiteBright(\"\\n Error while attempting deploy \\n\")));\n console.error(error);\n console.log(chalk.gray(\"\\nWaiting for file changes…\\n\"));\n }\n }),\n filter(isDefined)\n );\n\n deploys$.subscribe();\n },\n};\n\nexport default commandModule;\n"],"mappings":"wCAEA,OAAOA,OAAe,yBACtB,OAAOC,OAAW,qBCFlB,OAAS,cAAAC,OAAkB,0BAI3B,OAAS,mBAAAC,OAAuB,6BCLhC,OAAS,cAAAC,GAAY,gBAAAC,GAAc,iBAAAC,OAAqB,UACxD,OAAOC,MAAU,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AA;AAAA,CAA+B,CAAC,CACzD,CACF,CAAC,EACDhB,GAAOC,EAAS,CAClB,EAES,UAAU,CACrB,CACF,EAEO8B,GAAQ3B,G7C/FR,IAAM4B,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EACF","names":["gasReport","abiTs","loadConfig","getSrcDirectory","existsSync","readFileSync","writeFileSync","path","tablegen","worldgen","forge","getForgeConfig","getRemappings","glob","basename","getExistingContracts","srcDir","path","createDebug","debug","error","execa","debug","build","config","srcDir","foundryProfile","outPath","path","remappings","getRemappings","tablegen","worldgen","getExistingContracts","forgeConfig","getForgeConfig","cacheFilePath","existsSync","solidityFilesCache","readFileSync","worldInterfacePath","writeFileSync","forge","commandModule","yargs","configPath","profile","config","loadConfig","srcDir","getSrcDirectory","build","build_default","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","commandModule","yargs","name","greeting","hello_default","path","loadConfig","tablegen","getRemappings","getSrcDirectory","commandModule","yargs","configPath","config","srcDir","remappings","tablegen_default","path","existsSync","mkdirSync","readFileSync","writeFileSync","getAddress","getBytecode","sendRawTransaction","sendTransaction","waitForTransactionReceipt","deployment_default","debug","error","deployer","deployment_default","ensureDeployer","client","getBytecode","debug","gasTx","sendTransaction","gasReceipt","waitForTransactionReceipt","deployTx","sendRawTransaction","deployReceipt","waitForTransactionReceipt","accessManagementSystemBuild","balanceTransferSystemBuild","batchCallSystemBuild","coreRegistrationSystemBuild","coreModuleBuild","coreModuleAbi","worldFactoryBuild","worldFactoryAbi","getCreate2Address","encodeDeployData","size","padHex","storeConfig","worldConfig","IBaseWorldAbi","IModuleAbi","resourceToHex","resolveUserTypes","configToTables","config","userTypes","key","tableName","table","helloStoreEvent","helloWorldEvent","salt","padHex","contractSizeLimit","storeTables","configToTables","storeConfig","worldTables","worldConfig","worldDeployEvents","worldAbi","IBaseWorldAbi","IModuleAbi","supportedStoreVersions","supportedWorldVersions","waitForTransactionReceipt","concatHex","getCreate2Address","getBytecode","sendTransaction","pRetry","wait","ensureContract","client","bytecode","deployedBytecodeSize","label","address","getCreate2Address","deployer","salt","getBytecode","debug","contractSizeLimit","sendTransaction","concatHex","error","delay","ensureContractsDeployed","client","contracts","txs","contract","ensureContract","debug","tx","waitForTransactionReceipt","accessManagementSystemDeployedBytecodeSize","size","accessManagementSystemBuild","accessManagementSystemBytecode","encodeDeployData","accessManagementSystem","getCreate2Address","deployer","salt","balanceTransferSystemDeployedBytecodeSize","balanceTransferSystemBuild","balanceTransferSystemBytecode","balanceTransferSystem","batchCallSystemDeployedBytecodeSize","batchCallSystemBuild","batchCallSystemBytecode","batchCallSystem","coreRegistrationSystemDeployedBytecodeSize","coreRegistrationSystemBuild","coreRegistrationSystemBytecode","coreRegistrationSystem","coreModuleDeployedBytecodeSize","coreModuleBuild","coreModuleBytecode","coreModuleAbi","coreModule","worldFactoryDeployedBytecodeSize","worldFactoryBuild","worldFactoryBytecode","worldFactoryAbi","worldFactory","worldFactoryContracts","ensureWorldFactory","client","ensureContractsDeployed","WorldFactoryAbi","writeContract","AbiEventSignatureNotFoundError","decodeEventLog","hexToString","parseAbi","trim","isDefined","logsToWorldDeploy","logs","deployLogs","log","decodeEventLog","parseAbi","worldDeployEvents","error","AbiEventSignatureNotFoundError","address","deployBlock","worldVersion","storeVersion","deploy","hexToString","trim","deployWorld","client","ensureWorldFactory","debug","tx","writeContract","worldFactory","WorldFactoryAbi","receipt","waitForTransactionReceipt","deploy","logsToWorldDeploy","log","writeContract","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","resourceLabel","namespace","name","parseAbiItem","decodeAbiParameters","parseAbiParameters","hexToResource","storeSetRecordEvent","getLogs","decodeKey","decodeValueArgs","hexToSchema","getTables","client","worldDeploy","debug","tables","parseAbiItem","storeTables","log","tableId","namespace","name","hexToResource","value","keySchemaFields","valueSchemaFields","keyNames","decodeAbiParameters","parseAbiParameters","fieldNames","valueAbiTypes","keySchema","abiType","i","valueSchema","pRetry","wait","ensureTables","client","worldDeploy","tables","worldTableIds","getTables","table","existingTables","debug","resourceLabel","missingTables","writeContract","worldAbi","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","error","delay","getAddress","writeContract","parseAbiItem","getLogs","storeSpliceStaticDataEvent","getResourceIds","client","worldDeploy","debug","resourceIds","getLogs","parseAbiItem","storeSpliceStaticDataEvent","storeTables","log","hexToResource","decodeValueArgs","encodeKey","readContract","getTableValue","client","worldDeploy","table","key","staticData","encodedLengths","dynamicData","worldAbi","encodeKey","decodeValueArgs","getFunctionSelector","parseAbiItem","storeSetRecordEvent","getLogs","decodeValueArgs","hexToResource","getFunctions","client","worldDeploy","debug","signatures","getLogs","parseAbiItem","storeSetRecordEvent","worldTables","log","decodeValueArgs","signature","selector","getFunctionSelector","systemId","systemFunctionSelector","getTableValue","namespace","name","systemFunctionSignature","parseAbiItem","getAddress","storeSpliceStaticDataEvent","getLogs","decodeKey","getResourceAccess","client","worldDeploy","debug","keys","getLogs","parseAbiItem","storeSpliceStaticDataEvent","worldTables","log","decodeKey","access","key","getTableValue","value","getAddress","getSystems","client","worldDeploy","resourceIds","functions","resourceAccess","getResourceIds","getFunctions","getResourceAccess","systems","hexToResource","resource","debug","resourceLabel","system","address","publicAccess","getTableValue","worldTables","systemFunctions","func","resourceId","uniqueBy","wait","pRetry","ensureSystems","client","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","systemIds","system","currentAccess","resourceId","desiredAccess","address","accessToAdd","access","getAddress","accessToRemove","debug","accessTxs","pRetry","writeContract","worldAbi","error","delay","wait","existingSystems","worldSystem","resourceLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","ensureContractsDeployed","uniqueBy","registerTxs","waitForTransactionReceipt","getAddress","parseAbi","getBlockNumber","getLogs","deploys","getWorldDeploy","client","worldAddress","address","getAddress","deploy","debug","stateBlock","getBlockNumber","logs","getLogs","parseAbi","worldDeployEvents","logsToWorldDeploy","hexToResource","writeContract","pRetry","wait","ensureFunctions","client","worldDeploy","functions","worldFunctions","getFunctions","worldSelectorToFunction","func","toSkip","toAdd","debug","wrongSystem","namespace","hexToResource","writeContract","worldAbi","error","delay","BaseError","getAddress","writeContract","isDefined","uniqueBy","wait","pRetry","ensureModules","client","worldDeploy","modules","ensureContractsDeployed","uniqueBy","mod","getAddress","debug","pRetry","writeContract","worldAbi","error","BaseError","delay","wait","isDefined","getAddress","hexToResource","resourceToHex","writeContract","ensureNamespaceOwner","client","worldDeploy","resourceIds","desiredNamespaces","resourceId","hexToResource","existingResourceIds","getResourceIds","existingNamespaces","debug","namespace","existingDesiredNamespaces","unauthorizedNamespaces","owner","getTableValue","worldTables","resourceToHex","getAddress","missingNamespaces","writeContract","worldAbi","uniqueBy","deploy","client","config","existingWorldAddress","tables","systems","ensureDeployer","ensureContractsDeployed","worldFactoryContracts","uniqueBy","system","getAddress","resourceLabel","mod","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","namespaceTxs","ensureNamespaceOwner","table","debug","tx","waitForTransactionReceipt","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","createWalletClient","http","privateKeyToAccount","loadConfig","getOutDirectory","getRpcUrl","getSrcDirectory","chalk","MUDError","resolveWorldConfig","resourceToHex","hexToResource","resolveWithContext","encodeField","getFunctionSelector","getCreate2Address","getAddress","hexToBytes","bytesToHex","getFunctionSignature","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","size","defaultModuleContracts","readFileSync","path","MUDError","size","getContractData","contractName","forgeOutDirectory","data","contractDataPath","bytecode","deployedBytecode","abi","resolveConfig","config","forgeSourceDir","forgeOutDir","tables","configToTables","contractNames","getExistingContracts","basename","resolvedConfig","resolveWorldConfig","baseSystemFunctions","getContractData","item","getFunctionSignature","systems","systemName","system","namespace","name","systemId","resourceToHex","contractData","systemFunctions","sig","worldSignature","getFunctionSelector","getCreate2Address","deployer","salt","systemsWithAccess","allowedAddresses","allowedSystemIds","allowedSystemAddresses","targetSystem","s","resourceLabel","hexToResource","addr","getAddress","resolveContext","tableName","table","hexToBytes","modules","mod","defaultModuleContracts","defaultMod","installArgs","arg","resolveWithContext","value","bytesToHex","encodeField","getChainId","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","postDeployPath","deployOptions","runDeploy","opts","profile","config","loadConfig","chalk","srcDir","getSrcDirectory","outDir","getOutDirectory","rpc","getRpcUrl","build","privateKey","MUDError","resolvedConfig","resolveConfig","client","createWalletClient","http","privateKeyToAccount","startTime","worldDeploy","deploy","postDeploy","deploymentInfo","chainId","getChainId","deploysDir","path","mkdirSync","writeFileSync","localChains","deploys","existsSync","readFileSync","commandModule","yargs","deployOptions","opts","runDeploy","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","readFileSync","writeFileSync","path","MUDError","package_default","glob","ZodError","z","envSchema","value","parseEnv","error","_errors","invalidEnvVars","mudPackages","commandModule","yargs","options","mutuallyExclusiveOptions","numMutuallyExclusiveOptions","acc","opt","MUDError","resolveVersion","packageJsons","glob","p","packageJson","updatePackageJson","e","logError","npmResult","chalk","package_default","version","commit","v","filePath","link","mudVersion","readPackageJson","mudPackageNames","mudPackages","mudDependencies","packageName","mudDevDependencies","resolveMudVersion","writeFileSync","logComparison","key","type","resolveLinkPath","path","jsonString","readFileSync","prev","curr","packageJsonPath","mudLinkPath","packageJsonToRootPath","set_version_default","anvil","forge","getRpcUrl","chalk","testOptions","deployOptions","commandModule","yargs","opts","anvilArgs","anvil","forkRpc","getRpcUrl","worldAddress","runDeploy","chalk","userOptions","forge","e","test_default","existsSync","readFileSync","ethers","loadConfig","MUDError","cast","getRpcUrl","getSrcDirectory","resolveWorldConfig","IBaseWorldAbi","worldConfig","resourceToHex","createClient","http","getChainId","systemsTableId","resourceToHex","worldConfig","commandModule","yargs","args","profile","getSrcDirectory","getRpcUrl","tx","configPath","srcDir","rpc","existingContracts","getExistingContracts","mudConfig","loadConfig","resolvedConfig","resolveWorldConfig","basename","worldAddress","getWorldAddress","provider","ethers","WorldContract","IBaseWorldAbi","namespace","names","name","systemTableFieldLayout","labels","systemSelector","address","result","cast","trace_default","worldsFile","existsSync","client","chainId","deploys","readFileSync","MUDError","anvil","getScriptDirectory","getSrcDirectory","chalk","chokidar","loadConfig","resolveConfigPath","path","homedir","rmSync","BehaviorSubject","debounceTime","exhaustMap","filter","isDefined","devOptions","deployOptions","commandModule","yargs","opts","rpc","configPath","resolveConfigPath","srcDir","getSrcDirectory","scriptDir","getScriptDirectory","initialConfig","loadConfig","chalk","userHomeDir","homedir","rmSync","path","anvil","lastChange$","chokidar","_","updatePath","worldAddress","lastChange","deploy","runDeploy","error","dev_contracts_default","commands","build_default","deploy_default","devnode_default","faucet_default","gasReport","hello_default","tablegen_default","worldgen_default","set_version_default","test_default","trace_default","dev_contracts_default","abiTs"]}
|
package/dist/mud.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-XGN6V2Y3.js"),{commands:t}=await import("./commands-
|
2
|
+
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-XGN6V2Y3.js"),{commands:t}=await import("./commands-DSIRJZEM.js");r(e(process.argv)).scriptName("mud").command(t).strict().fail((a,n)=>{console.error(o.red(a)),a.includes("Missing required argument")&&console.log(o.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),n!=null&&(s(n),console.log("")),process.exit(1)}).alias({h:"help"}).argv}l();
|
3
3
|
//# sourceMappingURL=mud.js.map
|