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