@latticexyz/cli 2.2.5 → 2.2.6-main-22c37c3dbec5726f52055ed61c4e5f0e52ed30c1

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