@latticexyz/cli 2.0.0-next.12 → 2.0.0-next.13

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.
@@ -0,0 +1,4 @@
1
+ import e from"chalk";import{ZodError as s}from"zod";import{fromZodError as i,ValidationError as l}from"zod-validation-error";import{NotInsideProjectError as t}from"@latticexyz/config";import{MUDError as r}from"@latticexyz/common/errors";function p(o){if(o instanceof l)console.log(e.redBright(o.message));else if(o instanceof s){let n=i(o,{prefixSeparator:`
2
+ - `,issueSeparator:`
3
+ - `});console.log(e.redBright(n.message))}else o instanceof t?(console.log(e.red(o.message)),console.log(""),console.log(e.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):o instanceof r?console.log(e.red(o)):console.log(o)}export{p as a};
4
+ //# sourceMappingURL=chunk-22IIKR4S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/errors.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n"],"mappings":"AAAA,OAAOA,MAAW,QAClB,OAAS,YAAAC,MAAgB,MACzB,OAAS,gBAAAC,EAAc,mBAAAC,MAAuB,uBAC9C,OAAS,yBAAAC,MAA6B,qBACtC,OAAS,YAAAC,MAAgB,4BAElB,SAASC,EAASC,EAAgB,CACvC,GAAIA,aAAiBJ,EACnB,QAAQ,IAAIH,EAAM,UAAUO,EAAM,OAAO,CAAC,UACjCA,aAAiBN,EAAU,CAGpC,IAAMO,EAAkBN,EAAaK,EAAO,CAC1C,gBAAiB;AAAA,IACjB,eAAgB;AAAA,GAClB,CAAC,EACD,QAAQ,IAAIP,EAAM,UAAUQ,EAAgB,OAAO,CAAC,OAC3CD,aAAiBH,GAC1B,QAAQ,IAAIJ,EAAM,IAAIO,EAAM,OAAO,CAAC,EACpC,QAAQ,IAAI,EAAE,EAGd,QAAQ,IAAIP,EAAM,KAAK,qFAAqF,CAAC,GACpGO,aAAiBF,EAC1B,QAAQ,IAAIL,EAAM,IAAIO,CAAK,CAAC,EAE5B,QAAQ,IAAIA,CAAK,CAErB","names":["chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError"]}
@@ -0,0 +1,23 @@
1
+ import{a as H}from"./chunk-22IIKR4S.js";import Rn from"@latticexyz/gas-report";import $n from"@latticexyz/abi-ts";import{rmSync as go}from"fs";import{homedir as bo}from"os";import ho from"path";import{execa as wo}from"execa";var xo={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=bo();go(ho.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=wo("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
2
+ gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},se=xo;import{FaucetServiceDefinition as Co}from"@latticexyz/services/faucet";import{createChannel as So,createClient as vo}from"nice-grpc-web";import ae from"chalk";import{NodeHttpTransport as Do}from"@improbable-eng/grpc-web-node-http-transport";function To(e){return vo(Co,So(e,Do()))}var ko={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:t}){let r=To(o);e&&(console.log(ae.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(ae.yellow("Success"))),process.exit(0)}},ie=ko;var Ao={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)}},ce=Ao;import Io from"path";import{loadConfig as Oo}from"@latticexyz/config/node";import{tablegen as Po}from"@latticexyz/store/codegen";import{getRemappings as Mo,getSrcDirectory as Wo}from"@latticexyz/common/foundry";var Fo={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 Oo(e),t=await Wo(),r=await Mo();await Po(o,Io.join(t,o.codegenDirectory),r),process.exit(0)}},de=Fo;import G from"node:path";import{existsSync as br,mkdirSync as hr,readFileSync as wr,writeFileSync as oe}from"node:fs";import{getAddress as Ue}from"viem";import{getBytecode as $o,sendRawTransaction as Eo,sendTransaction as No,waitForTransactionReceipt as me}from"viem/actions";var F={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import Ro from"debug";var le=Ro("mud:cli");var l=le.extend("deploy");var v=`0x${F.address}`;async function pe(e){if(await $o(e,{address:v})){l("found create2 deployer at",v);return}l("sending gas for create2 deployer to signer at",F.signerAddress);let t=await No(e,{chain:e.chain??null,to:`0x${F.signerAddress}`,value:BigInt(F.gasLimit)*BigInt(F.gasPrice)}),r=await me(e,{hash:t});if(r.status!=="success")throw console.error("failed to send gas to deployer signer",r),new Error("failed to send gas to deployer signer");l("deploying create2 deployer at",v);let n=await Eo(e,{serializedTransaction:`0x${F.transaction}`}),s=await me(e,{hash:n});if(s.contractAddress!==v)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as ct}from"viem/actions";import et from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import ot from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as tt,getCreate2Address as be,encodeDeployData as he}from"viem";import{padHex as Ho}from"viem";import Vo from"@latticexyz/store/mud.config.js";import Uo from"@latticexyz/world/mud.config.js";import _o from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Lo from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as Bo}from"@latticexyz/common";import{resolveUserTypes as fe}from"@latticexyz/store";function N(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([t])=>[t,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([t,r])=>[`${e.namespace}_${t}`,{namespace:e.namespace,name:r.name,tableId:Bo({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:fe(r.keySchema,o),valueSchema:fe(r.valueSchema,o)}]))}import{helloStoreEvent as Ko}from"@latticexyz/store";import{helloWorldEvent as zo}from"@latticexyz/world";var k=Ho("0x",{size:32}),j=N(Vo),D=N(Uo),V=[Ko,zo],C=[..._o,...Lo],ue=["1.0.0-unaudited"],ye=["1.0.0-unaudited"];import{waitForTransactionReceipt as Xo}from"viem/actions";import{concatHex as Jo,getCreate2Address as qo}from"viem";import{getBytecode as Go}from"viem/actions";import{sendTransaction as Yo}from"@latticexyz/common";import Zo from"p-retry";import{wait as Qo}from"@latticexyz/common/utils";async function ge({client:e,bytecode:o,label:t="contract"}){let r=qo({from:v,salt:k,bytecode:o});return await Go(e,{address:r,blockTag:"pending"})?(l("found",t,"at",r),[]):(l("deploying",t,"at",r),[await Zo(()=>Yo(e,{chain:e.chain??null,to:v,data:Jo([k,o])}),{retries:3,onFailedAttempt:async s=>{let d=s.attemptNumber*500;l(`failed to deploy ${t}, retrying in ${d}ms...`),await Qo(d)}})])}async function I({client:e,contracts:o}){let t=(await Promise.all(o.map(r=>ge({client:e,...r})))).flat();if(t.length){l("waiting for contracts");for(let r of t)await Xo(e,{hash:r})}return t}var U=he({bytecode:et.bytecode.object,abi:[]}),rt=be({from:v,bytecode:U,salt:k}),_=he({bytecode:ot.bytecode.object,abi:tt(["constructor(address)"]),args:[rt]}),we=be({from:v,bytecode:_,salt:k});async function xe(e){return await I({client:e,contracts:[{bytecode:U,label:"core module"},{bytecode:_,label:"world factory"}]})}import dt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as lt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as nt,decodeEventLog as st,hexToString as Ce,parseAbi as at,trim as Se}from"viem";import{isDefined as it}from"@latticexyz/common/utils";function L(e){let o=e.map(d=>{try{return{...d,...st({strict:!0,abi:at(V),topics:d.topics,data:d.data})}}catch(a){if(a instanceof nt)return;throw a}}).filter(it),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((d,a)=>({...d,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:Ce(Se(a.args.worldVersion,{dir:"right"}))}:null,...a.eventName==="HelloStore"?{storeVersion:Ce(Se(a.args.storeVersion,{dir:"right"}))}:null}),{});if(t==null)throw new Error("could not find world address");if(r==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:t,deployBlock:r,worldVersion:n,storeVersion:s}}async function ve(e){await xe(e),l("deploying world");let o=await lt(e,{chain:e.chain??null,address:we,abi:dt,functionName:"deployWorld"});l("waiting for world deploy");let t=await ct(e,{hash:o});if(t.status!=="success")throw console.error("world deploy failed",t),new Error("world deploy failed");let r=L(t.logs.map(n=>n));return l("deployed world to",r.address,"at block",r.deployBlock),{...r,stateBlock:r.deployBlock}}import{writeContract as bt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as ht,keySchemaToHex as wt,valueSchemaToHex as xt}from"@latticexyz/protocol-parser";function x({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as mt,decodeAbiParameters as De,parseAbiParameters as Te}from"viem";import{hexToResource as pt}from"@latticexyz/common";import{storeSetRecordEvent as ft}from"@latticexyz/store";import{getLogs as ut}from"viem/actions";import{decodeKey as yt,decodeValueArgs as gt,hexToSchema as ke}from"@latticexyz/protocol-parser";async function Ae({client:e,worldDeploy:o}){l("looking up tables for",o.address);let r=(await ut(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:mt(ft),args:{tableId:j.store_Tables.tableId}})).map(n=>{let{tableId:s}=yt(j.store_Tables.keySchema,n.args.keyTuple),{namespace:d,name:a}=pt(s),p=gt(j.store_Tables.valueSchema,n.args),i=ke(p.keySchema),m=ke(p.valueSchema),u=De(Te("string[]"),p.abiEncodedKeyNames)[0],S=De(Te("string[]"),p.abiEncodedFieldNames)[0],f=[...m.staticFields,...m.dynamicFields],g=Object.fromEntries(i.staticFields.map((b,c)=>[u[c],b])),h=Object.fromEntries(f.map((b,c)=>[S[c],b]));return{namespace:d,name:a,tableId:s,keySchema:g,valueSchema:h}});return l("found",r.length,"tables for",o.address),r}import Ct from"p-retry";import{wait as St}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,tables:t}){let n=(await Ae({client:e,worldDeploy:o})).map(a=>a.tableId),s=t.filter(a=>n.includes(a.tableId));s.length&&l("existing tables",s.map(x).join(", "));let d=t.filter(a=>!n.includes(a.tableId));return d.length?(l("registering tables",d.map(x).join(", ")),await Promise.all(d.map(a=>Ct(()=>bt(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerTable",args:[a.tableId,ht(a.valueSchema),wt(a.keySchema),xt(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async p=>{let i=p.attemptNumber*500;l(`failed to register table ${x(a)}, retrying in ${i}ms...`),await St(i)}})))):[]}import{getAddress as A}from"viem";import{writeContract as Y}from"@latticexyz/common";import{parseAbiItem as vt}from"viem";import{getLogs as Dt}from"viem/actions";import{storeSpliceStaticDataEvent as Tt}from"@latticexyz/store";async function K({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let r=(await Dt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:vt(Tt),args:{tableId:j.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return l("found",r.length,"resource IDs for",o.address),r}import{hexToResource as Ht}from"@latticexyz/common";import{decodeValueArgs as kt,encodeKey as At}from"@latticexyz/protocol-parser";import{readContract as It}from"viem/actions";async function O({client:e,worldDeploy:o,table:t,key:r}){let[n,s,d]=await It(e,{blockNumber:o.stateBlock,address:o.address,abi:C,functionName:"getRecord",args:[t.tableId,At(t.keySchema,r)]});return kt(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:d})}import{getFunctionSelector as Ot,parseAbiItem as Pt}from"viem";import{storeSetRecordEvent as Mt}from"@latticexyz/store";import{getLogs as Wt}from"viem/actions";import{decodeValueArgs as Ft}from"@latticexyz/protocol-parser";import{hexToResource as jt}from"@latticexyz/common";async function z({client:e,worldDeploy:o}){l("looking up function signatures for",o.address);let r=(await Wt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Pt(Mt),args:{tableId:D.world_FunctionSignatures.tableId}})).map(s=>Ft(D.world_FunctionSignatures.valueSchema,s.args).functionSignature);return l("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let d=Ot(s),{systemId:a,systemFunctionSelector:p}=await O({client:e,worldDeploy:o,table:D.world_FunctionSelectors,key:{functionSelector:d}}),{namespace:i,name:m}=jt(a),u=i===""?s:s.replace(`${i}_${m}_`,"");return{signature:s,selector:d,systemId:a,systemFunctionSignature:u,systemFunctionSelector:p}}))}import{parseAbiItem as Rt,getAddress as $t}from"viem";import{storeSpliceStaticDataEvent as Et}from"@latticexyz/store";import{getLogs as Nt}from"viem/actions";import{decodeKey as Bt}from"@latticexyz/protocol-parser";async function J({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let r=(await Nt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Rt(Et),args:{tableId:D.world_ResourceAccess.tableId}})).map(s=>Bt(D.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await O({client:e,worldDeploy:o,table:D.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:$t(s.caller)}));return l("found",n.length,"resource<>address access pairs"),n}async function Oe({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([K({client:e,worldDeploy:o}),z({client:e,worldDeploy:o}),J({client:e,worldDeploy:o})]),s=t.map(Ht).filter(d=>d.type==="system");return l("looking up systems",s.map(x).join(", ")),await Promise.all(s.map(async d=>{let{system:a,publicAccess:p}=await O({client:e,worldDeploy:o,table:D.world_Systems,key:{systemId:d.resourceId}}),i=r.filter(m=>m.systemId===d.resourceId);return{address:a,namespace:d.namespace,name:d.name,systemId:d.resourceId,allowAll:p,allowedAddresses:n.filter(({resourceId:m})=>m===d.resourceId).map(({address:m})=>m),functions:i}}))}import{uniqueBy as Vt,wait as Z}from"@latticexyz/common/utils";import Q from"p-retry";async function Pe({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Oe({client:e,worldDeploy:o}),J({client:e,worldDeploy:o})]),s=t.map(c=>c.systemId),d=n.filter(({resourceId:c})=>s.includes(c)),a=t.flatMap(c=>c.allowedAddresses.map(y=>({resourceId:c.systemId,address:y}))),p=a.filter(c=>!d.some(({resourceId:y,address:w})=>y===c.resourceId&&A(w)===A(c.address))),i=d.filter(c=>!a.some(({resourceId:y,address:w})=>y===c.resourceId&&A(w)===A(c.address)));i.length&&l("revoking",i.length,"access grants"),p.length&&l("adding",p.length,"access grants");let m=[...i.map(c=>Q(()=>Y(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"revokeAccess",args:[c.resourceId,c.address]}),{retries:3,onFailedAttempt:async y=>{let w=y.attemptNumber*500;l(`failed to revoke access, retrying in ${w}ms...`),await Z(w)}})),...p.map(c=>Q(()=>Y(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"grantAccess",args:[c.resourceId,c.address]}),{retries:3,onFailedAttempt:async y=>{let w=y.attemptNumber*500;l(`failed to grant access, retrying in ${w}ms...`),await Z(w)}}))],u=t.filter(c=>r.some(y=>y.systemId===c.systemId&&A(y.address)===A(c.address)));u.length&&l("existing systems",u.map(x).join(", "));let S=u.map(c=>c.systemId),f=t.filter(c=>!S.includes(c.systemId));if(!f.length)return[];let g=f.filter(c=>r.some(y=>y.systemId===c.systemId&&A(y.address)!==A(c.address)));g.length&&l("upgrading systems",g.map(x).join(", "));let h=f.filter(c=>!r.some(y=>y.systemId===c.systemId));h.length&&l("registering new systems",h.map(x).join(", ")),await I({client:e,contracts:Vt(f,c=>A(c.address)).map(c=>({bytecode:c.bytecode,label:`${x(c)} system`}))});let b=f.map(c=>Q(()=>Y(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerSystem",args:[c.systemId,c.address,c.allowAll]}),{retries:3,onFailedAttempt:async y=>{let w=y.attemptNumber*500;l(`failed to register system ${x(c)}, retrying in ${w}ms...`),await Z(w)}}));return await Promise.all([...m,...b])}import{waitForTransactionReceipt as er}from"viem/actions";import{getAddress as Ut,parseAbi as _t}from"viem";import{getBlockNumber as Lt,getLogs as Kt}from"viem/actions";var Me=new Map;async function We(e,o){let t=Ut(o),r=Me.get(t);if(r!=null)return r;l("looking up world deploy for",t);let n=await Lt(e),s=await Kt(e,{strict:!0,address:t,events:_t(V),fromBlock:"earliest",toBlock:n});return r={...L(s),stateBlock:n},Me.set(t,r),l("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as zt,writeContract as Fe}from"@latticexyz/common";import je from"p-retry";import{wait as Re}from"@latticexyz/common/utils";async function $e({client:e,worldDeploy:o,functions:t}){let r=await z({client:e,worldDeploy:o}),n=Object.fromEntries(r.map(a=>[a.selector,a])),s=t.filter(a=>n[a.selector]),d=t.filter(a=>!s.includes(a));if(s.length){l("functions already registered:",s.map(p=>p.signature).join(", "));let a=s.filter(p=>p.systemId!==n[p.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(p=>p.signature).join(", "))}return d.length?(l("registering functions:",d.map(a=>a.signature).join(", ")),Promise.all(d.map(a=>{let{namespace:p}=zt(a.systemId);return p===""?je(()=>Fe(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSelector]}),{retries:3,onFailedAttempt:async i=>{let m=i.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${m}ms...`),await Re(m)}}):je(()=>Fe(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async i=>{let m=i.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${m}ms...`),await Re(m)}})}))):[]}import{BaseError as Jt,getAddress as qt}from"viem";import{writeContract as Ee}from"@latticexyz/common";import{isDefined as Gt,uniqueBy as Yt,wait as Zt}from"@latticexyz/common/utils";import Qt from"p-retry";async function Ne({client:e,worldDeploy:o,modules:t}){return t.length?(await I({client:e,contracts:Yt(t,r=>qt(r.address)).map(r=>({bytecode:r.bytecode,label:`${r.name} module`}))}),l("installing modules:",t.map(r=>r.name).join(", ")),(await Promise.all(t.map(r=>Qt(async()=>{try{return r.installAsRoot?await Ee(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"installRootModule",args:[r.address,r.installData]}):await Ee(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"installModule",args:[r.address,r.installData]})}catch(n){if(n instanceof Jt&&n.message.includes("Module_AlreadyInstalled")){l(`module ${r.name} already installed`);return}throw n}},{retries:3,onFailedAttempt:async n=>{let s=n.attemptNumber*500;l(`failed to install module ${r.name}, retrying in ${s}ms...`),await Zt(s)}})))).filter(Gt)):[]}import{getAddress as Be}from"viem";import{hexToResource as He,resourceToHex as Xt}from"@latticexyz/common";async function Ve({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(i=>He(i).namespace))),n=await K({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(i=>He(i).namespace))),d=r.filter(i=>s.includes(i)),p=(await Promise.all(d.map(async i=>{let{owner:m}=await O({client:e,worldDeploy:o,table:D.world_NamespaceOwner,key:{namespaceId:Xt({type:"namespace",namespace:i,name:""})}});return[i,m]}))).filter(([,i])=>Be(i)!==Be(e.account.address)).map(([i])=>i);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`)}import{uniqueBy as _e}from"@latticexyz/common/utils";async function Le({client:e,config:o,worldAddress:t}){let r=Object.values(o.tables),n=Object.values(o.systems);await pe(e),await I({client:e,contracts:[{bytecode:U,label:"core module"},{bytecode:_,label:"world factory"},..._e(n,u=>Ue(u.address)).map(u=>({bytecode:u.bytecode,label:`${x(u)} system`})),..._e(o.modules,u=>Ue(u.address)).map(u=>({bytecode:u.bytecode,label:`${u.name} module`}))]});let s=t?await We(e,t):await ve(e);if(!ue.includes(s.storeVersion))throw new Error(`Unsupported Store version: ${s.storeVersion}`);if(!ye.includes(s.worldVersion))throw new Error(`Unsupported World version: ${s.worldVersion}`);await Ve({client:e,worldDeploy:s,resourceIds:[...r.map(u=>u.tableId),...n.map(u=>u.systemId)]});let d=await Ie({client:e,worldDeploy:s,tables:r}),a=await Pe({client:e,worldDeploy:s,systems:n}),p=await $e({client:e,worldDeploy:s,functions:n.flatMap(u=>u.functions)}),i=await Ne({client:e,worldDeploy:s,modules:o.modules}),m=[...d,...a,...p,...i];l("waiting for all transactions to confirm");for(let u of m)await er(e,{hash:u});return l("deploy complete"),s}import{createWalletClient as xr,http as Cr}from"viem";import{privateKeyToAccount as Sr}from"viem/accounts";import{loadConfig as vr}from"@latticexyz/config/node";import{forge as Dr,getOutDirectory as Tr,getRemappings as kr,getRpcUrl as Ar,getSrcDirectory as Ir}from"@latticexyz/common/foundry";import R from"chalk";import{execa as Or}from"execa";import{MUDError as Pr}from"@latticexyz/common/errors";import{resolveWorldConfig as sr}from"@latticexyz/world";import{resourceToHex as ee,hexToResource as ar}from"@latticexyz/common";import{resolveWithContext as ir}from"@latticexyz/config";import{encodeField as cr}from"@latticexyz/protocol-parser";import{getFunctionSelector as Ge,getCreate2Address as Ye,getAddress as dr,hexToBytes as lr,bytesToHex as mr,getFunctionSignature as Ze}from"viem";import or from"glob";import{basename as tr}from"path";function P(e){return or.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:tr(o,".sol")}))}import Ke from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import ze from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Je from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var qe=[{name:"KeysWithValueModule",abi:Ke.abi,bytecode:Ke.bytecode},{name:"KeysInTableModule",abi:ze.abi,bytecode:ze.bytecode},{name:"UniqueEntityModule",abi:Je.abi,bytecode:Je.bytecode}];import{readFileSync as rr}from"fs";import nr from"path";import{MUDError as X}from"@latticexyz/common/errors";function q(e,o){let t,r=nr.join(o,e+".sol",e+".json");try{t=JSON.parse(rr(r,"utf8"))}catch{throw new X(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new X(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new X(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function Qe({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=N(e),n=P(o).map(({basename:f})=>f),s=sr(e,n),a=q("System",t).abi.filter(f=>f.type==="function").map(Ze),p=Object.entries(s.systems).map(([f,g])=>{let h=e.namespace,b=g.name,c=ee({type:"system",namespace:h,name:b}),y=q(f,t),w=y.abi.filter(T=>T.type==="function").map(Ze).filter(T=>!a.includes(T)).map(T=>{let ne=h===""?T:`${h}_${b}_${T}`;return{signature:ne,selector:Ge(ne),systemId:c,systemFunctionSignature:T,systemFunctionSelector:Ge(T)}});return{namespace:h,name:b,systemId:c,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(T=>ee({type:"system",namespace:h,name:s.systems[T].name})),address:Ye({from:v,bytecode:y.bytecode,salt:k}),bytecode:y.bytecode,abi:y.abi,functions:w}}),i=p.map(({allowedAddresses:f,allowedSystemIds:g,...h})=>{let b=g.map(c=>{let y=p.find(w=>w.systemId===c);if(!y)throw new Error(`System ${x(h)} wanted access to ${x(ar(c))}, but it wasn't found in the config.`);return y.address});return{...h,allowedAddresses:Array.from(new Set([...f,...b].map(c=>dr(c))))}}),m={tableIds:Object.fromEntries(Object.entries(e.tables).map(([f,g])=>[f,lr(ee({type:g.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:g.name}))]))},u=qe.map(f=>({name:f.name,bytecode:typeof f.bytecode=="string"?f.bytecode:f.bytecode.object,abi:f.abi})),S=e.modules.map(f=>{let g=u.find(b=>b.name===f.name)??q(f.name,t),h=f.args.map(b=>ir(b,m)).map(b=>{let c=b.value instanceof Uint8Array?mr(b.value):b.value;return cr(b.type,c)});if(h.length>1)throw new Error(`${f.name} module should only have 0-1 args, but had ${h.length} args.`);return{name:f.name,installAsRoot:f.root,installData:h.length===0?"0x":h[0],address:Ye({from:v,bytecode:g.bytecode,salt:k}),bytecode:g.bytecode,abi:g.abi}});return{tables:r,systems:i,modules:S}}import{getChainId as Mr}from"viem/actions";import{existsSync as pr}from"fs";import fr from"path";import ur from"chalk";import{getScriptDirectory as yr,forge as gr}from"@latticexyz/common/foundry";async function Xe(e,o,t,r){let n=fr.join(await yr(),e+".s.sol");pr(n)?(console.log(ur.blue(`Executing post deploy script at ${n}`)),await gr(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",t,"-vvv"],{profile:r})):console.log(`No script at ${n}, skipping post deploy hook`)}import{tablegen as Wr}from"@latticexyz/store/codegen";import{worldgen as Fr}from"@latticexyz/world/node";var M={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){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await vr(e.configPath);e.printConfig&&console.log(R.green(`
3
+ Resolved config:
4
+ `),JSON.stringify(t,null,2));let r=e.srcDir??await Ir(o),n=await Tr(o),s=await kr(),d=e.rpc??await Ar(o);if(console.log(R.bgBlue(R.whiteBright(`
5
+ Deploying MUD contracts${o?" with profile "+o:""} to RPC ${d}
6
+ `))),!e.skipBuild){let f=G.join(r,t.codegenDirectory);await Promise.all([Wr(t,f,s),Fr(t,P(r),f)]),await Dr(["build"],{profile:o}),await Or("mud",["abi-ts"],{stdio:"inherit"})}let a=process.env.PRIVATE_KEY;if(!a)throw new Pr(`Missing PRIVATE_KEY environment variable.
7
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
8
+ in your contracts directory to use the default anvil private key.`);let p=Qe({config:t,forgeSourceDir:r,forgeOutDir:n}),i=xr({transport:Cr(d),account:Sr(a)});console.log("Deploying from",i.account.address);let m=Date.now(),u=await Le({worldAddress:e.worldAddress,client:i,config:p});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await Xe(t.postDeployScript,u.address,d,o),console.log(R.green("Deployment completed in",(Date.now()-m)/1e3,"seconds"));let S={worldAddress:u.address,blockNumber:Number(u.deployBlock)};if(e.saveDeployment){let f=await Mr(i),g=G.join(t.deploysDirectory,f.toString());hr(g,{recursive:!0}),oe(G.join(g,"latest.json"),JSON.stringify(S,null,2)),oe(G.join(g,Date.now()+".json"),JSON.stringify(S,null,2));let h=[1337,31337],b=br(t.worldsFile)?JSON.parse(wr(t.worldsFile,"utf-8")):{};b[f]={address:S.worldAddress,blockNumber:h.includes(f)?void 0:S.blockNumber},oe(t.worldsFile,JSON.stringify(b,null,2)),console.log(R.bgGreen(R.whiteBright(`
9
+ Deployment result (written to ${t.worldsFile} and ${g}):
10
+ `)))}return console.log(S),u}var jr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await $(e)}catch(o){H(o),process.exit(1)}process.exit(0)}},eo=jr;import{loadConfig as Rr}from"@latticexyz/config/node";import{worldgen as $r}from"@latticexyz/world/node";import{getSrcDirectory as Er}from"@latticexyz/common/foundry";import oo from"path";import{rmSync as Nr}from"fs";var Br={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 Hr(e),process.exit(0)}};async function Hr(e){let o=e.srcDir??await Er(),t=P(o),r=e.config??await Rr(e.configPath),n=oo.join(o,r.codegenDirectory);e.clean&&Nr(oo.join(n,r.worldgenDirectory),{recursive:!0,force:!0}),await $r(r,t,n)}var to=Br;import B from"chalk";import{readFileSync as Kr,writeFileSync as zr}from"fs";import re from"path";import{MUDError as E}from"@latticexyz/common/errors";var ro={name:"@latticexyz/cli",version:"2.0.0-next.13",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 Jr from"glob";import{ZodError as Ur,z as no}from"zod";var _r=no.object({MUD_PACKAGES:no.string().transform(e=>JSON.parse(e))});function Lr(){try{return _r.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 Ur){let{_errors:o,...t}=e.format();console.error(`
11
+ Missing or invalid environment variables:
12
+
13
+ ${Object.keys(t).join(`
14
+ `)}
15
+ `),process.exit(1)}throw e}}var te=Lr().MUD_PACKAGES;var qr={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((n,s)=>e[s]?n+1:n,0);if(t===0)throw new E(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new E(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Gr(e);let r=Jr.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Yr(n,e)}catch(o){H(o)}finally{process.exit(0)}}};async function Gr(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(B.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${ro.name}`)).json()}catch{throw new E("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new E(`Could not find npm version with tag "${e.tag}"`);return console.log(B.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new E(`Could not find npm version based on commit "${e.commit}"`);return console.log(B.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Yr(e,o){let{link:t}=o,{mudVersion:r}=o,n=Zr(e),s=Object.keys(te),d={};for(let i in n.dependencies)s.includes(i)&&(d[i]=n.dependencies[i]);let a={};for(let i in n.devDependencies)s.includes(i)&&(a[i]=n.devDependencies[i]);for(let i in n.dependencies)s.includes(i)&&(n.dependencies[i]=p(i,"dependencies"));for(let i in n.devDependencies)s.includes(i)&&(n.devDependencies[i]=p(i,"devDependencies"));return zr(e,JSON.stringify(n,null,2)+`
16
+ `),console.log(`Updating ${e}`),so(d,n.dependencies),so(a,n.devDependencies),n;function p(i,m){return t&&(r=Qr(e,t,i)),r||n[m][i]}}function Zr(e){try{let o=Kr(e,"utf8");return JSON.parse(o)}catch{throw new E("Could not read JSON at "+e)}}function so(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${B.red(e[t])} -> ${B.green(o[t])}`)}function Qr(e,o,t){let r=re.relative(re.dirname(e),process.cwd());return"link:"+re.join(r,o,te[t].localPath)}var ao=qr;import{anvil as Xr,forge as en,getRpcUrl as on}from"@latticexyz/common/foundry";import tn from"chalk";var rn={...M,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"}},nn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(rn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Xr(n)}let o=e.worldAddress?await on(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await $({...e,saveDeployment:!1,rpc:o})).address;console.log(tn.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await en(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},io=nn;import{existsSync as sn,readFileSync as an}from"fs";import{ethers as co}from"ethers";import{loadConfig as cn}from"@latticexyz/config/node";import{MUDError as lo}from"@latticexyz/common/errors";import{cast as dn,getRpcUrl as ln,getSrcDirectory as mn}from"@latticexyz/common/foundry";import{resolveWorldConfig as pn}from"@latticexyz/world";import fn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import mo from"@latticexyz/world/mud.config.js";import{resourceToHex as fo}from"@latticexyz/common";import{createClient as un,http as yn}from"viem";import{getChainId as gn}from"viem/actions";var po=fo({type:"system",namespace:mo.namespace,name:mo.tables.Systems.name}),bn={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 mn(o),e.rpc??=await ln(o);let{tx:t,configPath:r,srcDir:n,rpc:s}=e,d=P(n),a=await cn(r),p=pn(a,d.map(({basename:c})=>c)),i=e.worldAddress??await hn(a.worldsFile,s),m=new co.providers.StaticJsonRpcProvider(s),u=new co.Contract(i,fn,m),S=a.namespace,f=Object.values(p.systems).map(({name:c})=>c),g=await u.getFieldLayout(po),h=[];for(let c of f){let y=fo({type:"system",namespace:S,name:c}),w=await u.getField(po,[y],0,g);h.push({name:c,address:w})}let b=await dn(["run","--label",`${i}:World`,...h.map(({name:c,address:y})=>["--label",`${y}:${c}`]).flat(),`${t}`]);console.log(b),process.exit(0)}},uo=bn;async function hn(e,o){if(sn(e)){let t=un({transport:yn(o)}),r=await gn(t),n=JSON.parse(an(e,"utf-8"));if(!n[r])throw new lo(`chainId ${r} is missing in worldsFile "${e}"`);return n[r].address}else throw new lo("worldAddress is not specified and worldsFile is missing")}import{anvil as wn,getScriptDirectory as xn,getSrcDirectory as Cn}from"@latticexyz/common/foundry";import W from"chalk";import Sn from"chokidar";import{loadConfig as vn,resolveConfigPath as Dn}from"@latticexyz/config/node";import Tn from"path";import{homedir as kn}from"os";import{rmSync as An}from"fs";import{BehaviorSubject as In,debounceTime as On,exhaustMap as Pn,filter as Mn}from"rxjs";import{isDefined as Wn}from"@latticexyz/common/utils";var Fn={rpc:M.rpc,configPath:M.configPath,alwaysRunPostDeploy:M.alwaysRunPostDeploy},jn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Fn)},async handler(e){let o=e.rpc,t=e.configPath??await Dn(e.configPath),r=await Cn(),n=await xn(),s=await vn(t);if(!e.rpc){console.log(W.gray("Cleaning devnode cache"));let i=kn();An(Tn.join(i,".foundry","anvil","tmp"),{recursive:!0,force:!0}),wn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let d=new In(Date.now());Sn.watch([t,r,n],{ignoreInitial:!0}).on("all",async(i,m)=>{m.includes(t)&&(console.log(W.blue("Config changed, queuing deploy\u2026")),d.next(Date.now())),(m.includes(r)||m.includes(n))&&(m.includes(s.codegenDirectory)||(console.log(W.blue("Contracts changed, queuing deploy\u2026")),d.next(Date.now())))});let a;d.pipe(On(200),Pn(async i=>{a&&console.log(W.blue("Rebuilding and upgrading world\u2026"));try{let m=await $({...e,configPath:t,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:a,srcDir:r});return a=m.address,i<d.value?d.next(d.value):console.log(W.gray(`
17
+ Waiting for file changes\u2026
18
+ `)),m}catch(m){console.error(W.bgRed(W.whiteBright(`
19
+ Error while attempting deploy
20
+ `))),console.error(m),console.log(W.gray(`
21
+ Waiting for file changes\u2026
22
+ `))}}),Mn(Wn)).subscribe()}},yo=jn;var Dm=[eo,se,ie,Rn,ce,de,to,ao,io,uo,yo,$n];export{Dm as commands};
23
+ //# sourceMappingURL=commands-AAHOIIJW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/index.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/debug.ts","../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/assertNamespaceOwner.ts","../src/deploy/resolveConfig.ts","../src/utils/getExistingContracts.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 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 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 { 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 { forge, getOutDirectory, getRemappings, getRpcUrl, getSrcDirectory } from \"@latticexyz/common/foundry\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\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 { tablegen } from \"@latticexyz/store/codegen\";\nimport { worldgen } from \"@latticexyz/world/node\";\nimport { getExistingContracts } from \"./utils/getExistingContracts\";\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 const remappings = await getRemappings();\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 const outPath = path.join(srcDir, config.codegenDirectory);\n await Promise.all([tablegen(config, outPath, remappings), worldgen(config, getExistingContracts(srcDir), outPath)]);\n await forge([\"build\"], { profile });\n await execa(\"mud\", [\"abi-ts\"], { stdio: \"inherit\" });\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 { assertNamespaceOwner } from \"./assertNamespaceOwner\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { ensureContract } from \"./ensureContract\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\nimport { coreModuleBytecode, worldFactoryBytecode } 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 { bytecode: coreModuleBytecode, label: \"core module\" },\n { bytecode: worldFactoryBytecode, label: \"world factory\" },\n ...uniqueBy(systems, (system) => getAddress(system.address)).map((system) => ({\n bytecode: system.bytecode,\n label: `${resourceLabel(system)} system`,\n })),\n ...uniqueBy(config.modules, (mod) => getAddress(mod.address)).map((mod) => ({\n bytecode: mod.bytecode,\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 await assertNamespaceOwner({\n client,\n worldDeploy,\n resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],\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 createDebug from \"debug\";\n\nexport const debug = createDebug(\"mud:cli\");\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\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 coreModuleBuild from \"@latticexyz/world/out/CoreModule.sol/CoreModule.json\" assert { type: \"json\" };\nimport worldFactoryBuild from \"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json\" assert { type: \"json\" };\nimport { Client, Transport, Chain, Account, Hex, parseAbi, getCreate2Address, encodeDeployData } from \"viem\";\nimport { deployer } from \"./ensureDeployer\";\nimport { salt } from \"./common\";\nimport { ensureContractsDeployed } from \"./ensureContractsDeployed\";\n\nexport const coreModuleBytecode = encodeDeployData({\n bytecode: coreModuleBuild.bytecode.object as Hex,\n abi: [],\n});\n\nexport const coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });\n\nexport const worldFactoryBytecode = encodeDeployData({\n bytecode: worldFactoryBuild.bytecode.object as Hex,\n abi: parseAbi([\"constructor(address)\"]),\n args: [coreModule],\n});\n\nexport const worldFactory = getCreate2Address({ from: deployer, bytecode: worldFactoryBytecode, salt });\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: [\n { bytecode: coreModuleBytecode, label: \"core module\" },\n { bytecode: worldFactoryBytecode, label: \"world factory\" },\n ],\n });\n}\n","import { Abi, Address, Hex, padHex } from \"viem\";\nimport storeConfig from \"@latticexyz/store/mud.config.js\";\nimport worldConfig from \"@latticexyz/world/mud.config.js\";\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// 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 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 } from \"viem\";\nimport { getBytecode } from \"viem/actions\";\nimport { deployer } from \"./ensureDeployer\";\nimport { 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 label?: string;\n};\n\nexport async function ensureContract({\n client,\n bytecode,\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 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 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\">[]> {\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 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, worldTables } from \"./common\";\nimport { hexToResource, resourceToHex } from \"@latticexyz/common\";\nimport { getResourceIds } from \"./getResourceIds\";\nimport { getTableValue } from \"./getTableValue\";\n\nexport async function assertNamespaceOwner({\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<void> {\n const desiredNamespaces = Array.from(new Set(resourceIds.map((resourceId) => hexToResource(resourceId).namespace)));\n const existingResourceIds = await getResourceIds({ client, worldDeploy });\n const existingNamespaces = Array.from(\n new Set(existingResourceIds.map((resourceId) => hexToResource(resourceId).namespace))\n );\n\n const namespaces = desiredNamespaces.filter((namespace) => existingNamespaces.includes(namespace));\n const namespaceOwners = await Promise.all(\n namespaces.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","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 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 defaultModules = defaultModuleContracts.map((mod) => ({\n name: mod.name,\n bytecode: (typeof mod.bytecode === \"string\" ? mod.bytecode : mod.bytecode.object) as Hex,\n abi: mod.abi as Abi,\n }));\n\n const modules = config.modules.map((mod) => {\n const contractData =\n defaultModules.find((defaultMod) => defaultMod.name === mod.name) ?? 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 abi: contractData.abi,\n };\n });\n\n return {\n tables,\n systems: systemsWithAccess,\n modules,\n };\n}\n","import glob from \"glob\";\nimport { basename } from \"path\";\n\n/**\n * Get a list of all contract paths/names within the provided src directory\n */\nexport function getExistingContracts(srcDir: string) {\n return glob.sync(`${srcDir}/**/*.sol`).map((path) => ({\n path,\n basename: basename(path, \".sol\"),\n }));\n}\n","import 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\" };\n\n// These modules are always deployed\nexport const defaultModuleContracts = [\n {\n name: \"KeysWithValueModule\",\n abi: KeysWithValueModuleData.abi,\n bytecode: KeysWithValueModuleData.bytecode,\n },\n {\n name: \"KeysInTableModule\",\n abi: KeysInTableModuleData.abi,\n bytecode: KeysInTableModuleData.bytecode,\n },\n {\n name: \"UniqueEntityModule\",\n abi: UniqueEntityModuleData.abi,\n bytecode: UniqueEntityModuleData.bytecode,\n },\n];\n","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { MUDError } from \"@latticexyz/common/errors\";\nimport { Abi, Hex } 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(contractName: string, forgeOutDirectory: string): { bytecode: Hex; abi: Abi } {\n let data: any;\n const contractDataPath = path.join(forgeOutDirectory, contractName + \".sol\", contractName + \".json\");\n try {\n data = JSON.parse(readFileSync(contractDataPath, \"utf8\"));\n } catch (error: any) {\n throw new MUDError(`Error reading file at ${contractDataPath}`);\n }\n\n const bytecode = data?.bytecode?.object;\n if (!bytecode) throw new MUDError(`No bytecode found in ${contractDataPath}`);\n\n const abi = data?.abi;\n if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);\n\n return { abi, bytecode };\n}\n","import { 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 // Resolve the version number from available options like `tag` or `commit`\n options.mudVersion = await resolveVersion(options);\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.13\",\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.js\";\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};\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: 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,qBCHlB,OAAS,UAAAC,OAAc,KACvB,OAAS,WAAAC,OAAe,KACxB,OAAOC,OAAU,OAEjB,OAAS,SAAAC,OAAa,QAMtB,IAAMC,GAAiD,CACrD,QAAS,UAET,SAAU,8CAEV,QAAQC,EAAO,CACb,OAAOA,EAAM,QAAQ,CACnB,UAAW,CAAE,KAAM,SAAU,QAAS,EAAG,KAAM,2CAA4C,CAC7F,CAAC,CACH,EAEA,MAAM,QAAQ,CAAE,UAAAC,CAAU,EAAG,CAC3B,QAAQ,IAAI,0BAA0B,EAC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AAK,IAAI,CAAC,GAGjC,CAAC,EAED,IAAII,EAEaJ,EAAY,KAE3BxB,GAAa,GAAG,EAChBC,GAAW,MAAO4B,GAAe,CAC3BD,GACF,QAAQ,IAAIV,EAAM,KAAK,sCAAiC,CAAC,EAG3D,GAAI,CACF,IAAMY,EAAS,MAAMC,EAAU,CAC7B,GAAGvB,EACH,WAAAE,EACA,IAAAD,EACA,UAAW,GACX,YAAa,GACb,QAAS,OACT,eAAgB,GAChB,aAAAmB,EACA,OAAAhB,CACF,CAAC,EACD,OAAAgB,EAAeE,EAAO,QAElBD,EAAaL,EAAY,MAC3BA,EAAY,KAAKA,EAAY,KAAK,EAElC,QAAQ,IAAIN,EAAM,KAAK;AAAA;AAAA,CAA+B,CAAC,EAElDY,CACT,OAASE,EAAP,CACA,QAAQ,MAAMd,EAAM,MAAMA,EAAM,YAAY;AAAA;AAAA,CAAqC,CAAC,CAAC,EACnF,QAAQ,MAAMc,CAAK,EACnB,QAAQ,IAAId,EAAM,KAAK;AAAA;AAAA,CAA+B,CAAC,CACzD,CACF,CAAC,EACDhB,GAAOC,EAAS,CAClB,EAES,UAAU,CACrB,CACF,EAEO8B,GAAQ3B,G3C/FR,IAAM4B,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EACF","names":["gasReport","abiTs","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","createDebug","debug","debug","deployer","deployment_default","ensureDeployer","client","getBytecode","debug","gasTx","sendTransaction","gasReceipt","waitForTransactionReceipt","deployTx","sendRawTransaction","deployReceipt","waitForTransactionReceipt","coreModuleBuild","worldFactoryBuild","parseAbi","getCreate2Address","encodeDeployData","padHex","storeConfig","worldConfig","IBaseWorldAbi","IModuleAbi","resourceToHex","resolveUserTypes","configToTables","config","userTypes","key","tableName","table","helloStoreEvent","helloWorldEvent","salt","padHex","storeTables","configToTables","storeConfig","worldTables","worldConfig","worldDeployEvents","worldAbi","IBaseWorldAbi","IModuleAbi","supportedStoreVersions","supportedWorldVersions","waitForTransactionReceipt","concatHex","getCreate2Address","getBytecode","sendTransaction","pRetry","wait","ensureContract","client","bytecode","label","address","getCreate2Address","deployer","salt","getBytecode","debug","sendTransaction","concatHex","error","delay","ensureContractsDeployed","client","contracts","txs","contract","ensureContract","debug","tx","waitForTransactionReceipt","coreModuleBytecode","encodeDeployData","coreModuleBuild","coreModule","getCreate2Address","deployer","salt","worldFactoryBytecode","worldFactoryBuild","parseAbi","worldFactory","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","assertNamespaceOwner","client","worldDeploy","resourceIds","desiredNamespaces","resourceId","hexToResource","existingResourceIds","getResourceIds","existingNamespaces","namespaces","namespace","unauthorizedNamespaces","owner","getTableValue","worldTables","resourceToHex","getAddress","uniqueBy","deploy","client","config","existingWorldAddress","tables","systems","ensureDeployer","ensureContractsDeployed","coreModuleBytecode","worldFactoryBytecode","uniqueBy","system","getAddress","resourceLabel","mod","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","assertNamespaceOwner","table","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","debug","tx","waitForTransactionReceipt","createWalletClient","http","privateKeyToAccount","loadConfig","forge","getOutDirectory","getRemappings","getRpcUrl","getSrcDirectory","chalk","execa","MUDError","resolveWorldConfig","resourceToHex","hexToResource","resolveWithContext","encodeField","getFunctionSelector","getCreate2Address","getAddress","hexToBytes","bytesToHex","getFunctionSignature","glob","basename","getExistingContracts","srcDir","path","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","defaultModuleContracts","readFileSync","path","MUDError","getContractData","contractName","forgeOutDirectory","data","contractDataPath","bytecode","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","defaultModules","defaultModuleContracts","mod","modules","defaultMod","installArgs","arg","resolveWithContext","value","bytesToHex","encodeField","getChainId","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","postDeployPath","tablegen","worldgen","deployOptions","runDeploy","opts","profile","config","loadConfig","chalk","srcDir","getSrcDirectory","outDir","getOutDirectory","remappings","getRemappings","rpc","getRpcUrl","outPath","path","tablegen","worldgen","getExistingContracts","forge","execa","privateKey","MUDError","resolvedConfig","resolveConfig","client","createWalletClient","http","privateKeyToAccount","startTime","worldDeploy","deploy","postDeploy","deploymentInfo","chainId","getChainId","deploysDir","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","deploy_default","devnode_default","faucet_default","gasReport","hello_default","tablegen_default","worldgen_default","set_version_default","test_default","trace_default","dev_contracts_default","abiTs"]}
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-22IIKR4S.js";export{a as logError};
2
+ //# sourceMappingURL=errors-XGN6V2Y3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}