@latticexyz/cli 2.0.7-main-013cae09 → 2.0.7-main-f0fea5af

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