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