@latticexyz/cli 2.2.0 → 2.2.1-main-0738d295f802be28524d517d75efe3b5837f10c1

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