@latticexyz/cli 2.0.0-main-ccc21e91 → 2.0.0-main-4e2a170f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mud.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import Fn from"yargs";import{hideBin as Rn}from"yargs/helpers";import Wn from"@latticexyz/gas-report";import jn from"@latticexyz/abi-ts";import{rmSync as So}from"fs";import{homedir as vo}from"os";import Co from"path";import{execa as To}from"execa";var ko={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=vo();So(Co.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=To("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
3
- gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},ne=ko;import{FaucetServiceDefinition as Do}from"@latticexyz/services/faucet";import{createChannel as Ao,createClient as Io}from"nice-grpc-web";import se from"chalk";import{NodeHttpTransport as Oo}from"@improbable-eng/grpc-web-node-http-transport";function Po(e){return Io(Do,Ao(e,Oo()))}var Mo={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=Po(o);e&&(console.log(se.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(se.yellow("Success"))),process.exit(0)}},ie=Mo;var Wo={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)}},ae=Wo;import jo from"path";import{loadConfig as Fo}from"@latticexyz/config/node";import{tablegen as Ro}from"@latticexyz/store/codegen";import{getRemappings as $o,getSrcDirectory as Eo}from"@latticexyz/common/foundry";var No={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 Fo(e),t=await Eo(),r=await $o();await Ro(o,jo.join(t,o.codegenDirectory),r),process.exit(0)}},ce=No;import N from"chalk";import{ZodError as Ho}from"zod";import{fromZodError as Bo,ValidationError as Uo}from"zod-validation-error";import{NotInsideProjectError as Vo}from"@latticexyz/config";import{MUDError as _o}from"@latticexyz/common/errors";function M(e){if(e instanceof Uo)console.log(N.redBright(e.message));else if(e instanceof Ho){let o=Bo(e,{prefixSeparator:`
2
+ import $n from"yargs";import{hideBin as Nn}from"yargs/helpers";import Rn from"@latticexyz/gas-report";import En from"@latticexyz/abi-ts";import{rmSync as wo}from"fs";import{homedir as xo}from"os";import So from"path";import{execa as vo}from"execa";var Co={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=xo();wo(So.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let r=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${r.join(" ")}`);let t=vo("anvil",r,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
3
+ gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},ne=Co;import{FaucetServiceDefinition as To}from"@latticexyz/services/faucet";import{createChannel as ko,createClient as Do}from"nice-grpc-web";import se from"chalk";import{NodeHttpTransport as Ao}from"@improbable-eng/grpc-web-node-http-transport";function Io(e){return Do(To,ko(e,Ao()))}var Oo={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:r}){let t=Io(o);e&&(console.log(se.yellow("Dripping to",r)),await t.dripDev({address:r}),console.log(se.yellow("Success"))),process.exit(0)}},ie=Oo;var Po={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)}},ae=Po;import Mo from"path";import{loadConfig as Wo}from"@latticexyz/config/node";import{tablegen as jo}from"@latticexyz/store/codegen";import{getRemappings as Fo,getSrcDirectory as Ro}from"@latticexyz/common/foundry";var Eo={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 Wo(e),r=await Ro(),t=await Fo();await jo(o,Mo.join(r,o.codegenDirectory),t),process.exit(0)}},ce=Eo;import N from"chalk";import{ZodError as $o}from"zod";import{fromZodError as No,ValidationError as Bo}from"zod-validation-error";import{NotInsideProjectError as Ho}from"@latticexyz/config";import{MUDError as Uo}from"@latticexyz/common/errors";function M(e){if(e instanceof Bo)console.log(N.redBright(e.message));else if(e instanceof $o){let o=No(e,{prefixSeparator:`
4
4
  - `,issueSeparator:`
5
- - `});console.log(N.redBright(o.message))}else e instanceof Vo?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof _o?console.log(N.red(e)):console.log(e)}import J from"node:path";import{existsSync as br,mkdirSync as hr,readFileSync as wr,writeFileSync as X}from"node:fs";import{getBytecode as zo,sendRawTransaction as Jo,sendTransaction as qo,waitForTransactionReceipt as de}from"viem/actions";var P={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import Ko from"debug";var le=Ko("mud:cli");var d=le.extend("deploy");var C=`0x${P.address}`;async function me(e){if(await zo(e,{address:C})){d("found create2 deployer at",C);return}d("sending gas for create2 deployer to signer at",P.signerAddress);let t=await qo(e,{chain:e.chain??null,to:`0x${P.signerAddress}`,value:BigInt(P.gasLimit)*BigInt(P.gasPrice)}),r=await de(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");d("deploying create2 deployer at",C);let n=await Jo(e,{serializedTransaction:`0x${P.transaction}`}),s=await de(e,{hash:n});if(s.contractAddress!==C)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as gt}from"viem/actions";import ct from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import lt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as dt,getCreate2Address as ye,encodeDeployData as ge}from"viem";import{concatHex as tt,getCreate2Address as rt}from"viem";import{getBytecode as nt}from"viem/actions";import{padHex as Yo}from"viem";import Zo from"@latticexyz/store/mud.config.js";import Qo from"@latticexyz/world/mud.config.js";import Xo from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Go}from"@latticexyz/common";import{resolveUserTypes as pe}from"@latticexyz/store";function H(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:Go({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:pe(r.keySchema,o),valueSchema:pe(r.valueSchema,o)}]))}import{helloStoreEvent as et}from"@latticexyz/store";import{helloWorldEvent as ot}from"@latticexyz/world";var D=Yo("0x",{size:32}),W=H(Zo),T=H(Qo),U=[et,ot],v=Xo,fe=["1.0.0-unaudited"],ue=["1.0.0-unaudited"];import{sendTransaction as st}from"@latticexyz/common";import it from"p-retry";import{wait as at}from"@latticexyz/common/utils";async function j({client:e,bytecode:o,label:t="contract"}){let r=rt({from:C,salt:D,bytecode:o});return await nt(e,{address:r,blockTag:"pending"})?(d("found",t,"at",r),[]):(d("deploying",t,"at",r),[await it(()=>st(e,{chain:e.chain??null,to:C,data:tt([D,o])}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to deploy ${t}, retrying in ${a}ms...`),await at(a)}})])}var be=ge({bytecode:ct.bytecode.object,abi:[]}),mt=ye({from:C,bytecode:be,salt:D}),he=ge({bytecode:lt.bytecode.object,abi:dt(["constructor(address)"]),args:[mt]}),we=ye({from:C,bytecode:he,salt:D});async function xe(e){return(await Promise.all([j({client:e,bytecode:be,label:"core module"}),j({client:e,bytecode:he,label:"world factory"})])).flat()}import bt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as ht}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as pt,decodeEventLog as ft,hexToString as Se,parseAbi as ut,trim as ve}from"viem";import{isDefined as yt}from"@latticexyz/common/utils";function V(e){let o=e.map(a=>{try{return{...a,...ft({strict:!0,abi:ut(U),topics:a.topics,data:a.data})}}catch(i){if(i instanceof pt)return;throw i}}).filter(yt),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((a,i)=>({...a,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Se(ve(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:Se(ve(i.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 Ce(e){await xe(e),d("deploying world");let o=await ht(e,{chain:e.chain??null,address:we,abi:bt,functionName:"deployWorld"});d("waiting for world deploy");let t=await gt(e,{hash:o});if(t.status!=="success")throw console.error("world deploy failed",t),new Error("world deploy failed");let r=V(t.logs.map(n=>n));return d("deployed world to",r.address,"at block",r.deployBlock),{...r,stateBlock:r.deployBlock}}import{writeContract as kt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Dt,keySchemaToHex as At,valueSchemaToHex as It}from"@latticexyz/protocol-parser";function S({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as wt,decodeAbiParameters as Te,parseAbiParameters as ke}from"viem";import{hexToResource as xt}from"@latticexyz/common";import{storeSetRecordEvent as St}from"@latticexyz/store";import{getLogs as vt}from"viem/actions";import{decodeKey as Ct,decodeValueArgs as Tt,hexToSchema as De}from"@latticexyz/protocol-parser";async function Ae({client:e,worldDeploy:o}){d("looking up tables for",o.address);let r=(await vt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:wt(St),args:{tableId:W.store_Tables.tableId}})).map(n=>{let{tableId:s}=Ct(W.store_Tables.keySchema,n.args.keyTuple),{namespace:a,name:i}=xt(s),m=Tt(W.store_Tables.valueSchema,n.args),c=De(m.keySchema),p=De(m.valueSchema),w=Te(ke("string[]"),m.abiEncodedKeyNames)[0],u=Te(ke("string[]"),m.abiEncodedFieldNames)[0],f=[...p.staticFields,...p.dynamicFields],g=Object.fromEntries(c.staticFields.map((b,l)=>[w[l],b])),h=Object.fromEntries(f.map((b,l)=>[u[l],b]));return{namespace:a,name:i,tableId:s,keySchema:g,valueSchema:h}});return d("found",r.length,"tables for",o.address),r}import Ot from"p-retry";import{wait as Pt}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,tables:t}){let n=(await Ae({client:e,worldDeploy:o})).map(i=>i.tableId),s=t.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(S).join(", "));let a=t.filter(i=>!n.includes(i.tableId));return a.length?(d("registering tables",a.map(S).join(", ")),await Promise.all(a.map(i=>Ot(()=>kt(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[i.tableId,Dt(i.valueSchema),At(i.keySchema),It(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let c=m.attemptNumber*500;d(`failed to register table ${S(i)}, retrying in ${c}ms...`),await Pt(c)}})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as Mt}from"viem";import{getLogs as Wt}from"viem/actions";import{storeSpliceStaticDataEvent as jt}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let r=(await Wt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:Mt(jt),args:{tableId:W.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",r.length,"resource IDs for",o.address),r}import{hexToResource as qt}from"@latticexyz/common";import{decodeValueArgs as Ft,encodeKey as Rt}from"@latticexyz/protocol-parser";import{readContract as $t}from"viem/actions";async function A({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await $t(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[t.tableId,Rt(t.keySchema,r)]});return Ft(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:a})}import{getFunctionSelector as Et,parseAbiItem as Nt}from"viem";import{storeSetRecordEvent as Ht}from"@latticexyz/store";import{getLogs as Bt}from"viem/actions";import{decodeValueArgs as Ut}from"@latticexyz/protocol-parser";import{hexToResource as Vt}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let r=(await Bt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Nt(Ht),args:{tableId:T.world_FunctionSignatures.tableId}})).map(s=>Ut(T.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let a=Et(s),{systemId:i,systemFunctionSelector:m}=await A({client:e,worldDeploy:o,table:T.world_FunctionSelectors,key:{functionSelector:a}}),{namespace:c,name:p}=Vt(i),w=c===""?s:s.replace(`${c}_${p}_`,"");return{signature:s,selector:a,systemId:i,systemFunctionSignature:w,systemFunctionSelector:m}}))}import{parseAbiItem as _t,getAddress as Lt}from"viem";import{storeSpliceStaticDataEvent as Kt}from"@latticexyz/store";import{getLogs as zt}from"viem/actions";import{decodeKey as Jt}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let r=(await zt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:_t(Kt),args:{tableId:T.world_ResourceAccess.tableId}})).map(s=>Jt(T.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await A({client:e,worldDeploy:o,table:T.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Lt(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Oe({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([_({client:e,worldDeploy:o}),L({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(qt).filter(a=>a.type==="system");return d("looking up systems",s.map(S).join(", ")),await Promise.all(s.map(async a=>{let{system:i,publicAccess:m}=await A({client:e,worldDeploy:o,table:T.world_Systems,key:{systemId:a.resourceId}}),c=r.filter(p=>p.systemId===a.resourceId);return{address:i,namespace:a.namespace,name:a.name,systemId:a.resourceId,allowAll:m,allowedAddresses:n.filter(({resourceId:p})=>p===a.resourceId).map(({address:p})=>p),functions:c}}))}import{wait as G}from"@latticexyz/common/utils";import Y from"p-retry";async function Pe({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Oe({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(l=>l.systemId),a=n.filter(({resourceId:l})=>s.includes(l)),i=t.flatMap(l=>l.allowedAddresses.map(y=>({resourceId:l.systemId,address:y}))),m=i.filter(l=>!a.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address))),c=a.filter(l=>!i.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address)));c.length&&d("revoking",c.length,"access grants"),m.length&&d("adding",m.length,"access grants");let p=[...c.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"revokeAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to revoke access, retrying in ${x}ms...`),await G(x)}})),...m.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"grantAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to grant access, retrying in ${x}ms...`),await G(x)}}))],w=t.filter(l=>r.some(y=>y.systemId===l.systemId&&I(y.address)===I(l.address)));w.length&&d("existing systems",w.map(S).join(", "));let u=w.map(l=>l.systemId),f=t.filter(l=>!u.includes(l.systemId));if(!f.length)return[];let g=f.filter(l=>r.some(y=>y.systemId===l.systemId&&I(y.address)!==I(l.address)));g.length&&d("upgrading systems",g.map(S).join(", "));let h=f.filter(l=>!r.some(y=>y.systemId===l.systemId));h.length&&d("registering new systems",h.map(S).join(", "));let b=f.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerSystem",args:[l.systemId,l.address,l.allowAll]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to register system ${S(l)}, retrying in ${x}ms...`),await G(x)}}));return await Promise.all([...p,...b])}import{waitForTransactionReceipt as Le}from"viem/actions";import{getAddress as Gt,parseAbi as Yt}from"viem";import{getBlockNumber as Zt,getLogs as Qt}from"viem/actions";var Me=new Map;async function We(e,o){let t=Gt(o),r=Me.get(t);if(r!=null)return r;d("looking up world deploy for",t);let n=await Zt(e),s=await Qt(e,{strict:!0,address:t,events:Yt(U),fromBlock:"earliest",toBlock:n});return r={...V(s),stateBlock:n},Me.set(t,r),d("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as Xt,writeContract as je}from"@latticexyz/common";import Fe from"p-retry";import{wait as Re}from"@latticexyz/common/utils";async function $e({client:e,worldDeploy:o,functions:t}){let r=await L({client:e,worldDeploy:o}),n=Object.fromEntries(r.map(i=>[i.selector,i])),s=t.filter(i=>n[i.selector]),a=t.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(m=>m.signature).join(", "));let i=s.filter(m=>m.systemId!==n[m.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(m=>m.signature).join(", "))}return a.length?(d("registering functions:",a.map(i=>i.signature).join(", ")),Promise.all(a.map(i=>{let{namespace:m}=Xt(i.systemId);return m===""?Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}),{retries:3,onFailedAttempt:async c=>{let p=c.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}}):Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let p=c.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}})}))):[]}import{writeContract as Ee}from"@latticexyz/common";import{wait as Ne}from"@latticexyz/common/utils";import He from"p-retry";async function Be({client:e,worldDeploy:o,modules:t}){if(!t.length)return[];d("installing modules:",t.map(n=>n.name).join(", "));let r=await Promise.all(t.map(n=>n.installAsRoot?He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installRootModule",args:[n.address,n.installData]}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to install root module ${n.name}, retrying in ${a}ms...`),await Ne(a)}}):He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installModule",args:[n.address,n.installData]}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to install module ${n.name}, retrying in ${a}ms...`),await Ne(a)}})));return await Promise.all(r)}import{getAddress as Ue}from"viem";import{hexToResource as Ve,resourceToHex as er}from"@latticexyz/common";async function _e({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(c=>Ve(c).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(c=>Ve(c).namespace))),a=r.filter(c=>s.includes(c)),m=(await Promise.all(a.map(async c=>{let{owner:p}=await A({client:e,worldDeploy:o,table:T.world_NamespaceOwner,key:{namespaceId:er({type:"namespace",namespace:c,name:""})}});return[c,p]}))).filter(([,c])=>Ue(c)!==Ue(e.account.address)).map(([c])=>c);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`)}import{uniqueBy as Ke}from"@latticexyz/common/utils";async function ze({client:e,config:o,worldAddress:t}){await me(e);let r=t?await We(e,t):await Ce(e);if(!fe.includes(r.storeVersion))throw new Error(`Unsupported Store version: ${r.storeVersion}`);if(!ue.includes(r.worldVersion))throw new Error(`Unsupported World version: ${r.worldVersion}`);let n=Object.values(o.tables),s=Object.values(o.systems);await _e({client:e,worldDeploy:r,resourceIds:[...n.map(u=>u.tableId),...s.map(u=>u.systemId)]});let a=(await Promise.all([...Ke(s,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${S(u)} system`})),...Ke(o.modules,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${u.name} module`}))])).flat();if(a.length){d("waiting for contracts");for(let u of a)await Le(e,{hash:u})}let i=await Ie({client:e,worldDeploy:r,tables:n}),m=await Pe({client:e,worldDeploy:r,systems:s}),c=await $e({client:e,worldDeploy:r,functions:s.flatMap(u=>u.functions)}),p=await Be({client:e,worldDeploy:r,modules:o.modules}),w=[...i,...m,...c,...p];d("waiting for all transactions to confirm");for(let u of w)await Le(e,{hash:u});return d("deploy complete"),r}import{createWalletClient as xr,http as Sr}from"viem";import{privateKeyToAccount as vr}from"viem/accounts";import{loadConfig as Cr}from"@latticexyz/config/node";import{forge as Tr,getOutDirectory as kr,getRemappings as Dr,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 Q,hexToResource as ir}from"@latticexyz/common";import{resolveWithContext as ar}from"@latticexyz/config";import{encodeField as cr}from"@latticexyz/protocol-parser";import{getFunctionSelector as Ze,getCreate2Address as Qe,getAddress as lr,hexToBytes as dr,bytesToHex as mr,getFunctionSignature as Xe}from"viem";import or from"glob";import{basename as tr}from"path";function F(e){return or.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:tr(o,".sol")}))}import Je from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import qe from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Ge from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var Ye=[{name:"KeysWithValueModule",abi:Je.abi,bytecode:Je.bytecode},{name:"KeysInTableModule",abi:qe.abi,bytecode:qe.bytecode},{name:"UniqueEntityModule",abi:Ge.abi,bytecode:Ge.bytecode}];import{readFileSync as rr}from"fs";import nr from"path";import{MUDError as Z}from"@latticexyz/common/errors";function z(e,o){let t,r=nr.join(o,e+".sol",e+".json");try{t=JSON.parse(rr(r,"utf8"))}catch{throw new Z(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new Z(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new Z(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function eo({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=H(e),n=F(o).map(({basename:f})=>f),s=sr(e,n),i=z("System",t).abi.filter(f=>f.type==="function").map(Xe),m=Object.entries(s.systems).map(([f,g])=>{let h=e.namespace,b=g.name,l=Q({type:"system",namespace:h,name:b}),y=z(f,t),x=y.abi.filter(k=>k.type==="function").map(Xe).filter(k=>!i.includes(k)).map(k=>{let re=h===""?k:`${h}_${b}_${k}`;return{signature:re,selector:Ze(re),systemId:l,systemFunctionSignature:k,systemFunctionSelector:Ze(k)}});return{namespace:h,name:b,systemId:l,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(k=>Q({type:"system",namespace:h,name:s.systems[k].name})),address:Qe({from:C,bytecode:y.bytecode,salt:D}),bytecode:y.bytecode,abi:y.abi,functions:x}}),c=m.map(({allowedAddresses:f,allowedSystemIds:g,...h})=>{let b=g.map(l=>{let y=m.find(x=>x.systemId===l);if(!y)throw new Error(`System ${S(h)} wanted access to ${S(ir(l))}, but it wasn't found in the config.`);return y.address});return{...h,allowedAddresses:Array.from(new Set([...f,...b].map(l=>lr(l))))}}),p={tableIds:Object.fromEntries(Object.entries(e.tables).map(([f,g])=>[f,dr(Q({type:g.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:g.name}))]))},w=Ye.map(f=>({name:f.name,bytecode:typeof f.bytecode=="string"?f.bytecode:f.bytecode.object,abi:f.abi})),u=e.modules.map(f=>{let g=w.find(b=>b.name===f.name)??z(f.name,t),h=f.args.map(b=>ar(b,p)).map(b=>{let l=b.value instanceof Uint8Array?mr(b.value):b.value;return cr(b.type,l)});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:Qe({from:C,bytecode:g.bytecode,salt:D}),bytecode:g.bytecode,abi:g.abi}});return{tables:r,systems:c,modules:u}}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 oo(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";var O={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 Cr(e.configPath);e.printConfig&&console.log(R.green(`
5
+ - `});console.log(N.redBright(o.message))}else e instanceof Ho?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Uo?console.log(N.red(e)):console.log(e)}import J from"node:path";import{existsSync as xr,mkdirSync as Sr,readFileSync as vr,writeFileSync as X}from"node:fs";import{getBytecode as Lo,sendRawTransaction as Ko,sendTransaction as zo,waitForTransactionReceipt as de}from"viem/actions";var P={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import _o from"debug";var le=_o("mud:cli");var d=le.extend("deploy");var C=`0x${P.address}`;async function me(e){if(await Lo(e,{address:C})){d("found create2 deployer at",C);return}d("sending gas for create2 deployer to signer at",P.signerAddress);let r=await zo(e,{chain:e.chain??null,to:`0x${P.signerAddress}`,value:BigInt(P.gasLimit)*BigInt(P.gasPrice)}),t=await de(e,{hash:r});if(t.status!=="success")throw console.error("failed to send gas to deployer signer",t),new Error("failed to send gas to deployer signer");d("deploying create2 deployer at",C);let n=await Ko(e,{serializedTransaction:`0x${P.transaction}`}),s=await de(e,{hash:n});if(s.contractAddress!==C)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as yt}from"viem/actions";import at from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import ct from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as lt,getCreate2Address as ye,encodeDeployData as ge}from"viem";import{concatHex as ot,getCreate2Address as tt}from"viem";import{getBytecode as rt}from"viem/actions";import{padHex as qo}from"viem";import Go from"@latticexyz/store/mud.config.js";import Yo from"@latticexyz/world/mud.config.js";import Zo from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Qo from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as Jo}from"@latticexyz/common";import{resolveUserTypes as pe}from"@latticexyz/store";function B(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([r])=>[r,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([r,t])=>[`${e.namespace}_${r}`,{namespace:e.namespace,name:t.name,tableId:Jo({type:t.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:t.name}),keySchema:pe(t.keySchema,o),valueSchema:pe(t.valueSchema,o)}]))}import{helloStoreEvent as Xo}from"@latticexyz/store";import{helloWorldEvent as et}from"@latticexyz/world";var D=qo("0x",{size:32}),W=B(Go),T=B(Yo),U=[Xo,et],v=[...Zo,...Qo],fe=["1.0.0-unaudited"],ue=["1.0.0-unaudited"];import{sendTransaction as nt}from"@latticexyz/common";import st from"p-retry";import{wait as it}from"@latticexyz/common/utils";async function j({client:e,bytecode:o,label:r="contract"}){let t=tt({from:C,salt:D,bytecode:o});return await rt(e,{address:t,blockTag:"pending"})?(d("found",r,"at",t),[]):(d("deploying",r,"at",t),[await st(()=>nt(e,{chain:e.chain??null,to:C,data:ot([D,o])}),{retries:3,onFailedAttempt:async s=>{let c=s.attemptNumber*500;d(`failed to deploy ${r}, retrying in ${c}ms...`),await it(c)}})])}var be=ge({bytecode:at.bytecode.object,abi:[]}),dt=ye({from:C,bytecode:be,salt:D}),he=ge({bytecode:ct.bytecode.object,abi:lt(["constructor(address)"]),args:[dt]}),we=ye({from:C,bytecode:he,salt:D});async function xe(e){return(await Promise.all([j({client:e,bytecode:be,label:"core module"}),j({client:e,bytecode:he,label:"world factory"})])).flat()}import gt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as bt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as mt,decodeEventLog as pt,hexToString as Se,parseAbi as ft,trim as ve}from"viem";import{isDefined as ut}from"@latticexyz/common/utils";function V(e){let o=e.map(c=>{try{return{...c,...pt({strict:!0,abi:ft(U),topics:c.topics,data:c.data})}}catch(i){if(i instanceof mt)return;throw i}}).filter(ut),{address:r,deployBlock:t,worldVersion:n,storeVersion:s}=o.reduce((c,i)=>({...c,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Se(ve(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:Se(ve(i.args.storeVersion,{dir:"right"}))}:null}),{});if(r==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:r,deployBlock:t,worldVersion:n,storeVersion:s}}async function Ce(e){await xe(e),d("deploying world");let o=await bt(e,{chain:e.chain??null,address:we,abi:gt,functionName:"deployWorld"});d("waiting for world deploy");let r=await yt(e,{hash:o});if(r.status!=="success")throw console.error("world deploy failed",r),new Error("world deploy failed");let t=V(r.logs.map(n=>n));return d("deployed world to",t.address,"at block",t.deployBlock),{...t,stateBlock:t.deployBlock}}import{writeContract as Tt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as kt,keySchemaToHex as Dt,valueSchemaToHex as At}from"@latticexyz/protocol-parser";function S({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as ht,decodeAbiParameters as Te,parseAbiParameters as ke}from"viem";import{hexToResource as wt}from"@latticexyz/common";import{storeSetRecordEvent as xt}from"@latticexyz/store";import{getLogs as St}from"viem/actions";import{decodeKey as vt,decodeValueArgs as Ct,hexToSchema as De}from"@latticexyz/protocol-parser";async function Ae({client:e,worldDeploy:o}){d("looking up tables for",o.address);let t=(await St(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:ht(xt),args:{tableId:W.store_Tables.tableId}})).map(n=>{let{tableId:s}=vt(W.store_Tables.keySchema,n.args.keyTuple),{namespace:c,name:i}=wt(s),m=Ct(W.store_Tables.valueSchema,n.args),a=De(m.keySchema),p=De(m.valueSchema),w=Te(ke("string[]"),m.abiEncodedKeyNames)[0],u=Te(ke("string[]"),m.abiEncodedFieldNames)[0],f=[...p.staticFields,...p.dynamicFields],g=Object.fromEntries(a.staticFields.map((b,l)=>[w[l],b])),h=Object.fromEntries(f.map((b,l)=>[u[l],b]));return{namespace:c,name:i,tableId:s,keySchema:g,valueSchema:h}});return d("found",t.length,"tables for",o.address),t}import It from"p-retry";import{wait as Ot}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,tables:r}){let n=(await Ae({client:e,worldDeploy:o})).map(i=>i.tableId),s=r.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(S).join(", "));let c=r.filter(i=>!n.includes(i.tableId));return c.length?(d("registering tables",c.map(S).join(", ")),await Promise.all(c.map(i=>It(()=>Tt(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[i.tableId,kt(i.valueSchema),Dt(i.keySchema),At(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let a=m.attemptNumber*500;d(`failed to register table ${S(i)}, retrying in ${a}ms...`),await Ot(a)}})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as Pt}from"viem";import{getLogs as Mt}from"viem/actions";import{storeSpliceStaticDataEvent as Wt}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let t=(await Mt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:Pt(Wt),args:{tableId:W.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",t.length,"resource IDs for",o.address),t}import{hexToResource as Jt}from"@latticexyz/common";import{decodeValueArgs as jt,encodeKey as Ft}from"@latticexyz/protocol-parser";import{readContract as Rt}from"viem/actions";async function A({client:e,worldDeploy:o,table:r,key:t}){let[n,s,c]=await Rt(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[r.tableId,Ft(r.keySchema,t)]});return jt(r.valueSchema,{staticData:n,encodedLengths:s,dynamicData:c})}import{getFunctionSelector as Et,parseAbiItem as $t}from"viem";import{storeSetRecordEvent as Nt}from"@latticexyz/store";import{getLogs as Bt}from"viem/actions";import{decodeValueArgs as Ht}from"@latticexyz/protocol-parser";import{hexToResource as Ut}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let t=(await Bt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:$t(Nt),args:{tableId:T.world_FunctionSignatures.tableId}})).map(s=>Ht(T.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",t.length,"function signatures for",o.address),await Promise.all(t.map(async s=>{let c=Et(s),{systemId:i,systemFunctionSelector:m}=await A({client:e,worldDeploy:o,table:T.world_FunctionSelectors,key:{functionSelector:c}}),{namespace:a,name:p}=Ut(i),w=a===""?s:s.replace(`${a}_${p}_`,"");return{signature:s,selector:c,systemId:i,systemFunctionSignature:w,systemFunctionSelector:m}}))}import{parseAbiItem as Vt,getAddress as _t}from"viem";import{storeSpliceStaticDataEvent as Lt}from"@latticexyz/store";import{getLogs as Kt}from"viem/actions";import{decodeKey as zt}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let t=(await Kt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Vt(Lt),args:{tableId:T.world_ResourceAccess.tableId}})).map(s=>zt(T.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(t.map(async s=>[s,await A({client:e,worldDeploy:o,table:T.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:_t(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Oe({client:e,worldDeploy:o}){let[r,t,n]=await Promise.all([_({client:e,worldDeploy:o}),L({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=r.map(Jt).filter(c=>c.type==="system");return d("looking up systems",s.map(S).join(", ")),await Promise.all(s.map(async c=>{let{system:i,publicAccess:m}=await A({client:e,worldDeploy:o,table:T.world_Systems,key:{systemId:c.resourceId}}),a=t.filter(p=>p.systemId===c.resourceId);return{address:i,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:m,allowedAddresses:n.filter(({resourceId:p})=>p===c.resourceId).map(({address:p})=>p),functions:a}}))}import{wait as G}from"@latticexyz/common/utils";import Y from"p-retry";async function Pe({client:e,worldDeploy:o,systems:r}){let[t,n]=await Promise.all([Oe({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=r.map(l=>l.systemId),c=n.filter(({resourceId:l})=>s.includes(l)),i=r.flatMap(l=>l.allowedAddresses.map(y=>({resourceId:l.systemId,address:y}))),m=i.filter(l=>!c.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address))),a=c.filter(l=>!i.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address)));a.length&&d("revoking",a.length,"access grants"),m.length&&d("adding",m.length,"access grants");let p=[...a.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"revokeAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to revoke access, retrying in ${x}ms...`),await G(x)}})),...m.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"grantAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to grant access, retrying in ${x}ms...`),await G(x)}}))],w=r.filter(l=>t.some(y=>y.systemId===l.systemId&&I(y.address)===I(l.address)));w.length&&d("existing systems",w.map(S).join(", "));let u=w.map(l=>l.systemId),f=r.filter(l=>!u.includes(l.systemId));if(!f.length)return[];let g=f.filter(l=>t.some(y=>y.systemId===l.systemId&&I(y.address)!==I(l.address)));g.length&&d("upgrading systems",g.map(S).join(", "));let h=f.filter(l=>!t.some(y=>y.systemId===l.systemId));h.length&&d("registering new systems",h.map(S).join(", "));let b=f.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerSystem",args:[l.systemId,l.address,l.allowAll]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to register system ${S(l)}, retrying in ${x}ms...`),await G(x)}}));return await Promise.all([...p,...b])}import{waitForTransactionReceipt as Ve}from"viem/actions";import{getAddress as qt,parseAbi as Gt}from"viem";import{getBlockNumber as Yt,getLogs as Zt}from"viem/actions";var Me=new Map;async function We(e,o){let r=qt(o),t=Me.get(r);if(t!=null)return t;d("looking up world deploy for",r);let n=await Yt(e),s=await Zt(e,{strict:!0,address:r,events:Gt(U),fromBlock:"earliest",toBlock:n});return t={...V(s),stateBlock:n},Me.set(r,t),d("found world deploy for",r,"at block",t.deployBlock),t}import{hexToResource as Qt,writeContract as je}from"@latticexyz/common";import Fe from"p-retry";import{wait as Re}from"@latticexyz/common/utils";async function Ee({client:e,worldDeploy:o,functions:r}){let t=await L({client:e,worldDeploy:o}),n=Object.fromEntries(t.map(i=>[i.selector,i])),s=r.filter(i=>n[i.selector]),c=r.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(m=>m.signature).join(", "));let i=s.filter(m=>m.systemId!==n[m.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(m=>m.signature).join(", "))}return c.length?(d("registering functions:",c.map(i=>i.signature).join(", ")),Promise.all(c.map(i=>{let{namespace:m}=Qt(i.systemId);return m===""?Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}),{retries:3,onFailedAttempt:async a=>{let p=a.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}}):Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]}),{retries:3,onFailedAttempt:async a=>{let p=a.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}})}))):[]}import{BaseError as Xt}from"viem";import{writeContract as $e}from"@latticexyz/common";import{isDefined as er,wait as or}from"@latticexyz/common/utils";import tr from"p-retry";async function Ne({client:e,worldDeploy:o,modules:r}){return r.length?(d("installing modules:",r.map(t=>t.name).join(", ")),(await Promise.all(r.map(t=>tr(async()=>{try{return t.installAsRoot?await $e(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installRootModule",args:[t.address,t.installData]}):await $e(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installModule",args:[t.address,t.installData]})}catch(n){if(n instanceof Xt&&n.message.includes("Module_AlreadyInstalled")){d(`module ${t.name} already installed`);return}throw n}},{retries:3,onFailedAttempt:async n=>{let s=n.attemptNumber*500;d(`failed to install module ${t.name}, retrying in ${s}ms...`),await or(s)}})))).filter(er)):[]}import{getAddress as Be}from"viem";import{hexToResource as He,resourceToHex as rr}from"@latticexyz/common";async function Ue({client:e,worldDeploy:o,resourceIds:r}){let t=Array.from(new Set(r.map(a=>He(a).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(a=>He(a).namespace))),c=t.filter(a=>s.includes(a)),m=(await Promise.all(c.map(async a=>{let{owner:p}=await A({client:e,worldDeploy:o,table:T.world_NamespaceOwner,key:{namespaceId:rr({type:"namespace",namespace:a,name:""})}});return[a,p]}))).filter(([,a])=>Be(a)!==Be(e.account.address)).map(([a])=>a);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`)}import{uniqueBy as _e}from"@latticexyz/common/utils";async function Le({client:e,config:o,worldAddress:r}){await me(e);let t=r?await We(e,r):await Ce(e);if(!fe.includes(t.storeVersion))throw new Error(`Unsupported Store version: ${t.storeVersion}`);if(!ue.includes(t.worldVersion))throw new Error(`Unsupported World version: ${t.worldVersion}`);let n=Object.values(o.tables),s=Object.values(o.systems);await Ue({client:e,worldDeploy:t,resourceIds:[...n.map(u=>u.tableId),...s.map(u=>u.systemId)]});let c=(await Promise.all([..._e(s,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${S(u)} system`})),..._e(o.modules,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${u.name} module`}))])).flat();if(c.length){d("waiting for contracts");for(let u of c)await Ve(e,{hash:u})}let i=await Ie({client:e,worldDeploy:t,tables:n}),m=await Pe({client:e,worldDeploy:t,systems:s}),a=await Ee({client:e,worldDeploy:t,functions:s.flatMap(u=>u.functions)}),p=await Ne({client:e,worldDeploy:t,modules:o.modules}),w=[...i,...m,...a,...p];d("waiting for all transactions to confirm");for(let u of w)await Ve(e,{hash:u});return d("deploy complete"),t}import{createWalletClient as Cr,http as Tr}from"viem";import{privateKeyToAccount as kr}from"viem/accounts";import{loadConfig as Dr}from"@latticexyz/config/node";import{forge as Ar,getOutDirectory as Ir,getRemappings as Or,getRpcUrl as Pr,getSrcDirectory as Mr}from"@latticexyz/common/foundry";import R from"chalk";import{execa as Wr}from"execa";import{MUDError as jr}from"@latticexyz/common/errors";import{resolveWorldConfig as cr}from"@latticexyz/world";import{resourceToHex as Q,hexToResource as lr}from"@latticexyz/common";import{resolveWithContext as dr}from"@latticexyz/config";import{encodeField as mr}from"@latticexyz/protocol-parser";import{getFunctionSelector as Ge,getCreate2Address as Ye,getAddress as pr,hexToBytes as fr,bytesToHex as ur,getFunctionSignature as Ze}from"viem";import nr from"glob";import{basename as sr}from"path";function F(e){return nr.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:sr(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 ir}from"fs";import ar from"path";import{MUDError as Z}from"@latticexyz/common/errors";function z(e,o){let r,t=ar.join(o,e+".sol",e+".json");try{r=JSON.parse(ir(t,"utf8"))}catch{throw new Z(`Error reading file at ${t}`)}let n=r?.bytecode?.object;if(!n)throw new Z(`No bytecode found in ${t}`);let s=r?.abi;if(!s)throw new Z(`No ABI found in ${t}`);return{abi:s,bytecode:n}}function Qe({config:e,forgeSourceDir:o,forgeOutDir:r}){let t=B(e),n=F(o).map(({basename:f})=>f),s=cr(e,n),i=z("System",r).abi.filter(f=>f.type==="function").map(Ze),m=Object.entries(s.systems).map(([f,g])=>{let h=e.namespace,b=g.name,l=Q({type:"system",namespace:h,name:b}),y=z(f,r),x=y.abi.filter(k=>k.type==="function").map(Ze).filter(k=>!i.includes(k)).map(k=>{let re=h===""?k:`${h}_${b}_${k}`;return{signature:re,selector:Ge(re),systemId:l,systemFunctionSignature:k,systemFunctionSelector:Ge(k)}});return{namespace:h,name:b,systemId:l,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(k=>Q({type:"system",namespace:h,name:s.systems[k].name})),address:Ye({from:C,bytecode:y.bytecode,salt:D}),bytecode:y.bytecode,abi:y.abi,functions:x}}),a=m.map(({allowedAddresses:f,allowedSystemIds:g,...h})=>{let b=g.map(l=>{let y=m.find(x=>x.systemId===l);if(!y)throw new Error(`System ${S(h)} wanted access to ${S(lr(l))}, but it wasn't found in the config.`);return y.address});return{...h,allowedAddresses:Array.from(new Set([...f,...b].map(l=>pr(l))))}}),p={tableIds:Object.fromEntries(Object.entries(e.tables).map(([f,g])=>[f,fr(Q({type:g.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:g.name}))]))},w=qe.map(f=>({name:f.name,bytecode:typeof f.bytecode=="string"?f.bytecode:f.bytecode.object,abi:f.abi})),u=e.modules.map(f=>{let g=w.find(b=>b.name===f.name)??z(f.name,r),h=f.args.map(b=>dr(b,p)).map(b=>{let l=b.value instanceof Uint8Array?ur(b.value):b.value;return mr(b.type,l)});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:C,bytecode:g.bytecode,salt:D}),bytecode:g.bytecode,abi:g.abi}});return{tables:t,systems:a,modules:u}}import{getChainId as Fr}from"viem/actions";import{existsSync as yr}from"fs";import gr from"path";import br from"chalk";import{getScriptDirectory as hr,forge as wr}from"@latticexyz/common/foundry";async function Xe(e,o,r,t){let n=gr.join(await hr(),e+".s.sol");yr(n)?(console.log(br.blue(`Executing post deploy script at ${n}`)),await wr(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",r,"-vvv"],{profile:t})):console.log(`No script at ${n}, skipping post deploy hook`)}import{tablegen as Rr}from"@latticexyz/store/codegen";var O={configPath:{type:"string",desc:"Path to the config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."}};async function E(e){let o=e.profile??process.env.FOUNDRY_PROFILE,r=await Dr(e.configPath);e.printConfig&&console.log(R.green(`
6
6
  Resolved config:
7
- `),JSON.stringify(t,null,2));let r=e.srcDir??await Ir(o),n=await kr(o),s=await Dr(),a=e.rpc??await Ar(o);if(console.log(R.bgBlue(R.whiteBright(`
8
- Deploying MUD contracts${o?" with profile "+o:""} to RPC ${a}
9
- `))),!e.skipBuild){let f=J.join(r,t.codegenDirectory);await Wr(t,f,s),await Tr(["build","--skip","test","script"],{profile:o}),await Or("mud",["abi-ts"],{stdio:"inherit"})}let i=process.env.PRIVATE_KEY;if(!i)throw new Pr(`Missing PRIVATE_KEY environment variable.
7
+ `),JSON.stringify(r,null,2));let t=e.srcDir??await Mr(o),n=await Ir(o),s=await Or(),c=e.rpc??await Pr(o);if(console.log(R.bgBlue(R.whiteBright(`
8
+ Deploying MUD contracts${o?" with profile "+o:""} to RPC ${c}
9
+ `))),!e.skipBuild){let f=J.join(t,r.codegenDirectory);await Rr(r,f,s),await Ar(["build","--skip","test","script"],{profile:o}),await Wr("mud",["abi-ts"],{stdio:"inherit"})}let i=process.env.PRIVATE_KEY;if(!i)throw new jr(`Missing PRIVATE_KEY environment variable.
10
10
  Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
11
- in your contracts directory to use the default anvil private key.`);let m=eo({config:t,forgeSourceDir:r,forgeOutDir:n}),c=xr({transport:Sr(a),account:vr(i)});console.log("Deploying from",c.account.address);let p=Date.now(),w=await ze({worldAddress:e.worldAddress,client:c,config:m});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await oo(t.postDeployScript,w.address,a,o),console.log(R.green("Deployment completed in",(Date.now()-p)/1e3,"seconds"));let u={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let f=await Mr(c),g=J.join(t.deploysDirectory,f.toString());hr(g,{recursive:!0}),X(J.join(g,"latest.json"),JSON.stringify(u,null,2)),X(J.join(g,Date.now()+".json"),JSON.stringify(u,null,2));let h=[1337,31337],b=br(t.worldsFile)?JSON.parse(wr(t.worldsFile,"utf-8")):{};b[f]={address:u.worldAddress,blockNumber:h.includes(f)?void 0:u.blockNumber},X(t.worldsFile,JSON.stringify(b,null,2)),console.log(R.bgGreen(R.whiteBright(`
12
- Deployment result (written to ${t.worldsFile} and ${g}):
13
- `)))}return console.log(u),w}var jr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(O)},async handler(e){try{await $(e)}catch(o){M(o),process.exit(1)}process.exit(0)}},to=jr;import{loadConfig as Fr}from"@latticexyz/config/node";import{worldgen as Rr}from"@latticexyz/world/node";import{getSrcDirectory as $r}from"@latticexyz/common/foundry";import ro from"path";import{rmSync as Er}from"fs";var Nr={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 $r(),t=F(o),r=e.config??await Fr(e.configPath),n=ro.join(o,r.codegenDirectory);e.clean&&Er(ro.join(n,r.worldgenDirectory),{recursive:!0,force:!0}),await Rr(r,t,n)}var no=Nr;import B from"chalk";import{readFileSync as Lr,writeFileSync as Kr}from"fs";import oe from"path";import{MUDError as E}from"@latticexyz/common/errors";var so={name:"@latticexyz/cli",version:"2.0.0-next.11",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",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 zr from"glob";import{ZodError as Ur,z as io}from"zod";var Vr=io.object({MUD_PACKAGES:io.string().transform(e=>JSON.parse(e))});function _r(){try{return Vr.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
+ in your contracts directory to use the default anvil private key.`);let m=Qe({config:r,forgeSourceDir:t,forgeOutDir:n}),a=Cr({transport:Tr(c),account:kr(i)});console.log("Deploying from",a.account.address);let p=Date.now(),w=await Le({worldAddress:e.worldAddress,client:a,config:m});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await Xe(r.postDeployScript,w.address,c,o),console.log(R.green("Deployment completed in",(Date.now()-p)/1e3,"seconds"));let u={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let f=await Fr(a),g=J.join(r.deploysDirectory,f.toString());Sr(g,{recursive:!0}),X(J.join(g,"latest.json"),JSON.stringify(u,null,2)),X(J.join(g,Date.now()+".json"),JSON.stringify(u,null,2));let h=[1337,31337],b=xr(r.worldsFile)?JSON.parse(vr(r.worldsFile,"utf-8")):{};b[f]={address:u.worldAddress,blockNumber:h.includes(f)?void 0:u.blockNumber},X(r.worldsFile,JSON.stringify(b,null,2)),console.log(R.bgGreen(R.whiteBright(`
12
+ Deployment result (written to ${r.worldsFile} and ${g}):
13
+ `)))}return console.log(u),w}var Er={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(O)},async handler(e){try{await E(e)}catch(o){M(o),process.exit(1)}process.exit(0)}},eo=Er;import{loadConfig as $r}from"@latticexyz/config/node";import{worldgen as Nr}from"@latticexyz/world/node";import{getSrcDirectory as Br}from"@latticexyz/common/foundry";import oo from"path";import{rmSync as Hr}from"fs";var Ur={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 Vr(e),process.exit(0)}};async function Vr(e){let o=e.srcDir??await Br(),r=F(o),t=e.config??await $r(e.configPath),n=oo.join(o,t.codegenDirectory);e.clean&&Hr(oo.join(n,t.worldgenDirectory),{recursive:!0,force:!0}),await Nr(t,r,n)}var to=Ur;import H from"chalk";import{readFileSync as Jr,writeFileSync as qr}from"fs";import oe from"path";import{MUDError as $}from"@latticexyz/common/errors";var ro={name:"@latticexyz/cli",version:"2.0.0-next.11",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",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 Gr from"glob";import{ZodError as Lr,z as no}from"zod";var Kr=no.object({MUD_PACKAGES:no.string().transform(e=>JSON.parse(e))});function zr(){try{return Kr.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 Lr){let{_errors:o,...r}=e.format();console.error(`
14
14
  Missing or invalid environment variables:
15
15
 
16
- ${Object.keys(t).join(`
16
+ ${Object.keys(r).join(`
17
17
  `)}
18
- `),process.exit(1)}throw e}}var ee=_r().MUD_PACKAGES;var Jr={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 qr(e);let r=zr.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Gr(n,e)}catch(o){M(o)}finally{process.exit(0)}}};async function qr(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/${so.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 Gr(e,o){let{link:t}=o,{mudVersion:r}=o,n=Yr(e),s=Object.keys(ee),a={};for(let c in n.dependencies)s.includes(c)&&(a[c]=n.dependencies[c]);let i={};for(let c in n.devDependencies)s.includes(c)&&(i[c]=n.devDependencies[c]);for(let c in n.dependencies)s.includes(c)&&(n.dependencies[c]=m(c,"dependencies"));for(let c in n.devDependencies)s.includes(c)&&(n.devDependencies[c]=m(c,"devDependencies"));return Kr(e,JSON.stringify(n,null,2)+`
19
- `),console.log(`Updating ${e}`),ao(a,n.dependencies),ao(i,n.devDependencies),n;function m(c,p){return t&&(r=Zr(e,t,c)),r||n[p][c]}}function Yr(e){try{let o=Lr(e,"utf8");return JSON.parse(o)}catch{throw new E("Could not read JSON at "+e)}}function ao(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${B.red(e[t])} -> ${B.green(o[t])}`)}function Zr(e,o,t){let r=oe.relative(oe.dirname(e),process.cwd());return"link:"+oe.join(r,o,ee[t].localPath)}var co=Jr;import{anvil as Qr,forge as Xr,getRpcUrl as en}from"@latticexyz/common/foundry";import on from"chalk";var tn={...O,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"}},rn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(tn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Qr(n)}let o=e.worldAddress?await en(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await $({...e,saveDeployment:!1,rpc:o})).address;console.log(on.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Xr(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},lo=rn;import{existsSync as nn,readFileSync as sn}from"fs";import{ethers as mo}from"ethers";import{loadConfig as an}from"@latticexyz/config/node";import{MUDError as po}from"@latticexyz/common/errors";import{cast as cn,getRpcUrl as ln,getSrcDirectory as dn}from"@latticexyz/common/foundry";import{resolveWorldConfig as mn}from"@latticexyz/world";import pn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import fo from"@latticexyz/world/mud.config.js";import{resourceToHex as yo}from"@latticexyz/common";import{createClient as fn,http as un}from"viem";import{getChainId as yn}from"viem/actions";var uo=yo({type:"system",namespace:fo.namespace,name:fo.tables.Systems.name}),gn={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 dn(o),e.rpc??=await ln(o);let{tx:t,configPath:r,srcDir:n,rpc:s}=e,a=F(n),i=await an(r),m=mn(i,a.map(({basename:l})=>l)),c=e.worldAddress??await bn(i.worldsFile,s),p=new mo.providers.StaticJsonRpcProvider(s),w=new mo.Contract(c,pn,p),u=i.namespace,f=Object.values(m.systems).map(({name:l})=>l),g=await w.getFieldLayout(uo),h=[];for(let l of f){let y=yo({type:"system",namespace:u,name:l}),x=await w.getField(uo,[y],0,g);h.push({name:l,address:x})}let b=await cn(["run","--label",`${c}:World`,...h.map(({name:l,address:y})=>["--label",`${y}:${l}`]).flat(),`${t}`]);console.log(b),process.exit(0)}},go=gn;async function bn(e,o){if(nn(e)){let t=fn({transport:un(o)}),r=await yn(t),n=JSON.parse(sn(e,"utf-8"));if(!n[r])throw new po(`chainId ${r} is missing in worldsFile "${e}"`);return n[r].address}else throw new po("worldAddress is not specified and worldsFile is missing")}import{anvil as hn,getScriptDirectory as wn,getSrcDirectory as xn}from"@latticexyz/common/foundry";import te from"chalk";import Sn from"chokidar";import{loadConfig as vn,resolveConfigPath as Cn}from"@latticexyz/config/node";import Tn from"path";import{homedir as kn}from"os";import{rmSync as Dn}from"fs";import{BehaviorSubject as An,debounceTime as In,exhaustMap as On}from"rxjs";var Pn={rpc:O.rpc,configPath:O.configPath,alwaysRunPostDeploy:O.alwaysRunPostDeploy},Mn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Pn)},async handler(e){let o=e.rpc,t=e.configPath??await Cn(e.configPath),r=await xn(),n=await wn(),s=await vn(t);if(!e.rpc){console.log(te.gray("Cleaning devnode cache"));let c=kn();Dn(Tn.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),hn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let a=new An(Date.now());Sn.watch([t,r,n]).on("all",async(c,p)=>{p.includes(t)&&a.next(Date.now()),(p.includes(r)||p.includes(n))&&(p.includes(s.codegenDirectory)||a.next(Date.now()))});let i;a.pipe(In(200),On(async c=>{i&&console.log(te.blue("Change detected, rebuilding and running deploy..."));let p=await $({...e,configPath:t,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:r});return i=p.address,c<a.value?a.next(a.value):console.log(te.gray("Watching for file changes...")),p})).subscribe()}},bo=Mn;var ho=[to,ne,ie,Wn,ae,ce,no,co,lo,go,bo,jn];import*as xo from"dotenv";import wo from"chalk";xo.config();Fn(Rn(process.argv)).scriptName("mud").command(ho).strict().fail((e,o)=>{console.error(wo.red(e)),e.includes("Missing required argument")&&console.log(wo.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(M(o),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
18
+ `),process.exit(1)}throw e}}var ee=zr().MUD_PACKAGES;var Yr={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],r=o.reduce((n,s)=>e[s]?n+1:n,0);if(r===0)throw new $(`You need to provide one these options: ${o.join(", ")}`);if(r>1)throw new $(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Zr(e);let t=Gr.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of t)Qr(n,e)}catch(o){M(o)}finally{process.exit(0)}}};async function Zr(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(H.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${ro.name}`)).json()}catch{throw new $("Could not fetch available MUD versions")}if(e.tag){let r=o["dist-tags"][e.tag];if(!r)throw new $(`Could not find npm version with tag "${e.tag}"`);return console.log(H.green(`Latest version with tag ${e.tag}: ${r}`)),r}if(e.commit){let r=e.commit.substring(0,8),t=Object.keys(o.versions).find(n=>n.includes(r));if(!t)throw new $(`Could not find npm version based on commit "${e.commit}"`);return console.log(H.green(`Version from commit ${e.commit}: ${t}`)),t}return e.mudVersion}function Qr(e,o){let{link:r}=o,{mudVersion:t}=o,n=Xr(e),s=Object.keys(ee),c={};for(let a in n.dependencies)s.includes(a)&&(c[a]=n.dependencies[a]);let i={};for(let a in n.devDependencies)s.includes(a)&&(i[a]=n.devDependencies[a]);for(let a in n.dependencies)s.includes(a)&&(n.dependencies[a]=m(a,"dependencies"));for(let a in n.devDependencies)s.includes(a)&&(n.devDependencies[a]=m(a,"devDependencies"));return qr(e,JSON.stringify(n,null,2)+`
19
+ `),console.log(`Updating ${e}`),so(c,n.dependencies),so(i,n.devDependencies),n;function m(a,p){return r&&(t=en(e,r,a)),t||n[p][a]}}function Xr(e){try{let o=Jr(e,"utf8");return JSON.parse(o)}catch{throw new $("Could not read JSON at "+e)}}function so(e,o){for(let r in e)e[r]!==o[r]&&console.log(`${r}: ${H.red(e[r])} -> ${H.green(o[r])}`)}function en(e,o,r){let t=oe.relative(oe.dirname(e),process.cwd());return"link:"+oe.join(t,o,ee[r].localPath)}var io=Yr;import{anvil as on,forge as tn,getRpcUrl as rn}from"@latticexyz/common/foundry";import nn from"chalk";var sn={...O,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"}},an={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(sn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];on(n)}let o=e.worldAddress?await rn(e.profile):`http://127.0.0.1:${e.port}`,r=e.worldAddress??(await E({...e,saveDeployment:!1,rpc:o})).address;console.log(nn.blue("World address",r));let t=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await tn(["test","--fork-url",o,...t],{profile:e.profile,env:{WORLD_ADDRESS:r}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ao=an;import{existsSync as cn,readFileSync as ln}from"fs";import{ethers as co}from"ethers";import{loadConfig as dn}from"@latticexyz/config/node";import{MUDError as lo}from"@latticexyz/common/errors";import{cast as mn,getRpcUrl as pn,getSrcDirectory as fn}from"@latticexyz/common/foundry";import{resolveWorldConfig as un}from"@latticexyz/world";import yn 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 gn,http as bn}from"viem";import{getChainId as hn}from"viem/actions";var po=fo({type:"system",namespace:mo.namespace,name:mo.tables.Systems.name}),wn={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 fn(o),e.rpc??=await pn(o);let{tx:r,configPath:t,srcDir:n,rpc:s}=e,c=F(n),i=await dn(t),m=un(i,c.map(({basename:l})=>l)),a=e.worldAddress??await xn(i.worldsFile,s),p=new co.providers.StaticJsonRpcProvider(s),w=new co.Contract(a,yn,p),u=i.namespace,f=Object.values(m.systems).map(({name:l})=>l),g=await w.getFieldLayout(po),h=[];for(let l of f){let y=fo({type:"system",namespace:u,name:l}),x=await w.getField(po,[y],0,g);h.push({name:l,address:x})}let b=await mn(["run","--label",`${a}:World`,...h.map(({name:l,address:y})=>["--label",`${y}:${l}`]).flat(),`${r}`]);console.log(b),process.exit(0)}},uo=wn;async function xn(e,o){if(cn(e)){let r=gn({transport:bn(o)}),t=await hn(r),n=JSON.parse(ln(e,"utf-8"));if(!n[t])throw new lo(`chainId ${t} is missing in worldsFile "${e}"`);return n[t].address}else throw new lo("worldAddress is not specified and worldsFile is missing")}import{anvil as Sn,getScriptDirectory as vn,getSrcDirectory as Cn}from"@latticexyz/common/foundry";import te from"chalk";import Tn from"chokidar";import{loadConfig as kn,resolveConfigPath as Dn}from"@latticexyz/config/node";import An from"path";import{homedir as In}from"os";import{rmSync as On}from"fs";import{BehaviorSubject as Pn,debounceTime as Mn,exhaustMap as Wn}from"rxjs";var jn={rpc:O.rpc,configPath:O.configPath,alwaysRunPostDeploy:O.alwaysRunPostDeploy},Fn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(jn)},async handler(e){let o=e.rpc,r=e.configPath??await Dn(e.configPath),t=await Cn(),n=await vn(),s=await kn(r);if(!e.rpc){console.log(te.gray("Cleaning devnode cache"));let a=In();On(An.join(a,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Sn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let c=new Pn(Date.now());Tn.watch([r,t,n]).on("all",async(a,p)=>{p.includes(r)&&c.next(Date.now()),(p.includes(t)||p.includes(n))&&(p.includes(s.codegenDirectory)||c.next(Date.now()))});let i;c.pipe(Mn(200),Wn(async a=>{i&&console.log(te.blue("Change detected, rebuilding and running deploy..."));let p=await E({...e,configPath:r,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:t});return i=p.address,a<c.value?c.next(c.value):console.log(te.gray("Watching for file changes...")),p})).subscribe()}},yo=Fn;var go=[eo,ne,ie,Rn,ae,ce,to,io,ao,uo,yo,En];import*as ho from"dotenv";import bo from"chalk";ho.config();$n(Nn(process.argv)).scriptName("mud").command(go).strict().fail((e,o)=>{console.error(bo.red(e)),e.includes("Missing required argument")&&console.log(bo.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(M(o),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
20
20
  //# sourceMappingURL=mud.js.map
package/dist/mud.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mud.ts","../src/commands/index.ts","../src/commands/devnode.ts","../src/commands/faucet.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/utils/errors.ts","../src/runDeploy.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/ensureContract.ts","../src/deploy/common.ts","../src/deploy/configToTables.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/deploy.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":["#!/usr/bin/env node\n\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { commands } from \"./commands\";\nimport { logError } from \"./utils/errors\";\n\n// Load .env file into process.env\nimport * as dotenv from \"dotenv\";\nimport chalk from \"chalk\";\ndotenv.config();\n\nyargs(hideBin(process.argv))\n // Explicit name to display in help (by default it's the entry file, which may not be \"mud\" for e.g. ts-node)\n .scriptName(\"mud\")\n // Use the commands directory to scaffold\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy\n .command(commands as any)\n // Enable strict mode.\n .strict()\n // Custom error handler\n .fail((msg, err) => {\n console.error(chalk.red(msg));\n if (msg.includes(\"Missing required argument\")) {\n console.log(\n chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)\n );\n }\n console.log(\"\");\n // Even though `.fail` type says we should get an `Error`, this can sometimes be undefined\n if (err != null) {\n logError(err);\n console.log(\"\");\n }\n\n process.exit(1);\n })\n // Useful aliases.\n .alias({ h: \"help\" }).argv;\n","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 chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n","import 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\";\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 forge build\n if (!opts.skipBuild) {\n const outPath = path.join(srcDir, config.codegenDirectory);\n await tablegen(config, outPath, remappings);\n await forge([\"build\", \"--skip\", \"test\", \"script\"], { 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, 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 { ensureContract } from \"./ensureContract\";\nimport { deployer } from \"./ensureDeployer\";\nimport { salt } from \"./common\";\n\nconst coreModuleBytecode = encodeDeployData({\n bytecode: coreModuleBuild.bytecode.object as Hex,\n abi: [],\n});\n\nconst coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });\n\nconst 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 (\n await Promise.all([\n ensureContract({ client, bytecode: coreModuleBytecode, label: \"core module\" }),\n ensureContract({ client, bytecode: worldFactoryBytecode, label: \"world factory\" }),\n ])\n ).flat();\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 async function ensureContract({\n client,\n bytecode,\n label = \"contract\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly bytecode: Hex;\n readonly label?: string;\n}): 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 { 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 { 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;\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\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","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 { 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 { wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\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 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 { Account, Address, Chain, Client, Transport } 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\";\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 await ensureDeployer(client);\n\n const worldDeploy = existingWorldAddress\n ? await getWorldDeploy(client, existingWorldAddress)\n : await deployWorld(client);\n\n if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {\n throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);\n }\n if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {\n throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);\n }\n\n const tables = Object.values(config.tables) as Table[];\n const systems = Object.values(config.systems);\n\n await assertNamespaceOwner({\n client,\n worldDeploy,\n resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],\n });\n\n // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.\n const contractTxs = (\n await Promise.all([\n ...uniqueBy(systems, (system) => system.address).map((system) =>\n ensureContract({ client, bytecode: system.bytecode, label: `${resourceLabel(system)} system` })\n ),\n ...uniqueBy(config.modules, (mod) => mod.address).map((mod) =>\n ensureContract({ client, bytecode: mod.bytecode, label: `${mod.name} module` })\n ),\n ])\n ).flat();\n\n if (contractTxs.length) {\n debug(\"waiting for contracts\");\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const tx of contractTxs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\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 { 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 } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\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 debug(\"installing modules:\", modules.map((mod) => mod.name).join(\", \"));\n const installTxs = await Promise.all(\n modules.map((mod) =>\n mod.installAsRoot\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: \"installRootModule\",\n args: [mod.address, mod.installData],\n }),\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n const delay = error.attemptNumber * 500;\n debug(`failed to install root module ${mod.name}, retrying in ${delay}ms...`);\n await wait(delay);\n },\n }\n )\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: \"installModule\",\n args: [mod.address, mod.installData],\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\n return await Promise.all(installTxs);\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.11\",\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 } from \"rxjs\";\nimport { Address } from \"viem\";\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]).on(\"all\", async (_, updatePath) => {\n if (updatePath.includes(configPath)) {\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 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(\"Change detected, rebuilding and running deploy...\"));\n }\n // TODO: handle errors\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(\"Watching for file changes...\"));\n }\n return deploy;\n })\n );\n\n deploys$.subscribe();\n },\n};\n\nexport default commandModule;\n"],"mappings":";AAEA,OAAOA,OAAW,QAClB,OAAS,WAAAC,OAAe,gBCDxB,OAAOC,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,EACtC,IAAMC,EAAcN,GAAQ,EAC5BD,GAAOE,GAAK,KAAKK,EAAa,WAAY,QAAS,KAAK,EAAG,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAE3F,IAAMC,EAAY,CAAC,KAAM,OAAOF,CAAS,EAAG,2BAA4B,GAAG,EAC3E,QAAQ,IAAI,kBAAkBE,E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,GACAC,EACF,EDtBA,UAAYC,OAAY,SACxB,OAAOC,OAAW,QACX,UAAO,EAEdC,GAAMC,GAAQ,QAAQ,IAAI,CAAC,EAExB,WAAW,KAAK,EAGhB,QAAQC,EAAe,EAEvB,OAAO,EAEP,KAAK,CAACC,EAAKC,IAAQ,CAClB,QAAQ,MAAML,GAAM,IAAII,CAAG,CAAC,EACxBA,EAAI,SAAS,2BAA2B,GAC1C,QAAQ,IACNJ,GAAM,OAAO,iBAAiB,QAAQ,KAAK,CAAC,2DAA2D,CACzG,EAEF,QAAQ,IAAI,EAAE,EAEVK,GAAO,OACTC,EAASD,CAAG,EACZ,QAAQ,IAAI,EAAE,GAGhB,QAAQ,KAAK,CAAC,CAChB,CAAC,EAEA,MAAM,CAAE,EAAG,MAAO,CAAC,EAAE","names":["yargs","hideBin","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","chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError","path","existsSync","mkdirSync","readFileSync","writeFileSync","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","concatHex","getCreate2Address","getBytecode","padHex","storeConfig","worldConfig","IBaseWorldAbi","resourceToHex","resolveUserTypes","configToTables","config","userTypes","key","tableName","table","helloStoreEvent","helloWorldEvent","salt","padHex","storeTables","configToTables","storeConfig","worldTables","worldConfig","worldDeployEvents","worldAbi","IBaseWorldAbi","supportedStoreVersions","supportedWorldVersions","sendTransaction","pRetry","wait","ensureContract","client","bytecode","label","address","getCreate2Address","deployer","salt","getBytecode","debug","sendTransaction","concatHex","error","delay","coreModuleBytecode","encodeDeployData","coreModuleBuild","coreModule","getCreate2Address","deployer","salt","worldFactoryBytecode","worldFactoryBuild","parseAbi","worldFactory","ensureWorldFactory","client","ensureContract","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","wait","pRetry","ensureSystems","client","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","systemIds","system","currentAccess","resourceId","desiredAccess","address","accessToAdd","access","getAddress","accessToRemove","debug","accessTxs","writeContract","worldAbi","error","delay","existingSystems","worldSystem","resourceLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","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","writeContract","wait","pRetry","ensureModules","client","worldDeploy","modules","debug","mod","installTxs","writeContract","worldAbi","error","delay","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","ensureDeployer","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","tables","systems","assertNamespaceOwner","table","system","contractTxs","ensureContract","resourceLabel","mod","debug","tx","waitForTransactionReceipt","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","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","deployOptions","runDeploy","opts","profile","config","loadConfig","chalk","srcDir","getSrcDirectory","outDir","getOutDirectory","remappings","getRemappings","rpc","getRpcUrl","outPath","path","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","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","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","dotenv","chalk","yargs","hideBin","commands","msg","err","logError"]}
1
+ {"version":3,"sources":["../src/mud.ts","../src/commands/index.ts","../src/commands/devnode.ts","../src/commands/faucet.ts","../src/commands/hello.ts","../src/commands/tablegen.ts","../src/utils/errors.ts","../src/runDeploy.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/ensureContract.ts","../src/deploy/common.ts","../src/deploy/configToTables.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/deploy.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":["#!/usr/bin/env node\n\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { commands } from \"./commands\";\nimport { logError } from \"./utils/errors\";\n\n// Load .env file into process.env\nimport * as dotenv from \"dotenv\";\nimport chalk from \"chalk\";\ndotenv.config();\n\nyargs(hideBin(process.argv))\n // Explicit name to display in help (by default it's the entry file, which may not be \"mud\" for e.g. ts-node)\n .scriptName(\"mud\")\n // Use the commands directory to scaffold\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy\n .command(commands as any)\n // Enable strict mode.\n .strict()\n // Custom error handler\n .fail((msg, err) => {\n console.error(chalk.red(msg));\n if (msg.includes(\"Missing required argument\")) {\n console.log(\n chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)\n );\n }\n console.log(\"\");\n // Even though `.fail` type says we should get an `Error`, this can sometimes be undefined\n if (err != null) {\n logError(err);\n console.log(\"\");\n }\n\n process.exit(1);\n })\n // Useful aliases.\n .alias({ h: \"help\" }).argv;\n","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 chalk from \"chalk\";\nimport { ZodError } from \"zod\";\nimport { fromZodError, ValidationError } from \"zod-validation-error\";\nimport { NotInsideProjectError } from \"@latticexyz/config\";\nimport { MUDError } from \"@latticexyz/common/errors\";\n\nexport function logError(error: unknown) {\n if (error instanceof ValidationError) {\n console.log(chalk.redBright(error.message));\n } else if (error instanceof ZodError) {\n // TODO currently this error shouldn't happen, use `fromZodErrorCustom`\n // (see https://github.com/latticexyz/mud/issues/438)\n const validationError = fromZodError(error, {\n prefixSeparator: \"\\n- \",\n issueSeparator: \"\\n- \",\n });\n console.log(chalk.redBright(validationError.message));\n } else if (error instanceof NotInsideProjectError) {\n console.log(chalk.red(error.message));\n console.log(\"\");\n // TODO add docs to the website and update the link to the specific page\n // (see https://github.com/latticexyz/mud/issues/445)\n console.log(chalk.blue(`To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/`));\n } else if (error instanceof MUDError) {\n console.log(chalk.red(error));\n } else {\n console.log(error);\n }\n}\n","import 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\";\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 forge build\n if (!opts.skipBuild) {\n const outPath = path.join(srcDir, config.codegenDirectory);\n await tablegen(config, outPath, remappings);\n await forge([\"build\", \"--skip\", \"test\", \"script\"], { 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, 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 { ensureContract } from \"./ensureContract\";\nimport { deployer } from \"./ensureDeployer\";\nimport { salt } from \"./common\";\n\nconst coreModuleBytecode = encodeDeployData({\n bytecode: coreModuleBuild.bytecode.object as Hex,\n abi: [],\n});\n\nconst coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });\n\nconst 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 (\n await Promise.all([\n ensureContract({ client, bytecode: coreModuleBytecode, label: \"core module\" }),\n ensureContract({ client, bytecode: worldFactoryBytecode, label: \"world factory\" }),\n ])\n ).flat();\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 async function ensureContract({\n client,\n bytecode,\n label = \"contract\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly bytecode: Hex;\n readonly label?: string;\n}): 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 { 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\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\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","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 { 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 { wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\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 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 { Account, Address, Chain, Client, Transport } 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\";\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 await ensureDeployer(client);\n\n const worldDeploy = existingWorldAddress\n ? await getWorldDeploy(client, existingWorldAddress)\n : await deployWorld(client);\n\n if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {\n throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);\n }\n if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {\n throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);\n }\n\n const tables = Object.values(config.tables) as Table[];\n const systems = Object.values(config.systems);\n\n await assertNamespaceOwner({\n client,\n worldDeploy,\n resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],\n });\n\n // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.\n const contractTxs = (\n await Promise.all([\n ...uniqueBy(systems, (system) => system.address).map((system) =>\n ensureContract({ client, bytecode: system.bytecode, label: `${resourceLabel(system)} system` })\n ),\n ...uniqueBy(config.modules, (mod) => mod.address).map((mod) =>\n ensureContract({ client, bytecode: mod.bytecode, label: `${mod.name} module` })\n ),\n ])\n ).flat();\n\n if (contractTxs.length) {\n debug(\"waiting for contracts\");\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const tx of contractTxs) {\n await waitForTransactionReceipt(client, { hash: tx });\n // TODO: throw if there was a revert?\n }\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 { 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 } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { debug } from \"./debug\";\nimport { isDefined, wait } from \"@latticexyz/common/utils\";\nimport pRetry from \"p-retry\";\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 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.11\",\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 } from \"rxjs\";\nimport { Address } from \"viem\";\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]).on(\"all\", async (_, updatePath) => {\n if (updatePath.includes(configPath)) {\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 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(\"Change detected, rebuilding and running deploy...\"));\n }\n // TODO: handle errors\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(\"Watching for file changes...\"));\n }\n return deploy;\n })\n );\n\n deploys$.subscribe();\n },\n};\n\nexport default commandModule;\n"],"mappings":";AAEA,OAAOA,OAAW,QACl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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","chalk","ZodError","fromZodError","ValidationError","NotInsideProjectError","MUDError","logError","error","validationError","path","existsSync","mkdirSync","readFileSync","writeFileSync","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","concatHex","getCreate2Address","getBytecode","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","sendTransaction","pRetry","wait","ensureContract","client","bytecode","label","address","getCreate2Address","deployer","salt","getBytecode","debug","sendTransaction","concatHex","error","delay","coreModuleBytecode","encodeDeployData","coreModuleBuild","coreModule","getCreate2Address","deployer","salt","worldFactoryBytecode","worldFactoryBuild","parseAbi","worldFactory","ensureWorldFactory","client","ensureContract","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","wait","pRetry","ensureSystems","client","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","systemIds","system","currentAccess","resourceId","desiredAccess","address","accessToAdd","access","getAddress","accessToRemove","debug","accessTxs","writeContract","worldAbi","error","delay","existingSystems","worldSystem","resourceLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","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","writeContract","isDefined","wait","pRetry","ensureModules","client","worldDeploy","modules","debug","mod","writeContract","worldAbi","error","BaseError","delay","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","ensureDeployer","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","tables","systems","assertNamespaceOwner","table","system","contractTxs","ensureContract","resourceLabel","mod","debug","tx","waitForTransactionReceipt","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","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","deployOptions","runDeploy","opts","profile","config","loadConfig","chalk","srcDir","getSrcDirectory","outDir","getOutDirectory","remappings","getRemappings","rpc","getRpcUrl","outPath","path","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","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","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","dotenv","chalk","yargs","hideBin","commands","msg","err","logError"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/cli",
3
- "version": "2.0.0-main-ccc21e91",
3
+ "version": "2.0.0-main-4e2a170f",
4
4
  "description": "Command line interface for mud",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,17 +40,17 @@
40
40
  "yargs": "^17.7.1",
41
41
  "zod": "^3.21.4",
42
42
  "zod-validation-error": "^1.3.0",
43
- "@latticexyz/abi-ts": "2.0.0-main-ccc21e91",
44
- "@latticexyz/common": "2.0.0-main-ccc21e91",
45
- "@latticexyz/config": "2.0.0-main-ccc21e91",
46
- "@latticexyz/gas-report": "2.0.0-main-ccc21e91",
47
- "@latticexyz/protocol-parser": "2.0.0-main-ccc21e91",
48
- "@latticexyz/schema-type": "2.0.0-main-ccc21e91",
49
- "@latticexyz/services": "2.0.0-main-ccc21e91",
50
- "@latticexyz/store": "2.0.0-main-ccc21e91",
51
- "@latticexyz/utils": "2.0.0-main-ccc21e91",
52
- "@latticexyz/world": "2.0.0-main-ccc21e91",
53
- "@latticexyz/world-modules": "2.0.0-main-ccc21e91"
43
+ "@latticexyz/abi-ts": "2.0.0-main-4e2a170f",
44
+ "@latticexyz/common": "2.0.0-main-4e2a170f",
45
+ "@latticexyz/config": "2.0.0-main-4e2a170f",
46
+ "@latticexyz/gas-report": "2.0.0-main-4e2a170f",
47
+ "@latticexyz/protocol-parser": "2.0.0-main-4e2a170f",
48
+ "@latticexyz/schema-type": "2.0.0-main-4e2a170f",
49
+ "@latticexyz/services": "2.0.0-main-4e2a170f",
50
+ "@latticexyz/store": "2.0.0-main-4e2a170f",
51
+ "@latticexyz/utils": "2.0.0-main-4e2a170f",
52
+ "@latticexyz/world": "2.0.0-main-4e2a170f",
53
+ "@latticexyz/world-modules": "2.0.0-main-4e2a170f"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/debug": "^4.1.7",
@@ -2,6 +2,7 @@ import { Abi, Address, Hex, padHex } from "viem";
2
2
  import storeConfig from "@latticexyz/store/mud.config.js";
3
3
  import worldConfig from "@latticexyz/world/mud.config.js";
4
4
  import IBaseWorldAbi from "@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json" assert { type: "json" };
5
+ import IModuleAbi from "@latticexyz/world-modules/out/IModule.sol/IModule.abi.json" assert { type: "json" };
5
6
  import { Tables, configToTables } from "./configToTables";
6
7
  import { StoreConfig, helloStoreEvent } from "@latticexyz/store";
7
8
  import { WorldConfig, helloWorldEvent } from "@latticexyz/world";
@@ -14,7 +15,7 @@ export const worldTables = configToTables(worldConfig);
14
15
 
15
16
  export const worldDeployEvents = [helloStoreEvent, helloWorldEvent] as const;
16
17
 
17
- export const worldAbi = IBaseWorldAbi;
18
+ export const worldAbi = [...IBaseWorldAbi, ...IModuleAbi] as const;
18
19
 
19
20
  export type WorldDeploy = {
20
21
  readonly address: Address;
@@ -1,8 +1,8 @@
1
- import { Client, Transport, Chain, Account, Hex } from "viem";
1
+ import { Client, Transport, Chain, Account, Hex, BaseError } from "viem";
2
2
  import { writeContract } from "@latticexyz/common";
3
3
  import { Module, WorldDeploy, worldAbi } from "./common";
4
4
  import { debug } from "./debug";
5
- import { wait } from "@latticexyz/common/utils";
5
+ import { isDefined, wait } from "@latticexyz/common/utils";
6
6
  import pRetry from "p-retry";
7
7
 
8
8
  export async function ensureModules({
@@ -17,49 +17,47 @@ export async function ensureModules({
17
17
  if (!modules.length) return [];
18
18
 
19
19
  debug("installing modules:", modules.map((mod) => mod.name).join(", "));
20
- const installTxs = await Promise.all(
21
- modules.map((mod) =>
22
- mod.installAsRoot
23
- ? pRetry(
24
- () =>
25
- writeContract(client, {
26
- chain: client.chain ?? null,
27
- address: worldDeploy.address,
28
- abi: worldAbi,
29
- // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
30
- functionName: "installRootModule",
31
- args: [mod.address, mod.installData],
32
- }),
33
- {
34
- retries: 3,
35
- onFailedAttempt: async (error) => {
36
- const delay = error.attemptNumber * 500;
37
- debug(`failed to install root module ${mod.name}, retrying in ${delay}ms...`);
38
- await wait(delay);
39
- },
20
+ return (
21
+ await Promise.all(
22
+ modules.map((mod) =>
23
+ pRetry(
24
+ async () => {
25
+ try {
26
+ return mod.installAsRoot
27
+ ? await writeContract(client, {
28
+ chain: client.chain ?? null,
29
+ address: worldDeploy.address,
30
+ abi: worldAbi,
31
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
32
+ functionName: "installRootModule",
33
+ args: [mod.address, mod.installData],
34
+ })
35
+ : await writeContract(client, {
36
+ chain: client.chain ?? null,
37
+ address: worldDeploy.address,
38
+ abi: worldAbi,
39
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
40
+ functionName: "installModule",
41
+ args: [mod.address, mod.installData],
42
+ });
43
+ } catch (error) {
44
+ if (error instanceof BaseError && error.message.includes("Module_AlreadyInstalled")) {
45
+ debug(`module ${mod.name} already installed`);
46
+ return;
47
+ }
48
+ throw error;
40
49
  }
41
- )
42
- : pRetry(
43
- () =>
44
- writeContract(client, {
45
- chain: client.chain ?? null,
46
- address: worldDeploy.address,
47
- abi: worldAbi,
48
- // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
49
- functionName: "installModule",
50
- args: [mod.address, mod.installData],
51
- }),
52
- {
53
- retries: 3,
54
- onFailedAttempt: async (error) => {
55
- const delay = error.attemptNumber * 500;
56
- debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);
57
- await wait(delay);
58
- },
59
- }
60
- )
50
+ },
51
+ {
52
+ retries: 3,
53
+ onFailedAttempt: async (error) => {
54
+ const delay = error.attemptNumber * 500;
55
+ debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);
56
+ await wait(delay);
57
+ },
58
+ }
59
+ )
60
+ )
61
61
  )
62
- );
63
-
64
- return await Promise.all(installTxs);
62
+ ).filter(isDefined);
65
63
  }