@latticexyz/cli 2.2.14 → 2.2.15-1673ff9c3edf534aff2bde811475a8d8da2e5e5a

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