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