@latticexyz/cli 2.0.0-main-e1dc88eb → 2.0.0-main-ccc21e91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mud.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import Rn from"yargs";import{hideBin as $n}from"yargs/helpers";import jn from"@latticexyz/gas-report";import Fn from"@latticexyz/abi-ts";import{rmSync as wo}from"fs";import{homedir as xo}from"os";import So from"path";import{execa as vo}from"execa";var Co={command:"devnode",describe:"Start a local Ethereum node for development",builder(e){return e.options({blocktime:{type:"number",default:1,decs:"Interval in which new blocks are produced"}})},async handler({blocktime:e}){console.log("Clearing devnode history");let o=xo();wo(So.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=vo("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
3
- gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},ne=Co;import{FaucetServiceDefinition as To}from"@latticexyz/services/faucet";import{createChannel as ko,createClient as Ao}from"nice-grpc-web";import se from"chalk";import{NodeHttpTransport as Do}from"@improbable-eng/grpc-web-node-http-transport";function Io(e){return Ao(To,ko(e,Do()))}var Oo={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:t}){let r=Io(o);e&&(console.log(se.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(se.yellow("Success"))),process.exit(0)}},ie=Oo;var Po={command:"hello <name>",describe:"Greet <name> with Hello",builder(e){return e.options({upper:{type:"boolean"}}).positional("name",{type:"string",demandOption:!0})},handler({name:e}){let o=`Gm, ${e}!`;console.log(o),process.exit(0)}},ae=Po;import Mo from"path";import{loadConfig as Wo}from"@latticexyz/config/node";import{tablegen as jo}from"@latticexyz/store/codegen";import{getRemappings as Fo,getSrcDirectory as Ro}from"@latticexyz/common/foundry";var $o={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"}})},async handler({configPath:e}){let o=await Wo(e),t=await Ro(),r=await Fo();await jo(o,Mo.join(t,o.codegenDirectory),r),process.exit(0)}},ce=$o;import N from"chalk";import{ZodError as Eo}from"zod";import{fromZodError as No,ValidationError as Ho}from"zod-validation-error";import{NotInsideProjectError as Bo}from"@latticexyz/config";import{MUDError as Uo}from"@latticexyz/common/errors";function W(e){if(e instanceof Ho)console.log(N.redBright(e.message));else if(e instanceof Eo){let o=No(e,{prefixSeparator:`
2
+ import Fn from"yargs";import{hideBin as Rn}from"yargs/helpers";import Wn from"@latticexyz/gas-report";import jn from"@latticexyz/abi-ts";import{rmSync as So}from"fs";import{homedir as vo}from"os";import Co from"path";import{execa as To}from"execa";var ko={command:"devnode",describe:"Start a local Ethereum node for development",builder(e){return e.options({blocktime:{type:"number",default:1,decs:"Interval in which new blocks are produced"}})},async handler({blocktime:e}){console.log("Clearing devnode history");let o=vo();So(Co.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=To("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
3
+ gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},ne=ko;import{FaucetServiceDefinition as Do}from"@latticexyz/services/faucet";import{createChannel as Ao,createClient as Io}from"nice-grpc-web";import se from"chalk";import{NodeHttpTransport as Oo}from"@improbable-eng/grpc-web-node-http-transport";function Po(e){return Io(Do,Ao(e,Oo()))}var Mo={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:t}){let r=Po(o);e&&(console.log(se.yellow("Dripping to",t)),await r.dripDev({address:t}),console.log(se.yellow("Success"))),process.exit(0)}},ie=Mo;var Wo={command:"hello <name>",describe:"Greet <name> with Hello",builder(e){return e.options({upper:{type:"boolean"}}).positional("name",{type:"string",demandOption:!0})},handler({name:e}){let o=`Gm, ${e}!`;console.log(o),process.exit(0)}},ae=Wo;import jo from"path";import{loadConfig as Fo}from"@latticexyz/config/node";import{tablegen as Ro}from"@latticexyz/store/codegen";import{getRemappings as $o,getSrcDirectory as Eo}from"@latticexyz/common/foundry";var No={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"}})},async handler({configPath:e}){let o=await Fo(e),t=await Eo(),r=await $o();await Ro(o,jo.join(t,o.codegenDirectory),r),process.exit(0)}},ce=No;import N from"chalk";import{ZodError as Ho}from"zod";import{fromZodError as Bo,ValidationError as Uo}from"zod-validation-error";import{NotInsideProjectError as Vo}from"@latticexyz/config";import{MUDError as _o}from"@latticexyz/common/errors";function M(e){if(e instanceof Uo)console.log(N.redBright(e.message));else if(e instanceof Ho){let o=Bo(e,{prefixSeparator:`
4
4
  - `,issueSeparator:`
5
- - `});console.log(N.redBright(o.message))}else e instanceof Bo?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof Uo?console.log(N.red(e)):console.log(e)}import J from"node:path";import{existsSync as hr,mkdirSync as wr,readFileSync as xr,writeFileSync as X}from"node:fs";import{getBytecode as Lo,sendRawTransaction as Ko,sendTransaction as zo,waitForTransactionReceipt as de}from"viem/actions";var O={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import _o from"debug";var le=_o("mud:cli");var l=le.extend("deploy");var T=`0x${O.address}`;async function me(e){if(await Lo(e,{address:T})){l("found create2 deployer at",T);return}l("sending gas for create2 deployer to signer at",O.signerAddress);let t=await zo(e,{chain:e.chain??null,to:`0x${O.signerAddress}`,value:BigInt(O.gasLimit)*BigInt(O.gasPrice)}),r=await de(e,{hash:t});if(r.status!=="success")throw console.error("failed to send gas to deployer signer",r),new Error("failed to send gas to deployer signer");l("deploying create2 deployer at",T);let n=await Ko(e,{serializedTransaction:`0x${O.transaction}`}),s=await de(e,{hash:n});if(s.contractAddress!==T)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as ut}from"viem/actions";import it from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import at from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as ct,getCreate2Address as ye,encodeDeployData as ge}from"viem";import{concatHex as et,getCreate2Address as ot}from"viem";import{getBytecode as tt}from"viem/actions";import{padHex as qo}from"viem";import Go from"@latticexyz/store/mud.config.js";import Yo from"@latticexyz/world/mud.config.js";import Zo from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Jo}from"@latticexyz/common";import{resolveUserTypes as pe}from"@latticexyz/store";function H(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([t])=>[t,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([t,r])=>[`${e.namespace}_${t}`,{namespace:e.namespace,name:r.name,tableId:Jo({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:pe(r.keySchema,o),valueSchema:pe(r.valueSchema,o)}]))}import{helloStoreEvent as Qo}from"@latticexyz/store";import{helloWorldEvent as Xo}from"@latticexyz/world";var A=qo("0x",{size:32}),j=H(Go),k=H(Yo),U=[Qo,Xo],v=Zo,fe=["1.0.0-unaudited"],ue=["1.0.0-unaudited"];import{sendTransaction as rt}from"@latticexyz/common";import nt from"p-retry";import{wait as st}from"@latticexyz/common/utils";async function P({client:e,bytecode:o,label:t="contract"}){let r=ot({from:T,salt:A,bytecode:o});return await tt(e,{address:r,blockTag:"pending"})?(l("found",t,"at",r),[]):(l("deploying",t,"at",r),[await nt(()=>rt(e,{chain:e.chain??null,to:T,data:et([A,o])}),{retries:3,onFailedAttempt:async s=>{let c=s.attemptNumber*500;l(`failed to deploy ${t}, retrying in ${c}ms...`),await st(c)}})])}var be=ge({bytecode:it.bytecode.object,abi:[]}),lt=ye({from:T,bytecode:be,salt:A}),he=ge({bytecode:at.bytecode.object,abi:ct(["constructor(address)"]),args:[lt]}),we=ye({from:T,bytecode:he,salt:A});async function xe(e){return(await Promise.all([P({client:e,bytecode:be,label:"core module"}),P({client:e,bytecode:he,label:"world factory"})])).flat()}import yt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as gt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as dt,decodeEventLog as mt,hexToString as Se,parseAbi as pt,trim as ve}from"viem";import{isDefined as ft}from"@latticexyz/common/utils";function V(e){let o=e.map(c=>{try{return{...c,...mt({strict:!0,abi:pt(U),topics:c.topics,data:c.data})}}catch(i){if(i instanceof dt)return;throw i}}).filter(ft),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((c,i)=>({...c,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Se(ve(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:Se(ve(i.args.storeVersion,{dir:"right"}))}:null}),{});if(t==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:s}}async function Ce(e){await xe(e),l("deploying world");let o=await gt(e,{chain:e.chain??null,address:we,abi:yt,functionName:"deployWorld"});l("waiting for world deploy");let t=await ut(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 Tt,keySchemaToHex as kt,valueSchemaToHex as At}from"@latticexyz/protocol-parser";function S({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as bt,decodeAbiParameters as Te,parseAbiParameters as ke}from"viem";import{hexToResource as ht}from"@latticexyz/common";import{storeSetRecordEvent as wt}from"@latticexyz/store";import{getLogs as xt}from"viem/actions";import{decodeKey as St,decodeValueArgs as vt,hexToSchema as Ae}from"@latticexyz/protocol-parser";async function De({client:e,worldDeploy:o}){l("looking up tables for",o.address);let r=(await xt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:bt(wt),args:{tableId:j.store_Tables.tableId}})).map(n=>{let{tableId:s}=St(j.store_Tables.keySchema,n.args.keyTuple),{namespace:c,name:i}=ht(s),m=vt(j.store_Tables.valueSchema,n.args),a=Ae(m.keySchema),p=Ae(m.valueSchema),u=Te(ke("string[]"),m.abiEncodedKeyNames)[0],C=Te(ke("string[]"),m.abiEncodedFieldNames)[0],f=[...p.staticFields,...p.dynamicFields],y=Object.fromEntries(a.staticFields.map((g,h)=>[u[h],g])),w=Object.fromEntries(f.map((g,h)=>[C[h],g]));return{namespace:c,name:i,tableId:s,keySchema:y,valueSchema:w}});return l("found",r.length,"tables for",o.address),r}import Dt from"p-retry";import{wait as It}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,tables:t}){let n=(await De({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 c=t.filter(i=>!n.includes(i.tableId));return c.length?(l("registering tables",c.map(S).join(", ")),await Promise.all(c.map(i=>Dt(()=>Ct(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[i.tableId,Tt(i.valueSchema),kt(i.keySchema),At(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let a=m.attemptNumber*500;l(`failed to register table ${S(i)}, retrying in ${a}ms...`),await It(a)}})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as Ot}from"viem";import{getLogs as Pt}from"viem/actions";import{storeSpliceStaticDataEvent as Mt}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let r=(await Pt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:Ot(Mt),args:{tableId:j.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return l("found",r.length,"resource IDs for",o.address),r}import{hexToResource as zt}from"@latticexyz/common";import{decodeValueArgs as Wt,encodeKey as jt}from"@latticexyz/protocol-parser";import{readContract as Ft}from"viem/actions";async function D({client:e,worldDeploy:o,table:t,key:r}){let[n,s,c]=await Ft(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[t.tableId,jt(t.keySchema,r)]});return Wt(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:c})}import{getFunctionSelector as Rt,parseAbiItem as $t}from"viem";import{storeSetRecordEvent as Et}from"@latticexyz/store";import{getLogs as Nt}from"viem/actions";import{decodeValueArgs as Ht}from"@latticexyz/protocol-parser";import{hexToResource as Bt}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){l("looking up function signatures for",o.address);let r=(await Nt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:$t(Et),args:{tableId:k.world_FunctionSignatures.tableId}})).map(s=>Ht(k.world_FunctionSignatures.valueSchema,s.args).functionSignature);return l("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let c=Rt(s),{systemId:i,systemFunctionSelector:m}=await D({client:e,worldDeploy:o,table:k.world_FunctionSelectors,key:{functionSelector:c}}),{namespace:a,name:p}=Bt(i),u=a===""?s:s.replace(`${a}_${p}_`,"");return{signature:s,selector:c,systemId:i,systemFunctionSignature:u,systemFunctionSelector:m}}))}import{parseAbiItem as Ut,getAddress as Vt}from"viem";import{storeSpliceStaticDataEvent as _t}from"@latticexyz/store";import{getLogs as Lt}from"viem/actions";import{decodeKey as Kt}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let r=(await Lt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Ut(_t),args:{tableId:k.world_ResourceAccess.tableId}})).map(s=>Kt(k.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await D({client:e,worldDeploy:o,table:k.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Vt(s.caller)}));return l("found",n.length,"resource<>address access pairs"),n}async function Oe({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([_({client:e,worldDeploy:o}),L({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(zt).filter(c=>c.type==="system");return l("looking up systems",s.map(S).join(", ")),await Promise.all(s.map(async c=>{let{system:i,publicAccess:m}=await D({client:e,worldDeploy:o,table:k.world_Systems,key:{systemId:c.resourceId}}),a=r.filter(p=>p.systemId===c.resourceId);return{address:i,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:m,allowedAddresses:n.filter(({resourceId:p})=>p===c.resourceId).map(({address:p})=>p),functions:a}}))}import{uniqueBy as Jt,wait as G}from"@latticexyz/common/utils";import Y from"p-retry";async function Pe({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Oe({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(d=>d.systemId),c=n.filter(({resourceId:d})=>s.includes(d)),i=t.flatMap(d=>d.allowedAddresses.map(b=>({resourceId:d.systemId,address:b}))),m=i.filter(d=>!c.some(({resourceId:b,address:x})=>b===d.resourceId&&I(x)===I(d.address))),a=c.filter(d=>!i.some(({resourceId:b,address:x})=>b===d.resourceId&&I(x)===I(d.address)));a.length&&l("revoking",a.length,"access grants"),m.length&&l("adding",m.length,"access grants");let p=await Promise.all([...a.map(d=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"revokeAccess",args:[d.resourceId,d.address]}),{retries:3,onFailedAttempt:async b=>{let x=b.attemptNumber*500;l(`failed to revoke access, retrying in ${x}ms...`),await G(x)}})),...m.map(d=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"grantAccess",args:[d.resourceId,d.address]}),{retries:3,onFailedAttempt:async b=>{let x=b.attemptNumber*500;l(`failed to grant access, retrying in ${x}ms...`),await G(x)}}))]),u=t.filter(d=>r.some(b=>b.systemId===d.systemId&&I(b.address)===I(d.address)));u.length&&l("existing systems",u.map(S).join(", "));let C=u.map(d=>d.systemId),f=t.filter(d=>!C.includes(d.systemId));if(!f.length)return[];let y=f.filter(d=>r.some(b=>b.systemId===d.systemId&&I(b.address)!==I(d.address)));y.length&&l("upgrading systems",y.map(S).join(", "));let w=f.filter(d=>!r.some(b=>b.systemId===d.systemId));w.length&&l("registering new systems",w.map(S).join(", "));let g=await Promise.all(Jt(f,d=>d.address).map(d=>P({client:e,bytecode:d.bytecode,label:`${S(d)} system`}))),h=await Promise.all(f.map(d=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerSystem",args:[d.systemId,d.address,d.allowAll]}),{retries:3,onFailedAttempt:async b=>{let x=b.attemptNumber*500;l(`failed to register system ${S(d)}, retrying in ${x}ms...`),await G(x)}})));return(await Promise.all([...p,...g,...h])).flat()}import{waitForTransactionReceipt as or}from"viem/actions";import{getAddress as qt,parseAbi as Gt}from"viem";import{getBlockNumber as Yt,getLogs as Zt}from"viem/actions";var Me=new Map;async function We(e,o){let t=qt(o),r=Me.get(t);if(r!=null)return r;l("looking up world deploy for",t);let n=await Yt(e),s=await Zt(e,{strict:!0,address:t,events:Gt(U),fromBlock:"earliest",toBlock:n});return r={...V(s),stateBlock:n},Me.set(t,r),l("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as Qt,writeContract as je}from"@latticexyz/common";import Fe from"p-retry";import{wait as Re}from"@latticexyz/common/utils";async function $e({client:e,worldDeploy:o,functions:t}){let r=await L({client:e,worldDeploy:o}),n=Object.fromEntries(r.map(i=>[i.selector,i])),s=t.filter(i=>n[i.selector]),c=t.filter(i=>!s.includes(i));if(s.length){l("functions already registered:",s.map(m=>m.signature).join(", "));let i=s.filter(m=>m.systemId!==n[m.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(m=>m.signature).join(", "))}return c.length?(l("registering functions:",c.map(i=>i.signature).join(", ")),Promise.all(c.map(i=>{let{namespace:m}=Qt(i.systemId);return m===""?Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}),{retries:3,onFailedAttempt:async a=>{let p=a.attemptNumber*500;l(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}}):Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]}),{retries:3,onFailedAttempt:async a=>{let p=a.attemptNumber*500;l(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}})}))):[]}import{writeContract as Ee}from"@latticexyz/common";import{uniqueBy as Xt,wait as Ne}from"@latticexyz/common/utils";import He from"p-retry";async function Be({client:e,worldDeploy:o,modules:t}){if(!t.length)return[];let r=await Promise.all(Xt(t,s=>s.address).map(s=>P({client:e,bytecode:s.bytecode,label:`${s.name} module`})));l("installing modules:",t.map(s=>s.name).join(", "));let n=await Promise.all(t.map(s=>s.installAsRoot?He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installRootModule",args:[s.address,s.installData]}),{retries:3,onFailedAttempt:async c=>{let i=c.attemptNumber*500;l(`failed to install root module ${s.name}, retrying in ${i}ms...`),await Ne(i)}}):He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installModule",args:[s.address,s.installData]}),{retries:3,onFailedAttempt:async c=>{let i=c.attemptNumber*500;l(`failed to install module ${s.name}, retrying in ${i}ms...`),await Ne(i)}})));return(await Promise.all([...r,...n])).flat()}import{getAddress as Ue}from"viem";import{hexToResource as Ve,resourceToHex as er}from"@latticexyz/common";async function _e({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(a=>Ve(a).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(a=>Ve(a).namespace))),c=r.filter(a=>s.includes(a)),m=(await Promise.all(c.map(async a=>{let{owner:p}=await D({client:e,worldDeploy:o,table:k.world_NamespaceOwner,key:{namespaceId:er({type:"namespace",namespace:a,name:""})}});return[a,p]}))).filter(([,a])=>Ue(a)!==Ue(e.account.address)).map(([a])=>a);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`)}async function Le({client:e,config:o,worldAddress:t}){await me(e);let r=t?await We(e,t):await Ce(e);if(!fe.includes(r.storeVersion))throw new Error(`Unsupported Store version: ${r.storeVersion}`);if(!ue.includes(r.worldVersion))throw new Error(`Unsupported World version: ${r.worldVersion}`);let n=Object.values(o.tables),s=Object.values(o.systems);await _e({client:e,worldDeploy:r,resourceIds:[...n.map(u=>u.tableId),...s.map(u=>u.systemId)]});let c=await Ie({client:e,worldDeploy:r,tables:n}),i=await Pe({client:e,worldDeploy:r,systems:s}),m=await $e({client:e,worldDeploy:r,functions:s.flatMap(u=>u.functions)}),a=await Be({client:e,worldDeploy:r,modules:o.modules}),p=[...c,...i,...m,...a];l("waiting for transactions to confirm");for(let u of p)await or(e,{hash:u});return l("deploy complete"),r}import{createWalletClient as Sr,http as vr}from"viem";import{privateKeyToAccount as Cr}from"viem/accounts";import{loadConfig as Tr}from"@latticexyz/config/node";import{forge as kr,getOutDirectory as Ar,getRemappings as Dr,getRpcUrl as Ir,getSrcDirectory as Or}from"@latticexyz/common/foundry";import R from"chalk";import{execa as Pr}from"execa";import{MUDError as Mr}from"@latticexyz/common/errors";import{resolveWorldConfig as ir}from"@latticexyz/world";import{resourceToHex as Q,hexToResource as ar}from"@latticexyz/common";import{resolveWithContext as cr}from"@latticexyz/config";import{encodeField as lr}from"@latticexyz/protocol-parser";import{getFunctionSelector as Ge,getCreate2Address as Ye,getAddress as dr,hexToBytes as mr,bytesToHex as pr,getFunctionSignature as Ze}from"viem";import tr from"glob";import{basename as rr}from"path";function F(e){return tr.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:rr(o,".sol")}))}import Ke from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import ze from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Je from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var qe=[{name:"KeysWithValueModule",abi:Ke.abi,bytecode:Ke.bytecode},{name:"KeysInTableModule",abi:ze.abi,bytecode:ze.bytecode},{name:"UniqueEntityModule",abi:Je.abi,bytecode:Je.bytecode}];import{readFileSync as nr}from"fs";import sr from"path";import{MUDError as Z}from"@latticexyz/common/errors";function z(e,o){let t,r=sr.join(o,e+".sol",e+".json");try{t=JSON.parse(nr(r,"utf8"))}catch{throw new Z(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new Z(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new Z(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function Qe({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=H(e),n=F(o).map(({basename:f})=>f),s=ir(e,n),i=z("System",t).abi.filter(f=>f.type==="function").map(Ze),m=Object.entries(s.systems).map(([f,y])=>{let w=e.namespace,g=y.name,h=Q({type:"system",namespace:w,name:g}),d=z(f,t),b=d.abi.filter(x=>x.type==="function").map(Ze).filter(x=>!i.includes(x)).map(x=>{let re=w===""?x:`${w}_${g}_${x}`;return{signature:re,selector:Ge(re),systemId:h,systemFunctionSignature:x,systemFunctionSelector:Ge(x)}});return{namespace:w,name:g,systemId:h,allowAll:y.openAccess,allowedAddresses:y.accessListAddresses,allowedSystemIds:y.accessListSystems.map(x=>Q({type:"system",namespace:w,name:s.systems[x].name})),address:Ye({from:T,bytecode:d.bytecode,salt:A}),bytecode:d.bytecode,abi:d.abi,functions:b}}),a=m.map(({allowedAddresses:f,allowedSystemIds:y,...w})=>{let g=y.map(h=>{let d=m.find(b=>b.systemId===h);if(!d)throw new Error(`System ${S(w)} wanted access to ${S(ar(h))}, but it wasn't found in the config.`);return d.address});return{...w,allowedAddresses:Array.from(new Set([...f,...g].map(h=>dr(h))))}}),p={tableIds:Object.fromEntries(Object.entries(e.tables).map(([f,y])=>[f,mr(Q({type:y.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:y.name}))]))},u=qe.map(f=>({name:f.name,bytecode:typeof f.bytecode=="string"?f.bytecode:f.bytecode.object,abi:f.abi})),C=e.modules.map(f=>{let y=u.find(g=>g.name===f.name)??z(f.name,t),w=f.args.map(g=>cr(g,p)).map(g=>{let h=g.value instanceof Uint8Array?pr(g.value):g.value;return lr(g.type,h)});if(w.length>1)throw new Error(`${f.name} module should only have 0-1 args, but had ${w.length} args.`);return{name:f.name,installAsRoot:f.root,installData:w.length===0?"0x":w[0],address:Ye({from:T,bytecode:y.bytecode,salt:A}),bytecode:y.bytecode,abi:y.abi}});return{tables:r,systems:a,modules:C}}import{getChainId as Wr}from"viem/actions";import{existsSync as fr}from"fs";import ur from"path";import yr from"chalk";import{getScriptDirectory as gr,forge as br}from"@latticexyz/common/foundry";async function Xe(e,o,t,r){let n=ur.join(await gr(),e+".s.sol");fr(n)?(console.log(yr.blue(`Executing post deploy script at ${n}`)),await br(["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 jr}from"@latticexyz/store/codegen";var M={configPath:{type:"string",desc:"Path to the config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"}};async function $(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await Tr(e.configPath);e.printConfig&&console.log(R.green(`
5
+ - `});console.log(N.redBright(o.message))}else e instanceof Vo?(console.log(N.red(e.message)),console.log(""),console.log(N.blue("To learn more about MUD's configuration, please go to https://mud.dev/packages/cli/"))):e instanceof _o?console.log(N.red(e)):console.log(e)}import J from"node:path";import{existsSync as br,mkdirSync as hr,readFileSync as wr,writeFileSync as X}from"node:fs";import{getBytecode as zo,sendRawTransaction as Jo,sendTransaction as qo,waitForTransactionReceipt as de}from"viem/actions";var P={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c"};import Ko from"debug";var le=Ko("mud:cli");var d=le.extend("deploy");var C=`0x${P.address}`;async function me(e){if(await zo(e,{address:C})){d("found create2 deployer at",C);return}d("sending gas for create2 deployer to signer at",P.signerAddress);let t=await qo(e,{chain:e.chain??null,to:`0x${P.signerAddress}`,value:BigInt(P.gasLimit)*BigInt(P.gasPrice)}),r=await de(e,{hash:t});if(r.status!=="success")throw console.error("failed to send gas to deployer signer",r),new Error("failed to send gas to deployer signer");d("deploying create2 deployer at",C);let n=await Jo(e,{serializedTransaction:`0x${P.transaction}`}),s=await de(e,{hash:n});if(s.contractAddress!==C)throw console.error("unexpected contract address for deployer",s),new Error("unexpected contract address for deployer")}import{waitForTransactionReceipt as gt}from"viem/actions";import ct from"@latticexyz/world/out/CoreModule.sol/CoreModule.json"assert{type:"json"};import lt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import{parseAbi as dt,getCreate2Address as ye,encodeDeployData as ge}from"viem";import{concatHex as tt,getCreate2Address as rt}from"viem";import{getBytecode as nt}from"viem/actions";import{padHex as Yo}from"viem";import Zo from"@latticexyz/store/mud.config.js";import Qo from"@latticexyz/world/mud.config.js";import Xo from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Go}from"@latticexyz/common";import{resolveUserTypes as pe}from"@latticexyz/store";function H(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([t])=>[t,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([t,r])=>[`${e.namespace}_${t}`,{namespace:e.namespace,name:r.name,tableId:Go({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:pe(r.keySchema,o),valueSchema:pe(r.valueSchema,o)}]))}import{helloStoreEvent as et}from"@latticexyz/store";import{helloWorldEvent as ot}from"@latticexyz/world";var D=Yo("0x",{size:32}),W=H(Zo),T=H(Qo),U=[et,ot],v=Xo,fe=["1.0.0-unaudited"],ue=["1.0.0-unaudited"];import{sendTransaction as st}from"@latticexyz/common";import it from"p-retry";import{wait as at}from"@latticexyz/common/utils";async function j({client:e,bytecode:o,label:t="contract"}){let r=rt({from:C,salt:D,bytecode:o});return await nt(e,{address:r,blockTag:"pending"})?(d("found",t,"at",r),[]):(d("deploying",t,"at",r),[await it(()=>st(e,{chain:e.chain??null,to:C,data:tt([D,o])}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to deploy ${t}, retrying in ${a}ms...`),await at(a)}})])}var be=ge({bytecode:ct.bytecode.object,abi:[]}),mt=ye({from:C,bytecode:be,salt:D}),he=ge({bytecode:lt.bytecode.object,abi:dt(["constructor(address)"]),args:[mt]}),we=ye({from:C,bytecode:he,salt:D});async function xe(e){return(await Promise.all([j({client:e,bytecode:be,label:"core module"}),j({client:e,bytecode:he,label:"world factory"})])).flat()}import bt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as ht}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as pt,decodeEventLog as ft,hexToString as Se,parseAbi as ut,trim as ve}from"viem";import{isDefined as yt}from"@latticexyz/common/utils";function V(e){let o=e.map(a=>{try{return{...a,...ft({strict:!0,abi:ut(U),topics:a.topics,data:a.data})}}catch(i){if(i instanceof pt)return;throw i}}).filter(yt),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((a,i)=>({...a,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Se(ve(i.args.worldVersion,{dir:"right"}))}:null,...i.eventName==="HelloStore"?{storeVersion:Se(ve(i.args.storeVersion,{dir:"right"}))}:null}),{});if(t==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:s}}async function Ce(e){await xe(e),d("deploying world");let o=await ht(e,{chain:e.chain??null,address:we,abi:bt,functionName:"deployWorld"});d("waiting for world deploy");let t=await gt(e,{hash:o});if(t.status!=="success")throw console.error("world deploy failed",t),new Error("world deploy failed");let r=V(t.logs.map(n=>n));return d("deployed world to",r.address,"at block",r.deployBlock),{...r,stateBlock:r.deployBlock}}import{writeContract as kt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Dt,keySchemaToHex as At,valueSchemaToHex as It}from"@latticexyz/protocol-parser";function S({namespace:e,name:o}){return`${e}:${o}`}import{parseAbiItem as wt,decodeAbiParameters as Te,parseAbiParameters as ke}from"viem";import{hexToResource as xt}from"@latticexyz/common";import{storeSetRecordEvent as St}from"@latticexyz/store";import{getLogs as vt}from"viem/actions";import{decodeKey as Ct,decodeValueArgs as Tt,hexToSchema as De}from"@latticexyz/protocol-parser";async function Ae({client:e,worldDeploy:o}){d("looking up tables for",o.address);let r=(await vt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:wt(St),args:{tableId:W.store_Tables.tableId}})).map(n=>{let{tableId:s}=Ct(W.store_Tables.keySchema,n.args.keyTuple),{namespace:a,name:i}=xt(s),m=Tt(W.store_Tables.valueSchema,n.args),c=De(m.keySchema),p=De(m.valueSchema),w=Te(ke("string[]"),m.abiEncodedKeyNames)[0],u=Te(ke("string[]"),m.abiEncodedFieldNames)[0],f=[...p.staticFields,...p.dynamicFields],g=Object.fromEntries(c.staticFields.map((b,l)=>[w[l],b])),h=Object.fromEntries(f.map((b,l)=>[u[l],b]));return{namespace:a,name:i,tableId:s,keySchema:g,valueSchema:h}});return d("found",r.length,"tables for",o.address),r}import Ot from"p-retry";import{wait as Pt}from"@latticexyz/common/utils";async function Ie({client:e,worldDeploy:o,tables:t}){let n=(await Ae({client:e,worldDeploy:o})).map(i=>i.tableId),s=t.filter(i=>n.includes(i.tableId));s.length&&d("existing tables",s.map(S).join(", "));let a=t.filter(i=>!n.includes(i.tableId));return a.length?(d("registering tables",a.map(S).join(", ")),await Promise.all(a.map(i=>Ot(()=>kt(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[i.tableId,Dt(i.valueSchema),At(i.keySchema),It(i.valueSchema),Object.keys(i.keySchema),Object.keys(i.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let c=m.attemptNumber*500;d(`failed to register table ${S(i)}, retrying in ${c}ms...`),await Pt(c)}})))):[]}import{getAddress as I}from"viem";import{writeContract as q}from"@latticexyz/common";import{parseAbiItem as Mt}from"viem";import{getLogs as Wt}from"viem/actions";import{storeSpliceStaticDataEvent as jt}from"@latticexyz/store";async function _({client:e,worldDeploy:o}){d("looking up resource IDs for",o.address);let r=(await Wt(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:Mt(jt),args:{tableId:W.store_ResourceIds.tableId}})).map(n=>n.args.keyTuple[0]);return d("found",r.length,"resource IDs for",o.address),r}import{hexToResource as qt}from"@latticexyz/common";import{decodeValueArgs as Ft,encodeKey as Rt}from"@latticexyz/protocol-parser";import{readContract as $t}from"viem/actions";async function A({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await $t(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[t.tableId,Rt(t.keySchema,r)]});return Ft(t.valueSchema,{staticData:n,encodedLengths:s,dynamicData:a})}import{getFunctionSelector as Et,parseAbiItem as Nt}from"viem";import{storeSetRecordEvent as Ht}from"@latticexyz/store";import{getLogs as Bt}from"viem/actions";import{decodeValueArgs as Ut}from"@latticexyz/protocol-parser";import{hexToResource as Vt}from"@latticexyz/common";async function L({client:e,worldDeploy:o}){d("looking up function signatures for",o.address);let r=(await Bt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Nt(Ht),args:{tableId:T.world_FunctionSignatures.tableId}})).map(s=>Ut(T.world_FunctionSignatures.valueSchema,s.args).functionSignature);return d("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let a=Et(s),{systemId:i,systemFunctionSelector:m}=await A({client:e,worldDeploy:o,table:T.world_FunctionSelectors,key:{functionSelector:a}}),{namespace:c,name:p}=Vt(i),w=c===""?s:s.replace(`${c}_${p}_`,"");return{signature:s,selector:a,systemId:i,systemFunctionSignature:w,systemFunctionSelector:m}}))}import{parseAbiItem as _t,getAddress as Lt}from"viem";import{storeSpliceStaticDataEvent as Kt}from"@latticexyz/store";import{getLogs as zt}from"viem/actions";import{decodeKey as Jt}from"@latticexyz/protocol-parser";async function K({client:e,worldDeploy:o}){d("looking up resource access for",o.address);let r=(await zt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:_t(Kt),args:{tableId:T.world_ResourceAccess.tableId}})).map(s=>Jt(T.world_ResourceAccess.keySchema,s.args.keyTuple)),n=(await Promise.all(r.map(async s=>[s,await A({client:e,worldDeploy:o,table:T.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Lt(s.caller)}));return d("found",n.length,"resource<>address access pairs"),n}async function Oe({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([_({client:e,worldDeploy:o}),L({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(qt).filter(a=>a.type==="system");return d("looking up systems",s.map(S).join(", ")),await Promise.all(s.map(async a=>{let{system:i,publicAccess:m}=await A({client:e,worldDeploy:o,table:T.world_Systems,key:{systemId:a.resourceId}}),c=r.filter(p=>p.systemId===a.resourceId);return{address:i,namespace:a.namespace,name:a.name,systemId:a.resourceId,allowAll:m,allowedAddresses:n.filter(({resourceId:p})=>p===a.resourceId).map(({address:p})=>p),functions:c}}))}import{wait as G}from"@latticexyz/common/utils";import Y from"p-retry";async function Pe({client:e,worldDeploy:o,systems:t}){let[r,n]=await Promise.all([Oe({client:e,worldDeploy:o}),K({client:e,worldDeploy:o})]),s=t.map(l=>l.systemId),a=n.filter(({resourceId:l})=>s.includes(l)),i=t.flatMap(l=>l.allowedAddresses.map(y=>({resourceId:l.systemId,address:y}))),m=i.filter(l=>!a.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address))),c=a.filter(l=>!i.some(({resourceId:y,address:x})=>y===l.resourceId&&I(x)===I(l.address)));c.length&&d("revoking",c.length,"access grants"),m.length&&d("adding",m.length,"access grants");let p=[...c.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"revokeAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to revoke access, retrying in ${x}ms...`),await G(x)}})),...m.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"grantAccess",args:[l.resourceId,l.address]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to grant access, retrying in ${x}ms...`),await G(x)}}))],w=t.filter(l=>r.some(y=>y.systemId===l.systemId&&I(y.address)===I(l.address)));w.length&&d("existing systems",w.map(S).join(", "));let u=w.map(l=>l.systemId),f=t.filter(l=>!u.includes(l.systemId));if(!f.length)return[];let g=f.filter(l=>r.some(y=>y.systemId===l.systemId&&I(y.address)!==I(l.address)));g.length&&d("upgrading systems",g.map(S).join(", "));let h=f.filter(l=>!r.some(y=>y.systemId===l.systemId));h.length&&d("registering new systems",h.map(S).join(", "));let b=f.map(l=>Y(()=>q(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerSystem",args:[l.systemId,l.address,l.allowAll]}),{retries:3,onFailedAttempt:async y=>{let x=y.attemptNumber*500;d(`failed to register system ${S(l)}, retrying in ${x}ms...`),await G(x)}}));return await Promise.all([...p,...b])}import{waitForTransactionReceipt as Le}from"viem/actions";import{getAddress as Gt,parseAbi as Yt}from"viem";import{getBlockNumber as Zt,getLogs as Qt}from"viem/actions";var Me=new Map;async function We(e,o){let t=Gt(o),r=Me.get(t);if(r!=null)return r;d("looking up world deploy for",t);let n=await Zt(e),s=await Qt(e,{strict:!0,address:t,events:Yt(U),fromBlock:"earliest",toBlock:n});return r={...V(s),stateBlock:n},Me.set(t,r),d("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as Xt,writeContract as je}from"@latticexyz/common";import Fe from"p-retry";import{wait as Re}from"@latticexyz/common/utils";async function $e({client:e,worldDeploy:o,functions:t}){let r=await L({client:e,worldDeploy:o}),n=Object.fromEntries(r.map(i=>[i.selector,i])),s=t.filter(i=>n[i.selector]),a=t.filter(i=>!s.includes(i));if(s.length){d("functions already registered:",s.map(m=>m.signature).join(", "));let i=s.filter(m=>m.systemId!==n[m.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(m=>m.signature).join(", "))}return a.length?(d("registering functions:",a.map(i=>i.signature).join(", ")),Promise.all(a.map(i=>{let{namespace:m}=Xt(i.systemId);return m===""?Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSelector]}),{retries:3,onFailedAttempt:async c=>{let p=c.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}}):Fe(()=>je(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let p=c.attemptNumber*500;d(`failed to register function ${i.signature}, retrying in ${p}ms...`),await Re(p)}})}))):[]}import{writeContract as Ee}from"@latticexyz/common";import{wait as Ne}from"@latticexyz/common/utils";import He from"p-retry";async function Be({client:e,worldDeploy:o,modules:t}){if(!t.length)return[];d("installing modules:",t.map(n=>n.name).join(", "));let r=await Promise.all(t.map(n=>n.installAsRoot?He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installRootModule",args:[n.address,n.installData]}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to install root module ${n.name}, retrying in ${a}ms...`),await Ne(a)}}):He(()=>Ee(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"installModule",args:[n.address,n.installData]}),{retries:3,onFailedAttempt:async s=>{let a=s.attemptNumber*500;d(`failed to install module ${n.name}, retrying in ${a}ms...`),await Ne(a)}})));return await Promise.all(r)}import{getAddress as Ue}from"viem";import{hexToResource as Ve,resourceToHex as er}from"@latticexyz/common";async function _e({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(c=>Ve(c).namespace))),n=await _({client:e,worldDeploy:o}),s=Array.from(new Set(n.map(c=>Ve(c).namespace))),a=r.filter(c=>s.includes(c)),m=(await Promise.all(a.map(async c=>{let{owner:p}=await A({client:e,worldDeploy:o,table:T.world_NamespaceOwner,key:{namespaceId:er({type:"namespace",namespace:c,name:""})}});return[c,p]}))).filter(([,c])=>Ue(c)!==Ue(e.account.address)).map(([c])=>c);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`)}import{uniqueBy as Ke}from"@latticexyz/common/utils";async function ze({client:e,config:o,worldAddress:t}){await me(e);let r=t?await We(e,t):await Ce(e);if(!fe.includes(r.storeVersion))throw new Error(`Unsupported Store version: ${r.storeVersion}`);if(!ue.includes(r.worldVersion))throw new Error(`Unsupported World version: ${r.worldVersion}`);let n=Object.values(o.tables),s=Object.values(o.systems);await _e({client:e,worldDeploy:r,resourceIds:[...n.map(u=>u.tableId),...s.map(u=>u.systemId)]});let a=(await Promise.all([...Ke(s,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${S(u)} system`})),...Ke(o.modules,u=>u.address).map(u=>j({client:e,bytecode:u.bytecode,label:`${u.name} module`}))])).flat();if(a.length){d("waiting for contracts");for(let u of a)await Le(e,{hash:u})}let i=await Ie({client:e,worldDeploy:r,tables:n}),m=await Pe({client:e,worldDeploy:r,systems:s}),c=await $e({client:e,worldDeploy:r,functions:s.flatMap(u=>u.functions)}),p=await Be({client:e,worldDeploy:r,modules:o.modules}),w=[...i,...m,...c,...p];d("waiting for all transactions to confirm");for(let u of w)await Le(e,{hash:u});return d("deploy complete"),r}import{createWalletClient as xr,http as Sr}from"viem";import{privateKeyToAccount as vr}from"viem/accounts";import{loadConfig as Cr}from"@latticexyz/config/node";import{forge as Tr,getOutDirectory as kr,getRemappings as Dr,getRpcUrl as Ar,getSrcDirectory as Ir}from"@latticexyz/common/foundry";import R from"chalk";import{execa as Or}from"execa";import{MUDError as Pr}from"@latticexyz/common/errors";import{resolveWorldConfig as sr}from"@latticexyz/world";import{resourceToHex as Q,hexToResource as ir}from"@latticexyz/common";import{resolveWithContext as ar}from"@latticexyz/config";import{encodeField as cr}from"@latticexyz/protocol-parser";import{getFunctionSelector as Ze,getCreate2Address as Qe,getAddress as lr,hexToBytes as dr,bytesToHex as mr,getFunctionSignature as Xe}from"viem";import or from"glob";import{basename as tr}from"path";function F(e){return or.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:tr(o,".sol")}))}import Je from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import qe from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import Ge from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};var Ye=[{name:"KeysWithValueModule",abi:Je.abi,bytecode:Je.bytecode},{name:"KeysInTableModule",abi:qe.abi,bytecode:qe.bytecode},{name:"UniqueEntityModule",abi:Ge.abi,bytecode:Ge.bytecode}];import{readFileSync as rr}from"fs";import nr from"path";import{MUDError as Z}from"@latticexyz/common/errors";function z(e,o){let t,r=nr.join(o,e+".sol",e+".json");try{t=JSON.parse(rr(r,"utf8"))}catch{throw new Z(`Error reading file at ${r}`)}let n=t?.bytecode?.object;if(!n)throw new Z(`No bytecode found in ${r}`);let s=t?.abi;if(!s)throw new Z(`No ABI found in ${r}`);return{abi:s,bytecode:n}}function eo({config:e,forgeSourceDir:o,forgeOutDir:t}){let r=H(e),n=F(o).map(({basename:f})=>f),s=sr(e,n),i=z("System",t).abi.filter(f=>f.type==="function").map(Xe),m=Object.entries(s.systems).map(([f,g])=>{let h=e.namespace,b=g.name,l=Q({type:"system",namespace:h,name:b}),y=z(f,t),x=y.abi.filter(k=>k.type==="function").map(Xe).filter(k=>!i.includes(k)).map(k=>{let re=h===""?k:`${h}_${b}_${k}`;return{signature:re,selector:Ze(re),systemId:l,systemFunctionSignature:k,systemFunctionSelector:Ze(k)}});return{namespace:h,name:b,systemId:l,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(k=>Q({type:"system",namespace:h,name:s.systems[k].name})),address:Qe({from:C,bytecode:y.bytecode,salt:D}),bytecode:y.bytecode,abi:y.abi,functions:x}}),c=m.map(({allowedAddresses:f,allowedSystemIds:g,...h})=>{let b=g.map(l=>{let y=m.find(x=>x.systemId===l);if(!y)throw new Error(`System ${S(h)} wanted access to ${S(ir(l))}, but it wasn't found in the config.`);return y.address});return{...h,allowedAddresses:Array.from(new Set([...f,...b].map(l=>lr(l))))}}),p={tableIds:Object.fromEntries(Object.entries(e.tables).map(([f,g])=>[f,dr(Q({type:g.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:g.name}))]))},w=Ye.map(f=>({name:f.name,bytecode:typeof f.bytecode=="string"?f.bytecode:f.bytecode.object,abi:f.abi})),u=e.modules.map(f=>{let g=w.find(b=>b.name===f.name)??z(f.name,t),h=f.args.map(b=>ar(b,p)).map(b=>{let l=b.value instanceof Uint8Array?mr(b.value):b.value;return cr(b.type,l)});if(h.length>1)throw new Error(`${f.name} module should only have 0-1 args, but had ${h.length} args.`);return{name:f.name,installAsRoot:f.root,installData:h.length===0?"0x":h[0],address:Qe({from:C,bytecode:g.bytecode,salt:D}),bytecode:g.bytecode,abi:g.abi}});return{tables:r,systems:c,modules:u}}import{getChainId as Mr}from"viem/actions";import{existsSync as pr}from"fs";import fr from"path";import ur from"chalk";import{getScriptDirectory as yr,forge as gr}from"@latticexyz/common/foundry";async function oo(e,o,t,r){let n=fr.join(await yr(),e+".s.sol");pr(n)?(console.log(ur.blue(`Executing post deploy script at ${n}`)),await gr(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",t,"-vvv"],{profile:r})):console.log(`No script at ${n}, skipping post deploy hook`)}import{tablegen as Wr}from"@latticexyz/store/codegen";var O={configPath:{type:"string",desc:"Path to the config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."}};async function $(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await Cr(e.configPath);e.printConfig&&console.log(R.green(`
6
6
  Resolved config:
7
- `),JSON.stringify(t,null,2));let r=e.srcDir??await Or(o),n=await Ar(o),s=await Dr(),c=e.rpc??await Ir(o);if(console.log(R.bgBlue(R.whiteBright(`
8
- Deploying MUD contracts${o?" with profile "+o:""} to RPC ${c}
9
- `))),!e.skipBuild){let f=J.join(r,t.codegenDirectory);await jr(t,f,s),await kr(["build","--skip","test","script"],{profile:o}),await Pr("mud",["abi-ts"],{stdio:"inherit"})}let i=process.env.PRIVATE_KEY;if(!i)throw new Mr(`Missing PRIVATE_KEY environment variable.
7
+ `),JSON.stringify(t,null,2));let r=e.srcDir??await Ir(o),n=await kr(o),s=await Dr(),a=e.rpc??await Ar(o);if(console.log(R.bgBlue(R.whiteBright(`
8
+ Deploying MUD contracts${o?" with profile "+o:""} to RPC ${a}
9
+ `))),!e.skipBuild){let f=J.join(r,t.codegenDirectory);await Wr(t,f,s),await Tr(["build","--skip","test","script"],{profile:o}),await Or("mud",["abi-ts"],{stdio:"inherit"})}let i=process.env.PRIVATE_KEY;if(!i)throw new Pr(`Missing PRIVATE_KEY environment variable.
10
10
  Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
11
- in your contracts directory to use the default anvil private key.`);let m=Qe({config:t,forgeSourceDir:r,forgeOutDir:n}),a=Sr({transport:vr(c),account:Cr(i)});console.log("Deploying from",a.account.address);let p=Date.now(),u=await Le({worldAddress:e.worldAddress,client:a,config:m});e.worldAddress==null&&await Xe(t.postDeployScript,u.address,c,o),console.log(R.green("Deployment completed in",(Date.now()-p)/1e3,"seconds"));let C={worldAddress:u.address,blockNumber:Number(u.deployBlock)};if(e.saveDeployment){let f=await Wr(a),y=J.join(t.deploysDirectory,f.toString());wr(y,{recursive:!0}),X(J.join(y,"latest.json"),JSON.stringify(C,null,2)),X(J.join(y,Date.now()+".json"),JSON.stringify(C,null,2));let w=[1337,31337],g=hr(t.worldsFile)?JSON.parse(xr(t.worldsFile,"utf-8")):{};g[f]={address:C.worldAddress,blockNumber:w.includes(f)?void 0:C.blockNumber},X(t.worldsFile,JSON.stringify(g,null,2)),console.log(R.bgGreen(R.whiteBright(`
12
- Deployment result (written to ${t.worldsFile} and ${y}):
13
- `)))}return console.log(C),u}var Fr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await $(e)}catch(o){W(o),process.exit(1)}process.exit(0)}},eo=Fr;import{loadConfig as Rr}from"@latticexyz/config/node";import{worldgen as $r}from"@latticexyz/world/node";import{getSrcDirectory as Er}from"@latticexyz/common/foundry";import oo from"path";import{rmSync as Nr}from"fs";var Hr={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 Br(e),process.exit(0)}};async function Br(e){let o=e.srcDir??await Er(),t=F(o),r=e.config??await Rr(e.configPath),n=oo.join(o,r.codegenDirectory);e.clean&&Nr(oo.join(n,r.worldgenDirectory),{recursive:!0,force:!0}),await $r(r,t,n)}var to=Hr;import B from"chalk";import{readFileSync as Kr,writeFileSync as zr}from"fs";import oe from"path";import{MUDError as E}from"@latticexyz/common/errors";var ro={name:"@latticexyz/cli",version:"2.0.0-next.11",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",typescript:"5.1.6",viem:"1.14.0",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};import Jr from"glob";import{ZodError as Vr,z as no}from"zod";var _r=no.object({MUD_PACKAGES:no.string().transform(e=>JSON.parse(e))});function Lr(){try{return _r.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/noise":{"localPath":"packages/noise"},"@latticexyz/phaserx":{"localPath":"packages/phaserx"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"@latticexyz/services":{"localPath":"packages/services"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof Vr){let{_errors:o,...t}=e.format();console.error(`
11
+ in your contracts directory to use the default anvil private key.`);let m=eo({config:t,forgeSourceDir:r,forgeOutDir:n}),c=xr({transport:Sr(a),account:vr(i)});console.log("Deploying from",c.account.address);let p=Date.now(),w=await ze({worldAddress:e.worldAddress,client:c,config:m});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await oo(t.postDeployScript,w.address,a,o),console.log(R.green("Deployment completed in",(Date.now()-p)/1e3,"seconds"));let u={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let f=await Mr(c),g=J.join(t.deploysDirectory,f.toString());hr(g,{recursive:!0}),X(J.join(g,"latest.json"),JSON.stringify(u,null,2)),X(J.join(g,Date.now()+".json"),JSON.stringify(u,null,2));let h=[1337,31337],b=br(t.worldsFile)?JSON.parse(wr(t.worldsFile,"utf-8")):{};b[f]={address:u.worldAddress,blockNumber:h.includes(f)?void 0:u.blockNumber},X(t.worldsFile,JSON.stringify(b,null,2)),console.log(R.bgGreen(R.whiteBright(`
12
+ Deployment result (written to ${t.worldsFile} and ${g}):
13
+ `)))}return console.log(u),w}var jr={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(O)},async handler(e){try{await $(e)}catch(o){M(o),process.exit(1)}process.exit(0)}},to=jr;import{loadConfig as Fr}from"@latticexyz/config/node";import{worldgen as Rr}from"@latticexyz/world/node";import{getSrcDirectory as $r}from"@latticexyz/common/foundry";import ro from"path";import{rmSync as Er}from"fs";var Nr={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await Hr(e),process.exit(0)}};async function Hr(e){let o=e.srcDir??await $r(),t=F(o),r=e.config??await Fr(e.configPath),n=ro.join(o,r.codegenDirectory);e.clean&&Er(ro.join(n,r.worldgenDirectory),{recursive:!0,force:!0}),await Rr(r,t,n)}var no=Nr;import B from"chalk";import{readFileSync as Lr,writeFileSync as Kr}from"fs";import oe from"path";import{MUDError as E}from"@latticexyz/common/errors";var so={name:"@latticexyz/cli",version:"2.0.0-next.11",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",typescript:"5.1.6",viem:"1.14.0",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"},gitHead:"914a1e0ae4a573d685841ca2ea921435057deb8f"};import zr from"glob";import{ZodError as Ur,z as io}from"zod";var Vr=io.object({MUD_PACKAGES:io.string().transform(e=>JSON.parse(e))});function _r(){try{return Vr.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/noise":{"localPath":"packages/noise"},"@latticexyz/phaserx":{"localPath":"packages/phaserx"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"@latticexyz/services":{"localPath":"packages/services"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof Ur){let{_errors:o,...t}=e.format();console.error(`
14
14
  Missing or invalid environment variables:
15
15
 
16
16
  ${Object.keys(t).join(`
17
17
  `)}
18
- `),process.exit(1)}throw e}}var ee=Lr().MUD_PACKAGES;var qr={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((n,s)=>e[s]?n+1:n,0);if(t===0)throw new E(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new E(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await Gr(e);let r=Jr.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Yr(n,e)}catch(o){W(o)}finally{process.exit(0)}}};async function Gr(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(B.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${ro.name}`)).json()}catch{throw new E("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new E(`Could not find npm version with tag "${e.tag}"`);return console.log(B.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new E(`Could not find npm version based on commit "${e.commit}"`);return console.log(B.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Yr(e,o){let{link:t}=o,{mudVersion:r}=o,n=Zr(e),s=Object.keys(ee),c={};for(let a in n.dependencies)s.includes(a)&&(c[a]=n.dependencies[a]);let i={};for(let a in n.devDependencies)s.includes(a)&&(i[a]=n.devDependencies[a]);for(let a in n.dependencies)s.includes(a)&&(n.dependencies[a]=m(a,"dependencies"));for(let a in n.devDependencies)s.includes(a)&&(n.devDependencies[a]=m(a,"devDependencies"));return zr(e,JSON.stringify(n,null,2)+`
19
- `),console.log(`Updating ${e}`),so(c,n.dependencies),so(i,n.devDependencies),n;function m(a,p){return t&&(r=Qr(e,t,a)),r||n[p][a]}}function Zr(e){try{let o=Kr(e,"utf8");return JSON.parse(o)}catch{throw new E("Could not read JSON at "+e)}}function so(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${B.red(e[t])} -> ${B.green(o[t])}`)}function Qr(e,o,t){let r=oe.relative(oe.dirname(e),process.cwd());return"link:"+oe.join(r,o,ee[t].localPath)}var io=qr;import{anvil as Xr,forge as en,getRpcUrl as on}from"@latticexyz/common/foundry";import tn from"chalk";var rn={...M,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}},nn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(rn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Xr(n)}let o=e.worldAddress?await on(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await $({...e,saveDeployment:!1,rpc:o})).address;console.log(tn.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await en(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ao=nn;import{existsSync as sn,readFileSync as an}from"fs";import{ethers as co}from"ethers";import{loadConfig as cn}from"@latticexyz/config/node";import{MUDError as lo}from"@latticexyz/common/errors";import{cast as ln,getRpcUrl as dn,getSrcDirectory as mn}from"@latticexyz/common/foundry";import{resolveWorldConfig as pn}from"@latticexyz/world";import fn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import mo from"@latticexyz/world/mud.config.js";import{resourceToHex as fo}from"@latticexyz/common";import{createClient as un,http as yn}from"viem";import{getChainId as gn}from"viem/actions";var po=fo({type:"system",namespace:mo.namespace,name:mo.tables.Systems.name}),bn={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the config file"},profile:{type:"string",description:"The foundry profile to use"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await mn(o),e.rpc??=await dn(o);let{tx:t,configPath:r,srcDir:n,rpc:s}=e,c=F(n),i=await cn(r),m=pn(i,c.map(({basename:h})=>h)),a=e.worldAddress??await hn(i.worldsFile,s),p=new co.providers.StaticJsonRpcProvider(s),u=new co.Contract(a,fn,p),C=i.namespace,f=Object.values(m.systems).map(({name:h})=>h),y=await u.getFieldLayout(po),w=[];for(let h of f){let d=fo({type:"system",namespace:C,name:h}),b=await u.getField(po,[d],0,y);w.push({name:h,address:b})}let g=await ln(["run","--label",`${a}:World`,...w.map(({name:h,address:d})=>["--label",`${d}:${h}`]).flat(),`${t}`]);console.log(g),process.exit(0)}},uo=bn;async function hn(e,o){if(sn(e)){let t=un({transport:yn(o)}),r=await gn(t),n=JSON.parse(an(e,"utf-8"));if(!n[r])throw new lo(`chainId ${r} is missing in worldsFile "${e}"`);return n[r].address}else throw new lo("worldAddress is not specified and worldsFile is missing")}import{anvil as wn,getScriptDirectory as xn,getSrcDirectory as Sn}from"@latticexyz/common/foundry";import te from"chalk";import vn from"chokidar";import{loadConfig as Cn,resolveConfigPath as Tn}from"@latticexyz/config/node";import kn from"path";import{homedir as An}from"os";import{rmSync as Dn}from"fs";import{BehaviorSubject as In,debounceTime as On,exhaustMap as Pn}from"rxjs";var Mn={rpc:M.rpc,configPath:M.configPath},Wn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Mn)},async handler(e){let o=e.rpc,t=e.configPath??await Tn(e.configPath),r=await Sn(),n=await xn(),s=await Cn(t);if(!e.rpc){console.log(te.gray("Cleaning devnode cache"));let a=An();Dn(kn.join(a,".foundry","anvil","tmp"),{recursive:!0,force:!0}),wn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let c=new In(Date.now());vn.watch([t,r,n]).on("all",async(a,p)=>{p.includes(t)&&c.next(Date.now()),(p.includes(r)||p.includes(n))&&(p.includes(s.codegenDirectory)||c.next(Date.now()))});let i;c.pipe(On(200),Pn(async a=>{i&&console.log(te.blue("Change detected, rebuilding and running deploy..."));let p=await $({configPath:t,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:r});return i=p.address,a<c.value?c.next(c.value):console.log(te.gray("Watching for file changes...")),p})).subscribe()}},yo=Wn;var go=[eo,ne,ie,jn,ae,ce,to,io,ao,uo,yo,Fn];import*as ho from"dotenv";import bo from"chalk";ho.config();Rn($n(process.argv)).scriptName("mud").command(go).strict().fail((e,o)=>{console.error(bo.red(e)),e.includes("Missing required argument")&&console.log(bo.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(W(o),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
18
+ `),process.exit(1)}throw e}}var ee=_r().MUD_PACKAGES;var Jr={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((n,s)=>e[s]?n+1:n,0);if(t===0)throw new E(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new E(`These options are mutually exclusive: ${o.join(", ")}`);e.mudVersion=await qr(e);let r=zr.sync("**/package.json").filter(n=>!n.includes("node_modules"));for(let n of r)Gr(n,e)}catch(o){M(o)}finally{process.exit(0)}}};async function qr(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(B.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${so.name}`)).json()}catch{throw new E("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new E(`Could not find npm version with tag "${e.tag}"`);return console.log(B.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new E(`Could not find npm version based on commit "${e.commit}"`);return console.log(B.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Gr(e,o){let{link:t}=o,{mudVersion:r}=o,n=Yr(e),s=Object.keys(ee),a={};for(let c in n.dependencies)s.includes(c)&&(a[c]=n.dependencies[c]);let i={};for(let c in n.devDependencies)s.includes(c)&&(i[c]=n.devDependencies[c]);for(let c in n.dependencies)s.includes(c)&&(n.dependencies[c]=m(c,"dependencies"));for(let c in n.devDependencies)s.includes(c)&&(n.devDependencies[c]=m(c,"devDependencies"));return Kr(e,JSON.stringify(n,null,2)+`
19
+ `),console.log(`Updating ${e}`),ao(a,n.dependencies),ao(i,n.devDependencies),n;function m(c,p){return t&&(r=Zr(e,t,c)),r||n[p][c]}}function Yr(e){try{let o=Lr(e,"utf8");return JSON.parse(o)}catch{throw new E("Could not read JSON at "+e)}}function ao(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${B.red(e[t])} -> ${B.green(o[t])}`)}function Zr(e,o,t){let r=oe.relative(oe.dirname(e),process.cwd());return"link:"+oe.join(r,o,ee[t].localPath)}var co=Jr;import{anvil as Qr,forge as Xr,getRpcUrl as en}from"@latticexyz/common/foundry";import on from"chalk";var tn={...O,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}},rn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(tn)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Qr(n)}let o=e.worldAddress?await en(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await $({...e,saveDeployment:!1,rpc:o})).address;console.log(on.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Xr(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},lo=rn;import{existsSync as nn,readFileSync as sn}from"fs";import{ethers as mo}from"ethers";import{loadConfig as an}from"@latticexyz/config/node";import{MUDError as po}from"@latticexyz/common/errors";import{cast as cn,getRpcUrl as ln,getSrcDirectory as dn}from"@latticexyz/common/foundry";import{resolveWorldConfig as mn}from"@latticexyz/world";import pn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import fo from"@latticexyz/world/mud.config.js";import{resourceToHex as yo}from"@latticexyz/common";import{createClient as fn,http as un}from"viem";import{getChainId as yn}from"viem/actions";var uo=yo({type:"system",namespace:fo.namespace,name:fo.tables.Systems.name}),gn={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the config file"},profile:{type:"string",description:"The foundry profile to use"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await dn(o),e.rpc??=await ln(o);let{tx:t,configPath:r,srcDir:n,rpc:s}=e,a=F(n),i=await an(r),m=mn(i,a.map(({basename:l})=>l)),c=e.worldAddress??await bn(i.worldsFile,s),p=new mo.providers.StaticJsonRpcProvider(s),w=new mo.Contract(c,pn,p),u=i.namespace,f=Object.values(m.systems).map(({name:l})=>l),g=await w.getFieldLayout(uo),h=[];for(let l of f){let y=yo({type:"system",namespace:u,name:l}),x=await w.getField(uo,[y],0,g);h.push({name:l,address:x})}let b=await cn(["run","--label",`${c}:World`,...h.map(({name:l,address:y})=>["--label",`${y}:${l}`]).flat(),`${t}`]);console.log(b),process.exit(0)}},go=gn;async function bn(e,o){if(nn(e)){let t=fn({transport:un(o)}),r=await yn(t),n=JSON.parse(sn(e,"utf-8"));if(!n[r])throw new po(`chainId ${r} is missing in worldsFile "${e}"`);return n[r].address}else throw new po("worldAddress is not specified and worldsFile is missing")}import{anvil as hn,getScriptDirectory as wn,getSrcDirectory as xn}from"@latticexyz/common/foundry";import te from"chalk";import Sn from"chokidar";import{loadConfig as vn,resolveConfigPath as Cn}from"@latticexyz/config/node";import Tn from"path";import{homedir as kn}from"os";import{rmSync as Dn}from"fs";import{BehaviorSubject as An,debounceTime as In,exhaustMap as On}from"rxjs";var Pn={rpc:O.rpc,configPath:O.configPath,alwaysRunPostDeploy:O.alwaysRunPostDeploy},Mn={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Pn)},async handler(e){let o=e.rpc,t=e.configPath??await Cn(e.configPath),r=await xn(),n=await wn(),s=await vn(t);if(!e.rpc){console.log(te.gray("Cleaning devnode cache"));let c=kn();Dn(Tn.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),hn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let a=new An(Date.now());Sn.watch([t,r,n]).on("all",async(c,p)=>{p.includes(t)&&a.next(Date.now()),(p.includes(r)||p.includes(n))&&(p.includes(s.codegenDirectory)||a.next(Date.now()))});let i;a.pipe(In(200),On(async c=>{i&&console.log(te.blue("Change detected, rebuilding and running deploy..."));let p=await $({...e,configPath:t,rpc:o,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,worldAddress:i,srcDir:r});return i=p.address,c<a.value?a.next(a.value):console.log(te.gray("Watching for file changes...")),p})).subscribe()}},bo=Mn;var ho=[to,ne,ie,Wn,ae,ce,no,co,lo,go,bo,jn];import*as xo from"dotenv";import wo from"chalk";xo.config();Fn(Rn(process.argv)).scriptName("mud").command(ho).strict().fail((e,o)=>{console.error(wo.red(e)),e.includes("Missing required argument")&&console.log(wo.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),o!=null&&(M(o),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
20
20
  //# sourceMappingURL=mud.js.map