@latticexyz/cli 2.2.17-e45e3751c0ea10c7b1f0088d674121419b0d0acb → 2.2.17-f52b1476f04ce0be68691e3b021a81e0fb9cce99

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