@latticexyz/cli 2.0.7-main-7183364f → 2.0.7-main-013cae09

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,36 @@
1
+ import{a as J}from"./chunk-QXUPZVZL.js";import gs from"@latticexyz/gas-report";import bs from"@latticexyz/abi-ts";import{loadConfig as No}from"@latticexyz/config/node";import{getSrcDirectory as zo}from"@latticexyz/common/foundry";import Ro from"node:path";import{tablegen as Mo}from"@latticexyz/store/codegen";import{worldgen as Wo}from"@latticexyz/world/node";import{worldToV1 as $o}from"@latticexyz/world/config/v2";import{forge as Ho,getRemappings as Fo}from"@latticexyz/common/foundry";import jo from"glob";import{basename as Oo}from"path";function I(e){return jo.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:Oo(o,".sol")}))}import{execa as Eo}from"execa";async function q({config:e,srcDir:o,foundryProfile:n=process.env.FOUNDRY_PROFILE}){let r=$o(e),t=Ro.join(o,r.codegenDirectory),s=await Fo(n);await Promise.all([Mo(e,t,s),Wo(e,I(o),t)]),await Ho(["build"],{profile:n}),await Eo("mud",["abi-ts"],{stdio:"inherit"})}var Lo={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({configPath:e,profile:o}){let n=await No(e),r=await zo();await q({config:n,srcDir:r,foundryProfile:o}),process.exit(0)}},he=Lo;import{rmSync as Uo}from"fs";import{homedir as Vo}from"os";import _o from"path";import{execa as Ko}from"execa";var Jo={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=Vo();Uo(_o.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=Ko("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}},we=Jo;import{FaucetServiceDefinition as qo}from"@latticexyz/services/faucet";import{createChannel as Yo,createClient as Go}from"nice-grpc-web";import xe from"chalk";import{NodeHttpTransport as Zo}from"@improbable-eng/grpc-web-node-http-transport";function Qo(e){return Go(qo,Yo(e,Zo()))}var Xo={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:n}){let r=Qo(o);e&&(console.log(xe.yellow("Dripping to",n)),await r.dripDev({address:n}),console.log(xe.yellow("Success"))),process.exit(0)}},Se=Xo;var et={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)}},Ce=et;import ot from"path";import{loadConfig as tt}from"@latticexyz/config/node";import{tablegen as rt}from"@latticexyz/store/codegen";import{getRemappings as nt,getSrcDirectory as st}from"@latticexyz/common/foundry";var at={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({configPath:e}){let o=await tt(e),n=await st(),r=await nt();await rt(o,ot.join(n,o.codegen.outputDirectory),r),process.exit(0)}},De=at;import ye from"node:path";import{existsSync as on,mkdirSync as tn,readFileSync as rn,writeFileSync as ue}from"node:fs";import{sliceHex as lt}from"viem";import{getBalance as mt,getBytecode as pt,sendRawTransaction as ft,sendTransaction as ve,waitForTransactionReceipt as Ae}from"viem/actions";var A={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Te from"debug";var Y=Te("mud:cli"),dt=Te("mud:cli");Y.log=console.debug.bind(console);dt.log=console.error.bind(console);var c=Y.extend("deploy"),ct=Y.extend("deploy");c.log=console.debug.bind(console);ct.log=console.error.bind(console);var R=`0x${A.address}`;async function ke(e){let o=await pt(e,{address:R});if(o)return c("found CREATE2 deployer at",R),o!==lt(`0x${A.creationCode}`,14)&&console.warn(`
3
+ \u26A0\uFE0F Bytecode for deployer at ${R} did not match the expected CREATE2 bytecode. You may have unexpected results.
4
+ `),R;let n=BigInt(A.gasLimit)*BigInt(A.gasPrice),r=await mt(e,{address:`0x${A.signerAddress}`}),t=n-r;if(t>0){c("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}),d=await Ae(e,{hash:a});if(d.status!=="success")throw console.error("failed to send gas to deployer signer",d),new Error("failed to send gas to deployer signer")}c("deploying CREATE2 deployer at",R);let s=await ft(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
+ `),c("deploying CREATE2 deployer"),ve(e,{chain:e.chain??null,data:`0x${A.creationCode}`});throw a}),i=await Ae(e,{hash:s});if(!i.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return i.contractAddress!==R&&console.warn(`
9
+ \u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${R})`),i.contractAddress}import{waitForTransactionReceipt as zt}from"viem/actions";import Oe from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Re from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Me from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import We from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import $e from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Ot from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import Rt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Mt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import Wt from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import $t from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as $,encodeDeployData as He,size as H}from"viem";import{padHex as ut}from"viem";import gt from"@latticexyz/store/mud.config";import bt from"@latticexyz/world/mud.config";import ht from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import wt from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as yt}from"@latticexyz/common";import{resolveUserTypes as Ie}from"@latticexyz/store/internal";function z(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([n])=>[n,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([n,r])=>[`${e.namespace}_${n}`,{namespace:e.namespace,name:r.name,tableId:yt({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:Ie(r.keySchema,o),valueSchema:Ie(r.valueSchema,o)}]))}import{helloStoreEvent as xt}from"@latticexyz/store";import{helloWorldEvent as St}from"@latticexyz/world";import{storeToV1 as Ct}from"@latticexyz/store/config/v2";import{worldToV1 as Dt}from"@latticexyz/world/config/v2";var T=ut("0x",{size:32}),L=parseInt("6000",16),W=z(Ct(gt)),v=z(Dt(bt)),G=[xt,St],D=[...ht,...wt],Pe=["2.0.0","2.0.1"],Be=["2.0.0","2.0.1"];import{waitForTransactionReceipt as Bt}from"viem/actions";import{concatHex as Tt,getCreate2Address as vt}from"viem";import{getBytecode as At}from"viem/actions";import{sendTransaction as kt}from"@latticexyz/common";import It from"p-retry";import{wait as Pt}from"@latticexyz/common/utils";async function je({client:e,deployerAddress:o,bytecode:n,deployedBytecodeSize:r,label:t="contract"}){if(n.includes("__$"))throw new Error(`Found unlinked public library in ${t} bytecode`);let s=vt({from:o,salt:T,bytecode:n});return await At(e,{address:s,blockTag:"pending"})?(c("found",t,"at",s),[]):(r>L?console.warn(`
10
+ Bytecode for ${t} (${r} bytes) is over the contract size limit (${L} bytes). Run \`forge build --sizes\` for more info.
11
+ `):r>L*.95&&console.warn(`
12
+ Bytecode for ${t} (${r} bytes) is almost over the contract size limit (${L} bytes). Run \`forge build --sizes\` for more info.
13
+ `),c("deploying",t,"at",s),[await It(()=>kt(e,{chain:e.chain??null,to:o,data:Tt([T,n])}),{retries:3,onFailedAttempt:async a=>{let d=a.attemptNumber*500;c(`failed to deploy ${t}, retrying in ${d}ms...`),await Pt(d)}})])}import{uniqueBy as jt}from"@latticexyz/common/utils";async function P({client:e,deployerAddress:o,contracts:n}){let r=jt(n,s=>s.bytecode),t=(await Promise.all(r.map(s=>je({client:e,deployerAddress:o,...s})))).flat();if(t.length){c("waiting for contracts");for(let s of t)await Bt(e,{hash:s})}return t}async function Z(e,o,n){let r=H(Oe.deployedBytecode.object),t=Oe.bytecode.object,s=$({from:o,bytecode:t,salt:T}),i=H(Re.deployedBytecode.object),a=Re.bytecode.object,d=$({from:o,bytecode:a,salt:T}),l=H(Me.deployedBytecode.object),f=Me.bytecode.object,u=$({from:o,bytecode:f,salt:T}),x=H(We.deployedBytecode.object),S=We.bytecode.object,y=$({from:o,bytecode:S,salt:T}),m=H($e.deployedBytecode.object),h=He({bytecode:$e.bytecode.object,abi:Ot,args:[s,d,u,y]}),w=$({from:o,bytecode:h,salt:T}),C=n?Wt:Rt,p=n?$t:Mt,g=H(C.deployedBytecode.object),b=He({bytecode:C.bytecode.object,abi:p,args:[w]}),K=$({from:o,bytecode:b,salt:T});return await P({client:e,deployerAddress:o,contracts:[{bytecode:t,deployedBytecodeSize:r,label:"access management system"},{bytecode:a,deployedBytecodeSize:i,label:"balance transfer system"},{bytecode:f,deployedBytecodeSize:l,label:"batch call system"},{bytecode:S,deployedBytecodeSize:x,label:"core registration system"},{bytecode:h,deployedBytecodeSize:m,label:"core module"},{bytecode:b,deployedBytecodeSize:g,label:"world factory"}]}),K}import Lt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as Ut}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as Ht,decodeEventLog as Ft,hexToString as Fe,parseAbi as Et}from"viem";import{isDefined as Nt}from"@latticexyz/common/utils";function Q(e){let o=e.map(i=>{try{return{...i,...Ft({strict:!0,abi:Et(G),topics:i.topics,data:i.data})}}catch(a){if(a instanceof Ht)return;throw a}}).filter(Nt),{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 Ee(e,o,n,r){let t=await Z(e,o,r);c("deploying world");let s=await Ut(e,{chain:e.chain??null,address:t,abi:Lt,functionName:"deployWorld",args:[n]});c("waiting for world deploy");let i=await zt(e,{hash:s});if(i.status!=="success")throw console.error("world deploy failed",i),new Error("world deploy failed");let a=Q(i.logs);return c("deployed world to",a.address,"at block",a.deployBlock),{...a,stateBlock:a.deployBlock}}import{resourceToLabel as ce,writeContract as Gt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Zt,keySchemaToHex as Qt,valueSchemaToHex as Xt}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as Vt,decodeAbiParameters as Ne,parseAbiParameters as ze}from"viem";import{hexToResource as _t}from"@latticexyz/common";import{storeSetRecordEvent as Kt}from"@latticexyz/store";import{getLogs as Jt}from"viem/actions";import{decodeKey as qt,decodeValueArgs as Yt,hexToSchema as Le}from"@latticexyz/protocol-parser/internal";async function Ue({client:e,worldDeploy:o}){c("looking up tables for",o.address);let r=(await Jt(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Vt(Kt),args:{tableId:W.store_Tables.tableId}})).map(t=>{let{tableId:s}=qt(W.store_Tables.keySchema,t.args.keyTuple),{namespace:i,name:a}=_t(s),d=Yt(W.store_Tables.valueSchema,t.args),l=Le(d.keySchema),f=Le(d.valueSchema),u=Ne(ze("string[]"),d.abiEncodedKeyNames)[0],x=Ne(ze("string[]"),d.abiEncodedFieldNames)[0],S=[...f.staticFields,...f.dynamicFields],y=Object.fromEntries(l.staticFields.map((h,w)=>[u[w],h])),m=Object.fromEntries(S.map((h,w)=>[x[w],h]));return{namespace:i,name:a,tableId:s,keySchema:y,valueSchema:m}});return c("found",r.length,"tables for",o.address),r}import er from"p-retry";import{wait as or}from"@latticexyz/common/utils";async function Ve({client:e,worldDeploy:o,tables:n}){let t=(await Ue({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>t.includes(a.tableId));s.length&&c("existing tables",s.map(ce).join(", "));let i=n.filter(a=>!t.includes(a.tableId));return i.length?(c("registering tables",i.map(ce).join(", ")),await Promise.all(i.map(a=>er(()=>Gt(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[a.tableId,Zt(a.valueSchema),Qt(a.keySchema),Xt(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async d=>{let l=d.attemptNumber*500;c(`failed to register table ${ce(a)}, retrying in ${l}ms...`),await or(l)}})))):[]}import{getAddress as j}from"viem";import{writeContract as le,resourceToLabel as U}from"@latticexyz/common";import{parseAbiItem as tr,HttpRequestError as rr}from"viem";import{getLogs as nr}from"viem/actions";import{storeSpliceStaticDataEvent as sr}from"@latticexyz/store";import ar from"p-retry";async function X({client:e,worldDeploy:o}){c("looking up resource IDs for",o.address);let r=(await ar(()=>nr(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:tr(sr),args:{tableId:W.store_ResourceIds.tableId}}),{retries:3,onFailedAttempt:async t=>{if(!(t instanceof rr&&t.status===400&&t.message.includes("block is out of range")))throw t}})).map(t=>t.args.keyTuple[0]);return c("found",r.length,"resource IDs for",o.address),r}import{hexToResource as Sr,resourceToLabel as Cr}from"@latticexyz/common";import{decodeValueArgs as ir,encodeKey as dr}from"@latticexyz/protocol-parser/internal";import{readContract as cr}from"viem/actions";async function B({client:e,worldDeploy:o,table:n,key:r}){let[t,s,i]=await cr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[n.tableId,dr(n.keySchema,r)]});return ir(n.valueSchema,{staticData:t,encodedLengths:s,dynamicData:i})}import{toFunctionSelector as lr,parseAbiItem as mr}from"viem";import{storeSetRecordEvent as pr}from"@latticexyz/store";import{getLogs as fr}from"viem/actions";import{decodeValueArgs as yr}from"@latticexyz/protocol-parser/internal";import{hexToResource as ur}from"@latticexyz/common";async function ee({client:e,worldDeploy:o}){c("looking up function signatures for",o.address);let r=(await fr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:mr(pr),args:{tableId:v.world_FunctionSignatures.tableId}})).map(s=>yr(v.world_FunctionSignatures.valueSchema,s.args).functionSignature);return c("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let i=lr(s),{systemId:a,systemFunctionSelector:d}=await B({client:e,worldDeploy:o,table:v.world_FunctionSelectors,key:{worldFunctionSelector:i}}),{namespace:l,name:f}=ur(a),u=l===""?s:s.replace(`${l}_${f}_`,"");return{signature:s,selector:i,systemId:a,systemFunctionSignature:u,systemFunctionSelector:d}}))}import{parseAbiItem as gr,getAddress as br}from"viem";import{storeSpliceStaticDataEvent as hr}from"@latticexyz/store";import{getLogs as wr}from"viem/actions";import{decodeKey as xr}from"@latticexyz/protocol-parser/internal";async function oe({client:e,worldDeploy:o}){c("looking up resource access for",o.address);let r=(await wr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:gr(hr),args:{tableId:v.world_ResourceAccess.tableId}})).map(s=>xr(v.world_ResourceAccess.keySchema,s.args.keyTuple)),t=(await Promise.all(r.map(async s=>[s,await B({client:e,worldDeploy:o,table:v.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:br(s.caller)}));return c("found",t.length,"resource<>address access pairs"),t}async function _e({client:e,worldDeploy:o}){let[n,r,t]=await Promise.all([X({client:e,worldDeploy:o}),ee({client:e,worldDeploy:o}),oe({client:e,worldDeploy:o})]),s=n.map(Sr).filter(i=>i.type==="system");return c("looking up systems",s.map(Cr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:d}=await B({client:e,worldDeploy:o,table:v.world_Systems,key:{systemId:i.resourceId}}),l=r.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:d,allowedAddresses:t.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:l}}))}import{wait as me}from"@latticexyz/common/utils";import pe from"p-retry";async function Ke({client:e,deployerAddress:o,libraries:n,worldDeploy:r,systems:t}){let[s,i]=await Promise.all([_e({client:e,worldDeploy:r}),oe({client:e,worldDeploy:r})]),a=t.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)===j(p.prepareDeploy(o,n).address)));a.length&&c("existing systems",a.map(U).join(", "));let d=a.map(p=>p.systemId),l=t.filter(p=>!d.includes(p.systemId));if(!l.length)return[];let f=l.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)!==j(p.prepareDeploy(o,n).address)));f.length&&c("upgrading systems",f.map(U).join(", "));let u=l.filter(p=>!s.some(g=>g.systemId===p.systemId));u.length&&c("registering new systems",u.map(U).join(", ")),await P({client:e,deployerAddress:o,contracts:l.map(p=>({bytecode:p.prepareDeploy(o,n).bytecode,deployedBytecodeSize:p.deployedBytecodeSize,label:`${U(p)} system`}))});let x=await Promise.all(l.map(p=>pe(()=>le(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"registerSystem",args:[p.systemId,p.prepareDeploy(o,n).address,p.allowAll]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to register system ${U(p)}, retrying in ${b}ms...`),await me(b)}}))),S=t.map(p=>p.systemId),y=i.filter(({resourceId:p})=>S.includes(p)),m=[...t.flatMap(p=>p.allowedAddresses.map(g=>({resourceId:p.systemId,address:g}))),...t.flatMap(p=>p.allowedSystemIds.map(g=>({resourceId:p.systemId,address:s.find(b=>b.systemId===g)?.address??t.find(b=>b.systemId===g)?.prepareDeploy(o,n).address})).filter(g=>g.address!=null))],h=m.filter(p=>!y.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address))),w=y.filter(p=>!m.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address)));w.length&&c("revoking",w.length,"access grants"),h.length&&c("adding",h.length,"access grants");let C=await Promise.all([...w.map(p=>pe(()=>le(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"revokeAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to revoke access, retrying in ${b}ms...`),await me(b)}})),...h.map(p=>pe(()=>le(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"grantAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to grant access, retrying in ${b}ms...`),await me(b)}}))]);return[...x,...C]}import{waitForTransactionReceipt as so}from"viem/actions";import{getAddress as Dr,parseAbi as Tr}from"viem";import{getBlockNumber as vr,getLogs as Ar}from"viem/actions";var Je=new Map;async function qe(e,o){let n=Dr(o),r=Je.get(n);if(r!=null)return r;c("looking up world deploy for",n);let t=await vr(e),s=await Ar(e,{strict:!0,address:n,events:Tr(G),fromBlock:"earliest",toBlock:t});return r={...Q(s),stateBlock:t},Je.set(n,r),c("found world deploy for",n,"at block",r.deployBlock),r}import{hexToResource as kr,writeContract as Ye}from"@latticexyz/common";import Ge from"p-retry";import{wait as Ze}from"@latticexyz/common/utils";async function Qe({client:e,worldDeploy:o,functions:n}){let r=await ee({client:e,worldDeploy:o}),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){c("functions already registered:",s.map(d=>d.signature).join(", "));let a=s.filter(d=>d.systemId!==t[d.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(d=>d.signature).join(", "))}return i.length?(c("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:d}=kr(a.systemId);return d===""?Ge(()=>Ye(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;c(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Ze(f)}}):Ge(()=>Ye(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;c(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Ze(f)}})}))):[]}import{BaseError as Ir}from"viem";import{writeContract as Xe}from"@latticexyz/common";import{isDefined as Pr,wait as Br}from"@latticexyz/common/utils";import jr from"p-retry";async function eo({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,label:`${s.name} module`}))}),c("installing modules:",t.map(s=>s.name).join(", ")),(await Promise.all(t.map(s=>jr(async()=>{try{let i=s.prepareDeploy(o,n).address;return s.installAsRoot?await Xe(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"installRootModule",args:[i,s.installData]}):await Xe(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"installModule",args:[i,s.installData]})}catch(i){if(i instanceof Ir&&i.message.includes("Module_AlreadyInstalled")){c(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;c(`failed to install module ${s.name}, retrying in ${a}ms...`),await Br(a)}})))).filter(Pr)):[]}import{getAddress as oo}from"viem";import{hexToResource as to,resourceToHex as ro,writeContract as Or}from"@latticexyz/common";async function no({client:e,worldDeploy:o,resourceIds:n}){let r=Array.from(new Set(n.map(u=>to(u).namespace))),t=await X({client:e,worldDeploy:o}),s=new Set(t.map(u=>to(u).namespace));s.size&&c("found",s.size,"existing namespaces:",Array.from(s).map(u=>u===""?"<root>":u).join(", "));let i=r.filter(u=>s.has(u)),d=(await Promise.all(i.map(async u=>{let{owner:x}=await B({client:e,worldDeploy:o,table:v.world_NamespaceOwner,key:{namespaceId:ro({type:"namespace",namespace:u,name:""})}});return[u,x]}))).filter(([,u])=>oo(u)!==oo(e.account.address)).map(([u])=>u);if(d.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${d.join(", ")}`);let l=r.filter(u=>!s.has(u));return l.length>0&&c("registering namespaces",Array.from(l).join(", ")),Promise.all(l.map(u=>Or(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[ro({namespace:u,type:"namespace",name:""})]})))}import{resourceToLabel as Rr}from"@latticexyz/common";import{randomBytes as Mr}from"crypto";async function ao({client:e,config:o,salt:n,worldAddress:r,deployerAddress:t,withWorldProxy:s}){let i=Object.values(o.tables),a=t??await ke(e);await Z(e,a,s),await P({client:e,deployerAddress:a,contracts:[...o.libraries.map(m=>({bytecode:m.prepareDeploy(a,o.libraries).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${m.path}:${m.name} library`})),...o.systems.map(m=>({bytecode:m.prepareDeploy(a,o.libraries).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${Rr(m)} system`})),...o.modules.map(m=>({bytecode:m.prepareDeploy(a,o.libraries).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${m.name} module`}))]});let d=r?await qe(e,r):await Ee(e,a,n??`0x${Mr(32).toString("hex")}`,s);if(!Pe.includes(d.storeVersion))throw new Error(`Unsupported Store version: ${d.storeVersion}`);if(!Be.includes(d.worldVersion))throw new Error(`Unsupported World version: ${d.worldVersion}`);let l=await no({client:e,worldDeploy:d,resourceIds:[...i.map(m=>m.tableId),...o.systems.map(m=>m.systemId)]});c("waiting for all namespace registration transactions to confirm");for(let m of l)await so(e,{hash:m});let f=await Ve({client:e,worldDeploy:d,tables:i}),u=await Ke({client:e,deployerAddress:a,libraries:o.libraries,worldDeploy:d,systems:o.systems}),x=await Qe({client:e,worldDeploy:d,functions:o.systems.flatMap(m=>m.functions)}),S=await eo({client:e,deployerAddress:a,libraries:o.libraries,worldDeploy:d,modules:o.modules}),y=[...f,...u,...x,...S];c("waiting for all transactions to confirm");for(let m of y)await so(e,{hash:m});return c("deploy complete"),d}import{createWalletClient as nn,http as sn,isHex as an}from"viem";import{privateKeyToAccount as dn}from"viem/accounts";import{loadConfig as cn}from"@latticexyz/config/node";import{worldToV1 as ln}from"@latticexyz/world/config/v2";import{getOutDirectory as mn,getRpcUrl as pn,getSrcDirectory as fn}from"@latticexyz/common/foundry";import F from"chalk";import{MUDError as uo}from"@latticexyz/common/errors";import Ur from"path";import{resolveWorldConfig as Vr}from"@latticexyz/world/internal";import{resourceToHex as fe}from"@latticexyz/common";import{resolveWithContext as _r}from"@latticexyz/config/library";import{encodeField as Kr}from"@latticexyz/protocol-parser/internal";import{hexToBytes as Jr,bytesToHex as qr,toFunctionSelector as mo,toFunctionSignature as po}from"viem";import te from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import re from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import ne from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import se from"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"assert{type:"json"};import{size as ae}from"viem";function M(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}))))}var io=[{name:"KeysWithValueModule",abi:te.abi,bytecode:te.bytecode.object,placeholders:M(te.bytecode.linkReferences),deployedBytecodeSize:ae(te.deployedBytecode.object)},{name:"KeysInTableModule",abi:re.abi,bytecode:re.bytecode.object,placeholders:M(re.bytecode.linkReferences),deployedBytecodeSize:ae(re.deployedBytecode.object)},{name:"UniqueEntityModule",abi:ne.abi,bytecode:ne.bytecode.object,placeholders:M(ne.bytecode.linkReferences),deployedBytecodeSize:ae(ne.deployedBytecode.object)},{name:"Unstable_CallWithSignatureModule",abi:se.abi,bytecode:se.bytecode.object,placeholders:M(se.bytecode.linkReferences),deployedBytecodeSize:ae(se.deployedBytecode.object)}];import{readFileSync as Wr}from"fs";import $r from"path";import{MUDError as ie}from"@latticexyz/common/errors";import{size as Hr}from"viem";function V(e,o,n){let r,t=$r.join(n,e,o+".json");try{r=JSON.parse(Wr(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 d=M(r?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:d,deployedBytecodeSize:Hr(i)}}import{groupBy as Yr}from"@latticexyz/common/utils";import{readFileSync as Er}from"fs";import Nr from"glob";import Fr from"toposort";function co(e,o,n){let r=Fr(e.flatMap(t=>n(t).map(s=>[o(t),s])));return[...e].sort((t,s)=>r.indexOf(o(t))-r.indexOf(o(s)))}function lo(e){let n=Nr.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(r=>JSON.parse(Er(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,d])=>Object.keys(d).map(l=>({path:a,name:l,dependentPath:t,dependentName:s})))});return co(n,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{spliceHex as zr}from"@latticexyz/common";import{getCreate2Address as Lr}from"viem";function de(e,o){return function(r,t){let s=e;for(let i of o){let a=t.find(d=>d.path===i.path&&d.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=zr(s,i.start,i.length,a.prepareDeploy(r,t).address)}return{bytecode:s,address:Lr({from:r,bytecode:s,salt:T})}}}function fo({config:e,forgeSourceDir:o,forgeOutDir:n}){let r=lo(n).map(y=>{let m=V(Ur.basename(y.path),y.name,n);return{path:y.path,name:y.name,abi:m.abi,prepareDeploy:de(m.bytecode,m.placeholders),deployedBytecodeSize:m.deployedBytecodeSize}}),t=z(e),s=I(o).map(({basename:y})=>y),i=Vr(e,s),d=V("System.sol","System",n).abi.filter(y=>y.type==="function").map(po),l=Object.entries(i.systems).map(([y,m])=>{let h=e.namespace,w=m.name,C=fe({type:"system",namespace:h,name:w}),p=V(`${y}.sol`,y,n),g=p.abi.filter(b=>b.type==="function").map(po).filter(b=>!d.includes(b)).map(b=>{let K=h===""?b:`${h}__${b}`;return{signature:K,selector:mo(K),systemId:C,systemFunctionSignature:b,systemFunctionSelector:mo(b)}});return{namespace:h,name:w,systemId:C,allowAll:m.openAccess,allowedAddresses:m.accessListAddresses,allowedSystemIds:m.accessListSystems.map(b=>fe({type:"system",namespace:h,name:i.systems[b].name})),prepareDeploy:de(p.bytecode,p.placeholders),deployedBytecodeSize:p.deployedBytecodeSize,abi:p.abi,functions:g}}),f=Yr(l,y=>y.systemId),u=Array.from(f.values()).filter(y=>y.length>1).flat();if(u.length){let y=u.map(m=>m.name);throw new Error(`Found systems with overlapping system ID: ${y.join(", ")}.
14
+
15
+ System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}let x={tableIds:Object.fromEntries(Object.entries(e.tables).map(([y,m])=>[y,Jr(fe({type:m.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:m.name}))]))},S=e.modules.map(y=>{let m=io.find(w=>w.name===y.name)??V(`${y.name}.sol`,y.name,n),h=y.args.map(w=>_r(w,x)).map(w=>{let C=w.value instanceof Uint8Array?qr(w.value):w.value;return Kr(w.type,C)});if(h.length>1)throw new Error(`${y.name} module should only have 0-1 args, but had ${h.length} args.`);return{name:y.name,installAsRoot:y.root,installData:h.length===0?"0x":h[0],prepareDeploy:de(m.bytecode,m.placeholders),deployedBytecodeSize:m.deployedBytecodeSize,abi:m.abi}});return{tables:t,systems:l,modules:S,libraries:r}}import{getChainId as yn}from"viem/actions";import{existsSync as Gr}from"fs";import Zr from"path";import Qr from"chalk";import{getScriptDirectory as Xr,forge as en}from"@latticexyz/common/foundry";async function yo(e,o,n,r){let t=Zr.join(await Xr(),e+".s.sol");Gr(t)?(console.log(Qr.blue(`Executing post deploy script at ${t}`)),await en(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",n,"-vvv"],{profile:r})):console.log(`No script at ${t}, skipping post deploy hook`)}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"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},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."},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."}};async function E(e){let o=e.salt;if(o!=null&&!an(o))throw new uo("Expected hex string for salt");let n=e.profile??process.env.FOUNDRY_PROFILE,r=await cn(e.configPath),t=ln(r);e.printConfig&&console.log(F.green(`
16
+ Resolved config:
17
+ `),JSON.stringify(t,null,2));let s=e.srcDir??await fn(n),i=await mn(n),a=e.rpc??await pn(n);console.log(F.bgBlue(F.whiteBright(`
18
+ Deploying MUD contracts${n?" with profile "+n:""} to RPC ${a}
19
+ `))),e.skipBuild||await q({config:r,srcDir:s,foundryProfile:n});let d=process.env.PRIVATE_KEY;if(!d)throw new uo(`Missing PRIVATE_KEY environment variable.
20
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
21
+ in your contracts directory to use the default anvil private key.`);let l=fo({config:t,forgeSourceDir:s,forgeOutDir:i}),f=nn({transport:sn(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:dn(d)});console.log("Deploying from",f.account.address);let u=Date.now(),x=await ao({deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:f,config:l,withWorldProxy:r.deploy.useProxy});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await yo(t.postDeployScript,x.address,a,n),console.log(F.green("Deployment completed in",(Date.now()-u)/1e3,"seconds"));let S={worldAddress:x.address,blockNumber:Number(x.deployBlock)};if(e.saveDeployment){let y=await yn(f),m=ye.join(t.deploysDirectory,y.toString());tn(m,{recursive:!0}),ue(ye.join(m,"latest.json"),JSON.stringify(S,null,2)),ue(ye.join(m,Date.now()+".json"),JSON.stringify(S,null,2));let h=[1337,31337],w=on(t.worldsFile)?JSON.parse(rn(t.worldsFile,"utf-8")):{};w[y]={address:S.worldAddress,blockNumber:h.includes(y)?void 0:S.blockNumber},ue(t.worldsFile,JSON.stringify(w,null,2)),console.log(F.bgGreen(F.whiteBright(`
22
+ Deployment result (written to ${t.worldsFile} and ${m}):
23
+ `)))}return console.log(S),x}var un={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(k)},async handler(e){try{await E(e)}catch(o){J(o),process.exit(1)}process.exit(0)}},go=un;import{loadConfig as gn}from"@latticexyz/config/node";import{worldgen as bn}from"@latticexyz/world/node";import{getSrcDirectory as hn}from"@latticexyz/common/foundry";import bo from"path";import{rmSync as wn}from"fs";var xn={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 Sn(e),process.exit(0)}};async function Sn(e){let o=e.srcDir??await hn(),n=I(o),r=e.config??await gn(e.configPath),t=bo.join(o,r.codegen.outputDirectory);e.clean&&wn(bo.join(t,r.codegen.worldgenDirectory),{recursive:!0,force:!0}),await bn(r,n,t)}var ho=xn;import _ from"chalk";import{readFileSync as An,writeFileSync as kn}from"fs";import be from"path";import{MUDError as N}from"@latticexyz/common/errors";var wo={name:"@latticexyz/cli",version:"2.0.6",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"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},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:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.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.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@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 In from"glob";import{ZodError as Dn,z as xo}from"zod";var Tn=xo.object({MUD_PACKAGES:xo.string().transform(e=>JSON.parse(e))});function vn(){try{return Tn.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"},"@latticexyz/services":{"localPath":"packages/services"},"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-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof Dn){let{...o}=e.format();console.error(`
24
+ Missing or invalid environment variables:
25
+
26
+ ${Object.keys(o).join(`
27
+ `)}
28
+ `),process.exit(1)}throw e}}var ge=vn().MUD_PACKAGES;var Pn={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 N(`You need to provide one these options: ${o.join(", ")}`);if(n>1)throw new N(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Bn(e));let r=In.sync("**/package.json").filter(t=>!t.includes("node_modules"));for(let t of r)jn(t,e)}catch(o){J(o)}finally{process.exit(0)}}};async function Bn(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(_.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${wo.name}`)).json()}catch{throw new N("Could not fetch available MUD versions")}if(e.tag){let n=o["dist-tags"][e.tag];if(!n)throw new N(`Could not find npm version with tag "${e.tag}"`);return console.log(_.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 N(`Could not find npm version based on commit "${e.commit}"`);return console.log(_.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function jn(e,o){let{link:n}=o,{mudVersion:r}=o,t=On(e),s=Object.keys(ge),i={};for(let l in t.dependencies)s.includes(l)&&(i[l]=t.dependencies[l]);let a={};for(let l in t.devDependencies)s.includes(l)&&(a[l]=t.devDependencies[l]);for(let l in t.dependencies)s.includes(l)&&(t.dependencies[l]=d(l,"dependencies"));for(let l in t.devDependencies)s.includes(l)&&(t.devDependencies[l]=d(l,"devDependencies"));return kn(e,JSON.stringify(t,null,2)+`
29
+ `),console.log(`Updating ${e}`),So(i,t.dependencies),So(a,t.devDependencies),t;function d(l,f){return n&&(r=Rn(e,n,l)),r||t[f][l]}}function On(e){try{let o=An(e,"utf8");return JSON.parse(o)}catch{throw new N("Could not read JSON at "+e)}}function So(e,o){for(let n in e)e[n]!==o[n]&&console.log(`${n}: ${_.red(e[n])} -> ${_.green(o[n])}`)}function Rn(e,o,n){let r=be.relative(be.dirname(e),process.cwd());return"link:"+be.join(r,o,ge[n].localPath)}var Co=Pn;import{anvil as Mn,forge as Wn,getRpcUrl as $n}from"@latticexyz/common/foundry";import Hn from"chalk";var Fn={...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"}},En={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Fn)},async handler(e){if(!e.worldAddress){let t=["--block-base-fee-per-gas","0","--port",String(e.port)];Mn(t)}let o=e.worldAddress?await $n(e.profile):`http://127.0.0.1:${e.port}`,n=e.worldAddress??(await E({...e,saveDeployment:!1,rpc:o})).address;console.log(Hn.blue("World address",n));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Wn(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:n}}),process.exit(0)}catch(t){console.error(t),process.exit(1)}}},Do=En;import{existsSync as Nn,readFileSync as zn}from"fs";import{ethers as To}from"ethers";import{loadConfig as Ln}from"@latticexyz/config/node";import{MUDError as vo}from"@latticexyz/common/errors";import{cast as Un,getRpcUrl as Vn,getSrcDirectory as _n}from"@latticexyz/common/foundry";import{resolveWorldConfig as Kn}from"@latticexyz/world/internal";import Jn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Ao from"@latticexyz/world/mud.config";import{resourceToHex as Io}from"@latticexyz/common";import{createClient as qn,http as Yn}from"viem";import{getChainId as Gn}from"viem/actions";import{worldToV1 as Zn}from"@latticexyz/world/config/v2";var ko=Io({type:"system",namespace:Ao.namespace,name:Ao.tables.world__Systems.name}),Qn={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"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await _n(o),e.rpc??=await Vn(o);let{tx:n,configPath:r,srcDir:t,rpc:s}=e,i=I(t),a=await Ln(r),d=Zn(a),l=Kn(d,i.map(({basename:C})=>C)),f=e.worldAddress??await Xn(d.worldsFile,s),u=new To.providers.StaticJsonRpcProvider(s),x=new To.Contract(f,Jn,u),S=d.namespace,y=Object.values(l.systems).map(({name:C})=>C),m=await x.getFieldLayout(ko),h=[];for(let C of y){let p=Io({type:"system",namespace:S,name:C}),g=await x.getField(ko,[p],0,m);h.push({name:C,address:g})}let w=await Un(["run","--label",`${f}:World`,...h.map(({name:C,address:p})=>["--label",`${p}:${C}`]).flat(),`${n}`]);console.log(w),process.exit(0)}},Po=Qn;async function Xn(e,o){if(Nn(e)){let n=qn({transport:Yn(o)}),r=await Gn(n),t=JSON.parse(zn(e,"utf-8"));if(!t[r])throw new vo(`chainId ${r} is missing in worldsFile "${e}"`);return t[r].address}else throw new vo("worldAddress is not specified and worldsFile is missing")}import{anvil as es,getScriptDirectory as os,getSrcDirectory as ts}from"@latticexyz/common/foundry";import O from"chalk";import rs from"chokidar";import{loadConfig as ns,resolveConfigPath as ss}from"@latticexyz/config/node";import as from"path";import{homedir as is}from"os";import{rmSync as ds}from"fs";import{BehaviorSubject as cs,debounceTime as ls,exhaustMap as ms,filter as ps}from"rxjs";import{isDefined as fs}from"@latticexyz/common/utils";var ys={rpc:k.rpc,configPath:k.configPath,alwaysRunPostDeploy:k.alwaysRunPostDeploy,worldAddress:k.worldAddress},us={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ys)},async handler(e){let o=e.rpc,n=e.configPath??await ss(e.configPath),r=await ts(),t=await os(),s=await ns(n);if(!e.rpc){console.log(O.gray("Cleaning devnode cache"));let l=is();ds(as.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),es(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let i=new cs(Date.now());rs.watch([n,r,t],{ignoreInitial:!0}).on("all",async(l,f)=>{f.includes(n)&&(console.log(O.blue("Config changed, queuing deploy\u2026")),i.next(Date.now())),(f.includes(r)||f.includes(t))&&(f.includes(s.codegen.outputDirectory)||(console.log(O.blue("Contracts changed, queuing deploy\u2026")),i.next(Date.now())))});let a=e.worldAddress;i.pipe(ls(200),ms(async l=>{a&&console.log(O.blue("Rebuilding and upgrading world\u2026"));try{let f=await E({...e,configPath:n,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:a,srcDir:r,salt:"0x"});return a=f.address,l<i.value?i.next(i.value):console.log(O.gray(`
30
+ Waiting for file changes\u2026
31
+ `)),f}catch(f){console.error(O.bgRed(O.whiteBright(`
32
+ Error while attempting deploy
33
+ `))),console.error(f),console.log(O.gray(`
34
+ Waiting for file changes\u2026
35
+ `))}}),ps(fs)).subscribe()}},Bo=us;var qp=[he,go,we,Se,gs,Ce,De,ho,Co,Do,Po,Bo,bs];export{qp as commands};
36
+ //# sourceMappingURL=commands-JRVLW7H6.js.map