@latticexyz/cli 2.2.15-1e092407da570f8ba52e89e73dda50cdff161a93 → 2.2.15-2d2aa0867580dd910cc772b5cdd42c802e8652e3

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.
@@ -0,0 +1,43 @@
1
+ import{a as te}from"./chunk-JXC4VYGI.js";import{command as Ya}from"@latticexyz/gas-report/internal";import{command as Ga}from"@latticexyz/abi-ts/internal";import{loadConfig as Ct,resolveConfigPath as Dt}from"@latticexyz/config/node";import{tablegen as ht}from"@latticexyz/store/codegen";import{buildSystemsManifest as wt,worldgen as xt}from"@latticexyz/world/node";import{forge as vt}from"@latticexyz/common/foundry";import{execa as St}from"execa";async function E({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([ht({rootDir:e,config:o}),xt({rootDir:e,config:o})]),await vt(["build"],{profile:t}),await wt({rootDir:e,config:o}),await St("mud",["abi-ts"],{stdio:"inherit"})}import At from"node:path";var kt={command:"build",describe:"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler(e){let o=await Dt(e.configPath),t=await Ct(o);await E({rootDir:At.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},Fe=kt;import{rmSync as Tt}from"fs";import{homedir as Pt}from"os";import Ot from"path";import{execa as Mt}from"execa";var Bt={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=Pt();Tt(Ot.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=Mt("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
2
+ gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},Ee=Bt;var Ht={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)}},Le=Ht;import{loadConfig as It,resolveConfigPath as Wt}from"@latticexyz/config/node";import{tablegen as jt}from"@latticexyz/store/codegen";import Rt from"node:path";var $t={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 MUD config file"}})},async handler(e){let o=await Wt(e.configPath),t=await It(o);await jt({rootDir:Rt.dirname(o),config:t}),process.exit(0)}},ze=$t;import he from"node:path";import{existsSync as Jo,mkdirSync as qn,readFileSync as qo,writeFileSync as Oe}from"node:fs";import{stringToHex as mn}from"viem";import{waitForTransactionReceipt as rr}from"viem/actions";import Je from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Lt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{encodeDeployData as zt,size as Nt}from"viem";import Ne from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Ue from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import _e from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import Ve from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import Ke from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Ft from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{encodeDeployData as Et,size as q}from"viem";import{getContractAddress as Y}from"@latticexyz/common/internal";function L(e){let o=q(Ne.deployedBytecode.object),t=Ne.bytecode.object,r=Y({deployerAddress:e,bytecode:t}),n=q(Ue.deployedBytecode.object),a=Ue.bytecode.object,s=Y({deployerAddress:e,bytecode:a}),i=q(_e.deployedBytecode.object),c=_e.bytecode.object,l=Y({deployerAddress:e,bytecode:c}),p=q(Ve.deployedBytecode.object),y=Ve.bytecode.object,u=Y({deployerAddress:e,bytecode:y}),d=q(Ke.deployedBytecode.object),f=Et({bytecode:Ke.bytecode.object,abi:Ft,args:[r,s,l,u]}),h=Y({deployerAddress:e,bytecode:f});return{AccessManagementSystem:{bytecode:t,deployedBytecodeSize:o,debugLabel:"access management system",address:r},BalanceTransferSystem:{bytecode:a,deployedBytecodeSize:n,debugLabel:"balance transfer system",address:s},BatchCallSystem:{bytecode:c,deployedBytecodeSize:i,debugLabel:"batch call system",address:l},RegistrationSystem:{bytecode:y,deployedBytecodeSize:p,debugLabel:"core registration system",address:u},InitModule:{bytecode:f,deployedBytecodeSize:d,debugLabel:"core module",address:h}}}import{getContractAddress as Ut}from"@latticexyz/common/internal";function re(e){let o=L(e),t=Nt(Je.deployedBytecode.object),r=zt({bytecode:Je.bytecode.object,abi:Lt,args:[o.InitModule.address]}),n=Ut({deployerAddress:e,bytecode:r});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import qe from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import _t from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{encodeDeployData as Vt,size as Kt}from"viem";import{getContractAddress as Jt}from"@latticexyz/common/internal";function ne(e){let o=L(e),t=Kt(qe.deployedBytecode.object),r=Vt({bytecode:qe.bytecode.object,abi:_t,args:[o.InitModule.address]}),n=Jt({deployerAddress:e,bytecode:r});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world proxy factory",address:n}}}import{ensureContractsDeployed as Ye}from"@latticexyz/common/internal";async function Ge(e,o,t){if(t){let n=ne(o);return await Ye({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=re(o);return await Ye({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import nr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as sr}from"@latticexyz/common";import Qe from"debug";var O=Qe("mud:cli"),qt=Qe("mud:cli");O.log=console.debug.bind(console);qt.log=console.error.bind(console);var g=O.extend("deploy"),Yt=O.extend("deploy");g.log=console.debug.bind(console);Yt.log=console.error.bind(console);import{AbiEventSignatureNotFoundError as Xt,decodeEventLog as er,hexToString as eo,parseAbi as or}from"viem";import Gt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as Qt}from"@latticexyz/store";import{helloWorldEvent as Zt}from"@latticexyz/world";var se=[Qt,Zt],D=Gt,Ze=["2.0.0","2.0.1","2.0.2"],Xe=["2.0.0","2.0.1","2.0.2"];import{isDefined as tr}from"@latticexyz/common/utils";function z(e){let o=e.map(s=>{try{return{...s,...er({strict:!0,abi:or(se),topics:s.topics,data:s.data})}}catch(i){if(i instanceof Xt)return;throw i}}).filter(tr),{address:t,deployBlock:r,worldVersion:n,storeVersion:a}=o.reduce((s,i)=>({...s,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:eo(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:eo(i.args.storeVersion).replace(/\0+$/,"")}: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(a==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:a}}async function oo(e,o,t,r){let n=await Ge(e,o,r);g("deploying world");let a=await sr(e,{chain:e.chain??null,address:n,abi:nr,functionName:"deployWorld",args:[t]});g("waiting for world deploy");let s=await rr(e,{hash:a});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");let i=z(s.logs);return g("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as ie,writeContract as dr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as so,valueSchemaToHex as ao,getSchemaTypes as N,getValueSchema as io,getKeySchema as lo}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as to,parseAbiParameters as ro}from"viem";import{hexToResource as ar}from"@latticexyz/common";import{hexToSchema as no}from"@latticexyz/protocol-parser/internal";import ir from"@latticexyz/store/mud.config";import{getRecords as lr}from"@latticexyz/store-sync";async function ae({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up tables for",o.address);let{records:n}=await lr({table:ir.namespaces.store.tables.Tables,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.map(s=>{let{type:i,namespace:c,name:l}=ar(s.tableId),p=no(s.keySchema),y=no(s.valueSchema),u=to(ro("string[]"),s.abiEncodedKeyNames)[0],d=to(ro("string[]"),s.abiEncodedFieldNames)[0],f=[...y.staticFields,...y.dynamicFields],h=Object.fromEntries(p.staticFields.map((A,k)=>[u[k],{type:A,internalType:A}])),S=Object.fromEntries(f.map((A,k)=>[d[k],{type:A,internalType:A}]));return{type:i,namespace:c,name:l,tableId:s.tableId,schema:{...h,...S},key:Object.keys(h),keySchema:h,keySchemaHex:s.keySchema,valueSchema:S,valueSchemaHex:s.valueSchema}});return g("found",a.length,"tables for",o.address),a}import mr from"p-retry";import{isDefined as pr}from"@latticexyz/common/utils";async function co({client:e,worldDeploy:o,tables:t,indexerUrl:r,chainId:n}){let a=new Map(t.map(p=>{let y=N(lo(p)),u=N(io(p)),d=so(y),f=ao(u);return[p.tableId,{...p,keySchema:y,keySchemaHex:d,valueSchema:u,valueSchemaHex:f}]})),i=(await ae({client:e,worldDeploy:o,indexerUrl:r,chainId:n})).filter(({tableId:p})=>a.has(p));if(i.length){g("existing tables:",i.map(ie).join(", "));let p=i.map(y=>{let u=a.get(y.tableId);if(y.keySchemaHex!==u.keySchemaHex||y.valueSchemaHex!==u.valueSchemaHex)return[`"${ie(y)}" table:`,` Registered schema: ${JSON.stringify({schema:N(y.schema),key:y.key})}`,` Config schema: ${JSON.stringify({schema:N(u.schema),key:u.key})}`].join(`
3
+ `)}).filter(pr);if(p.length)throw new Error(["Table schemas are immutable, but found registered tables with a different schema than what you have configured.",...p,"You can either update your config with the registered schema or change the table name to register a new table."].join(`
4
+
5
+ `)+`
6
+ `)}let c=new Set(i.map(({tableId:p})=>p)),l=t.filter(p=>!c.has(p.tableId));return l.length?(g("registering tables:",l.map(ie).join(", ")),await Promise.all(l.map(p=>{let y=N(lo(p)),u=N(io(p));return mr(()=>dr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[p.tableId,cr(u),so(y),ao(u),Object.keys(y),Object.keys(u)]}),{retries:3,onFailedAttempt:()=>g(`failed to register table ${ie(p)}, retrying...`)})}))):[]}import{getAddress as I}from"viem";import{writeContract as Se,resourceToLabel as G}from"@latticexyz/common";import{hexToResource as Cr,resourceToLabel as Dr}from"@latticexyz/common";import{getFunctions as Ar}from"@latticexyz/store-sync/world";import fr from"@latticexyz/store/mud.config";import{getRecords as yr}from"@latticexyz/store-sync";async function U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource IDs for",o.address);let{records:n}=await yr({table:fr.namespaces.store.tables.ResourceIds,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.map(s=>s.resourceId);return g("found",a.length,"resource IDs for",o.address),a}import{decodeValueArgs as ur,encodeKey as gr,getKeySchema as br,getSchemaTypes as mo,getValueSchema as hr}from"@latticexyz/protocol-parser/internal";import{readContract as wr}from"viem/actions";async function le({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await wr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,gr(mo(br(t)),r)]});return ur(mo(hr(t)),{staticData:n,encodedLengths:a,dynamicData:s})}import{getAddress as xr}from"viem";import vr from"@latticexyz/world/mud.config";import{getRecords as Sr}from"@latticexyz/store-sync";async function de({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource access for",o.address);let{records:n}=await Sr({table:vr.namespaces.world.tables.ResourceAccess,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.filter(s=>s.access).map(s=>({resourceId:s.resourceId,address:xr(s.caller)}));return g("found",a.length,"resource<>address access pairs"),a}import kr from"@latticexyz/world/mud.config";async function po({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){let[n,a,s]=await Promise.all([U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}),Ar({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:t,chainId:r}),de({client:e,worldDeploy:o,indexerUrl:t,chainId:r})]),i=n.map(Cr).filter(c=>c.type==="system");return g("looking up systems:",i.map(Dr).join(", ")),await Promise.all(i.map(async c=>{let{system:l,publicAccess:p}=await le({client:e,worldDeploy:o,table:kr.namespaces.world.tables.Systems,key:{systemId:c.resourceId}}),y=a.filter(u=>u.systemId===c.resourceId);return{address:l,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:p,allowedAddresses:s.filter(({resourceId:u})=>u===c.resourceId).map(({address:u})=>u),worldFunctions:y}}))}import Ce from"p-retry";import{ensureContractsDeployed as Tr}from"@latticexyz/common/internal";async function fo({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n,indexerUrl:a,chainId:s}){let[i,c]=await Promise.all([po({client:e,worldDeploy:r,indexerUrl:a,chainId:s}),de({client:e,worldDeploy:r,indexerUrl:a,chainId:s})]),l=n.filter(m=>i.some(b=>b.systemId===m.systemId&&I(b.address)===I(m.prepareDeploy(o,t).address)));l.length&&g("existing systems:",l.map(G).join(", "));let p=l.map(m=>m.systemId),y=n.filter(m=>!p.includes(m.systemId));if(!y.length)return[];let u=y.filter(m=>i.some(b=>b.systemId===m.systemId&&I(b.address)!==I(m.prepareDeploy(o,t).address)));u.length&&g("upgrading systems:",u.map(G).join(", "));let d=y.filter(m=>!i.some(b=>b.systemId===m.systemId));d.length&&g("registering new systems:",d.map(G).join(", ")),await Tr({client:e,deployerAddress:o,contracts:y.map(m=>({bytecode:m.prepareDeploy(o,t).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,debugLabel:`${G(m)} system`}))});let f=await Promise.all(y.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"registerSystem",args:[m.systemId,m.prepareDeploy(o,t).address,m.allowAll]}),{retries:3,onFailedAttempt:()=>g(`failed to register system ${G(m)}, retrying...`)}))),h=n.map(m=>m.systemId),S=c.filter(({resourceId:m})=>h.includes(m)),A=[...n.flatMap(m=>m.allowedAddresses.map(b=>({resourceId:m.systemId,address:b}))),...n.flatMap(m=>m.allowedSystemIds.map(b=>({resourceId:m.systemId,address:i.find(T=>T.systemId===b)?.address??n.find(T=>T.systemId===b)?.prepareDeploy(o,t).address})).filter(b=>b.address!=null))],k=A.filter(m=>!S.some(({resourceId:b,address:T})=>b===m.resourceId&&I(T)===I(m.address))),x=S.filter(m=>!A.some(({resourceId:b,address:T})=>b===m.resourceId&&I(T)===I(m.address)));x.length&&g("revoking",x.length,"access grants"),k.length&&g("adding",k.length,"access grants");let w=await Promise.all([...x.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"revokeAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to revoke access, retrying...")})),...k.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"grantAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to grant access, retrying...")}))]);return[...f,...w]}import{getAddress as Pr,parseAbi as Or}from"viem";import{getBlock as De}from"viem/actions";import{fetchBlockLogs as Mr}from"@latticexyz/block-logs-stream";var yo=new Map;async function ce(e,o,t){let r=Pr(o),n=yo.get(r);if(n!=null)return{...n,stateBlock:(await De(e,{blockTag:"latest"})).number};g("looking up world deploy for",r);let[a,s]=t?[{number:t},{number:t}]:await Promise.all([De(e,{blockTag:"earliest"}),De(e,{blockTag:"latest"})]),i=await Mr({publicClient:e,address:r,events:Or(se),fromBlock:a.number,toBlock:s.number,maxBlockRange:100000n});if(i.length===0)throw new Error("could not find `HelloWorld` or `HelloStore` event");return n={...z(i.flatMap(c=>c.logs)),stateBlock:s.number},yo.set(r,n),g("found world deploy for",r,"at block",n.deployBlock),n}import{hexToResource as Br,writeContract as Hr}from"@latticexyz/common";import{getFunctions as Ir}from"@latticexyz/store-sync/world";import Wr from"p-retry";async function uo({client:e,worldDeploy:o,functions:t,indexerUrl:r,chainId:n}){let a=await Ir({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:r,chainId:n}),s=Object.fromEntries(a.map(l=>[l.selector,l])),i=t.filter(l=>s[l.selector]),c=t.filter(l=>!i.includes(l));if(i.length){g("functions already registered:",i.map(p=>p.signature).join(", "));let l=i.filter(p=>p.systemId!==s[p.selector]?.systemId);l.length&&console.warn("found",l.length,"functions already registered but pointing at a different system ID:",l.map(p=>p.signature).join(", "))}return c.length?(g("registering functions:",c.map(l=>l.signature).join(", ")),Promise.all(c.map(l=>{let{namespace:p}=Br(l.systemId),y=p===""?{functionName:"registerRootFunctionSelector",args:[l.systemId,l.systemFunctionSignature,l.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[l.systemId,l.systemFunctionSignature]};return Wr(()=>Hr(e,{chain:e.chain??null,address:o.address,abi:D,...y}),{retries:3,onFailedAttempt:()=>g(`failed to register function ${l.signature}, retrying...`)})}))):[]}import{BaseError as jr}from"viem";import{writeContract as Rr}from"@latticexyz/common";import{isDefined as $r}from"@latticexyz/common/utils";import Fr from"p-retry";import{ensureContractsDeployed as Er}from"@latticexyz/common/internal";async function me({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await Er({client:e,deployerAddress:o,contracts:n.map(a=>({bytecode:a.prepareDeploy(o,t).bytecode,deployedBytecodeSize:a.deployedBytecodeSize,debugLabel:`${a.name} module`}))}),g("installing modules:",n.map(a=>a.name).join(", ")),(await Promise.all(n.map(a=>Fr(async()=>{try{let s=[...D,...a.abi],i=a.prepareDeploy(o,t).address,c=a.installAsRoot?{functionName:"installRootModule",args:[i,a.installData]}:{functionName:"installModule",args:[i,a.installData]};return await Rr(e,{chain:e.chain??null,address:r.address,abi:s,...c})}catch(s){if(s instanceof jr&&s.message.includes("Module_AlreadyInstalled")){g(`module ${a.name} already installed`);return}if(a.optional){g(`optional module ${a.name} install failed, skipping`),g(s);return}throw s}},{retries:3,onFailedAttempt:()=>g(`failed to install module ${a.name}, retrying...`)})))).filter($r)):[]}import{getAddress as go}from"viem";import{hexToResource as bo,resourceToHex as ho,writeContract as Lr}from"@latticexyz/common";import zr from"@latticexyz/world/mud.config";async function wo({client:e,worldDeploy:o,resourceIds:t,indexerUrl:r,chainId:n}){let a=Array.from(new Set(t.map(d=>bo(d).namespace))),s=await U({client:e,worldDeploy:o,indexerUrl:r,chainId:n}),i=new Set(s.map(d=>bo(d).namespace));i.size&&g("found",i.size,"existing namespaces:",Array.from(i).map(d=>d===""?"<root>":d).join(", "));let c=a.filter(d=>i.has(d)),p=(await Promise.all(c.map(async d=>{let{owner:f}=await le({client:e,worldDeploy:o,table:zr.namespaces.world.tables.NamespaceOwner,key:{namespaceId:ho({type:"namespace",namespace:d,name:""})}});return[d,f]}))).filter(([,d])=>go(d)!==go(e.account.address)).map(([d])=>d);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`);let y=a.filter(d=>!i.has(d));return y.length>0&&g("registering namespaces:",Array.from(y).join(", ")),Promise.all(y.map(d=>Lr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[ho({namespace:d,type:"namespace",name:""})]})))}import{resourceToHex as pn,resourceToLabel as fn}from"@latticexyz/common";import{randomBytes as yn}from"crypto";import{stringToHex as qr,BaseError as Yr,concatHex as So}from"viem";import{hexToResource as Gr,writeContract as Qr}from"@latticexyz/common";import{identity as Zr,isDefined as Xr}from"@latticexyz/common/utils";import Ae from"@latticexyz/world-module-metadata/mud.config";import en from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import on from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as Nr,size as Ur}from"viem";function pe(e){return Object.entries(e).flatMap(([o,t])=>Object.entries(t).flatMap(([r,n])=>n.map(a=>({path:o,name:r,start:a.start,length:a.length}))))}import{z as B}from"zod";import{Abi as _r}from"abitype/zod";function Vr(e){return Nr(e,{strict:!1})}var xo=B.object({object:B.string().refine(Vr),linkReferences:B.record(B.record(B.array(B.object({start:B.number(),length:B.number()})))).optional()}),Kr=B.object({bytecode:xo,deployedBytecode:xo,abi:_r});function fe(e){let o=Kr.parse(e),t=pe(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:Ur(o.deployedBytecode.object)}}import{spliceHex as Jr}from"@latticexyz/common";import{getContractAddress as vo}from"@latticexyz/common/internal";function R(e,o){return function(r,n){let a=e;if(o.length===0)return{bytecode:a,address:vo({deployerAddress:r,bytecode:a})};if(!n)throw new Error("Libraries must be provided if there are placeholders");for(let s of o){let i=n.getAddress({name:s.name,path:s.path,deployer:r});a=Jr(a,s.start,s.length,i)}return{bytecode:a,address:vo({deployerAddress:r,bytecode:a})}}}import{getKeyTuple as Co}from"@latticexyz/protocol-parser/internal";import{getRecords as tn}from"@latticexyz/store-sync";import{waitForTransactions as rn}from"@latticexyz/common/internal";var ye=fe(on);async function Do({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:a=Zr,indexerUrl:s,chainId:i}){g("ensuring",n.length,"resource tags"),g("looking up existing resource tags");let{records:c}=await tn({table:Ae.tables.metadata__ResourceTag,worldAddress:r.address,chainId:i,indexerUrl:s,client:e,fromBlock:r.deployBlock,toBlock:r.stateBlock});g("found",c.length,"resource tags");let l=new Map(c.map(d=>[So(Co(Ae.tables.metadata__ResourceTag,d)),d.value])),y=n.map(d=>({resource:d.resourceId,tag:qr(d.tag,{size:32}),value:a(d.value)})).filter(d=>{let f=So(Co(Ae.tables.metadata__ResourceTag,d));return l.get(f)!==d.value});if(y.length===0)return[];let u=await me({client:e,deployerAddress:o,worldDeploy:r,libraryMap:t,modules:[{optional:!0,name:"MetadataModule",installAsRoot:!1,installData:"0x",prepareDeploy:R(ye.bytecode,ye.placeholders),deployedBytecodeSize:ye.deployedBytecodeSize,abi:ye.abi}]});return await rn({client:e,hashes:u,debugLabel:"metadata module installation"}),g("setting",y.length,"resource tags"),(await Promise.all(y.map(async d=>{let f=Gr(d.resource),h=`${f.type}:${f.namespace}:${f.name}`;g(`tagging ${h} with ${d.tag}: ${JSON.stringify(d.value)}`);try{return await Qr(e,{chain:e.chain??null,address:r.address,abi:en,functionName:"metadata__setResourceTag",args:[d.resource,d.tag,d.value]})}catch(S){g(`failed to set resource tag for ${h}, skipping
7
+ ${S instanceof Yr?S.shortMessage:S}`)}}))).filter(Xr)}import{concatHex as nn,encodeDeployData as sn,isHex as Po}from"viem";import{waitForTransactionReceipt as an}from"viem/actions";import{resourceToHex as ln,sendTransaction as dn,writeContract as Ao}from"@latticexyz/common";import{ensureContractsDeployed as ko,getContractAddress as cn,waitForTransactions as To}from"@latticexyz/common/internal";function Te(e,o){let t=o.find(r=>r.sourcePath===e.sourcePath&&r.name===e.name);if(!t)throw new Error(`Could not find referenced artifact at "${e.sourcePath}:${e.name}".`);return t}function Oo(e,o){return e.bytecode.filter(t=>!Po(t)).flatMap(t=>Oo(Te(t,o),o))}function ke(e,o,t){return nn(o.bytecode.map(r=>Po(r)?r:cn({deployerAddress:e,bytecode:ke(e,Te(r,t),t)})))}async function Mo({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=L(o);await ko({client:e,deployerAddress:o,contracts:Object.values(n)});let a=Te(r,t),s=Oo(a,t);s.length&&(g(`deploying ${s.length} world dependencies`),await ko({client:e,deployerAddress:o,contracts:s.map(u=>ke(o,u,t)).reverse().map(u=>({bytecode:u}))})),g("deploying custom world");let i=await dn(e,{chain:e.chain??null,data:sn({abi:a.abi,args:[],bytecode:ke(o,a,t)})});g("waiting for custom world deploy");let c=await an(e,{hash:i});if(c.status!=="success")throw console.error("world deploy failed",c),new Error("world deploy failed");let l=z(c.logs);g("deployed custom world to",l.address,"at block",l.deployBlock);let p=await Ao(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"initialize",args:[n.InitModule.address]});await To({client:e,hashes:[p],debugLabel:"world init"});let y=await Ao(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"transferOwnership",args:[ln({type:"namespace",namespace:"",name:""}),e.account.address]});return await To({client:e,hashes:[y],debugLabel:"world ownership transfer"}),{...l,stateBlock:l.deployBlock}}import{uniqueBy as un}from"@latticexyz/common/utils";function Bo({path:e,name:o}){return`${e}:${o}`}function Ho(e){let o=Object.fromEntries(e.map(r=>[Bo(r),r])),t={getAddress:({path:r,name:n,deployer:a})=>{let s=o[Bo({path:r,name:n})];if(!s)throw new Error(`Could not find library for bytecode placeholder ${r}:${n}`);return s.address??={},s.address[a]??=s.prepareDeploy(a,t).address,s.address[a]}};return t}import{ensureContractsDeployed as gn,ensureDeployer as bn,waitForTransactions as Pe}from"@latticexyz/common/internal";async function Io({config:e,client:o,tables:t,systems:r,libraries:n,modules:a=[],artifacts:s,salt:i,worldAddress:c,worldDeployBlock:l,deployerAddress:p,indexerUrl:y,chainId:u}){let d=p??await bn(o),f=c?await ce(o,c,l):e.deploy.customWorld?await Mo({client:o,deployerAddress:d,artifacts:s,customWorld:e.deploy.customWorld}):await oo(o,d,i??`0x${yn(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation),h={client:o,indexerUrl:y,chainId:u,worldDeploy:f};if(!Ze.includes(f.storeVersion))throw new Error(`Unsupported Store version: ${f.storeVersion}`);if(!Xe.includes(f.worldVersion))throw new Error(`Unsupported World version: ${f.worldVersion}`);let S=Ho(n);await gn({...h,deployerAddress:d,contracts:[...n.map(v=>({bytecode:v.prepareDeploy(d,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${v.path}:${v.name} library`})),...r.map(v=>({bytecode:v.prepareDeploy(d,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${fn(v)} system`})),...a.map(v=>({bytecode:v.prepareDeploy(d,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${v.name} module`}))]});let A=await wo({...h,resourceIds:[...t.map(({tableId:v})=>v),...r.map(({systemId:v})=>v)]});await Pe({client:o,hashes:A,debugLabel:"namespace registrations"});let k=await co({...h,tables:t}),x=await fo({...h,deployerAddress:d,libraryMap:S,systems:r});await Pe({client:o,hashes:[...k,...x],debugLabel:"table and system registrations"});let w=await uo({...h,functions:r.flatMap(v=>v.worldFunctions)}),m=await me({...h,deployerAddress:d,libraryMap:S,modules:a}),b=un([...t,...r].filter(({namespace:v,namespaceLabel:P})=>P!==v).map(({namespace:v,namespaceLabel:P})=>({resourceId:pn({type:"namespace",namespace:v,name:""}),tag:"label",value:P})),v=>v.resourceId),T=t.filter(v=>v.label!==v.name).map(({tableId:v,label:P})=>({resourceId:v,tag:"label",value:P})),j=r.flatMap(({name:v,systemId:P,label:oe,abi:C,worldAbi:bt})=>[...oe!==v?[{resourceId:P,tag:"label",value:oe}]:[],{resourceId:P,tag:"abi",value:C.join(`
8
+ `)},{resourceId:P,tag:"worldAbi",value:bt.join(`
9
+ `)}]),ee=await Do({...h,deployerAddress:d,libraryMap:S,tags:[...b,...T,...j],valueToHex:mn});return await Pe({client:o,hashes:[...w,...m,...ee],debugLabel:"remaining transactions"}),g("deploy complete"),f}import{createWalletClient as Yn,http as Gn,isHex as Qn}from"viem";import{privateKeyToAccount as Zn}from"viem/accounts";import{loadConfig as Xn,resolveConfigPath as es}from"@latticexyz/config/node";import{getOutDirectory as os,getRpcUrl as ts}from"@latticexyz/common/foundry";import V from"chalk";import{MUDError as Me}from"@latticexyz/common/errors";import Ro from"path";import{loadSystemsManifest as Dn,resolveSystems as An}from"@latticexyz/world/node";import{isHex as $o,toFunctionSelector as Fo,toFunctionSignature as Eo}from"viem";import{readFileSync as hn}from"fs";import wn from"path";import{MUDError as ue}from"@latticexyz/common/errors";import{size as xn}from"viem";function _(e,o,t){let r,n=wn.join(t,e,o+".json");try{r=JSON.parse(hn(n,"utf8"))}catch{throw new ue(`Error reading file at ${n}`)}let a=r?.bytecode?.object;if(!a)throw new ue(`No bytecode found in ${n}`);let s=r?.deployedBytecode?.object;if(!s)throw new ue(`No deployed bytecode found in ${n}`);let i=r?.abi;if(!i)throw new ue(`No ABI found in ${n}`);let c=pe(r?.bytecode?.linkReferences??{});return{abi:i,bytecode:a,placeholders:c,deployedBytecodeSize:xn(s)}}import{groupBy as kn}from"@latticexyz/common/utils";import{readFileSync as Sn}from"fs";import{globSync as Cn}from"glob";import vn from"toposort";function Wo(e,o,t){let r=vn(e.flatMap(n=>t(n).map(a=>[o(n),a])));return[...e].sort((n,a)=>r.indexOf(o(n))-r.indexOf(o(a)))}function jo(e){let t=Cn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(Sn(r,"utf8"))).flatMap(r=>{if(!r.metadata)return[];let n=Object.keys(r.metadata.settings.compilationTarget)[0],a=r.metadata.settings.compilationTarget[n],s=r.bytecode.linkReferences;return Object.entries(s).flatMap(([i,c])=>Object.keys(c).map(l=>({path:i,name:l,dependentPath:n,dependentName:a})))});return Wo(t,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{findUp as Tn}from"find-up";import{createRequire as Pn}from"node:module";async function Lo({rootDir:e,config:o,forgeOutDir:t}){let r=await Tn("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=Pn(r),a=o.modules.flatMap(f=>f.artifactPath==null?[]:[Ro.join(n.resolve(f.artifactPath),"../../")]),s=[t,...a].flatMap(f=>jo(f).map(h=>{let S=_(Ro.basename(h.path),h.name,f);return{path:h.path,name:h.name,abi:S.abi,prepareDeploy:R(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize}})),c=_("System.sol","System",t).abi.filter(f=>f.type==="function").map(Eo),l=await An({rootDir:e,config:o}),p=await Dn({rootDir:e,config:o}),y=l.filter(f=>!f.deploy.disabled).map(f=>{let h=p.systems.find(({systemId:w})=>w===f.systemId);if(!h)throw new Error(`System "${f.label}" not found in systems manifest. Run \`mud build\` before trying again.`);let S=_(`${f.label}.sol`,f.label,t),A=f.deploy.registerWorldFunctions?S.abi.filter(w=>w.type==="function").map(Eo).filter(w=>!c.includes(w)).map(w=>{let m=f.namespace===""?w:`${f.namespace}__${w}`;return{signature:m,selector:Fo(m),systemId:f.systemId,systemFunctionSignature:w,systemFunctionSelector:Fo(w)}}):[],k=f.accessList.filter(w=>$o(w)),x=f.accessList.filter(w=>!$o(w)).map(w=>l.find(b=>b.label===w).systemId);return{...f,allowAll:f.openAccess,allowedAddresses:k,allowedSystemIds:x,prepareDeploy:R(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize,worldFunctions:A,abi:h.abi,worldAbi:h.worldAbi}}),u=kn(y,f=>f.systemId),d=Array.from(u.values()).filter(f=>f.length>1).flat();if(d.length){let f=d.map(h=>h.name);throw new Error(`Found systems with overlapping system ID: ${f.join(", ")}.
10
+
11
+ System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}return{systems:y,libraries:s}}import{getChainId as rs}from"viem/actions";import{existsSync as On}from"fs";import Mn from"path";import Bn from"chalk";import{getScriptDirectory as Hn,forge as In}from"@latticexyz/common/foundry";async function zo(e,o,t,r,n,a){let s=n?.replaceAll("\\","").split(" ")??[],i=Mn.join(await Hn(),e+".s.sol");if(!On(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(Bn.blue(`Executing post deploy script at ${i}`)),await In(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",a?"--aws":"",...s],{profile:r})}import{kmsKeyToAccount as ns}from"@latticexyz/common/kms";import Uo from"node:path";import{encodeField as Rn}from"@latticexyz/protocol-parser/internal";import{bytesToHex as $n}from"viem";import{createRequire as Wn}from"node:module";import{findUp as jn}from"find-up";async function No({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await jn("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=Wn(r)(o)}catch(r){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),r}return fe(t)}import{resolveWithContext as Fn}from"@latticexyz/world/internal";var En={KeysWithValueModule:"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json",KeysInTableModule:"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json",UniqueEntityModule:"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json",Unstable_CallWithSignatureModule:"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"};async function ge(e,o){return await Promise.all(e.modules.map(async r=>{let n=r.artifactPath;if(!n)if(r.name)n=En[r.name]??Uo.join(o,`${r.name}.sol`,`${r.name}.json`),console.warn(["","\u26A0\uFE0F Your `mud.config.ts` is using a module with a `name`, but this option is deprecated.","","To resolve this, you can replace this:","",` name: ${JSON.stringify(r.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(n)}`,""].join(`
12
+ `));else throw new Error("No `artifactPath` provided for module.");let a=Uo.basename(n,".json"),s=await No({artifactPath:n}),i=r.args.map(c=>Fn(c,{config:e})).map(c=>{let l=c.value instanceof Uint8Array?$n(c.value):c.value;return Rn(c.type,l)});if(i.length>1)throw new Error(`${a} module should only have 0-1 args, but had ${i.length} args.`);return{name:a,installAsRoot:r.root,installData:i.length===0?"0x":i[0],prepareDeploy:R(s.bytecode,s.placeholders),deployedBytecodeSize:s.deployedBytecodeSize,abi:s.abi}}))}import{findContractArtifacts as ss}from"@latticexyz/world/node";import{getAutomine as Ln,getBlock as _o,setAutomine as zn,setIntervalMining as Nn}from"viem/actions";import{getAction as Q}from"viem/utils";async function Ko(e){let o=await Un(e).catch(()=>{});if(!(!o||o.type==="automine"))return O("Enabling automine"),await Vo(e,{type:"automine"}),{reset:()=>(O("Disabling automine"),Vo(e,o))}}async function Un(e){let o={mode:"anvil",...e};return await Q(o,Ln,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await _n(e)}}async function Vo(e,o){o.type==="automine"?await Q(e,zn,"setAutomine")(!0):await Q(e,Nn,"setIntervalMining")({interval:o.blockTime})}async function _n(e){let o=await Q(e,_o,"getBlock")({blockTag:"latest"}),t=await Q(e,_o,"getBlock")({blockNumber:o.number-1n}),r=o.timestamp-t.timestamp;return Number(r)}import{redstone as Vn,garnet as Kn,rhodolite as Jn}from"@latticexyz/common/chains";var be=[Vn,Kn,Jn];var M={configPath:{type:"string",desc:"Path to the MUD 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"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},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."},forgeScriptOptions:{type:"string",description:"Options to pass to forge script PostDeploy.s.sol"},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."},kms:{type:"boolean",desc:"Deploy the World with an AWS KMS key instead of local private key."},indexerUrl:{type:"string",desc:"The indexer URL to use.",required:!1}};async function K(e){let o=e.salt;if(o!=null&&!Qn(o))throw new Me("Expected hex string for salt");let t=e.profile??process.env.FOUNDRY_PROFILE,r=await es(e.configPath),n=await Xn(r),a=he.dirname(r);e.printConfig&&console.log(V.green(`
13
+ Resolved config:
14
+ `),JSON.stringify(n,null,2));let s=await os(t),i=e.rpc??await ts(t);console.log(V.bgBlue(V.whiteBright(`
15
+ Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
16
+ `))),e.skipBuild||await E({rootDir:a,config:n,foundryProfile:t});let{systems:c,libraries:l}=await Lo({rootDir:a,config:n,forgeOutDir:s}),p=await ss({forgeOutDir:s}),y=await ge(n,s),u=Object.values(n.namespaces).flatMap(b=>Object.values(b.tables)).filter(b=>!b.deploy.disabled),d=await(async()=>{if(e.kms){let b=process.env.AWS_KMS_KEY_ID;if(!b)throw new Me("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await ns({keyId:b})}else{let b=process.env.PRIVATE_KEY;if(!b)throw new Me(`Missing PRIVATE_KEY environment variable.
17
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
18
+ in your contracts directory to use the default anvil private key.`);return Zn(b)}})(),f=Yn({transport:Gn(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:d}),h=await rs(f),S=e.indexerUrl??be.find(b=>b.id===h)?.indexerUrl,A=e.worldAddress?as({worldAddress:e.worldAddress,worldsFile:n.deploy.worldsFile,chainId:h}):void 0;console.log("Deploying from",f.account.address);let k=await Ko(f),x=Date.now(),w=await Io({config:n,deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,worldDeployBlock:A,client:f,tables:u,systems:c,libraries:l,modules:y,artifacts:p,indexerUrl:S,chainId:h});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await zo(n.deploy.postDeployScript,w.address,i,t,e.forgeScriptOptions,!!e.kms),await k?.reset(),console.log(V.green("Deployment completed in",(Date.now()-x)/1e3,"seconds"));let m={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let b=he.join(n.deploy.deploysDirectory,h.toString());qn(b,{recursive:!0}),Oe(he.join(b,"latest.json"),JSON.stringify(m,null,2)),Oe(he.join(b,Date.now()+".json"),JSON.stringify(m,null,2));let T=[1337,31337],j=Jo(n.deploy.worldsFile)?JSON.parse(qo(n.deploy.worldsFile,"utf-8")):{};j[h]={address:m.worldAddress,blockNumber:T.includes(h)?void 0:m.blockNumber},Oe(n.deploy.worldsFile,JSON.stringify(j,null,2)),console.log(V.bgGreen(V.whiteBright(`
19
+ Deployment result (written to ${n.deploy.worldsFile} and ${b}):
20
+ `)))}return console.log(m),w}function as({chainId:e,worldAddress:o,worldsFile:t}){let r=Jo(t)?JSON.parse(qo(t,"utf-8")):{},n=r[e]?.address===o?r[e].blockNumber:void 0;return n?BigInt(n):void 0}var is={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await K(e)}catch(o){te(o),process.exit(1)}process.exit(0)}},Yo=is;import ls from"node:path";import{loadConfig as ds,resolveConfigPath as cs}from"@latticexyz/config/node";import{worldgen as ms}from"@latticexyz/world/node";var ps={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 MUD config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await fs(e),process.exit(0)}};async function fs(e){let o=await cs(e.configPath),t=await ds(o),r=ls.dirname(o);await ms({rootDir:r,config:t,clean:e.clean})}var Go=ps;import Z from"chalk";import{readFileSync as hs,writeFileSync as ws}from"fs";import He from"path";import{MUDError as J}from"@latticexyz/common/errors";var Qo={name:"@latticexyz/cli",version:"2.2.14",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},typesVersions:{"*":{index:["./dist/index.d.ts"]}},bin:{mud:"./bin/mud.js"},files:["bin","dist"],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":"shx rm -rf dist","clean:test-tables":"shx rm -rf src/**/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ark/util":"0.2.2","@aws-sdk/client-kms":"^3.556.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/block-logs-stream":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/store-sync":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-module-metadata":"workspace:*",abitype:"1.0.6","asn1.js":"^5.4.1",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",execa:"^7.0.0","find-up":"^6.3.0",glob:"^10.4.2",openurl:"^1.1.1","p-queue":"^7.4.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",toposort:"^2.0.2",typescript:"5.4.2",viem:"2.21.19",yargs:"^17.7.1",zod:"3.23.8","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/toposort":"^2.0.6","@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",vitest:"0.34.6"}};import{globSync as xs}from"glob";import{ZodError as us,z as Zo}from"zod";var gs=Zo.object({MUD_PACKAGES:Zo.string().transform(e=>JSON.parse(e))});function bs(){try{return gs.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/explorer":{"localPath":"packages/explorer"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/paymaster":{"localPath":"packages/paymaster"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/stash":{"localPath":"packages/stash"},"@latticexyz/store-consumer":{"localPath":"packages/store-consumer"},"@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-module-erc20":{"localPath":"packages/world-module-erc20"},"@latticexyz/world-module-metadata":{"localPath":"packages/world-module-metadata"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof us){let{...o}=e.format();console.error(`
21
+ Missing or invalid environment variables:
22
+
23
+ ${Object.keys(o).join(`
24
+ `)}
25
+ `),process.exit(1)}throw e}}var Be=bs().MUD_PACKAGES;var vs={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,a)=>e[a]?n+1:n,0);if(t===0)throw new J(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new J(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Ss(e));let r=xs("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)Cs(n,e)}catch(o){te(o)}finally{process.exit(0)}}};async function Ss(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(Z.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Qo.name}`)).json()}catch{throw new J("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new J(`Could not find npm version with tag "${e.tag}"`);return console.log(Z.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 J(`Could not find npm version based on commit "${e.commit}"`);return console.log(Z.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Cs(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ds(e),a=Object.keys(Be),s={};for(let l in n.dependencies)a.includes(l)&&(s[l]=n.dependencies[l]);let i={};for(let l in n.devDependencies)a.includes(l)&&(i[l]=n.devDependencies[l]);for(let l in n.dependencies)a.includes(l)&&(n.dependencies[l]=c(l,"dependencies"));for(let l in n.devDependencies)a.includes(l)&&(n.devDependencies[l]=c(l,"devDependencies"));return ws(e,JSON.stringify(n,null,2)+`
26
+ `),console.log(`Updating ${e}`),Xo(s,n.dependencies),Xo(i,n.devDependencies),n;function c(l,p){return t&&(r=As(e,t,l)),r||n[p][l]}}function Ds(e){try{let o=hs(e,"utf8");return JSON.parse(o)}catch{throw new J("Could not read JSON at "+e)}}function Xo(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${Z.red(e[t])} -> ${Z.green(o[t])}`)}function As(e,o,t){let r=He.relative(He.dirname(e),process.cwd());return"link:"+He.join(r,o,Be[t].localPath)}var et=vs;import{anvil as ks,forge as Ts,getRpcUrl as Ps}from"@latticexyz/common/foundry";import Os from"chalk";var Ms={...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"}},Bs={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Ms)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];ks(n)}let o=e.worldAddress?await Ps(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await K({...e,saveDeployment:!1,rpc:o})).address;console.log(Os.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Ts(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ot=Bs;import Hs from"node:path";import tt from"node:fs";import{loadConfig as Is,resolveConfigPath as Ws}from"@latticexyz/config/node";import{MUDError as rt}from"@latticexyz/common/errors";import{cast as js,getRpcUrl as Rs}from"@latticexyz/common/foundry";import $s from"@latticexyz/world/mud.config";import{createClient as Fs,http as Es}from"viem";import{getChainId as Ls,readContract as zs}from"viem/actions";import{resolveSystems as Ns}from"@latticexyz/world/node";var Us=$s.namespaces.world.tables.Systems.tableId;function _s(e,o){if(!tt.existsSync(e))throw new rt(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(tt.readFileSync(e,"utf-8"));if(!t[o])throw new rt(`Missing chain ID ${o} in "${e}"`);return t[o].address}var Vs={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 MUD config file"},profile:{type:"string",description:"The foundry profile to use"},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){let o=await Ws(e.configPath),t=Hs.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await Rs(r),a=await Is(o),s=Fs({transport:Es(n)}),i=await Ls(s),c=e.worldAddress??_s(a.deploy.worldsFile,i),l=await Ns({rootDir:t,config:a}),p=await Promise.all(l.map(async u=>({label:u.label,address:await zs(s,{abi:D,address:c,functionName:"getField",args:[Us,[u.systemId],0]})}))),y=await js(["run","--label",`${c}:World`,...p.map(({label:u,address:d})=>["--label",`${d}:${u}`]).flat(),`${e.tx}`]);console.log(y),process.exit(0)}},nt=Vs;import{anvil as Ks,getScriptDirectory as Js,getSrcDirectory as qs}from"@latticexyz/common/foundry";import W from"chalk";import Ys from"chokidar";import{loadConfig as Gs,resolveConfigPath as Qs}from"@latticexyz/config/node";import Zs from"path";import{homedir as Xs}from"os";import{rmSync as ea}from"fs";import{BehaviorSubject as oa,debounceTime as ta,exhaustMap as ra,filter as na}from"rxjs";import{isDefined as sa}from"@latticexyz/common/utils";var aa={rpc:M.rpc,configPath:M.configPath,alwaysRunPostDeploy:M.alwaysRunPostDeploy,forgeScriptOptions:M.forgeScriptOptions,worldAddress:M.worldAddress},ia={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(aa)},async handler(e){let o=e.rpc,t=e.configPath??await Qs(e.configPath),r=await qs(),n=await Js(),a=await Gs(t);if(!e.rpc){console.log(W.gray("Cleaning devnode cache"));let l=Xs();ea(Zs.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Ks(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let s=new oa(Date.now());Ys.watch([t,r,n],{ignoreInitial:!0}).on("all",async(l,p)=>{p.includes(t)&&(console.log(W.blue("Config changed, queuing deploy\u2026")),s.next(Date.now())),(p.includes(r)||p.includes(n))&&(p.includes(a.codegen.outputDirectory)||(console.log(W.blue("Contracts changed, queuing deploy\u2026")),s.next(Date.now())))});let i=e.worldAddress;s.pipe(ta(200),ra(async l=>{i&&console.log(W.blue("Rebuilding and upgrading world\u2026"));try{let p=await K({...e,configPath:t,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:i,salt:"0x",kms:void 0,indexerUrl:void 0});return i=p.address,l<s.value?s.next(s.value):console.log(W.gray(`
27
+ Waiting for file changes\u2026
28
+ `)),p}catch(p){console.error(W.bgRed(W.whiteBright(`
29
+ Error while attempting deploy
30
+ `))),console.error(p),console.log(W.gray(`
31
+ Waiting for file changes\u2026
32
+ `))}}),na(sa)).subscribe()}},st=ia;import{sliceHex as da,zeroHash as ca}from"viem";import{forge as la}from"@latticexyz/common/foundry";async function $(e){let o=["verify-contract",e.address,e.name,"--rpc-url",e.rpc];e.verifier&&o.push("--verifier",e.verifier),e.verifierUrl&&o.push("--verifier-url",e.verifierUrl),await la(o,{cwd:e.cwd})}import ma from"p-queue";import{MUDError as pa}from"@latticexyz/common/errors";import{getStorageAt as fa}from"viem/actions";import{execa as Ie}from"execa";import{getContractAddress as at,getDeployer as ya}from"@latticexyz/common/internal";var ua="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function it({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:a,verifier:s,verifierUrl:i}){let c=a??await ya(e);if(!c)throw new pa("No deployer address provided or found.");let l=await fa(e,{address:n,slot:ua}),p=l&&l!==ca,y=new ma({concurrency:4});if(t.map(({name:u,bytecode:d})=>y.add(()=>$({name:u,rpc:o,verifier:s,verifierUrl:i,address:at({deployerAddress:c,bytecode:d})}).catch(f=>{console.error(`Error verifying system contract ${u}:`,f)}))),s==="sourcify")if(await Ie("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await Ie("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await Ie("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(p?ne(c):re(c)).map(([u,{bytecode:d}])=>y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:u,rpc:o,verifier:s,verifierUrl:i,address:at({deployerAddress:c,bytecode:d})}).catch(f=>{console.error(`Error verifying world factory contract ${u}:`,f)}))),r.map(({name:u,prepareDeploy:d})=>{let{address:f}=d(c);return y.add(()=>$({cwd:"node_modules/@latticexyz/world-modules",name:u,rpc:o,verifier:s,verifierUrl:i,address:f}).catch(h=>{console.error(`Error verifying module contract ${u}:`,h)}))}),p){let u=da(l,-20);y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(d=>{console.error("Error verifying WorldProxy contract:",d)})),y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:u}).catch(d=>{console.error("Error verifying World contract:",d)}))}else y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(u=>{console.error("Error verifying World contract:",u)}));else console.log(""),console.log(`Note: MUD is currently unable to verify store, world, and world-modules contracts with ${s}. We are planning to expand support in a future version.`),console.log("")}import{loadConfig as ga,resolveConfigPath as ba}from"@latticexyz/config/node";import{resolveSystems as ha}from"@latticexyz/world/node";import{getOutDirectory as wa,getRpcUrl as xa}from"@latticexyz/common/foundry";import{createWalletClient as va,http as Sa}from"viem";import lt from"chalk";import Ca from"node:path";var Da={deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",required:!0,desc:"Verify an existing World at the given address"},configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},verifier:{type:"string",desc:"The verifier to use. Defaults to blockscout",default:"blockscout"},verifierUrl:{type:"string",desc:"The verification provider."}},Aa={command:"verify",describe:"Verify contracts",builder(e){return e.options(Da)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await ba(e.configPath),r=Ca.dirname(t),n=await ga(t),a=await wa(o),s=e.rpc??await xa(o);console.log(lt.bgBlue(lt.whiteBright(`
33
+ Verifying MUD contracts${o?" with profile "+o:""} to RPC ${s}
34
+ `)));let i=va({transport:Sa(s,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await ha({rootDir:r,config:n})).map(y=>{let u=_(`${y.name}.sol`,y.name,a);return{name:y.name,bytecode:u.bytecode}}),p=await ge(n,a);await it({client:i,rpc:s,systems:l,modules:p,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},dt=Aa;import{getRpcUrl as Na}from"@latticexyz/common/foundry";import{createClient as Ua,http as _a}from"viem";import ve from"chalk";import{hexToString as We,parseAbiItem as ct,stringToHex as je}from"viem";import{getSchemaTypes as Ia}from"@latticexyz/protocol-parser/internal";import{hexToResource as Wa,resourceToHex as ja}from"@latticexyz/common";import Re from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as ka,getKeyTuple as Ta,getSchemaTypes as Pa,getValueSchema as Oa}from"@latticexyz/protocol-parser/internal";import{readContract as Ma}from"viem/actions";import{mapObject as Ba}from"@latticexyz/common/utils";async function we({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Ma(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,Ta(t,r)]}),i={...r,...ka(Pa(Oa(t)),{staticData:n,encodedLengths:a,dynamicData:s})};return Ba(t.schema,(c,l)=>i[l])}import F from"node:path";import xe from"node:fs/promises";import{getFunctions as Ra}from"@latticexyz/store-sync/world";import{abiToInterface as mt,formatSolidity as pt,formatTypescript as $a}from"@latticexyz/common/codegen";var H=O.extend("pull"),Ha=O.extend("pull");H.log=console.debug.bind(console);Ha.log=console.error.bind(console);import{defineWorld as Fa}from"@latticexyz/world";import{findUp as Ea}from"find-up";import{isDefined as ft}from"@latticexyz/common/utils";var La=new Set(["store","world","metadata"]);function yt(e){return ja({type:"namespace",namespace:e,name:""})}var X=class extends Error{constructor(t){super(`Attempted to write file at "${t}", but it already exists.`);this.filename=t}name="WriteFileExistsError"};async function ut({rootDir:e,client:o,worldAddress:t,replace:r,indexerUrl:n,chainId:a}){let s=r??await Ea(".git",{cwd:e})!=null,i=await ce(o,t),c=await U({client:o,worldDeploy:i,indexerUrl:n,chainId:a}),l=c.map(Wa).filter(x=>!La.has(x.namespace)),p=await ae({client:o,worldDeploy:i,indexerUrl:n,chainId:a}),y=Object.fromEntries((await Promise.all(c.map(async x=>{let{value:w}=await we({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:x,tag:je("label",{size:32})}}),m=We(w);return[x,m===""?null:m]}))).filter(([,x])=>x!=null));y[yt("")]??="root";let u=await Ra({client:o,worldAddress:i.address,fromBlock:i.deployBlock,toBlock:i.stateBlock,indexerUrl:n,chainId:a}),d=l.filter(x=>x.type==="namespace"),f=await Promise.all(l.filter(x=>x.type==="system").map(async({namespace:x,name:w,resourceId:m})=>{let b=yt(x),T=y[m]??w.replace(/(S(y(s(t(e(m)?)?)?)?)?)?$/,"System"),[j,ee]=await Promise.all([we({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:m,tag:je("abi",{size:32})}}).then(C=>We(C.value)).then(C=>C!==""?C.split(`
35
+ `):[]),we({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:m,tag:je("worldAbi",{size:32})}}).then(C=>We(C.value)).then(C=>C!==""?C.split(`
36
+ `):[])]),v=u.filter(C=>C.systemId===m),P=(j.length?j:v.map(C=>`function ${C.systemFunctionSignature}`)).map(C=>{try{return ct(C)}catch{H(`Skipping invalid system signature: ${C}`)}}).filter(ft),oe=(ee.length?ee:v.map(C=>`function ${C.signature}`)).map(C=>{try{return ct(C)}catch{H(`Skipping invalid world signature: ${C}`)}}).filter(ft);return{namespaceId:b,namespaceLabel:y[b]??x,label:T,systemId:m,namespace:x,name:w,abi:P,worldAbi:oe}}));H("generating config");let h={namespaces:Object.fromEntries(d.map(({namespace:x,resourceId:w})=>{let m=y[w]??x;return[m,{...m!==x?{namespace:x}:null,tables:Object.fromEntries(p.filter(b=>b.namespace===x).map(b=>{let T=y[b.tableId]??b.name;return[T,{...T!==b.name?{name:b.name}:null,...b.type!=="table"?{type:b.type}:null,schema:Ia(b.schema),key:b.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let S=Fa(h);H("writing config"),await $e(F.join(e,"mud.config.ts"),await $a(`
37
+ import { defineWorld } from "@latticexyz/world";
38
+
39
+ export default defineWorld(${JSON.stringify(h)});
40
+ `),{overwrite:s});let A=F.join(S.sourceDirectory,"remote");s&&await xe.rm(A,{recursive:!0,force:!0});for(let x of f.filter(w=>w.abi.length)){let w=`I${x.label}`,m=F.join(A,"namespaces",x.namespaceLabel,`${w}.sol`);H("writing system interface",w,"to",m);let b=mt({name:w,systemId:x.systemId,abi:x.abi});await $e(F.join(e,m),await pt(b),{overwrite:s})}let k=f.flatMap(x=>x.worldAbi);if(k.length){let x="IWorldSystems",w=F.join(A,`${x}.sol`);H("writing world systems interface to",w);let m=mt({name:x,abi:k});await $e(F.join(e,w),await pt(m),{overwrite:s})}return{config:S}}async function za(e){return xe.access(e).then(()=>!0,()=>!1)}async function $e(e,o,t={}){if(!t.overwrite&&await za(e))throw new X(e);await xe.mkdir(F.dirname(e),{recursive:!0}),await xe.writeFile(e,o)}import Va from"node:path";import{getChainId as Ka}from"viem/actions";var Ja={worldAddress:{type:"string",required:!0,desc:"Remote world address"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},replace:{type:"boolean",desc:"Replace existing files and directories with data from remote world."},indexerUrl:{type:"string",desc:"The indexer URL to pull from.",required:!1}},qa={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(Ja)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await Na(o),r=Ua({transport:_a(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),n=await Ka(r),a=e.indexerUrl??be.find(i=>i.id===n)?.indexerUrl;console.log(ve.bgBlue(ve.whiteBright(`
41
+ Pulling MUD config from world at ${e.worldAddress}
42
+ `)));let s=process.cwd();try{let{config:i}=await ut({rootDir:s,client:r,worldAddress:e.worldAddress,indexerUrl:a,chainId:n,replace:e.replace});await E({rootDir:s,config:i,foundryProfile:o})}catch(i){if(i instanceof X){console.log(),console.log(ve.bgRed(ve.whiteBright(" Error "))),console.log(` Attempted to write file at "${Va.relative(s,i.filename)}", but it already exists.`),console.log(),console.log(" To overwrite files, use `--replace` when running this command."),console.log();return}throw i}}},gt=qa;var Zy=[Fe,Yo,Ee,Ya,Le,ze,Go,et,ot,nt,st,Ga,dt,gt];export{Zy as commands};
43
+ //# sourceMappingURL=commands-NZS235TP.js.map