@latticexyz/cli 2.2.15-6aff69a91c627ddcc0c1dbccf7b71580e8e0a8fa → 2.2.15-7482a5ae322f26278722081838b6103ce6d264e6

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 Ga}from"@latticexyz/gas-report/internal";import{command as Qa}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 L({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 L({rootDir:At.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},$e=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}},Fe=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)}},Ee=$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 Ke from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Et from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{encodeDeployData as zt,size as Nt}from"viem";import ze from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Ne from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Ue from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import _e from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import Ve 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 Lt,size as q}from"viem";import{getContractAddress as Y}from"@latticexyz/common/internal";function E(e){let o=q(ze.deployedBytecode.object),t=ze.bytecode.object,r=Y({deployerAddress:e,bytecode:t}),n=q(Ne.deployedBytecode.object),a=Ne.bytecode.object,s=Y({deployerAddress:e,bytecode:a}),i=q(Ue.deployedBytecode.object),c=Ue.bytecode.object,l=Y({deployerAddress:e,bytecode:c}),p=q(_e.deployedBytecode.object),y=_e.bytecode.object,u=Y({deployerAddress:e,bytecode:y}),d=q(Ve.deployedBytecode.object),f=Lt({bytecode:Ve.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=E(e),t=Nt(Ke.deployedBytecode.object),r=zt({bytecode:Ke.bytecode.object,abi:Et,args:[o.InitModule.address]}),n=Ut({deployerAddress:e,bytecode:r});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import Je 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=E(e),t=Kt(Je.deployedBytecode.object),r=Vt({bytecode:Je.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 qe}from"@latticexyz/common/internal";async function Ye(e,o,t){if(t){let n=ne(o);return await qe({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=re(o);return await qe({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 Ge from"debug";var O=Ge("mud:cli"),qt=Ge("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 Xe,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,Qe=["2.0.0","2.0.1","2.0.2"],Ze=["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:Xe(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:Xe(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 eo(e,o,t,r){let n=await Ye(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 no,valueSchemaToHex as so,getSchemaTypes as N,getValueSchema as ao,getKeySchema as io}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as oo,parseAbiParameters as to}from"viem";import{hexToResource as ar}from"@latticexyz/common";import{hexToSchema as ro}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=ro(s.keySchema),y=ro(s.valueSchema),u=oo(to("string[]"),s.abiEncodedKeyNames)[0],d=oo(to("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 lo({client:e,worldDeploy:o,tables:t,indexerUrl:r,chainId:n}){let a=new Map(t.map(p=>{let y=N(io(p)),u=N(ao(p)),d=no(y),f=so(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(io(p)),u=N(ao(p));return mr(()=>dr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[p.tableId,cr(u),no(y),so(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 co,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(co(br(t)),r)]});return ur(co(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 mo({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 po({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n,indexerUrl:a,chainId:s}){let[i,c]=await Promise.all([mo({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 fo=new Map;async function ce(e,o,t){let r=Pr(o),n=fo.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},fo.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 yo({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 Lr}from"@latticexyz/common/internal";async function me({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await Lr({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 uo}from"viem";import{hexToResource as go,resourceToHex as bo,writeContract as Er}from"@latticexyz/common";import zr from"@latticexyz/world/mud.config";async function ho({client:e,worldDeploy:o,resourceIds:t,indexerUrl:r,chainId:n}){let a=Array.from(new Set(t.map(d=>go(d).namespace))),s=await U({client:e,worldDeploy:o,indexerUrl:r,chainId:n}),i=new Set(s.map(d=>go(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:bo({type:"namespace",namespace:d,name:""})}});return[d,f]}))).filter(([,d])=>uo(d)!==uo(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=>Er(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[bo({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 vo}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 wo=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:wo,deployedBytecode:wo,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 xo}from"@latticexyz/common/internal";function R(e,o){return function(r,n){let a=e;if(o.length===0)return{bytecode:a,address:xo({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:xo({deployerAddress:r,bytecode:a})}}}import{getKeyTuple as So}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 Co({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=>[vo(So(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=vo(So(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 To}from"viem";import{waitForTransactionReceipt as an}from"viem/actions";import{resourceToHex as ln,sendTransaction as dn,writeContract as Do}from"@latticexyz/common";import{ensureContractsDeployed as Ao,getContractAddress as cn,waitForTransactions as ko}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 Po(e,o){return e.bytecode.filter(t=>!To(t)).flatMap(t=>Po(Te(t,o),o))}function ke(e,o,t){return nn(o.bytecode.map(r=>To(r)?r:cn({deployerAddress:e,bytecode:ke(e,Te(r,t),t)})))}async function Oo({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=E(o);await Ao({client:e,deployerAddress:o,contracts:Object.values(n)});let a=Te(r,t),s=Po(a,t);s.length&&(g(`deploying ${s.length} world dependencies`),await Ao({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 Do(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"initialize",args:[n.InitModule.address]});await ko({client:e,hashes:[p],debugLabel:"world init"});let y=await Do(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"transferOwnership",args:[ln({type:"namespace",namespace:"",name:""}),e.account.address]});return await ko({client:e,hashes:[y],debugLabel:"world ownership transfer"}),{...l,stateBlock:l.deployBlock}}import{uniqueBy as un}from"@latticexyz/common/utils";function Mo({path:e,name:o}){return`${e}:${o}`}function Bo(e){let o=Object.fromEntries(e.map(r=>[Mo(r),r])),t={getAddress:({path:r,name:n,deployer:a})=>{let s=o[Mo({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 Ho({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 Oo({client:o,deployerAddress:d,artifacts:s,customWorld:e.deploy.customWorld}):await eo(o,d,i??`0x${yn(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation),h={client:o,indexerUrl:y,chainId:u,worldDeploy:f};if(!Qe.includes(f.storeVersion))throw new Error(`Unsupported Store version: ${f.storeVersion}`);if(!Ze.includes(f.worldVersion))throw new Error(`Unsupported World version: ${f.worldVersion}`);let S=Bo(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 ho({...h,resourceIds:[...t.map(({tableId:v})=>v),...r.map(({systemId:v})=>v)]});await Pe({client:o,hashes:A,debugLabel:"namespace registrations"});let k=await lo({...h,tables:t}),x=await po({...h,deployerAddress:d,libraryMap:S,systems:r});await Pe({client:o,hashes:[...k,...x],debugLabel:"table and system registrations"});let w=await yo({...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 Co({...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,stringToHex as Zn}from"viem";import{privateKeyToAccount as Xn}from"viem/accounts";import{loadConfig as es,resolveConfigPath as os}from"@latticexyz/config/node";import{getOutDirectory as ts,getRpcUrl as rs}from"@latticexyz/common/foundry";import V from"chalk";import{MUDError as Ko}from"@latticexyz/common/errors";import jo from"path";import{loadSystemsManifest as Dn,resolveSystems as An}from"@latticexyz/world/node";import{isHex as Ro,toFunctionSelector as $o,toFunctionSignature as Fo}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 Io(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 Wo(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 Io(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?[]:[jo.join(n.resolve(f.artifactPath),"../../")]),s=[t,...a].flatMap(f=>Wo(f).map(h=>{let S=_(jo.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(Fo),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(Fo).filter(w=>!c.includes(w)).map(w=>{let m=f.namespace===""?w:`${f.namespace}__${w}`;return{signature:m,selector:$o(m),systemId:f.systemId,systemFunctionSignature:w,systemFunctionSelector:$o(w)}}):[],k=f.accessList.filter(w=>Ro(w)),x=f.accessList.filter(w=>!Ro(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 ns}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 Eo(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 ss}from"@latticexyz/common/kms";import No 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 zo({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 Ln={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=Ln[r.name]??No.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=No.basename(n,".json"),s=await zo({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 as}from"@latticexyz/world/node";import{getAutomine as En,getBlock as Uo,setAutomine as zn,setIntervalMining as Nn}from"viem/actions";import{getAction as Q}from"viem/utils";async function Vo(e){let o=await Un(e).catch(()=>{});if(!(!o||o.type==="automine"))return O("Enabling automine"),await _o(e,{type:"automine"}),{reset:()=>(O("Disabling automine"),_o(e,o))}}async function Un(e){let o={mode:"anvil",...e};return await Q(o,En,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await _n(e)}}async function _o(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,Uo,"getBlock")({blockTag:"latest"}),t=await Q(e,Uo,"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!=null?Qn(e.salt)?e.salt:Zn(e.salt):void 0,t=e.profile??process.env.FOUNDRY_PROFILE,r=await os(e.configPath),n=await es(r),a=he.dirname(r);e.printConfig&&console.log(V.green(`
13
+ Resolved config:
14
+ `),JSON.stringify(n,null,2));let s=await ts(t),i=e.rpc??await rs(t);console.log(V.bgBlue(V.whiteBright(`
15
+ Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
16
+ `))),e.skipBuild||await L({rootDir:a,config:n,foundryProfile:t});let{systems:c,libraries:l}=await Lo({rootDir:a,config:n,forgeOutDir:s}),p=await as({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 Ko("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await ss({keyId:b})}else{let b=process.env.PRIVATE_KEY;if(!b)throw new Ko(`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 Xn(b)}})(),f=Yn({transport:Gn(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:d}),h=await ns(f),S=e.indexerUrl??be.find(b=>b.id===h)?.indexerUrl,A=e.worldAddress?is({worldAddress:e.worldAddress,worldsFile:n.deploy.worldsFile,chainId:h}):void 0;console.log("Deploying from",f.account.address);let k=await Vo(f),x=Date.now(),w=await Ho({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 Eo(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 is({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 ls={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=ls;import ds from"node:path";import{loadConfig as cs,resolveConfigPath as ms}from"@latticexyz/config/node";import{worldgen as ps}from"@latticexyz/world/node";var fs={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 ys(e),process.exit(0)}};async function ys(e){let o=await ms(e.configPath),t=await cs(o),r=ds.dirname(o);await ps({rootDir:r,config:t,clean:e.clean})}var Go=fs;import Z from"chalk";import{readFileSync as ws,writeFileSync as xs}from"fs";import Be 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 vs}from"glob";import{ZodError as gs,z as Zo}from"zod";var bs=Zo.object({MUD_PACKAGES:Zo.string().transform(e=>JSON.parse(e))});function hs(){try{return bs.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/entrykit":{"localPath":"packages/entrykit"},"@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 gs){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 Me=hs().MUD_PACKAGES;var Ss={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 Cs(e));let r=vs("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)Ds(n,e)}catch(o){te(o)}finally{process.exit(0)}}};async function Cs(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 Ds(e,o){let{link:t}=o,{mudVersion:r}=o,n=As(e),a=Object.keys(Me),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 xs(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=ks(e,t,l)),r||n[p][l]}}function As(e){try{let o=ws(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 ks(e,o,t){let r=Be.relative(Be.dirname(e),process.cwd());return"link:"+Be.join(r,o,Me[t].localPath)}var et=Ss;import{anvil as Ts,forge as Ps,getRpcUrl as Os}from"@latticexyz/common/foundry";import Ms from"chalk";var Bs={...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"}},Hs={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Bs)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Ts(n)}let o=e.worldAddress?await Os(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await K({...e,saveDeployment:!1,rpc:o})).address;console.log(Ms.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Ps(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ot=Hs;import Is from"node:path";import tt from"node:fs";import{loadConfig as Ws,resolveConfigPath as js}from"@latticexyz/config/node";import{MUDError as rt}from"@latticexyz/common/errors";import{cast as Rs,getRpcUrl as $s}from"@latticexyz/common/foundry";import Fs from"@latticexyz/world/mud.config";import{createClient as Ls,http as Es}from"viem";import{getChainId as zs,readContract as Ns}from"viem/actions";import{resolveSystems as Us}from"@latticexyz/world/node";var _s=Fs.namespaces.world.tables.Systems.tableId;function Vs(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 Ks={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 js(e.configPath),t=Is.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await $s(r),a=await Ws(o),s=Ls({transport:Es(n)}),i=await zs(s),c=e.worldAddress??Vs(a.deploy.worldsFile,i),l=await Us({rootDir:t,config:a}),p=await Promise.all(l.map(async u=>({label:u.label,address:await Ns(s,{abi:D,address:c,functionName:"getField",args:[_s,[u.systemId],0]})}))),y=await Rs(["run","--label",`${c}:World`,...p.map(({label:u,address:d})=>["--label",`${d}:${u}`]).flat(),`${e.tx}`]);console.log(y),process.exit(0)}},nt=Ks;import{anvil as Js,getScriptDirectory as qs,getSrcDirectory as Ys}from"@latticexyz/common/foundry";import W from"chalk";import Gs from"chokidar";import{loadConfig as Qs,resolveConfigPath as Zs}from"@latticexyz/config/node";import Xs from"path";import{homedir as ea}from"os";import{rmSync as oa}from"fs";import{BehaviorSubject as ta,debounceTime as ra,exhaustMap as na,filter as sa}from"rxjs";import{isDefined as aa}from"@latticexyz/common/utils";var ia={rpc:M.rpc,configPath:M.configPath,alwaysRunPostDeploy:M.alwaysRunPostDeploy,forgeScriptOptions:M.forgeScriptOptions,worldAddress:M.worldAddress},la={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ia)},async handler(e){let o=e.rpc,t=e.configPath??await Zs(e.configPath),r=await Ys(),n=await qs(),a=await Qs(t);if(!e.rpc){console.log(W.gray("Cleaning devnode cache"));let l=ea();oa(Xs.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Js(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let s=new ta(Date.now());Gs.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(ra(200),na(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
+ `))}}),sa(aa)).subscribe()}},st=la;import{sliceHex as ca,zeroHash as ma}from"viem";import{forge as da}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 da(o,{cwd:e.cwd})}import pa from"p-queue";import{MUDError as fa}from"@latticexyz/common/errors";import{getStorageAt as ya}from"viem/actions";import{execa as He}from"execa";import{getContractAddress as at,getDeployer as ua}from"@latticexyz/common/internal";var ga="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function it({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:a,verifier:s,verifierUrl:i}){let c=a??await ua(e);if(!c)throw new fa("No deployer address provided or found.");let l=await ya(e,{address:n,slot:ga}),p=l&&l!==ma,y=new pa({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 He("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await He("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await He("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=ca(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 ba,resolveConfigPath as ha}from"@latticexyz/config/node";import{resolveSystems as wa}from"@latticexyz/world/node";import{getOutDirectory as xa,getRpcUrl as va}from"@latticexyz/common/foundry";import{createWalletClient as Sa,http as Ca}from"viem";import lt from"chalk";import Da from"node:path";var Aa={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."}},ka={command:"verify",describe:"Verify contracts",builder(e){return e.options(Aa)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await ha(e.configPath),r=Da.dirname(t),n=await ba(t),a=await xa(o),s=e.rpc??await va(o);console.log(lt.bgBlue(lt.whiteBright(`
33
+ Verifying MUD contracts${o?" with profile "+o:""} to RPC ${s}
34
+ `)));let i=Sa({transport:Ca(s,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await wa({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=ka;import{getRpcUrl as Ua}from"@latticexyz/common/foundry";import{createClient as _a,http as Va}from"viem";import ve from"chalk";import{hexToString as Ie,parseAbiItem as ct,stringToHex as We}from"viem";import{getSchemaTypes as Wa}from"@latticexyz/protocol-parser/internal";import{hexToResource as ja,resourceToHex as Ra}from"@latticexyz/common";import je from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as Ta,getKeyTuple as Pa,getSchemaTypes as Oa,getValueSchema as Ma}from"@latticexyz/protocol-parser/internal";import{readContract as Ba}from"viem/actions";import{mapObject as Ha}from"@latticexyz/common/utils";async function we({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Ba(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,Pa(t,r)]}),i={...r,...Ta(Oa(Ma(t)),{staticData:n,encodedLengths:a,dynamicData:s})};return Ha(t.schema,(c,l)=>i[l])}import F from"node:path";import xe from"node:fs/promises";import{getFunctions as $a}from"@latticexyz/store-sync/world";import{abiToInterface as mt,formatSolidity as pt,formatTypescript as Fa}from"@latticexyz/common/codegen";var H=O.extend("pull"),Ia=O.extend("pull");H.log=console.debug.bind(console);Ia.log=console.error.bind(console);import{defineWorld as La}from"@latticexyz/world";import{findUp as Ea}from"find-up";import{isDefined as ft}from"@latticexyz/common/utils";var za=new Set(["store","world","metadata"]);function yt(e){return Ra({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(ja).filter(x=>!za.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:je.tables.metadata__ResourceTag,key:{resource:x,tag:We("label",{size:32})}}),m=Ie(w);return[x,m===""?null:m]}))).filter(([,x])=>x!=null));y[yt("")]??="root";let u=await $a({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:je.tables.metadata__ResourceTag,key:{resource:m,tag:We("abi",{size:32})}}).then(C=>Ie(C.value)).then(C=>C!==""?C.split(`
35
+ `):[]),we({client:o,worldDeploy:i,table:je.tables.metadata__ResourceTag,key:{resource:m,tag:We("worldAbi",{size:32})}}).then(C=>Ie(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:Wa(b.schema),key:b.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let S=La(h);H("writing config"),await Re(F.join(e,"mud.config.ts"),await Fa(`
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 Re(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 Re(F.join(e,w),await pt(m),{overwrite:s})}return{config:S}}async function Na(e){return xe.access(e).then(()=>!0,()=>!1)}async function Re(e,o,t={}){if(!t.overwrite&&await Na(e))throw new X(e);await xe.mkdir(F.dirname(e),{recursive:!0}),await xe.writeFile(e,o)}import Ka from"node:path";import{getChainId as Ja}from"viem/actions";var qa={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}},Ya={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(qa)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await Ua(o),r=_a({transport:Va(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),n=await Ja(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 L({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 "${Ka.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=Ya;var Xy=[$e,Yo,Fe,Ga,Le,Ee,Go,et,ot,nt,st,Qa,dt,gt];export{Xy as commands};
43
+ //# sourceMappingURL=commands-OHNLNGYD.js.map