@latticexyz/cli 2.1.1-main-fad4e85853d9ee80753ae1b0b161b60bf9874846 → 2.1.1-main-91028bf231c1c427306750d09a1064f13bf6115a

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