@latticexyz/cli 2.0.0-main-6ca1874e → 2.0.0-main-e1dc88eb

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