@latticexyz/cli 2.0.9 → 2.0.10-230513-threejs-template-use-namespace-d6ab6d80

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