@latticexyz/cli 2.0.0-main-1cc2c502 → 2.0.0-main-e667ee80
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 +8 -8
- package/dist/mud.js.map +1 -1
- package/package.json +12 -12
- package/src/commands/dev-contracts.ts +0 -1
- package/src/runDeploy.ts +1 -10
package/dist/mud.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import kn from"yargs";import{hideBin as Dn}from"yargs/helpers";import Cn from"@latticexyz/gas-report";import Tn from"@latticexyz/abi-ts";import{rmSync as
|
|
3
|
-
gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},te=
|
|
2
|
+
import kn from"yargs";import{hideBin as Dn}from"yargs/helpers";import Cn from"@latticexyz/gas-report";import Tn from"@latticexyz/abi-ts";import{rmSync as fo}from"fs";import{homedir as uo}from"os";import yo from"path";import{execa as go}from"execa";var bo={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=uo();fo(yo.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=go("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}},te=bo;import{FaucetServiceDefinition as ho}from"@latticexyz/services/faucet";import{createChannel as wo,createClient as xo}from"nice-grpc-web";import re from"chalk";import{NodeHttpTransport as So}from"@improbable-eng/grpc-web-node-http-transport";function vo(e){return xo(ho,wo(e,So()))}var Co={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=vo(o);e&&(console.log(re.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(re.yellow("Success"))),process.exit(0)}},ne=Co;var To={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)}},se=To;import ko from"path";import{loadConfig as Do}from"@latticexyz/config/node";import{tablegen as Ao}from"@latticexyz/store/codegen";import{getRemappings as Io,getSrcDirectory as Oo}from"@latticexyz/common/foundry";var Po={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 Do(e),t=await Oo(),r=await Io();await Ao(o,ko.join(t,o.codegenDirectory),r),process.exit(0)}},ie=Po;import H from"chalk";import{ZodError as Mo}from"zod";import{fromZodError as Wo,ValidationError as jo}from"zod-validation-error";import{NotInsideProjectError as Eo}from"@latticexyz/config";import{MUDError as Fo}from"@latticexyz/common/errors";function W(e){if(e instanceof jo)console.log(H.redBright(e.message));else if(e instanceof Mo){let o=Wo(e,{prefixSeparator:`
|
|
4
4
|
- `,issueSeparator:`
|
|
5
|
-
- `});console.log(H.redBright(o.message))}else e instanceof Fo?(console.log(H.red(e.message)),console.log(""),console.log(H.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Ro?console.log(H.red(e)):console.log(e)}import J from"node:path";import{existsSync as lr,mkdirSync as dr,readFileSync as mr,writeFileSync as Z}from"node:fs";import{getBytecode as Bo,sendRawTransaction as No,sendTransaction as Uo,waitForTransactionReceipt as ce}from"viem/actions";var O={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import Ho from"debug";var ae=Ho("mud:cli");var d=ae.extend("deploy");var C=`0x${O.address}`;async function le(e){if(await Bo(e,{address:C})){d("found create2 deployer at",C);return}d("sending gas for create2 deployer to signer at",O.signerAddress);let t=await Uo(e,{chain:e.chain??null,to:`0x${O.signerAddress}`,value:BigInt(O.gasLimit)*BigInt(O.gasPrice)}),r=await ce(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 No(e,{serializedTransaction:`0x${O.transaction}`}),s=await ce(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 at}from"viem/actions";import Xo from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import et from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as ot,getCreate2Address as fe,encodeDeployData as ue}from"viem";import{concatHex as Go,getCreate2Address as Yo}from"viem";import{getBytecode as Zo}from"viem/actions";import{padHex as _o}from"viem";import Lo from"@latticexyz/store/mud.config.js";import Ko from"@latticexyz/world/mud.config.js";import zo from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Vo}from"@latticexyz/common";import{resolveUserTypes as de}from"@latticexyz/store";function B(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:Vo({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:de(r.keySchema,o),valueSchema:de(r.valueSchema,o)}]))}import{helloStoreEvent as Jo}from"@latticexyz/store";import{helloWorldEvent as qo}from"@latticexyz/world";var D=_o("0x",{size:32}),j=B(Lo),k=B(Ko),U=[Jo,qo],S=zo,me=["1.0.0-unaudited"],pe=["1.0.0-unaudited"];import{sendTransaction as Qo}from"@latticexyz/common";async function P({client:e,bytecode:o,label:t="contract"}){let r=Yo({from:C,salt:D,bytecode:o});return await Zo(e,{address:r,blockTag:"pending"})?(d("found",t,"at",r),[]):(d("deploying",t,"at",r),[await Qo(e,{chain:e.chain??null,to:C,data:Go([D,o])})])}var ye=ue({bytecode:Xo.bytecode.object,abi:[]}),tt=fe({from:C,bytecode:ye,salt:D}),ge=ue({bytecode:et.bytecode.object,abi:ot(["constructor(address)"]),args:[tt]}),be=fe({from:C,bytecode:ge,salt:D});async function he(e){return(await Promise.all([P({client:e,bytecode:ye,label:"core module"}),P({client:e,bytecode:ge,label:"world factory"})])).flat()}import ct from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as lt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as rt,decodeEventLog as nt,hexToString as we,parseAbi as st,trim as xe}from"viem";import{isDefined as it}from"@latticexyz/common/utils";function V(e){let o=e.map(c=>{try{return{...c,...nt({strict:!0,abi:st(U),topics:c.topics,data:c.data})}}catch(i){if(i instanceof rt)return;throw i}}).filter(it),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((c,i)=>({...c,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:we(xe(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:we(xe(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 Se(e){await he(e),d("deploying world");let o=await lt(e,{chain:e.chain??null,address:be,abi:ct,functionName:"deployWorld"});d("waiting for world deploy");let t=await at(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 gt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as bt,keySchemaToHex as ht,valueSchemaToHex as wt}from"@latticexyz/protocol-parser";function T({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as dt,decodeAbiParameters as ve,parseAbiParameters as Ce}from"viem";import{hexToResource as mt}from"@latticexyz/common";import{storeSetRecordEvent as pt}from"@latticexyz/store";import{getLogs as ft}from"viem/actions";import{decodeKey as ut,decodeValueArgs as yt,hexToSchema as Te}from"@latticexyz/protocol-parser";async function ke({client:e,worldDeploy:o}){d("looking up tables for",o.address);let r=(await ft(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:dt(pt),args:{tableId:j.store_Tables.tableId}})).map(n=>{let{tableId:s}=ut(j.store_Tables.keySchema,n.args.keyTuple),{namespace:c,name:i}=mt(s),p=yt(j.store_Tables.valueSchema,n.args),a=Te(p.keySchema),f=Te(p.valueSchema),u=ve(Ce("string[]"),p.abiEncodedKeyNames)[0],v=ve(Ce("string[]"),p.abiEncodedFieldNames)[0],m=[...f.staticFields,...f.dynamicFields],y=Object.fromEntries(a.staticFields.map((g,b)=>[u[b],g])),h=Object.fromEntries(m.map((g,b)=>[v[b],g]));return{namespace:c,name:i,tableId:s,keySchema:y,valueSchema:h}});return d("found",r.length,"tables for",o.address),r}async function De({client:e,worldDeploy:o,tables:t}){let n=(await ke({client:e,worldDeploy:o})).map(i=>i.tableId),s=t.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(T).join(", "));let c=t.filter(i=>!n.includes(i.tableId));return c.length?(d("registering tables",c.map(T).join(", ")),await Promise.all(c.map(i=>gt(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerTable",args:[i.tableId,bt(i.valueSchema),ht(i.keySchema),wt(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as xt}from"viem";import{getLogs as St}from"viem/actions";import{storeSpliceStaticDataEvent as vt}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let r=(await St(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:xt(vt),args:{tableId:j.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",r.length,"resource IDs for",o.address),r}import{hexToResource as $t}from"@latticexyz/common";import{decodeValueArgs as Ct,encodeKey as Tt}from"@latticexyz/protocol-parser";import{readContract as kt}from"viem/actions";async function A({client:e,worldDeploy:o,table:t,key:r}){let[n,s,c]=await kt(e,{blockNumber:o.stateBlock,address:o.address,abi:S,functionName:"getRecord",args:[t.tableId,Tt(t.keySchema,r)]});return Ct(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:c})}import{getFunctionSelector as Dt,parseAbiItem as At}from"viem";import{storeSetRecordEvent as It}from"@latticexyz/store";import{getLogs as Ot}from"viem/actions";import{decodeValueArgs as Pt}from"@latticexyz/protocol-parser";import{hexToResource as Mt}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let r=(await Ot(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:At(It),args:{tableId:k.world_FunctionSignatures.tableId}})).map(s=>Pt(k.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let c=Dt(s),{systemId:i,systemFunctionSelector:p}=await A({client:e,worldDeploy:o,table:k.world_FunctionSelectors,key:{functionSelector:c}}),{namespace:a,name:f}=Mt(i),u=a===""?s:s.replace(`${a}_${f}_`,"");return{signature:s,selector:c,systemId:i,systemFunctionSignature:u,systemFunctionSelector:p}}))}import{parseAbiItem as Wt,getAddress as jt}from"viem";import{storeSpliceStaticDataEvent as Et}from"@latticexyz/store";import{getLogs as Ft}from"viem/actions";import{decodeKey as Rt}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let r=(await Ft(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Wt(Et),args:{tableId:k.world_ResourceAccess.tableId}})).map(s=>Rt(k.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await A({client:e,worldDeploy:o,table:k.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:jt(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Ae({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($t).filter(c=>c.type==="system");return d("looking up systems",s.map(T).join(", ")),await Promise.all(s.map(async c=>{let{system:i,publicAccess:p}=await A({client:e,worldDeploy:o,table:k.world_Systems,key:{systemId:c.resourceId}}),a=r.filter(f=>f.systemId===c.resourceId);return{address:i,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:p,allowedAddresses:n.filter(({resourceId:f})=>f===c.resourceId).map(({address:f})=>f),functions:a}}))}import{uniqueBy as Ht}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Ae({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(l=>l.systemId),c=n.filter(({resourceId:l})=>s.includes(l)),i=t.flatMap(l=>l.allowedAddresses.map(w=>({resourceId:l.systemId,address:w}))),p=i.filter(l=>!c.some(({resourceId:w,address:x})=>w===l.resourceId&&I(x)===I(l.address))),a=c.filter(l=>!i.some(({resourceId:w,address:x})=>w===l.resourceId&&I(x)===I(l.address)));a.length&&d("revoking",a.length,"access grants"),p.length&&d("adding",p.length,"access grants");let f=await Promise.all([...a.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"revokeAccess",args:[l.resourceId,l.address]})),...p.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"grantAccess",args:[l.resourceId,l.address]}))]),u=t.filter(l=>r.some(w=>w.systemId===l.systemId&&I(w.address)===I(l.address)));u.length&&d("existing systems",u.map(T).join(", "));let v=u.map(l=>l.systemId),m=t.filter(l=>!v.includes(l.systemId));if(!m.length)return[];let y=m.filter(l=>r.some(w=>w.systemId===l.systemId&&I(w.address)!==I(l.address)));y.length&&d("upgrading systems",y.map(T).join(", "));let h=m.filter(l=>!r.some(w=>w.systemId===l.systemId));h.length&&d("registering new systems",h.map(T).join(", "));let g=await Promise.all(Ht(m,l=>l.address).map(l=>P({client:e,bytecode:l.bytecode,label:`${T(l)} system`}))),b=await Promise.all(m.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerSystem",args:[l.systemId,l.address,l.allowAll]})));return(await Promise.all([...f,...g,...b])).flat()}import{waitForTransactionReceipt as zt}from"viem/actions";import{getAddress as Bt,parseAbi as Nt}from"viem";import{getBlockNumber as Ut,getLogs as Vt}from"viem/actions";var Oe=new Map;async function Pe(e,o){let t=Bt(o),r=Oe.get(t);if(r!=null)return r;d("looking up world deploy for",t);let n=await Ut(e),s=await Vt(e,{strict:!0,address:t,events:Nt(U),fromBlock:"earliest",toBlock:n});return r={...V(s),stateBlock:n},Oe.set(t,r),d("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as _t,writeContract as Me}from"@latticexyz/common";async function We({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]),c=t.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(p=>p.signature).join(", "));let i=s.filter(p=>p.systemId!==n[p.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(p=>p.signature).join(", "))}return c.length?(d("registering functions:",c.map(i=>i.signature).join(", ")),Promise.all(c.map(i=>{let{namespace:p}=_t(i.systemId);return p===""?Me(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}):Me(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]})}))):[]}import{writeContract as je}from"@latticexyz/common";import{uniqueBy as Lt}from"@latticexyz/common/utils";async function Ee({client:e,worldDeploy:o,modules:t}){if(!t.length)return[];let r=await Promise.all(Lt(t,s=>s.address).map(s=>P({client:e,bytecode:s.bytecode,label:`${s.name} module`})));d("installing modules:",t.map(s=>s.name).join(", "));let n=await Promise.all(t.map(s=>s.installAsRoot?je(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"installRootModule",args:[s.address,s.installData]}):je(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"installModule",args:[s.address,s.installData]})));return(await Promise.all([...r,...n])).flat()}import{getAddress as Fe}from"viem";import{hexToResource as Re,resourceToHex as Kt}from"@latticexyz/common";async function $e({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(a=>Re(a).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(a=>Re(a).namespace))),c=r.filter(a=>s.includes(a)),p=(await Promise.all(c.map(async a=>{let{owner:f}=await A({client:e,worldDeploy:o,table:k.world_NamespaceOwner,key:{namespaceId:Kt({type:"namespace",namespace:a,name:""})}});return[a,f]}))).filter(([,a])=>Fe(a)!==Fe(e.account.address)).map(([a])=>a);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`)}async function He({client:e,config:o,worldAddress:t}){await le(e);let r=t?await Pe(e,t):await Se(e);if(!me.includes(r.storeVersion))throw new Error(`Unsupported Store version: ${r.storeVersion}`);if(!pe.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 c=await De({client:e,worldDeploy:r,tables:n}),i=await Ie({client:e,worldDeploy:r,systems:s}),p=await We({client:e,worldDeploy:r,functions:s.flatMap(u=>u.functions)}),a=await Ee({client:e,worldDeploy:r,modules:o.modules}),f=[...c,...i,...p,...a];d("waiting for transactions to confirm");for(let u of f)await zt(e,{hash:u});return d("deploy complete"),r}import{createWalletClient as pr,http as fr}from"viem";import{privateKeyToAccount as ur}from"viem/accounts";import{loadConfig as yr}from"@latticexyz/config/node";import{forge as qe,getOutDirectory as gr,getRemappings as br,getRpcUrl as hr,getSrcDirectory as wr}from"@latticexyz/common/foundry";import F from"chalk";import{execa as xr}from"execa";import{MUDError as Sr}from"@latticexyz/common/errors";import{resolveWorldConfig as Zt}from"@latticexyz/world";import{resourceToHex as Y,hexToResource as Qt}from"@latticexyz/common";import{resolveWithContext as Xt}from"@latticexyz/config";import{encodeField as er}from"@latticexyz/protocol-parser";import{getFunctionSelector as _e,getCreate2Address as Le,getAddress as or,hexToBytes as tr,bytesToHex as rr,getFunctionSignature as Ke}from"viem";import Jt from"glob";import{basename as qt}from"path";function E(e){return Jt.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:qt(o,".sol")}))}import Be from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import Ne from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Ue from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var Ve=[{name:"KeysWithValueModule",abi:Be.abi,bytecode:Be.bytecode},{name:"KeysInTableModule",abi:Ne.abi,bytecode:Ne.bytecode},{name:"UniqueEntityModule",abi:Ue.abi,bytecode:Ue.bytecode}];import{readFileSync as Gt}from"fs";import Yt from"path";import{MUDError as G}from"@latticexyz/common/errors";function z(e,o){let t,r=Yt.join(o,e+".sol",e+".json");try{t=JSON.parse(Gt(r,"utf8"))}catch{throw new G(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new G(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new G(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function ze({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=B(e),n=E(o).map(({basename:m})=>m),s=Zt(e,n),i=z("System",t).abi.filter(m=>m.type==="function").map(Ke),p=Object.entries(s.systems).map(([m,y])=>{let h=e.namespace,g=y.name,b=Y({type:"system",namespace:h,name:g}),l=z(m,t),w=l.abi.filter(x=>x.type==="function").map(Ke).filter(x=>!i.includes(x)).map(x=>{let oe=h===""?x:`${h}_${g}_${x}`;return{signature:oe,selector:_e(oe),systemId:b,systemFunctionSignature:x,systemFunctionSelector:_e(x)}});return{namespace:h,name:g,systemId:b,allowAll:y.openAccess,allowedAddresses:y.accessListAddresses,allowedSystemIds:y.accessListSystems.map(x=>Y({type:"system",namespace:h,name:s.systems[x].name})),address:Le({from:C,bytecode:l.bytecode,salt:D}),bytecode:l.bytecode,abi:l.abi,functions:w}}),a=p.map(({allowedAddresses:m,allowedSystemIds:y,...h})=>{let g=y.map(b=>{let l=p.find(w=>w.systemId===b);if(!l)throw new Error(`System ${T(h)} wanted access to ${T(Qt(b))}, but it wasn't found in the config.`);return l.address});return{...h,allowedAddresses:Array.from(new Set([...m,...g].map(b=>or(b))))}}),f={tableIds:Object.fromEntries(Object.entries(e.tables).map(([m,y])=>[m,tr(Y({type:y.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:y.name}))]))},u=Ve.map(m=>({name:m.name,bytecode:typeof m.bytecode=="string"?m.bytecode:m.bytecode.object,abi:m.abi})),v=e.modules.map(m=>{let y=u.find(g=>g.name===m.name)??z(m.name,t),h=m.args.map(g=>Xt(g,f)).map(g=>{let b=g.value instanceof Uint8Array?rr(g.value):g.value;return er(g.type,b)});if(h.length>1)throw new Error(`${m.name} module should only have 0-1 args, but had ${h.length} args.`);return{name:m.name,installAsRoot:m.root,installData:h.length===0?"0x":h[0],address:Le({from:C,bytecode:y.bytecode,salt:D}),bytecode:y.bytecode,abi:y.abi}});return{tables:r,systems:a,modules:v}}import{getChainId as vr}from"viem/actions";import{existsSync as nr}from"fs";import sr from"path";import ir from"chalk";import{getScriptDirectory as ar,forge as cr}from"@latticexyz/common/foundry";async function Je(e,o,t,r){let n=sr.join(await ar(),e+".s.sol");nr(n)?(console.log(ir.blue(`Executing post deploy script at ${n}`)),await cr(["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 Cr}from"@latticexyz/store/codegen";var M={configPath:{type:"string",desc:"Path to the config file"},clean:{type:"boolean",desc:"Remove the build forge artifacts and cache directories before building",default:!1},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"}};async function R(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await yr(e.configPath);e.printConfig&&console.log(F.green(`
|
|
5
|
+
- `});console.log(H.redBright(o.message))}else e instanceof Eo?(console.log(H.red(e.message)),console.log(""),console.log(H.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Fo?console.log(H.red(e)):console.log(e)}import J from"node:path";import{existsSync as cr,mkdirSync as lr,readFileSync as dr,writeFileSync as Z}from"node:fs";import{getBytecode as Ho,sendRawTransaction as Bo,sendTransaction as No,waitForTransactionReceipt as ce}from"viem/actions";var O={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import $o from"debug";var ae=$o("mud:cli");var d=ae.extend("deploy");var C=`0x${O.address}`;async function le(e){if(await Ho(e,{address:C})){d("found create2 deployer at",C);return}d("sending gas for create2 deployer to signer at",O.signerAddress);let t=await No(e,{chain:e.chain??null,to:`0x${O.signerAddress}`,value:BigInt(O.gasLimit)*BigInt(O.gasPrice)}),r=await ce(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 Bo(e,{serializedTransaction:`0x${O.transaction}`}),s=await ce(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 it}from"viem/actions";import Qo from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import Xo from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as et,getCreate2Address as fe,encodeDeployData as ue}from"viem";import{concatHex as qo,getCreate2Address as Go}from"viem";import{getBytecode as Yo}from"viem/actions";import{padHex as Vo}from"viem";import _o from"@latticexyz/store/mud.config.js";import Lo from"@latticexyz/world/mud.config.js";import Ko from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Uo}from"@latticexyz/common";import{resolveUserTypes as de}from"@latticexyz/store";function B(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:Uo({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:de(r.keySchema,o),valueSchema:de(r.valueSchema,o)}]))}import{helloStoreEvent as zo}from"@latticexyz/store";import{helloWorldEvent as Jo}from"@latticexyz/world";var D=Vo("0x",{size:32}),j=B(_o),k=B(Lo),U=[zo,Jo],S=Ko,me=["1.0.0-unaudited"],pe=["1.0.0-unaudited"];import{sendTransaction as Zo}from"@latticexyz/common";async function P({client:e,bytecode:o,label:t="contract"}){let r=Go({from:C,salt:D,bytecode:o});return await Yo(e,{address:r,blockTag:"pending"})?(d("found",t,"at",r),[]):(d("deploying",t,"at",r),[await Zo(e,{chain:e.chain??null,to:C,data:qo([D,o])})])}var ye=ue({bytecode:Qo.bytecode.object,abi:[]}),ot=fe({from:C,bytecode:ye,salt:D}),ge=ue({bytecode:Xo.bytecode.object,abi:et(["constructor(address)"]),args:[ot]}),be=fe({from:C,bytecode:ge,salt:D});async function he(e){return(await Promise.all([P({client:e,bytecode:ye,label:"core module"}),P({client:e,bytecode:ge,label:"world factory"})])).flat()}import at from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as ct}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as tt,decodeEventLog as rt,hexToString as we,parseAbi as nt,trim as xe}from"viem";import{isDefined as st}from"@latticexyz/common/utils";function V(e){let o=e.map(c=>{try{return{...c,...rt({strict:!0,abi:nt(U),topics:c.topics,data:c.data})}}catch(i){if(i instanceof tt)return;throw i}}).filter(st),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((c,i)=>({...c,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:we(xe(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:we(xe(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 Se(e){await he(e),d("deploying world");let o=await ct(e,{chain:e.chain??null,address:be,abi:at,functionName:"deployWorld"});d("waiting for world deploy");let t=await it(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 yt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as gt,keySchemaToHex as bt,valueSchemaToHex as ht}from"@latticexyz/protocol-parser";function T({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as lt,decodeAbiParameters as ve,parseAbiParameters as Ce}from"viem";import{hexToResource as dt}from"@latticexyz/common";import{storeSetRecordEvent as mt}from"@latticexyz/store";import{getLogs as pt}from"viem/actions";import{decodeKey as ft,decodeValueArgs as ut,hexToSchema as Te}from"@latticexyz/protocol-parser";async function ke({client:e,worldDeploy:o}){d("looking up tables for",o.address);let r=(await pt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:lt(mt),args:{tableId:j.store_Tables.tableId}})).map(n=>{let{tableId:s}=ft(j.store_Tables.keySchema,n.args.keyTuple),{namespace:c,name:i}=dt(s),p=ut(j.store_Tables.valueSchema,n.args),a=Te(p.keySchema),f=Te(p.valueSchema),u=ve(Ce("string[]"),p.abiEncodedKeyNames)[0],v=ve(Ce("string[]"),p.abiEncodedFieldNames)[0],m=[...f.staticFields,...f.dynamicFields],y=Object.fromEntries(a.staticFields.map((g,b)=>[u[b],g])),h=Object.fromEntries(m.map((g,b)=>[v[b],g]));return{namespace:c,name:i,tableId:s,keySchema:y,valueSchema:h}});return d("found",r.length,"tables for",o.address),r}async function De({client:e,worldDeploy:o,tables:t}){let n=(await ke({client:e,worldDeploy:o})).map(i=>i.tableId),s=t.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(T).join(", "));let c=t.filter(i=>!n.includes(i.tableId));return c.length?(d("registering tables",c.map(T).join(", ")),await Promise.all(c.map(i=>yt(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerTable",args:[i.tableId,gt(i.valueSchema),bt(i.keySchema),ht(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as wt}from"viem";import{getLogs as xt}from"viem/actions";import{storeSpliceStaticDataEvent as St}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let r=(await xt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:wt(St),args:{tableId:j.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",r.length,"resource IDs for",o.address),r}import{hexToResource as Rt}from"@latticexyz/common";import{decodeValueArgs as vt,encodeKey as Ct}from"@latticexyz/protocol-parser";import{readContract as Tt}from"viem/actions";async function A({client:e,worldDeploy:o,table:t,key:r}){let[n,s,c]=await Tt(e,{blockNumber:o.stateBlock,address:o.address,abi:S,functionName:"getRecord",args:[t.tableId,Ct(t.keySchema,r)]});return vt(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:c})}import{getFunctionSelector as kt,parseAbiItem as Dt}from"viem";import{storeSetRecordEvent as At}from"@latticexyz/store";import{getLogs as It}from"viem/actions";import{decodeValueArgs as Ot}from"@latticexyz/protocol-parser";import{hexToResource as Pt}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let r=(await It(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Dt(At),args:{tableId:k.world_FunctionSignatures.tableId}})).map(s=>Ot(k.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let c=kt(s),{systemId:i,systemFunctionSelector:p}=await A({client:e,worldDeploy:o,table:k.world_FunctionSelectors,key:{functionSelector:c}}),{namespace:a,name:f}=Pt(i),u=a===""?s:s.replace(`${a}_${f}_`,"");return{signature:s,selector:c,systemId:i,systemFunctionSignature:u,systemFunctionSelector:p}}))}import{parseAbiItem as Mt,getAddress as Wt}from"viem";import{storeSpliceStaticDataEvent as jt}from"@latticexyz/store";import{getLogs as Et}from"viem/actions";import{decodeKey as Ft}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let r=(await Et(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Mt(jt),args:{tableId:k.world_ResourceAccess.tableId}})).map(s=>Ft(k.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await A({client:e,worldDeploy:o,table:k.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Wt(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Ae({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(Rt).filter(c=>c.type==="system");return d("looking up systems",s.map(T).join(", ")),await Promise.all(s.map(async c=>{let{system:i,publicAccess:p}=await A({client:e,worldDeploy:o,table:k.world_Systems,key:{systemId:c.resourceId}}),a=r.filter(f=>f.systemId===c.resourceId);return{address:i,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:p,allowedAddresses:n.filter(({resourceId:f})=>f===c.resourceId).map(({address:f})=>f),functions:a}}))}import{uniqueBy as $t}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Ae({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(l=>l.systemId),c=n.filter(({resourceId:l})=>s.includes(l)),i=t.flatMap(l=>l.allowedAddresses.map(w=>({resourceId:l.systemId,address:w}))),p=i.filter(l=>!c.some(({resourceId:w,address:x})=>w===l.resourceId&&I(x)===I(l.address))),a=c.filter(l=>!i.some(({resourceId:w,address:x})=>w===l.resourceId&&I(x)===I(l.address)));a.length&&d("revoking",a.length,"access grants"),p.length&&d("adding",p.length,"access grants");let f=await Promise.all([...a.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"revokeAccess",args:[l.resourceId,l.address]})),...p.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"grantAccess",args:[l.resourceId,l.address]}))]),u=t.filter(l=>r.some(w=>w.systemId===l.systemId&&I(w.address)===I(l.address)));u.length&&d("existing systems",u.map(T).join(", "));let v=u.map(l=>l.systemId),m=t.filter(l=>!v.includes(l.systemId));if(!m.length)return[];let y=m.filter(l=>r.some(w=>w.systemId===l.systemId&&I(w.address)!==I(l.address)));y.length&&d("upgrading systems",y.map(T).join(", "));let h=m.filter(l=>!r.some(w=>w.systemId===l.systemId));h.length&&d("registering new systems",h.map(T).join(", "));let g=await Promise.all($t(m,l=>l.address).map(l=>P({client:e,bytecode:l.bytecode,label:`${T(l)} system`}))),b=await Promise.all(m.map(l=>q(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerSystem",args:[l.systemId,l.address,l.allowAll]})));return(await Promise.all([...f,...g,...b])).flat()}import{waitForTransactionReceipt as Kt}from"viem/actions";import{getAddress as Ht,parseAbi as Bt}from"viem";import{getBlockNumber as Nt,getLogs as Ut}from"viem/actions";var Oe=new Map;async function Pe(e,o){let t=Ht(o),r=Oe.get(t);if(r!=null)return r;d("looking up world deploy for",t);let n=await Nt(e),s=await Ut(e,{strict:!0,address:t,events:Bt(U),fromBlock:"earliest",toBlock:n});return r={...V(s),stateBlock:n},Oe.set(t,r),d("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as Vt,writeContract as Me}from"@latticexyz/common";async function We({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]),c=t.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(p=>p.signature).join(", "));let i=s.filter(p=>p.systemId!==n[p.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(p=>p.signature).join(", "))}return c.length?(d("registering functions:",c.map(i=>i.signature).join(", ")),Promise.all(c.map(i=>{let{namespace:p}=Vt(i.systemId);return p===""?Me(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}):Me(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]})}))):[]}import{writeContract as je}from"@latticexyz/common";import{uniqueBy as _t}from"@latticexyz/common/utils";async function Ee({client:e,worldDeploy:o,modules:t}){if(!t.length)return[];let r=await Promise.all(_t(t,s=>s.address).map(s=>P({client:e,bytecode:s.bytecode,label:`${s.name} module`})));d("installing modules:",t.map(s=>s.name).join(", "));let n=await Promise.all(t.map(s=>s.installAsRoot?je(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"installRootModule",args:[s.address,s.installData]}):je(e,{chain:e.chain??null,address:o.address,abi:S,functionName:"installModule",args:[s.address,s.installData]})));return(await Promise.all([...r,...n])).flat()}import{getAddress as Fe}from"viem";import{hexToResource as Re,resourceToHex as Lt}from"@latticexyz/common";async function $e({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(a=>Re(a).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(a=>Re(a).namespace))),c=r.filter(a=>s.includes(a)),p=(await Promise.all(c.map(async a=>{let{owner:f}=await A({client:e,worldDeploy:o,table:k.world_NamespaceOwner,key:{namespaceId:Lt({type:"namespace",namespace:a,name:""})}});return[a,f]}))).filter(([,a])=>Fe(a)!==Fe(e.account.address)).map(([a])=>a);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`)}async function He({client:e,config:o,worldAddress:t}){await le(e);let r=t?await Pe(e,t):await Se(e);if(!me.includes(r.storeVersion))throw new Error(`Unsupported Store version: ${r.storeVersion}`);if(!pe.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 c=await De({client:e,worldDeploy:r,tables:n}),i=await Ie({client:e,worldDeploy:r,systems:s}),p=await We({client:e,worldDeploy:r,functions:s.flatMap(u=>u.functions)}),a=await Ee({client:e,worldDeploy:r,modules:o.modules}),f=[...c,...i,...p,...a];d("waiting for transactions to confirm");for(let u of f)await Kt(e,{hash:u});return d("deploy complete"),r}import{createWalletClient as mr,http as pr}from"viem";import{privateKeyToAccount as fr}from"viem/accounts";import{loadConfig as ur}from"@latticexyz/config/node";import{forge as yr,getOutDirectory as gr,getRemappings as br,getRpcUrl as hr,getSrcDirectory as wr}from"@latticexyz/common/foundry";import F from"chalk";import{execa as xr}from"execa";import{MUDError as Sr}from"@latticexyz/common/errors";import{resolveWorldConfig as Yt}from"@latticexyz/world";import{resourceToHex as Y,hexToResource as Zt}from"@latticexyz/common";import{resolveWithContext as Qt}from"@latticexyz/config";import{encodeField as Xt}from"@latticexyz/protocol-parser";import{getFunctionSelector as _e,getCreate2Address as Le,getAddress as er,hexToBytes as or,bytesToHex as tr,getFunctionSignature as Ke}from"viem";import zt from"glob";import{basename as Jt}from"path";function E(e){return zt.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:Jt(o,".sol")}))}import Be from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import Ne from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Ue from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var Ve=[{name:"KeysWithValueModule",abi:Be.abi,bytecode:Be.bytecode},{name:"KeysInTableModule",abi:Ne.abi,bytecode:Ne.bytecode},{name:"UniqueEntityModule",abi:Ue.abi,bytecode:Ue.bytecode}];import{readFileSync as qt}from"fs";import Gt from"path";import{MUDError as G}from"@latticexyz/common/errors";function z(e,o){let t,r=Gt.join(o,e+".sol",e+".json");try{t=JSON.parse(qt(r,"utf8"))}catch{throw new G(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new G(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new G(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function ze({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=B(e),n=E(o).map(({basename:m})=>m),s=Yt(e,n),i=z("System",t).abi.filter(m=>m.type==="function").map(Ke),p=Object.entries(s.systems).map(([m,y])=>{let h=e.namespace,g=y.name,b=Y({type:"system",namespace:h,name:g}),l=z(m,t),w=l.abi.filter(x=>x.type==="function").map(Ke).filter(x=>!i.includes(x)).map(x=>{let oe=h===""?x:`${h}_${g}_${x}`;return{signature:oe,selector:_e(oe),systemId:b,systemFunctionSignature:x,systemFunctionSelector:_e(x)}});return{namespace:h,name:g,systemId:b,allowAll:y.openAccess,allowedAddresses:y.accessListAddresses,allowedSystemIds:y.accessListSystems.map(x=>Y({type:"system",namespace:h,name:s.systems[x].name})),address:Le({from:C,bytecode:l.bytecode,salt:D}),bytecode:l.bytecode,abi:l.abi,functions:w}}),a=p.map(({allowedAddresses:m,allowedSystemIds:y,...h})=>{let g=y.map(b=>{let l=p.find(w=>w.systemId===b);if(!l)throw new Error(`System ${T(h)} wanted access to ${T(Zt(b))}, but it wasn't found in the config.`);return l.address});return{...h,allowedAddresses:Array.from(new Set([...m,...g].map(b=>er(b))))}}),f={tableIds:Object.fromEntries(Object.entries(e.tables).map(([m,y])=>[m,or(Y({type:y.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:y.name}))]))},u=Ve.map(m=>({name:m.name,bytecode:typeof m.bytecode=="string"?m.bytecode:m.bytecode.object,abi:m.abi})),v=e.modules.map(m=>{let y=u.find(g=>g.name===m.name)??z(m.name,t),h=m.args.map(g=>Qt(g,f)).map(g=>{let b=g.value instanceof Uint8Array?tr(g.value):g.value;return Xt(g.type,b)});if(h.length>1)throw new Error(`${m.name} module should only have 0-1 args, but had ${h.length} args.`);return{name:m.name,installAsRoot:m.root,installData:h.length===0?"0x":h[0],address:Le({from:C,bytecode:y.bytecode,salt:D}),bytecode:y.bytecode,abi:y.abi}});return{tables:r,systems:a,modules:v}}import{getChainId as vr}from"viem/actions";import{existsSync as rr}from"fs";import nr from"path";import sr from"chalk";import{getScriptDirectory as ir,forge as ar}from"@latticexyz/common/foundry";async function Je(e,o,t,r){let n=nr.join(await ir(),e+".s.sol");rr(n)?(console.log(sr.blue(`Executing post deploy script at ${n}`)),await ar(["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 Cr}from"@latticexyz/store/codegen";var M={configPath:{type:"string",desc:"Path to the config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"}};async function R(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await ur(e.configPath);e.printConfig&&console.log(F.green(`
|
|
6
6
|
Resolved config:
|
|
7
7
|
`),JSON.stringify(t,null,2));let r=e.srcDir??await wr(o),n=await gr(o),s=await br(),c=e.rpc??await hr(o);if(console.log(F.bgBlue(F.whiteBright(`
|
|
8
8
|
Deploying MUD contracts${o?" with profile "+o:""} to RPC ${c}
|
|
9
|
-
`)))
|
|
9
|
+
`))),!e.skipBuild){let m=J.join(r,t.codegenDirectory);await Cr(t,m,s),await yr(["build","--skip","test","script"],{profile:o}),await xr("mud",["abi-ts"],{stdio:"inherit"})}let i=process.env.PRIVATE_KEY;if(!i)throw new Sr(`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 p=ze({config:t,forgeSourceDir:r,forgeOutDir:n}),a=
|
|
11
|
+
in your contracts directory to use the default anvil private key.`);let p=ze({config:t,forgeSourceDir:r,forgeOutDir:n}),a=mr({transport:pr(c),account:fr(i)});console.log("Deploying from",a.account.address);let f=Date.now(),u=await He({worldAddress:e.worldAddress,client:a,config:p});e.worldAddress==null&&await Je(t.postDeployScript,u.address,c,o),console.log(F.green("Deployment completed in",(Date.now()-f)/1e3,"seconds"));let v={worldAddress:u.address,blockNumber:Number(u.deployBlock)};if(e.saveDeployment){let m=await vr(a),y=J.join(t.deploysDirectory,m.toString());lr(y,{recursive:!0}),Z(J.join(y,"latest.json"),JSON.stringify(v,null,2)),Z(J.join(y,Date.now()+".json"),JSON.stringify(v,null,2));let h=[1337,31337],g=cr(t.worldsFile)?JSON.parse(dr(t.worldsFile,"utf-8")):{};g[m]={address:v.worldAddress,blockNumber:h.includes(m)?void 0:v.blockNumber},Z(t.worldsFile,JSON.stringify(g,null,2)),console.log(F.bgGreen(F.whiteBright(`
|
|
12
12
|
Deployment result (written to ${t.worldsFile} and ${y}):
|
|
13
|
-
`)))}return console.log(v),u}var Tr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await R(e)}catch(o){W(o),process.exit(1)}process.exit(0)}},
|
|
13
|
+
`)))}return console.log(v),u}var Tr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await R(e)}catch(o){W(o),process.exit(1)}process.exit(0)}},qe=Tr;import{loadConfig as kr}from"@latticexyz/config/node";import{worldgen as Dr}from"@latticexyz/world/node";import{getSrcDirectory as Ar}from"@latticexyz/common/foundry";import Ge from"path";import{rmSync as Ir}from"fs";var Or={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 Pr(e),process.exit(0)}};async function Pr(e){let o=e.srcDir??await Ar(),t=E(o),r=e.config??await kr(e.configPath),n=Ge.join(o,r.codegenDirectory);e.clean&&Ir(Ge.join(n,r.worldgenDirectory),{recursive:!0,force:!0}),await Dr(r,t,n)}var Ye=Or;import N from"chalk";import{readFileSync as Fr,writeFileSync as Rr}from"fs";import X from"path";import{MUDError as $}from"@latticexyz/common/errors";var Ze={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",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 $r from"glob";import{ZodError as Wr,z as Qe}from"zod";var jr=Qe.object({MUD_PACKAGES:Qe.string().transform(e=>JSON.parse(e))});function Er(){try{return jr.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 Wr){let{_errors:o,...t}=e.format();console.error(`
|
|
14
14
|
Missing or invalid environment variables:
|
|
15
15
|
|
|
16
16
|
${Object.keys(t).join(`
|
|
17
17
|
`)}
|
|
18
|
-
`),process.exit(1)}throw e}}var Q=Er().MUD_PACKAGES;var Hr={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 $(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new $(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Br(e);let r=$r.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Nr(n,e)}catch(o){W(o)}finally{process.exit(0)}}};async function Br(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(N.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${
|
|
19
|
-
`),console.log(`Updating ${e}`),
|
|
18
|
+
`),process.exit(1)}throw e}}var Q=Er().MUD_PACKAGES;var Hr={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 $(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new $(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Br(e);let r=$r.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Nr(n,e)}catch(o){W(o)}finally{process.exit(0)}}};async function Br(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(N.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Ze.name}`)).json()}catch{throw new $("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new $(`Could not find npm version with tag "${e.tag}"`);return console.log(N.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 $(`Could not find npm version based on commit "${e.commit}"`);return console.log(N.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Nr(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ur(e),s=Object.keys(Q),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]=p(a,"dependencies"));for(let a in n.devDependencies)s.includes(a)&&(n.devDependencies[a]=p(a,"devDependencies"));return Rr(e,JSON.stringify(n,null,2)+`
|
|
19
|
+
`),console.log(`Updating ${e}`),Xe(c,n.dependencies),Xe(i,n.devDependencies),n;function p(a,f){return t&&(r=Vr(e,t,a)),r||n[f][a]}}function Ur(e){try{let o=Fr(e,"utf8");return JSON.parse(o)}catch{throw new $("Could not read JSON at "+e)}}function Xe(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${N.red(e[t])} -> ${N.green(o[t])}`)}function Vr(e,o,t){let r=X.relative(X.dirname(e),process.cwd());return"link:"+X.join(r,o,Q[t].localPath)}var eo=Hr;import{anvil as _r,forge as Lr,getRpcUrl as Kr}from"@latticexyz/common/foundry";import zr from"chalk";var Jr={...M,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}},qr={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Jr)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];_r(n)}let o=e.worldAddress?await Kr(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await R({...e,saveDeployment:!1,rpc:o})).address;console.log(zr.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Lr(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},oo=qr;import{existsSync as Gr,readFileSync as Yr}from"fs";import{ethers as to}from"ethers";import{loadConfig as Zr}from"@latticexyz/config/node";import{MUDError as ro}from"@latticexyz/common/errors";import{cast as Qr,getRpcUrl as Xr,getSrcDirectory as en}from"@latticexyz/common/foundry";import{resolveWorldConfig as on}from"@latticexyz/world";import tn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import no from"@latticexyz/world/mud.config.js";import{resourceToHex as io}from"@latticexyz/common";import{createClient as rn,http as nn}from"viem";import{getChainId as sn}from"viem/actions";var so=io({type:"system",namespace:no.namespace,name:no.tables.Systems.name}),an={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 en(o),e.rpc??=await Xr(o);let{tx:t,configPath:r,srcDir:n,rpc:s}=e,c=E(n),i=await Zr(r),p=on(i,c.map(({basename:b})=>b)),a=e.worldAddress??await cn(i.worldsFile,s),f=new to.providers.StaticJsonRpcProvider(s),u=new to.Contract(a,tn,f),v=i.namespace,m=Object.values(p.systems).map(({name:b})=>b),y=await u.getFieldLayout(so),h=[];for(let b of m){let l=io({type:"system",namespace:v,name:b}),w=await u.getField(so,[l],0,y);h.push({name:b,address:w})}let g=await Qr(["run","--label",`${a}:World`,...h.map(({name:b,address:l})=>["--label",`${l}:${b}`]).flat(),`${t}`]);console.log(g),process.exit(0)}},ao=an;async function cn(e,o){if(Gr(e)){let t=rn({transport:nn(o)}),r=await sn(t),n=JSON.parse(Yr(e,"utf-8"));if(!n[r])throw new ro(`chainId ${r} is missing in worldsFile "${e}"`);return n[r].address}else throw new ro("worldAddress is not specified and worldsFile is missing")}import{anvil as ln,getScriptDirectory as dn,getSrcDirectory as mn}from"@latticexyz/common/foundry";import ee from"chalk";import pn from"chokidar";import{loadConfig as fn,resolveConfigPath as un}from"@latticexyz/config/node";import yn from"path";import{homedir as gn}from"os";import{rmSync as bn}from"fs";import{BehaviorSubject as hn,debounceTime as wn,exhaustMap as xn}from"rxjs";var Sn={rpc:M.rpc,configPath:M.configPath},vn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Sn)},async handler(e){let o=e.rpc,t=e.configPath??await un(e.configPath),r=await mn(),n=await dn(),s=await fn(t);if(!e.rpc){console.log(ee.gray("Cleaning devnode cache"));let a=gn();bn(yn.join(a,".foundry","anvil","tmp"),{recursive:!0,force:!0}),ln(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let c=new hn(Date.now());pn.watch([t,r,n]).on("all",async(a,f)=>{f.includes(t)&&c.next(Date.now()),(f.includes(r)||f.includes(n))&&(f.includes(s.codegenDirectory)||c.next(Date.now()))});let i;c.pipe(wn(200),xn(async a=>{i&&console.log(ee.blue("Change detected, rebuilding and running deploy..."));let f=await R({configPath:t,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:r});return i=f.address,a<c.value?c.next(c.value):console.log(ee.gray("Watching for file changes...")),f})).subscribe()}},co=vn;var lo=[qe,te,ne,Cn,se,ie,Ye,eo,oo,ao,co,Tn];import*as po from"dotenv";import mo from"chalk";po.config();kn(Dn(process.argv)).scriptName("mud").command(lo).strict().fail((e,o)=>{console.error(mo.red(e)),e.includes("Missing required argument")&&console.log(mo.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(W(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 clean: {\n type: \"boolean\",\n desc: \"Remove the build forge artifacts and cache directories before building\",\n default: false,\n },\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} 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 if (opts.clean) {\n await forge([\"clean\"], { profile });\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) {\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\";\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 sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployer,\n data: concatHex([salt, bytecode]),\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 System = {\n readonly namespace: string;\n readonly name: string;\n readonly systemId: Hex;\n readonly allowAll: boolean;\n readonly allowedAddresses: readonly Hex[];\n readonly address: Address;\n readonly bytecode: Hex;\n readonly abi: Abi;\n readonly functions: readonly WorldFunction[];\n};\n\nexport type Module = {\n readonly name: string;\n readonly installAsRoot: boolean;\n readonly installData: Hex; // TODO: figure out better naming for this\n readonly address: Address;\n readonly bytecode: Hex;\n readonly abi: Abi;\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\";\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 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 );\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 { ensureContract } from \"./ensureContract\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { getSystems } from \"./getSystems\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\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 = await Promise.all([\n ...accessToRemove.map((access) =>\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 ...accessToAdd.map((access) =>\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 ]);\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 // kick off contract deployments first, otherwise registering systems can fail\n const contractTxs = await Promise.all(\n uniqueBy(missingSystems, (system) => system.address).map((system) =>\n ensureContract({ client, bytecode: system.bytecode, label: `${resourceLabel(system)} system` })\n )\n );\n\n // then start registering systems\n const registerTxs = await Promise.all(\n missingSystems.map((system) =>\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 );\n\n return (await Promise.all([...accessTxs, ...contractTxs, ...registerTxs])).flat();\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 { getTransactionReceipt, 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\";\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 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 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\";\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 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 return 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 );\n}\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { ensureContract } from \"./ensureContract\";\nimport { debug } from \"./debug\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\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 // kick off contract deployments first, otherwise installing modules can fail\n const contractTxs = await Promise.all(\n uniqueBy(modules, (mod) => mod.address).map((mod) =>\n ensureContract({ client, bytecode: mod.bytecode, label: `${mod.name} module` })\n )\n );\n\n // then start installing modules\n debug(\"installing modules:\", modules.map((mod) => mod.name).join(\", \"));\n const installTxs = await Promise.all(\n modules.map((mod) =>\n mod.installAsRoot\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 : 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 );\n\n return (await Promise.all([...contractTxs, ...installTxs])).flat();\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 \"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};\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 configPath,\n rpc,\n clean: true,\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,EAAU,KAAK,GAAG,GAAG,EACnD,IAAMC,EAAQN,GAAM,QAASK,EAAW,CACtC,MAAO,CAAC,UAAW,UAAW,SAAS,CACzC,CAAC,EAED,QAAQ,GAAG,SAAU,IAAM,CACzB,QAAQ,IAAI;AAAA,8CAAiD,EAC7DC,EAAM,KAAK,EACX,QAAQ,KAAK,CACf,CAAC,EACD,MAAMA,CACR,CACF,EAEOC,GAAQN,GCxCf,OAAS,2BAAAO,OAA+B,8BACxC,OAAS,iBAAAC,GAAe,gBAAAC,OAAoB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EACA,IAAAD,EACA,MAAO,GACP,UAAW,GACX,YAAa,GACb,QAAS,OACT,eAAgB,GAChB,aAAAmB,EACA,OAAAhB,CACF,CAAC,EACD,OAAAgB,EAAeE,EAAO,QAElBD,EAAaL,EAAY,MAC3BA,EAAY,KAAKA,EAAY,KAAK,EAElC,QAAQ,IAAIN,GAAM,KAAK,8BAA8B,CAAC,EAEjDY,CACT,CAAC,CACH,EAES,UAAU,CACrB,CACF,EAEOE,GAAQ1B,G3CpFR,IAAM2B,GAAsC,CACjDC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,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","ensureContract","client","bytecode","label","address","getCreate2Address","deployer","salt","getBytecode","debug","sendTransaction","concatHex","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","ensureTables","client","worldDeploy","tables","worldTableIds","getTables","table","existingTables","debug","resourceLabel","missingTables","writeContract","worldAbi","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","getAddress","writeContract","parseAbiItem","getLogs","storeSpliceStaticDataEvent","getResourceIds","client","worldDeploy","debug","resourceIds","getLogs","parseAbiItem","storeSpliceStaticDataEvent","storeTables","log","hexToResource","decodeValueArgs","encodeKey","readContract","getTableValue","client","worldDeploy","table","key","staticData","encodedLengths","dynamicData","worldAbi","encodeKey","decodeValueArgs","getFunctionSelector","parseAbiItem","storeSetRecordEvent","getLogs","decodeValueArgs","hexToResource","getFunctions","client","worldDeploy","debug","signatures","getLogs","parseAbiItem","storeSetRecordEvent","worldTables","log","decodeValueArgs","signature","selector","getFunctionSelector","systemId","systemFunctionSelector","getTableValue","namespace","name","systemFunctionSignature","parseAbiItem","getAddress","storeSpliceStaticDataEvent","getLogs","decodeKey","getResourceAccess","client","worldDeploy","debug","keys","getLogs","parseAbiItem","storeSpliceStaticDataEvent","worldTables","log","decodeKey","access","key","getTableValue","value","getAddress","getSystems","client","worldDeploy","resourceIds","functions","resourceAccess","getResourceIds","getFunctions","getResourceAccess","systems","hexToResource","resource","debug","resourceLabel","system","address","publicAccess","getTableValue","worldTables","systemFunctions","func","resourceId","uniqueBy","ensureSystems","client","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","systemIds","system","currentAccess","resourceId","desiredAccess","address","accessToAdd","access","getAddress","accessToRemove","debug","accessTxs","writeContract","worldAbi","existingSystems","worldSystem","resourceLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","contractTxs","ensureContract","registerTxs","waitForTransactionReceipt","getAddress","parseAbi","getBlockNumber","getLogs","deploys","getWorldDeploy","client","worldAddress","address","getAddress","deploy","debug","stateBlock","getBlockNumber","logs","getLogs","parseAbi","worldDeployEvents","logsToWorldDeploy","hexToResource","writeContract","ensureFunctions","client","worldDeploy","functions","worldFunctions","getFunctions","worldSelectorToFunction","func","toSkip","toAdd","debug","wrongSystem","namespace","hexToResource","writeContract","worldAbi","writeContract","uniqueBy","ensureModules","client","worldDeploy","modules","contractTxs","mod","ensureContract","debug","installTxs","writeContract","worldAbi","getAddress","hexToResource","resourceToHex","assertNamespaceOwner","client","worldDeploy","resourceIds","desiredNamespaces","resourceId","hexToResource","existingResourceIds","getResourceIds","existingNamespaces","namespaces","namespace","unauthorizedNamespaces","owner","getTableValue","worldTables","resourceToHex","getAddress","deploy","client","config","existingWorldAddress","ensureDeployer","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","tables","systems","assertNamespaceOwner","table","system","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","debug","tx","waitForTransactionReceipt","createWalletClient","http","privateKeyToAccount","loadConfig","forge","getOutDirectory","getRemappings","getRpcUrl","getSrcDirectory","chalk","execa","MUDError","resolveWorldConfig","resourceToHex","hexToResource","resolveWithContext","encodeField","getFunctionSelector","getCreate2Address","getAddress","hexToBytes","bytesToHex","getFunctionSignature","glob","basename","getExistingContracts","srcDir","path","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","defaultModuleContracts","readFileSync","path","MUDError","getContractData","contractName","forgeOutDirectory","data","contractDataPath","bytecode","abi","resolveConfig","config","forgeSourceDir","forgeOutDir","tables","configToTables","contractNames","getExistingContracts","basename","resolvedConfig","resolveWorldConfig","baseSystemFunctions","getContractData","item","getFunctionSignature","systems","systemName","system","namespace","name","systemId","resourceToHex","contractData","systemFunctions","sig","worldSignature","getFunctionSelector","getCreate2Address","deployer","salt","systemsWithAccess","allowedAddresses","allowedSystemIds","allowedSystemAddresses","targetSystem","s","resourceLabel","hexToResource","addr","getAddress","resolveContext","tableName","table","hexToBytes","defaultModules","defaultModuleContracts","mod","modules","defaultMod","installArgs","arg","resolveWithContext","value","bytesToHex","encodeField","getChainId","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","postDeployPath","tablegen","deployOptions","runDeploy","opts","profile","config","loadConfig","chalk","srcDir","getSrcDirectory","outDir","getOutDirectory","remappings","getRemappings","rpc","getRpcUrl","forge","outPath","path","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, rmSync, 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} 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) {\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\";\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 sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployer,\n data: concatHex([salt, bytecode]),\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 System = {\n readonly namespace: string;\n readonly name: string;\n readonly systemId: Hex;\n readonly allowAll: boolean;\n readonly allowedAddresses: readonly Hex[];\n readonly address: Address;\n readonly bytecode: Hex;\n readonly abi: Abi;\n readonly functions: readonly WorldFunction[];\n};\n\nexport type Module = {\n readonly name: string;\n readonly installAsRoot: boolean;\n readonly installData: Hex; // TODO: figure out better naming for this\n readonly address: Address;\n readonly bytecode: Hex;\n readonly abi: Abi;\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\";\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 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 );\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 { ensureContract } from \"./ensureContract\";\nimport { debug } from \"./debug\";\nimport { resourceLabel } from \"./resourceLabel\";\nimport { getSystems } from \"./getSystems\";\nimport { getResourceAccess } from \"./getResourceAccess\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\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 = await Promise.all([\n ...accessToRemove.map((access) =>\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 ...accessToAdd.map((access) =>\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 ]);\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 // kick off contract deployments first, otherwise registering systems can fail\n const contractTxs = await Promise.all(\n uniqueBy(missingSystems, (system) => system.address).map((system) =>\n ensureContract({ client, bytecode: system.bytecode, label: `${resourceLabel(system)} system` })\n )\n );\n\n // then start registering systems\n const registerTxs = await Promise.all(\n missingSystems.map((system) =>\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 );\n\n return (await Promise.all([...accessTxs, ...contractTxs, ...registerTxs])).flat();\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 { getTransactionReceipt, 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\";\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 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 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\";\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 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 return 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 );\n}\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { writeContract } from \"@latticexyz/common\";\nimport { Module, WorldDeploy, worldAbi } from \"./common\";\nimport { ensureContract } from \"./ensureContract\";\nimport { debug } from \"./debug\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\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 // kick off contract deployments first, otherwise installing modules can fail\n const contractTxs = await Promise.all(\n uniqueBy(modules, (mod) => mod.address).map((mod) =>\n ensureContract({ client, bytecode: mod.bytecode, label: `${mod.name} module` })\n )\n );\n\n // then start installing modules\n debug(\"installing modules:\", modules.map((mod) => mod.name).join(\", \"));\n const installTxs = await Promise.all(\n modules.map((mod) =>\n mod.installAsRoot\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 : 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 );\n\n return (await Promise.all([...contractTxs, ...installTxs])).flat();\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 \"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};\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 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,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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","ensureContract","client","bytecode","label","address","getCreate2Address","deployer","salt","getBytecode","debug","sendTransaction","concatHex","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","ensureTables","client","worldDeploy","tables","worldTableIds","getTables","table","existingTables","debug","resourceLabel","missingTables","writeContract","worldAbi","valueSchemaToFieldLayoutHex","keySchemaToHex","valueSchemaToHex","getAddress","writeContract","parseAbiItem","getLogs","storeSpliceStaticDataEvent","getResourceIds","client","worldDeploy","debug","resourceIds","getLogs","parseAbiItem","storeSpliceStaticDataEvent","storeTables","log","hexToResource","decodeValueArgs","encodeKey","readContract","getTableValue","client","worldDeploy","table","key","staticData","encodedLengths","dynamicData","worldAbi","encodeKey","decodeValueArgs","getFunctionSelector","parseAbiItem","storeSetRecordEvent","getLogs","decodeValueArgs","hexToResource","getFunctions","client","worldDeploy","debug","signatures","getLogs","parseAbiItem","storeSetRecordEvent","worldTables","log","decodeValueArgs","signature","selector","getFunctionSelector","systemId","systemFunctionSelector","getTableValue","namespace","name","systemFunctionSignature","parseAbiItem","getAddress","storeSpliceStaticDataEvent","getLogs","decodeKey","getResourceAccess","client","worldDeploy","debug","keys","getLogs","parseAbiItem","storeSpliceStaticDataEvent","worldTables","log","decodeKey","access","key","getTableValue","value","getAddress","getSystems","client","worldDeploy","resourceIds","functions","resourceAccess","getResourceIds","getFunctions","getResourceAccess","systems","hexToResource","resource","debug","resourceLabel","system","address","publicAccess","getTableValue","worldTables","systemFunctions","func","resourceId","uniqueBy","ensureSystems","client","worldDeploy","systems","worldSystems","worldAccess","getSystems","getResourceAccess","systemIds","system","currentAccess","resourceId","desiredAccess","address","accessToAdd","access","getAddress","accessToRemove","debug","accessTxs","writeContract","worldAbi","existingSystems","worldSystem","resourceLabel","existingSystemIds","missingSystems","systemsToUpgrade","systemsToAdd","contractTxs","ensureContract","registerTxs","waitForTransactionReceipt","getAddress","parseAbi","getBlockNumber","getLogs","deploys","getWorldDeploy","client","worldAddress","address","getAddress","deploy","debug","stateBlock","getBlockNumber","logs","getLogs","parseAbi","worldDeployEvents","logsToWorldDeploy","hexToResource","writeContract","ensureFunctions","client","worldDeploy","functions","worldFunctions","getFunctions","worldSelectorToFunction","func","toSkip","toAdd","debug","wrongSystem","namespace","hexToResource","writeContract","worldAbi","writeContract","uniqueBy","ensureModules","client","worldDeploy","modules","contractTxs","mod","ensureContract","debug","installTxs","writeContract","worldAbi","getAddress","hexToResource","resourceToHex","assertNamespaceOwner","client","worldDeploy","resourceIds","desiredNamespaces","resourceId","hexToResource","existingResourceIds","getResourceIds","existingNamespaces","namespaces","namespace","unauthorizedNamespaces","owner","getTableValue","worldTables","resourceToHex","getAddress","deploy","client","config","existingWorldAddress","ensureDeployer","worldDeploy","getWorldDeploy","deployWorld","supportedStoreVersions","supportedWorldVersions","tables","systems","assertNamespaceOwner","table","system","tableTxs","ensureTables","systemTxs","ensureSystems","functionTxs","ensureFunctions","moduleTxs","ensureModules","txs","debug","tx","waitForTransactionReceipt","createWalletClient","http","privateKeyToAccount","loadConfig","forge","getOutDirectory","getRemappings","getRpcUrl","getSrcDirectory","chalk","execa","MUDError","resolveWorldConfig","resourceToHex","hexToResource","resolveWithContext","encodeField","getFunctionSelector","getCreate2Address","getAddress","hexToBytes","bytesToHex","getFunctionSignature","glob","basename","getExistingContracts","srcDir","path","KeysWithValueModuleData","KeysInTableModuleData","UniqueEntityModuleData","defaultModuleContracts","readFileSync","path","MUDError","getContractData","contractName","forgeOutDirectory","data","contractDataPath","bytecode","abi","resolveConfig","config","forgeSourceDir","forgeOutDir","tables","configToTables","contractNames","getExistingContracts","basename","resolvedConfig","resolveWorldConfig","baseSystemFunctions","getContractData","item","getFunctionSignature","systems","systemName","system","namespace","name","systemId","resourceToHex","contractData","systemFunctions","sig","worldSignature","getFunctionSelector","getCreate2Address","deployer","salt","systemsWithAccess","allowedAddresses","allowedSystemIds","allowedSystemAddresses","targetSystem","s","resourceLabel","hexToResource","addr","getAddress","resolveContext","tableName","table","hexToBytes","defaultModules","defaultModuleContracts","mod","modules","defaultMod","installArgs","arg","resolveWithContext","value","bytesToHex","encodeField","getChainId","existsSync","path","chalk","getScriptDirectory","forge","postDeploy","postDeployScript","worldAddress","rpc","profile","postDeployPath","tablegen","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-
|
|
3
|
+
"version": "2.0.0-main-e667ee80",
|
|
4
4
|
"description": "Command line interface for mud",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -39,17 +39,17 @@
|
|
|
39
39
|
"yargs": "^17.7.1",
|
|
40
40
|
"zod": "^3.21.4",
|
|
41
41
|
"zod-validation-error": "^1.3.0",
|
|
42
|
-
"@latticexyz/abi-ts": "2.0.0-main-
|
|
43
|
-
"@latticexyz/common": "2.0.0-main-
|
|
44
|
-
"@latticexyz/config": "2.0.0-main-
|
|
45
|
-
"@latticexyz/gas-report": "2.0.0-main-
|
|
46
|
-
"@latticexyz/protocol-parser": "2.0.0-main-
|
|
47
|
-
"@latticexyz/schema-type": "2.0.0-main-
|
|
48
|
-
"@latticexyz/services": "2.0.0-main-
|
|
49
|
-
"@latticexyz/store": "2.0.0-main-
|
|
50
|
-
"@latticexyz/utils": "2.0.0-main-
|
|
51
|
-
"@latticexyz/world": "2.0.0-main-
|
|
52
|
-
"@latticexyz/world-modules": "2.0.0-main-
|
|
42
|
+
"@latticexyz/abi-ts": "2.0.0-main-e667ee80",
|
|
43
|
+
"@latticexyz/common": "2.0.0-main-e667ee80",
|
|
44
|
+
"@latticexyz/config": "2.0.0-main-e667ee80",
|
|
45
|
+
"@latticexyz/gas-report": "2.0.0-main-e667ee80",
|
|
46
|
+
"@latticexyz/protocol-parser": "2.0.0-main-e667ee80",
|
|
47
|
+
"@latticexyz/schema-type": "2.0.0-main-e667ee80",
|
|
48
|
+
"@latticexyz/services": "2.0.0-main-e667ee80",
|
|
49
|
+
"@latticexyz/store": "2.0.0-main-e667ee80",
|
|
50
|
+
"@latticexyz/utils": "2.0.0-main-e667ee80",
|
|
51
|
+
"@latticexyz/world": "2.0.0-main-e667ee80",
|
|
52
|
+
"@latticexyz/world-modules": "2.0.0-main-e667ee80"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/debug": "^4.1.7",
|
package/src/runDeploy.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { InferredOptionTypes, Options } from "yargs";
|
|
4
4
|
import { deploy } from "./deploy/deploy";
|
|
5
5
|
import { createWalletClient, http, Hex } from "viem";
|
|
@@ -19,11 +19,6 @@ import { tablegen } from "@latticexyz/store/codegen";
|
|
|
19
19
|
|
|
20
20
|
export const deployOptions = {
|
|
21
21
|
configPath: { type: "string", desc: "Path to the config file" },
|
|
22
|
-
clean: {
|
|
23
|
-
type: "boolean",
|
|
24
|
-
desc: "Remove the build forge artifacts and cache directories before building",
|
|
25
|
-
default: false,
|
|
26
|
-
},
|
|
27
22
|
printConfig: { type: "boolean", desc: "Print the resolved config" },
|
|
28
23
|
profile: { type: "string", desc: "The foundry profile to use" },
|
|
29
24
|
saveDeployment: { type: "boolean", desc: "Save the deployment info to a file", default: true },
|
|
@@ -58,10 +53,6 @@ export async function runDeploy(opts: DeployOptions): Promise<WorldDeploy> {
|
|
|
58
53
|
)
|
|
59
54
|
);
|
|
60
55
|
|
|
61
|
-
if (opts.clean) {
|
|
62
|
-
await forge(["clean"], { profile });
|
|
63
|
-
}
|
|
64
|
-
|
|
65
56
|
// Run forge build
|
|
66
57
|
if (!opts.skipBuild) {
|
|
67
58
|
const outPath = path.join(srcDir, config.codegenDirectory);
|