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