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