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