@latticexyz/cli 2.2.13 → 2.2.14-main-8eaad304db2fe9ae79f087ec7860928f734039d4

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