@latticexyz/cli 2.2.17-bc49b98e90fdc4a618474c4f25c9ae9461397a58 → 2.2.17-c34bdde49b40a574958c2a9a4525884e4d5ac05e

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 Xa}from"@latticexyz/gas-report/internal";import{command as ei}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 Zn,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 un}from"viem";import{waitForTransactionReceipt as ar}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 ir from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as lr}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,getAddress as nr}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 sr}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}),address:nr(a.address)}}catch(i){if(i instanceof or)return;throw i}}).filter(sr),{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 lr(e,{chain:e.chain??null,address:n,abi:ir,functionName:"deployWorld",args:[t]});g("waiting for world deploy");let a=await ar(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 pr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as fr,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 dr}from"@latticexyz/common";import{hexToSchema as so}from"@latticexyz/protocol-parser/internal";import cr from"@latticexyz/store/mud.config";import{getRecords as mr}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 mr({table:cr.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}=dr(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 ur from"p-retry";import{isDefined as yr}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(yr);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 ur(()=>pr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[c.tableId,fr(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 kr,resourceToLabel as Tr}from"@latticexyz/common";import{getFunctions as Pr}from"@latticexyz/store-sync/world";import gr from"@latticexyz/store/mud.config";import{getRecords as br}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 br({table:gr.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 hr,encodeKey as wr,getKeySchema as xr,getSchemaTypes as po,getValueSchema as Sr}from"@latticexyz/protocol-parser/internal";import{readContract as vr}from"viem/actions";async function ce({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await vr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,wr(po(xr(t)),r)]});return hr(po(Sr(t)),{staticData:n,encodedLengths:s,dynamicData:a})}import{getAddress as Cr}from"viem";import Dr from"@latticexyz/world/mud.config";import{getRecords as Ar}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 Ar({table:Dr.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:Cr(a.caller)}));return g("found",s.length,"resource<>address access pairs"),s}import Mr 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}),Pr({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(kr).filter(p=>p.type==="system");return g("looking up systems:",i.map(Tr).join(", ")),await Promise.all(i.map(async p=>{let{system:l,publicAccess:c}=await ce({client:e,worldDeploy:o,table:Mr.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 Or}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 Or({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 Br,parseAbi as Hr}from"viem";import{getBlock as yo}from"viem/actions";import{fetchBlockLogs as Wr}from"@latticexyz/block-logs-stream";var go=new Map;async function pe(e,o,t){let r=Br(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 Wr({publicClient:e,address:r,events:Hr(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 Ir,writeContract as jr}from"@latticexyz/common";import{getFunctions as Rr}from"@latticexyz/store-sync/world";import $r from"p-retry";async function bo({client:e,worldDeploy:o,functions:t,indexerUrl:r,chainId:n}){let s=await Rr({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}=Ir(l.systemId),u=c===""?{functionName:"registerRootFunctionSelector",args:[l.systemId,l.systemFunctionSignature,l.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[l.systemId,l.systemFunctionSignature]};return $r(()=>jr(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 Fr}from"viem";import{writeContract as Lr}from"@latticexyz/common";import{isDefined as Er}from"@latticexyz/common/utils";import zr from"p-retry";import{ensureContractsDeployed as Nr}from"@latticexyz/common/internal";async function fe({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await Nr({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=>zr(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 Lr(e,{chain:e.chain??null,address:r.address,abi:a,...p})}catch(a){if(a instanceof Fr&&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(Er)):[]}import{getAddress as ho}from"viem";import{hexToResource as wo,resourceToHex as xo,writeContract as Ur}from"@latticexyz/common";import _r 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:_r.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=>Ur(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[xo({namespace:d,type:"namespace",name:""})]})))}import{resourceToHex as yn,resourceToLabel as gn}from"@latticexyz/common";import{randomBytes as bn}from"crypto";import{stringToHex as Qr,BaseError as Zr,concatHex as Do}from"viem";import{hexToResource as Xr,writeContract as en}from"@latticexyz/common";import{identity as on,isDefined as tn}from"@latticexyz/common/utils";import Te from"@latticexyz/world-module-metadata/mud.config";import rn from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import nn from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as Vr,size as Kr}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 Jr}from"abitype/zod";function qr(e){return Vr(e,{strict:!1})}var vo=B.object({object:B.string().refine(qr),linkReferences:B.record(B.record(B.array(B.object({start:B.number(),length:B.number()})))).optional()}),Yr=B.object({bytecode:vo,deployedBytecode:vo,abi:Jr});function V(e){let o=Yr.parse(e),t=ue(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:Kr(o.deployedBytecode.object)}}import{spliceHex as Gr}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=Gr(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 sn}from"@latticexyz/store-sync";import{waitForTransactions as an}from"@latticexyz/common/internal";var ye=V(nn);async function ko({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:s=on,indexerUrl:a,chainId:i}){g("ensuring",n.length,"resource tags"),g("looking up existing resource tags");let{records:p}=await sn({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:Qr(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 an({client:e,hashes:y,debugLabel:"metadata module installation"}),g("setting",u.length,"resource tags"),(await Promise.all(u.map(async d=>{let f=Xr(d.resource),h=`${f.type}:${f.namespace}:${f.name}`;g(`tagging ${h} with ${d.tag}: ${JSON.stringify(d.value)}`);try{return await en(e,{chain:e.chain??null,address:r.address,abi:rn,functionName:"metadata__setResourceTag",args:[d.resource,d.tag,d.value]})}catch(v){g(`failed to set resource tag for ${h}, skipping
7
+ ${v instanceof Zr?v.shortMessage:v}`)}}))).filter(tn)}import{concatHex as ln,encodeDeployData as dn,isHex as Oo}from"viem";import{waitForTransactionReceipt as cn}from"viem/actions";import{resourceToHex as mn,sendTransaction as pn,writeContract as To}from"@latticexyz/common";import{ensureContractsDeployed as Po,getContractAddress as fn,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 ln(o.bytecode.map(r=>Oo(r)?r:fn({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 pn(e,{chain:e.chain??null,data:dn({abi:s.abi,args:[],bytecode:Pe(o,s,t)})});g("waiting for custom world deploy");let p=await cn(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:[mn({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 hn}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 wn,ensureDeployer as xn,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 xn(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${bn(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 wn({...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:`${gn(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=hn([...t,...r].filter(({namespace:S,namespaceLabel:P})=>P!==S).map(({namespace:S,namespaceLabel:P})=>({resourceId:yn({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:un});return await Oe({client:o,hashes:[...w,...m,...te],debugLabel:"remaining transactions"}),g("deploy complete"),f}import{createWalletClient as Xn,http as es,isHex as os,stringToHex as ts}from"viem";import{privateKeyToAccount as rs}from"viem/accounts";import{loadConfig as ns,resolveConfigPath as ss}from"@latticexyz/config/node";import{getOutDirectory as as,getRpcUrl as is}from"@latticexyz/common/foundry";import $ from"chalk";import{MUDError as Yo}from"@latticexyz/common/errors";import Fo from"path";import{loadSystemsManifest as Tn,resolveSystems as Pn}from"@latticexyz/world/node";import{isHex as Lo,toFunctionSelector as Eo,toFunctionSignature as zo}from"viem";import{readFileSync as Sn}from"fs";import vn from"path";import{MUDError as ge}from"@latticexyz/common/errors";import{size as Cn}from"viem";function K(e,o,t){let r,n=vn.join(t,e,o+".json");try{r=JSON.parse(Sn(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:Cn(a)}}import{groupBy as Mn}from"@latticexyz/common/utils";import{readFileSync as An}from"fs";import{globSync as kn}from"glob";import Dn from"toposort";function Ro(e,o,t){let r=Dn(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=kn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(An(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 On}from"find-up";import{createRequire as Bn}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 On("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=Bn(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 Pn({rootDir:e,config:o}),c=await Tn({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=Mn(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 ls}from"viem/actions";import{existsSync as Hn}from"fs";import Wn from"path";import In from"chalk";import{getScriptDirectory as jn,forge as Rn}from"@latticexyz/common/foundry";async function Uo(e,o,t,r,n,s){let a=n?.replaceAll("\\","").split(" ")??[],i=Wn.join(await jn(),e+".s.sol");if(!Hn(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(In.blue(`Executing post deploy script at ${i}`)),await Rn(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",s?"--aws":"",...a],{profile:r})}import{kmsKeyToAccount as ds}from"@latticexyz/common/kms";import Vo from"node:path";import{encodeField as Ln}from"@latticexyz/protocol-parser/internal";import{bytesToHex as En}from"viem";import{createRequire as $n}from"node:module";import{findUp as Fn}from"find-up";async function _o({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await Fn("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=$n(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 zn}from"@latticexyz/world/internal";import Nn from"@latticexyz/world-module-callwithsignature/out/CallWithSignatureModule.sol/CallWithSignatureModule.json"assert{type:"json"};var he=V(Nn),Un={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=Un[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=>zn(l,{config:e})).map(l=>{let c=l.value instanceof Uint8Array?En(l.value):l.value;return Ln(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 cs}from"@latticexyz/world/node";import{getAutomine as _n,getBlock as Ko,setAutomine as Vn,setIntervalMining as Kn}from"viem/actions";import{getAction as X}from"viem/utils";async function qo(e){let o=await Jn(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 Jn(e){let o={mode:"anvil",...e};return await X(o,_n,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await qn(e)}}async function Jo(e,o){o.type==="automine"?await X(e,Vn,"setAutomine")(!0):await X(e,Kn,"setIntervalMining")({interval:o.blockTime})}async function qn(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 Yn,garnet as Gn,rhodolite as Qn}from"@latticexyz/common/chains";var xe=[Yn,Gn,Qn];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?os(e.salt)?e.salt:ts(e.salt):void 0,t=e.profile??process.env.FOUNDRY_PROFILE,r=await ss(e.configPath),n=await ns(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 as(t),i=e.rpc??await is(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 cs({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 ds({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 rs(b)}})(),f=Xn({transport:es(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:d}),h=await ls(f),v=e.indexerUrl??xe.find(b=>b.id===h)?.indexerUrl,A=e.worldAddress?ms({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());Zn(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 ms({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 ps={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=ps;import fs from"node:path";import{loadConfig as us,resolveConfigPath as ys}from"@latticexyz/config/node";import{worldgen as gs}from"@latticexyz/world/node";var bs={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 hs(e),process.exit(0)}};async function hs(e){let o=await ys(e.configPath),t=await us(o),r=fs.dirname(o);await gs({rootDir:r,config:t,clean:e.clean})}var Xo=bs;import ee from"chalk";import{readFileSync as vs,writeFileSync as Cs}from"fs";import We from"path";import{MUDError as q}from"@latticexyz/common/errors";import{globSync as Ds}from"glob";import{ZodError as ws,z as et}from"zod";var xs=et.object({MUD_PACKAGES:et.string().transform(e=>JSON.parse(e))});function Ss(){try{return xs.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 ws){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=Ss().MUD_PACKAGES;var As={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 ks(e));let r=Ds("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)Ts(n,e)}catch(o){ne(o)}finally{process.exit(0)}}};async function ks(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 Ts(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ps(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 Cs(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=Ms(e,t,l)),r||n[c][l]}}function Ps(e){try{let o=vs(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 Ms(e,o,t){let r=We.relative(We.dirname(e),process.cwd());return"link:"+We.join(r,o,He[t].localPath)}var tt=As;import{anvil as Os,forge as Bs,getRpcUrl as Hs}from"@latticexyz/common/foundry";import Ws from"chalk";var Is={...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"}},js={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Is)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Os(n)}let o=e.worldAddress?await Hs(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await J({...e,saveDeployment:!1,rpc:o})).address;console.log(Ws.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Bs(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},rt=js;import Rs from"node:path";import nt from"node:fs";import{loadConfig as $s,resolveConfigPath as Fs}from"@latticexyz/config/node";import{MUDError as st}from"@latticexyz/common/errors";import{cast as Ls,getRpcUrl as Es}from"@latticexyz/common/foundry";import zs from"@latticexyz/world/mud.config";import{createClient as Ns,http as Us}from"viem";import{getChainId as _s,readContract as Vs}from"viem/actions";import{resolveSystems as Ks}from"@latticexyz/world/node";var Js=zs.namespaces.world.tables.Systems.tableId;function qs(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 Ys={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 Fs(e.configPath),t=Rs.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await Es(r),s=await $s(o),a=Ns({transport:Us(n)}),i=await _s(a),p=e.worldAddress??qs(s.deploy.worldsFile,i),l=await Ks({rootDir:t,config:s}),c=await Promise.all(l.map(async y=>({label:y.label,address:await Vs(a,{abi:D,address:p,functionName:"getField",args:[Js,[y.systemId],0]})}))),u=await Ls(["run","--label",`${p}:World`,...c.map(({label:y,address:d})=>["--label",`${d}:${y}`]).flat(),`${e.tx}`]);console.log(u),process.exit(0)}},at=Ys;import{anvil as Gs,getScriptDirectory as Qs,getSrcDirectory as Zs}from"@latticexyz/common/foundry";import j from"chalk";import Xs from"chokidar";import{loadConfig as ea,resolveConfigPath as oa}from"@latticexyz/config/node";import ta from"path";import{homedir as ra}from"os";import{rmSync as na}from"fs";import{BehaviorSubject as sa,debounceTime as aa,exhaustMap as ia,filter as la}from"rxjs";import{isDefined as da}from"@latticexyz/common/utils";var ca={rpc:O.rpc,configPath:O.configPath,alwaysRunPostDeploy:O.alwaysRunPostDeploy,forgeScriptOptions:O.forgeScriptOptions,worldAddress:O.worldAddress},ma={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ca)},async handler(e){let o=e.rpc,t=e.configPath??await oa(e.configPath),r=await Zs(),n=await Qs(),s=await ea(t);if(!e.rpc){console.log(j.gray("Cleaning devnode cache"));let l=ra();na(ta.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Gs(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let a=new sa(Date.now());Xs.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(aa(200),ia(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
+ `))}}),la(da)).subscribe()}},it=ma;import{sliceHex as fa,zeroHash as ua}from"viem";import{forge as pa}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 pa(o,{cwd:e.cwd})}import ya from"p-queue";import{MUDError as ga}from"@latticexyz/common/errors";import{getStorageAt as ba}from"viem/actions";import{execa as Ie}from"execa";import{getContractAddress as lt,getDeployer as ha}from"@latticexyz/common/internal";var wa="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function dt({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:s,verifier:a,verifierUrl:i}){let p=s??await ha(e);if(!p)throw new ga("No deployer address provided or found.");let l=await ba(e,{address:n,slot:wa}),c=l&&l!==ua,u=new ya({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=fa(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 xa,resolveConfigPath as Sa}from"@latticexyz/config/node";import{resolveSystems as va}from"@latticexyz/world/node";import{getOutDirectory as Ca,getRpcUrl as Da}from"@latticexyz/common/foundry";import{createWalletClient as Aa,http as ka}from"viem";import ct from"chalk";import Ta from"node:path";var Pa={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."}},Ma={command:"verify",describe:"Verify contracts",builder(e){return e.options(Pa)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await Sa(e.configPath),r=Ta.dirname(t),n=await xa(t),s=await Ca(o),a=e.rpc??await Da(o);console.log(ct.bgBlue(ct.whiteBright(`
35
+ Verifying MUD contracts${o?" with profile "+o:""} to RPC ${a}
36
+ `)));let i=Aa({transport:ka(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await va({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=Ma;import{getRpcUrl as Ka}from"@latticexyz/common/foundry";import{createClient as Ja,http as qa}from"viem";import De from"chalk";import{hexToString as je,parseAbiItem as pt,stringToHex as Re}from"viem";import{getSchemaTypes as $a}from"@latticexyz/protocol-parser/internal";import{hexToResource as Fa,resourceToHex as La}from"@latticexyz/common";import $e from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as Oa,getKeyTuple as Ba,getSchemaTypes as Ha,getValueSchema as Wa}from"@latticexyz/protocol-parser/internal";import{readContract as Ia}from"viem/actions";import{mapObject as ja}from"@latticexyz/common/utils";async function ve({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await Ia(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,Ba(t,r)]}),i={...r,...Oa(Ha(Wa(t)),{staticData:n,encodedLengths:s,dynamicData:a})};return ja(t.schema,(p,l)=>i[l])}import L from"node:path";import Ce from"node:fs/promises";import{getFunctions as Ea}from"@latticexyz/store-sync/world";import{abiToInterface as ft,formatSolidity as ut,formatTypescript as za}from"@latticexyz/common/codegen";var H=M.extend("pull"),Ra=M.extend("pull");H.log=console.debug.bind(console);Ra.log=console.error.bind(console);import{defineWorld as Na}from"@latticexyz/world";import{findUp as Ua}from"find-up";import{isDefined as yt}from"@latticexyz/common/utils";var _a=new Set(["store","world","metadata"]);function gt(e){return La({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 Ua(".git",{cwd:e})!=null,i=await pe(o,t),p=await _({client:o,worldDeploy:i,indexerUrl:n,chainId:s}),l=p.map(Fa).filter(x=>!_a.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 Ea({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:$a(b.schema),key:b.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let v=Na(h);H("writing config"),await Fe(L.join(e,"mud.config.ts"),await za(`
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 Va(e){return Ce.access(e).then(()=>!0,()=>!1)}async function Fe(e,o,t={}){if(!t.overwrite&&await Va(e))throw new oe(e);await Ce.mkdir(L.dirname(e),{recursive:!0}),await Ce.writeFile(e,o)}import Ya from"node:path";import{getChainId as Ga}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}},Za={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 Ka(o),r=Ja({transport:qa(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),n=await Ga(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 "${Ya.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=Za;var ly=[Le,Zo,Ee,Xa,ze,Ne,Xo,tt,rt,at,it,ei,mt,ht];export{ly as commands};
45
+ //# sourceMappingURL=commands-L7SJDOUH.js.map