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