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