@latticexyz/cli 2.2.11-main-06b09edce3385ffca615d6bbcdade7329e241bd2 → 2.2.11-main-7ddcf64a222f184b1902a1dc93089064465b6acf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ import{a as G}from"./chunk-JXC4VYGI.js";import Ma from"@latticexyz/gas-report";import Ba from"@latticexyz/abi-ts";import{loadConfig as st,resolveConfigPath as at}from"@latticexyz/config/node";import{tablegen as et}from"@latticexyz/store/codegen";import{buildSystemsManifest as ot,worldgen as tt}from"@latticexyz/world/node";import{forge as rt}from"@latticexyz/common/foundry";import{execa as nt}from"execa";async function Q({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([et({rootDir:e,config:o}),tt({rootDir:e,config:o})]),await rt(["build"],{profile:t}),await ot({rootDir:e,config:o}),await nt("mud",["abi-ts"],{stdio:"inherit"})}import it from"node:path";var dt={command:"build",describe:"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler(e){let o=await at(e.configPath),t=await st(o);await Q({rootDir:it.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},ke=dt;import{rmSync as lt}from"fs";import{homedir as ct}from"os";import mt from"path";import{execa as pt}from"execa";var ft={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=ct();lt(mt.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=pt("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
2
+ gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},Pe=ft;var yt={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)}},Me=yt;import{loadConfig as ut,resolveConfigPath as gt}from"@latticexyz/config/node";import{tablegen as bt}from"@latticexyz/store/codegen";import ht from"node:path";var wt={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"}})},async handler(e){let o=await gt(e.configPath),t=await ut(o);await bt({rootDir:ht.dirname(o),config:t}),process.exit(0)}},Be=wt;import me from"node:path";import{existsSync as Qn,mkdirSync as Zn,readFileSync as Xn,writeFileSync as Ce}from"node:fs";import{stringToHex as xn}from"viem";import{getBalance as Dt,sendRawTransaction as Tt,sendTransaction as We,waitForTransactionReceipt as Ie}from"viem/actions";var D={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Oe from"debug";var H=Oe("mud:cli"),Ct=Oe("mud:cli");H.log=console.debug.bind(console);Ct.log=console.error.bind(console);var m=H.extend("deploy"),At=H.extend("deploy");m.log=console.debug.bind(console);At.log=console.error.bind(console);import{sliceHex as vt}from"viem";import{getBytecode as St}from"viem/actions";var Z=`0x${D.address}`;async function X(e){let o=await St(e,{address:Z});if(o)return m("found CREATE2 deployer at",Z),o!==vt(`0x${D.creationCode}`,14)&&console.warn(`
3
+ \u26A0\uFE0F Bytecode for deployer at ${Z} did not match the expected CREATE2 bytecode. You may have unexpected results.
4
+ `),Z}var pe=`0x${D.address}`;async function He(e){let o=await X(e);if(o!==void 0)return o;let t=BigInt(D.gasLimit)*BigInt(D.gasPrice),r=await Dt(e,{address:`0x${D.signerAddress}`}),n=t-r;if(n>0){m("sending gas for CREATE2 deployer to signer at",D.signerAddress);let i=await We(e,{chain:e.chain??null,to:`0x${D.signerAddress}`,value:n}),c=await Ie(e,{hash:i});if(c.status!=="success")throw console.error("failed to send gas to deployer signer",c),new Error("failed to send gas to deployer signer")}m("deploying CREATE2 deployer at",pe);let a=await Tt(e,{serializedTransaction:`0x${D.transaction}`}).catch(i=>{if(String(i).includes("only replay-protected (EIP-155) transactions allowed over RPC"))return console.warn(`
5
+ \u26A0\uFE0F Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.
6
+
7
+ We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.
8
+ `),m("deploying CREATE2 deployer"),We(e,{chain:e.chain??null,data:`0x${D.creationCode}`});throw i}),s=await Ie(e,{hash:a});if(!s.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return s.contractAddress!==pe&&console.warn(`
9
+ \u26A0\uFE0F CREATE2 deployer created at ${s.contractAddress} does not match the CREATE2 determinstic deployer we expected (${pe})`),s.contractAddress}import{waitForTransactionReceipt as Zt}from"viem/actions";import{concatHex as Ot,getCreate2Address as Wt}from"viem";import{getBytecode as It}from"viem/actions";import{padHex as kt}from"viem";import Pt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as Mt}from"@latticexyz/store";import{helloWorldEvent as Bt}from"@latticexyz/world";var x=kt("0x",{size:32}),U=parseInt("6000",16),ee=[Mt,Bt],C=Pt,Re=["2.0.0","2.0.1","2.0.2"],je=["2.0.0","2.0.1","2.0.2"];import{sendTransaction as Ht}from"@latticexyz/common";import Rt from"p-retry";async function $e({client:e,deployerAddress:o,bytecode:t,deployedBytecodeSize:r,debugLabel:n="contract"}){if(t.includes("__$"))throw new Error(`Found unlinked public library in ${n} bytecode`);let a=Wt({from:o,salt:x,bytecode:t});return await It(e,{address:a,blockTag:"pending"})?(m("found",n,"at",a),[]):(r!=null&&(r>U?console.warn(`
10
+ Bytecode for ${n} (${r} bytes) is over the contract size limit (${U} bytes). Run \`forge build --sizes\` for more info.
11
+ `):r>U*.95&&console.warn(`
12
+ Bytecode for ${n} (${r} bytes) is almost over the contract size limit (${U} bytes). Run \`forge build --sizes\` for more info.
13
+ `)),m("deploying",n,"at",a),[await Rt(()=>Ht(e,{chain:e.chain??null,to:o,data:Ot([x,t])}),{retries:3,onFailedAttempt:()=>m(`failed to deploy ${n}, retrying...`)})])}import{uniqueBy as $t}from"@latticexyz/common/utils";import{waitForTransactionReceipt as jt}from"viem/actions";async function P({client:e,hashes:o,debugLabel:t="transactions"}){if(o.length){m(`waiting for ${t} to confirm`);for(let r of o)if((await jt(e,{hash:r})).status==="reverted")throw new Error(`Transaction reverted: ${r}`)}}async function T({client:e,deployerAddress:o,contracts:t}){let r=$t(t,a=>a.bytecode),n=(await Promise.all(r.map(a=>$e({client:e,deployerAddress:o,...a})))).flat();return await P({client:e,hashes:n,debugLabel:"contract deploys"}),n}import Ve from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Ft from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as zt,encodeDeployData as Nt,size as Vt}from"viem";import Le from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Ee from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Fe from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import ze from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import Ne from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Lt from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as _,encodeDeployData as Et,size as K}from"viem";function $(e){let o=K(Le.deployedBytecode.object),t=Le.bytecode.object,r=_({from:e,bytecode:t,salt:x}),n=K(Ee.deployedBytecode.object),a=Ee.bytecode.object,s=_({from:e,bytecode:a,salt:x}),i=K(Fe.deployedBytecode.object),c=Fe.bytecode.object,l=_({from:e,bytecode:c,salt:x}),f=K(ze.deployedBytecode.object),d=ze.bytecode.object,y=_({from:e,bytecode:d,salt:x}),b=K(Ne.deployedBytecode.object),w=Et({bytecode:Ne.bytecode.object,abi:Lt,args:[r,s,l,y]}),v=_({from:e,bytecode:w,salt:x});return{AccessManagementSystem:{bytecode:t,deployedBytecodeSize:o,debugLabel:"access management system",address:r},BalanceTransferSystem:{bytecode:a,deployedBytecodeSize:n,debugLabel:"balance transfer system",address:s},BatchCallSystem:{bytecode:c,deployedBytecodeSize:i,debugLabel:"batch call system",address:l},RegistrationSystem:{bytecode:d,deployedBytecodeSize:f,debugLabel:"core registration system",address:y},InitModule:{bytecode:w,deployedBytecodeSize:b,debugLabel:"core module",address:v}}}function oe(e){let o=$(e),t=Vt(Ve.deployedBytecode.object),r=Nt({bytecode:Ve.bytecode.object,abi:Ft,args:[o.InitModule.address]}),n=zt({from:e,bytecode:r,salt:x});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import Ue from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import Ut from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as _t,encodeDeployData as Kt,size as Jt}from"viem";function te(e){let o=$(e),t=Jt(Ue.deployedBytecode.object),r=Kt({bytecode:Ue.bytecode.object,abi:Ut,args:[o.InitModule.address]}),n=_t({from:e,bytecode:r,salt:x});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world proxy factory",address:n}}}async function _e(e,o,t){if(t){let n=te(o);return await T({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=oe(o);return await T({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import Xt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as er}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as qt,decodeEventLog as Yt,hexToString as Ke,parseAbi as Gt}from"viem";import{isDefined as Qt}from"@latticexyz/common/utils";function L(e){let o=e.map(s=>{try{return{...s,...Yt({strict:!0,abi:Gt(ee),topics:s.topics,data:s.data})}}catch(i){if(i instanceof qt)return;throw i}}).filter(Qt),{address:t,deployBlock:r,worldVersion:n,storeVersion:a}=o.reduce((s,i)=>({...s,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Ke(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:Ke(i.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(t==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(a==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:a}}async function Je(e,o,t,r){let n=await _e(e,o,r);m("deploying world");let a=await er(e,{chain:e.chain??null,address:n,abi:Xt,functionName:"deployWorld",args:[t]});m("waiting for world deploy");let s=await Zt(e,{hash:a});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");let i=L(s.logs);return m("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as ye,writeContract as lr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as mr,valueSchemaToHex as pr,getSchemaTypes as Xe,getValueSchema as fr,getKeySchema as yr}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as qe,parseAbiParameters as Ye}from"viem";import{hexToResource as or}from"@latticexyz/common";import{decodeKey as tr,decodeValueArgs as rr,getKeySchema as nr,getSchemaTypes as Ge,getValueSchema as sr,hexToSchema as Qe}from"@latticexyz/protocol-parser/internal";import fe from"@latticexyz/store/mud.config";import{fetchBlockLogs as ar}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as ir,getStoreLogs as dr}from"@latticexyz/store/internal";async function Ze({client:e,worldDeploy:o}){m("looking up tables for",o.address);let t=await ar({fromBlock:o.deployBlock,toBlock:o.stateBlock,async getLogs({fromBlock:a,toBlock:s}){return dr(e,{address:o.address,fromBlock:a,toBlock:s,tableId:fe.namespaces.store.tables.Tables.tableId})}}),n=ir(t.flatMap(a=>a.logs)).map(a=>{let{tableId:s}=tr(Ge(nr(fe.namespaces.store.tables.Tables)),a.args.keyTuple),{type:i,namespace:c,name:l}=or(s),f=rr(Ge(sr(fe.namespaces.store.tables.Tables)),a.args),d=Qe(f.keySchema),y=Qe(f.valueSchema),b=qe(Ye("string[]"),f.abiEncodedKeyNames)[0],w=qe(Ye("string[]"),f.abiEncodedFieldNames)[0],v=[...y.staticFields,...y.dynamicFields],S=Object.fromEntries(d.staticFields.map((A,p)=>[b[p],{type:A,internalType:A}])),g=Object.fromEntries(v.map((A,p)=>[w[p],{type:A,internalType:A}]));return{type:i,namespace:c,name:l,tableId:s,schema:{...S,...g},key:Object.keys(S)}});return m("found",n.length,"tables for",o.address),n}import ur from"p-retry";async function eo({client:e,worldDeploy:o,tables:t}){let n=(await Ze({client:e,worldDeploy:o})).map(i=>i.tableId),a=t.filter(i=>n.includes(i.tableId));a.length&&m("existing tables:",a.map(ye).join(", "));let s=t.filter(i=>!n.includes(i.tableId));return s.length?(m("registering tables:",s.map(ye).join(", ")),await Promise.all(s.map(i=>{let c=Xe(yr(i)),l=Xe(fr(i));return ur(()=>lr(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerTable",args:[i.tableId,cr(l),mr(c),pr(l),Object.keys(c),Object.keys(l)]}),{retries:3,onFailedAttempt:()=>m(`failed to register table ${ye(i)}, retrying...`)})}))):[]}import{getAddress as W}from"viem";import{writeContract as ge,resourceToLabel as J}from"@latticexyz/common";import{hexToResource as Wr,resourceToLabel as Ir}from"@latticexyz/common";import{getFunctions as Hr}from"@latticexyz/world/internal";import{flattenStoreLogs as gr,getStoreLogs as br}from"@latticexyz/store/internal";import hr from"@latticexyz/store/mud.config";import{fetchBlockLogs as wr}from"@latticexyz/block-logs-stream";async function re({client:e,worldDeploy:o}){m("looking up resource IDs for",o.address);let t=await wr({fromBlock:o.deployBlock,toBlock:o.stateBlock,async getLogs({fromBlock:a,toBlock:s}){return br(e,{address:o.address,fromBlock:a,toBlock:s,tableId:hr.namespaces.store.tables.ResourceIds.tableId})}}),n=gr(t.flatMap(a=>a.logs)).map(a=>a.args.keyTuple[0]);return m("found",n.length,"resource IDs for",o.address),n}import{decodeValueArgs as xr,encodeKey as Cr,getKeySchema as Ar,getSchemaTypes as oo,getValueSchema as vr}from"@latticexyz/protocol-parser/internal";import{readContract as Sr}from"viem/actions";async function E({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Sr(e,{blockNumber:o.stateBlock,address:o.address,abi:C,functionName:"getRecord",args:[t.tableId,Cr(oo(Ar(t)),r)]});return xr(oo(vr(t)),{staticData:n,encodedLengths:a,dynamicData:s})}import{getAddress as Dr}from"viem";import{decodeKey as Tr,getKeySchema as kr,getSchemaTypes as Pr}from"@latticexyz/protocol-parser/internal";import ue from"@latticexyz/world/mud.config";import{fetchBlockLogs as Mr}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as Br,getStoreLogs as Or}from"@latticexyz/store/internal";async function ne({client:e,worldDeploy:o}){m("looking up resource access for",o.address);let t=await Mr({fromBlock:o.deployBlock,toBlock:o.stateBlock,async getLogs({fromBlock:s,toBlock:i}){return Or(e,{address:o.address,fromBlock:s,toBlock:i,tableId:ue.namespaces.world.tables.ResourceAccess.tableId})}}),n=Br(t.flatMap(s=>s.logs)).map(s=>Tr(Pr(kr(ue.namespaces.world.tables.ResourceAccess)),s.args.keyTuple)),a=(await Promise.all(n.map(async s=>[s,await E({client:e,worldDeploy:o,table:ue.namespaces.world.tables.ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Dr(s.caller)}));return m("found",a.length,"resource<>address access pairs"),a}import Rr from"@latticexyz/world/mud.config";async function to({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([re({client:e,worldDeploy:o}),Hr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock}),ne({client:e,worldDeploy:o})]),a=t.map(Wr).filter(s=>s.type==="system");return m("looking up systems:",a.map(Ir).join(", ")),await Promise.all(a.map(async s=>{let{system:i,publicAccess:c}=await E({client:e,worldDeploy:o,table:Rr.namespaces.world.tables.Systems,key:{systemId:s.resourceId}}),l=r.filter(f=>f.systemId===s.resourceId);return{address:i,namespace:s.namespace,name:s.name,systemId:s.resourceId,allowAll:c,allowedAddresses:n.filter(({resourceId:f})=>f===s.resourceId).map(({address:f})=>f),worldFunctions:l}}))}import be from"p-retry";async function ro({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n}){let[a,s]=await Promise.all([to({client:e,worldDeploy:r}),ne({client:e,worldDeploy:r})]),i=n.filter(p=>a.some(h=>h.systemId===p.systemId&&W(h.address)===W(p.prepareDeploy(o,t).address)));i.length&&m("existing systems:",i.map(J).join(", "));let c=i.map(p=>p.systemId),l=n.filter(p=>!c.includes(p.systemId));if(!l.length)return[];let f=l.filter(p=>a.some(h=>h.systemId===p.systemId&&W(h.address)!==W(p.prepareDeploy(o,t).address)));f.length&&m("upgrading systems:",f.map(J).join(", "));let d=l.filter(p=>!a.some(h=>h.systemId===p.systemId));d.length&&m("registering new systems:",d.map(J).join(", ")),await T({client:e,deployerAddress:o,contracts:l.map(p=>({bytecode:p.prepareDeploy(o,t).bytecode,deployedBytecodeSize:p.deployedBytecodeSize,debugLabel:`${J(p)} system`}))});let y=await Promise.all(l.map(p=>be(()=>ge(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"registerSystem",args:[p.systemId,p.prepareDeploy(o,t).address,p.allowAll]}),{retries:3,onFailedAttempt:()=>m(`failed to register system ${J(p)}, retrying...`)}))),b=n.map(p=>p.systemId),w=s.filter(({resourceId:p})=>b.includes(p)),v=[...n.flatMap(p=>p.allowedAddresses.map(h=>({resourceId:p.systemId,address:h}))),...n.flatMap(p=>p.allowedSystemIds.map(h=>({resourceId:p.systemId,address:a.find(k=>k.systemId===h)?.address??n.find(k=>k.systemId===h)?.prepareDeploy(o,t).address})).filter(h=>h.address!=null))],S=v.filter(p=>!w.some(({resourceId:h,address:k})=>h===p.resourceId&&W(k)===W(p.address))),g=w.filter(p=>!v.some(({resourceId:h,address:k})=>h===p.resourceId&&W(k)===W(p.address)));g.length&&m("revoking",g.length,"access grants"),S.length&&m("adding",S.length,"access grants");let A=await Promise.all([...g.map(p=>be(()=>ge(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"revokeAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:()=>m("failed to revoke access, retrying...")})),...S.map(p=>be(()=>ge(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"grantAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:()=>m("failed to grant access, retrying...")}))]);return[...y,...A]}import{getAddress as jr,parseAbi as $r}from"viem";import{getBlock as he}from"viem/actions";import{fetchBlockLogs as Lr}from"@latticexyz/block-logs-stream";var no=new Map;async function so(e,o){let t=jr(o),r=no.get(t);if(r!=null)return{...r,stateBlock:(await he(e,{blockTag:"latest"})).number};m("looking up world deploy for",t);let[n,a]=await Promise.all([he(e,{blockTag:"earliest"}),he(e,{blockTag:"latest"})]),s=await Lr({publicClient:e,address:t,events:$r(ee),fromBlock:n.number,toBlock:a.number,maxBlockRange:100000n});return r={...L(s.flatMap(i=>i.logs)),stateBlock:a.number},no.set(t,r),m("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as Er,writeContract as Fr}from"@latticexyz/common";import{getFunctions as zr}from"@latticexyz/world/internal";import Nr from"p-retry";async function ao({client:e,worldDeploy:o,functions:t}){let r=await zr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock}),n=Object.fromEntries(r.map(i=>[i.selector,i])),a=t.filter(i=>n[i.selector]),s=t.filter(i=>!a.includes(i));if(a.length){m("functions already registered:",a.map(c=>c.signature).join(", "));let i=a.filter(c=>c.systemId!==n[c.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(c=>c.signature).join(", "))}return s.length?(m("registering functions:",s.map(i=>i.signature).join(", ")),Promise.all(s.map(i=>{let{namespace:c}=Er(i.systemId),l=c===""?{functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]};return Nr(()=>Fr(e,{chain:e.chain??null,address:o.address,abi:C,...l}),{retries:3,onFailedAttempt:()=>m(`failed to register function ${i.signature}, retrying...`)})}))):[]}import{BaseError as Vr}from"viem";import{writeContract as Ur}from"@latticexyz/common";import{isDefined as _r}from"@latticexyz/common/utils";import Kr from"p-retry";async function se({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await T({client:e,deployerAddress:o,contracts:n.map(a=>({bytecode:a.prepareDeploy(o,t).bytecode,deployedBytecodeSize:a.deployedBytecodeSize,debugLabel:`${a.name} module`}))}),m("installing modules:",n.map(a=>a.name).join(", ")),(await Promise.all(n.map(a=>Kr(async()=>{try{let s=[...C,...a.abi],i=a.prepareDeploy(o,t).address,c=a.installAsRoot?{functionName:"installRootModule",args:[i,a.installData]}:{functionName:"installModule",args:[i,a.installData]};return await Ur(e,{chain:e.chain??null,address:r.address,abi:s,...c})}catch(s){if(s instanceof Vr&&s.message.includes("Module_AlreadyInstalled")){m(`module ${a.name} already installed`);return}if(a.optional){m(`optional module ${a.name} install failed, skipping`),m(s);return}throw s}},{retries:3,onFailedAttempt:()=>m(`failed to install module ${a.name}, retrying...`)})))).filter(_r)):[]}import{getAddress as io}from"viem";import{hexToResource as lo,resourceToHex as co,writeContract as Jr}from"@latticexyz/common";import qr from"@latticexyz/world/mud.config";async function mo({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(d=>lo(d).namespace))),n=await re({client:e,worldDeploy:o}),a=new Set(n.map(d=>lo(d).namespace));a.size&&m("found",a.size,"existing namespaces:",Array.from(a).map(d=>d===""?"<root>":d).join(", "));let s=r.filter(d=>a.has(d)),c=(await Promise.all(s.map(async d=>{let{owner:y}=await E({client:e,worldDeploy:o,table:qr.namespaces.world.tables.NamespaceOwner,key:{namespaceId:co({type:"namespace",namespace:d,name:""})}});return[d,y]}))).filter(([,d])=>io(d)!==io(e.account.address)).map(([d])=>d);if(c.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${c.join(", ")}`);let l=r.filter(d=>!a.has(d));return l.length>0&&m("registering namespaces:",Array.from(l).join(", ")),Promise.all(l.map(d=>Jr(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerNamespace",args:[co({namespace:d,type:"namespace",name:""})]})))}import{resourceToHex as Cn,resourceToLabel as An}from"@latticexyz/common";import{randomBytes as vn}from"crypto";import{stringToHex as uo,BaseError as an}from"viem";import{hexToResource as dn,writeContract as ln}from"@latticexyz/common";import{identity as cn,isDefined as go}from"@latticexyz/common/utils";import mn from"@latticexyz/world-module-metadata/mud.config";import pn from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import{decodeValueArgs as Yr,getKeyTuple as Gr,getSchemaTypes as Qr,getValueSchema as Zr}from"@latticexyz/protocol-parser/internal";import{readContract as Xr}from"viem/actions";import{mapObject as en}from"@latticexyz/common/utils";async function po({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Xr(e,{blockNumber:o.stateBlock,address:o.address,abi:C,functionName:"getRecord",args:[t.tableId,Gr(t,r)]}),i={...r,...Yr(Qr(Zr(t)),{staticData:n,encodedLengths:a,dynamicData:s})};return en(t.schema,(c,l)=>i[l])}import fn from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as on,size as tn}from"viem";function ae(e){return Object.entries(e).flatMap(([o,t])=>Object.entries(t).flatMap(([r,n])=>n.map(a=>({path:o,name:r,start:a.start,length:a.length}))))}import{z as O}from"zod";import{Abi as rn}from"abitype/zod";var fo=O.object({object:O.string().refine(on),linkReferences:O.record(O.record(O.array(O.object({start:O.number(),length:O.number()}))))}),nn=O.object({bytecode:fo,deployedBytecode:fo,abi:rn});function ie(e){let o=nn.parse(e),t=ae(o.bytecode.linkReferences);return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:tn(o.deployedBytecode.object)}}import{spliceHex as sn}from"@latticexyz/common";import{getCreate2Address as yo}from"viem";function R(e,o){return function(r,n){let a=e;if(o.length===0)return{bytecode:a,address:yo({from:r,bytecode:a,salt:x})};if(!n)throw new Error("Libraries must be provided if there are placeholders");for(let s of o){let i=n.getAddress({name:s.name,path:s.path,deployer:r});a=sn(a,s.start,s.length,i)}return{bytecode:a,address:yo({from:r,bytecode:a,salt:x})}}}var de=ie(fn);async function bo({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:a=cn}){let s=(await Promise.all(n.map(async c=>{let{value:l}=await po({client:e,worldDeploy:r,table:mn.tables.metadata__ResourceTag,key:{resource:c.resourceId,tag:uo(c.tag,{size:32})}});if(l!==a(c.value))return c}))).filter(go);if(s.length===0)return[];let i=await se({client:e,deployerAddress:o,worldDeploy:r,libraryMap:t,modules:[{optional:!0,name:"MetadataModule",installAsRoot:!1,installData:"0x",prepareDeploy:R(de.bytecode,de.placeholders),deployedBytecodeSize:de.deployedBytecodeSize,abi:de.abi}]});return await P({client:e,hashes:i,debugLabel:"metadata module installation"}),m("setting",s.length,"resource tags"),(await Promise.all(s.map(async c=>{let l=dn(c.resourceId),f=`${l.type}:${l.namespace}:${l.name}`;m(`tagging ${f} with ${c.tag}: ${JSON.stringify(c.value)}`);try{return await ln(e,{chain:e.chain??null,address:r.address,abi:pn,functionName:"metadata__setResourceTag",args:[c.resourceId,uo(c.tag,{size:32}),a(c.value)]})}catch(d){m(`failed to set resource tag for ${f}, skipping
14
+ ${d instanceof an?d.shortMessage:d}`)}}))).filter(go)}import{concatHex as yn,encodeDeployData as un,getCreate2Address as gn,isHex as wo}from"viem";import{waitForTransactionReceipt as bn}from"viem/actions";import{resourceToHex as hn,sendTransaction as wn,writeContract as ho}from"@latticexyz/common";function xe(e,o){let t=o.find(r=>r.sourcePath===e.sourcePath&&r.name===e.name);if(!t)throw new Error(`Could not find referenced artifact at "${e.sourcePath}:${e.name}".`);return t}function xo(e,o){return e.bytecode.filter(t=>!wo(t)).flatMap(t=>xo(xe(t,o),o))}function we(e,o,t){return yn(o.bytecode.map(r=>wo(r)?r:gn({from:e,salt:x,bytecode:we(e,xe(r,t),t)})))}async function Co({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=$(o);await T({client:e,deployerAddress:o,contracts:Object.values(n)});let a=xe(r,t),s=xo(a,t);s.length&&(m(`deploying ${s.length} world dependencies`),await T({client:e,deployerAddress:o,contracts:s.map(y=>we(o,y,t)).reverse().map(y=>({bytecode:y}))})),m("deploying custom world");let i=await wn(e,{chain:e.chain??null,data:un({abi:a.abi,args:[],bytecode:we(o,a,t)})});m("waiting for custom world deploy");let c=await bn(e,{hash:i});if(c.status!=="success")throw console.error("world deploy failed",c),new Error("world deploy failed");let l=L(c.logs);m("deployed custom world to",l.address,"at block",l.deployBlock);let f=await ho(e,{chain:e.chain??null,address:l.address,abi:C,functionName:"initialize",args:[n.InitModule.address]});await P({client:e,hashes:[f],debugLabel:"world init"});let d=await ho(e,{chain:e.chain??null,address:l.address,abi:C,functionName:"transferOwnership",args:[hn({type:"namespace",namespace:"",name:""}),e.account.address]});return await P({client:e,hashes:[d],debugLabel:"world ownership transfer"}),{...l,stateBlock:l.deployBlock}}import{uniqueBy as Sn}from"@latticexyz/common/utils";function Ao({path:e,name:o}){return`${e}:${o}`}function vo(e){let o=Object.fromEntries(e.map(r=>[Ao(r),r])),t={getAddress:({path:r,name:n,deployer:a})=>{let s=o[Ao({path:r,name:n})];if(!s)throw new Error(`Could not find library for bytecode placeholder ${r}:${n}`);return s.address??={},s.address[a]??=s.prepareDeploy(a,t).address,s.address[a]}};return t}async function So({config:e,client:o,tables:t,systems:r,libraries:n,modules:a=[],artifacts:s,salt:i,worldAddress:c,deployerAddress:l}){let f=l??await He(o),d=c?await so(o,c):e.deploy.customWorld?await Co({client:o,deployerAddress:f,artifacts:s,customWorld:e.deploy.customWorld}):await Je(o,f,i??`0x${vn(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation);if(!Re.includes(d.storeVersion))throw new Error(`Unsupported Store version: ${d.storeVersion}`);if(!je.includes(d.worldVersion))throw new Error(`Unsupported World version: ${d.worldVersion}`);let y=vo(n);await T({client:o,deployerAddress:f,contracts:[...n.map(u=>({bytecode:u.prepareDeploy(f,y).bytecode,deployedBytecodeSize:u.deployedBytecodeSize,debugLabel:`${u.path}:${u.name} library`})),...r.map(u=>({bytecode:u.prepareDeploy(f,y).bytecode,deployedBytecodeSize:u.deployedBytecodeSize,debugLabel:`${An(u)} system`})),...a.map(u=>({bytecode:u.prepareDeploy(f,y).bytecode,deployedBytecodeSize:u.deployedBytecodeSize,debugLabel:`${u.name} module`}))]});let b=await mo({client:o,worldDeploy:d,resourceIds:[...t.map(({tableId:u})=>u),...r.map(({systemId:u})=>u)]});await P({client:o,hashes:b,debugLabel:"namespace registrations"});let w=await eo({client:o,worldDeploy:d,tables:t}),v=await ro({client:o,deployerAddress:f,libraryMap:y,worldDeploy:d,systems:r});await P({client:o,hashes:[...w,...v],debugLabel:"table and system registrations"});let S=await ao({client:o,worldDeploy:d,functions:r.flatMap(u=>u.worldFunctions)}),g=await se({client:o,deployerAddress:f,libraryMap:y,worldDeploy:d,modules:a}),A=Sn([...t,...r].filter(({namespace:u,namespaceLabel:B})=>B!==u).map(({namespace:u,namespaceLabel:B})=>({resourceId:Cn({type:"namespace",namespace:u,name:""}),tag:"label",value:B})),u=>u.resourceId),p=t.filter(u=>u.label!==u.name).map(({tableId:u,label:B})=>({resourceId:u,tag:"label",value:B})),h=r.flatMap(({name:u,systemId:B,label:Te,abi:Zo,worldAbi:Xo})=>[...Te!==u?[{resourceId:B,tag:"label",value:Te}]:[],{resourceId:B,tag:"abi",value:Zo.join(`
15
+ `)},{resourceId:B,tag:"worldAbi",value:Xo.join(`
16
+ `)}]),k=await bo({client:o,deployerAddress:f,libraryMap:y,worldDeploy:d,tags:[...A,...p,...h],valueToHex:xn});return await P({client:o,hashes:[...S,...g,...k],debugLabel:"remaining transactions"}),m("deploy complete"),d}import{createWalletClient as es,http as os,isHex as ts}from"viem";import{privateKeyToAccount as rs}from"viem/accounts";import{loadConfig as ns,resolveConfigPath as ss}from"@latticexyz/config/node";import{getOutDirectory as as,getRpcUrl as is}from"@latticexyz/common/foundry";import z from"chalk";import{MUDError as Ae}from"@latticexyz/common/errors";import On from"path";import{loadSystemsManifest as Wn,resolveSystems as In}from"@latticexyz/world/node";import{isHex as ko,toFunctionSelector as Po,toFunctionSignature as Mo}from"viem";import{readFileSync as Dn}from"fs";import Tn from"path";import{MUDError as le}from"@latticexyz/common/errors";import{size as kn}from"viem";function F(e,o,t){let r,n=Tn.join(t,e,o+".json");try{r=JSON.parse(Dn(n,"utf8"))}catch{throw new le(`Error reading file at ${n}`)}let a=r?.bytecode?.object;if(!a)throw new le(`No bytecode found in ${n}`);let s=r?.deployedBytecode?.object;if(!s)throw new le(`No deployed bytecode found in ${n}`);let i=r?.abi;if(!i)throw new le(`No ABI found in ${n}`);let c=ae(r?.bytecode?.linkReferences??{});return{abi:i,bytecode:a,placeholders:c,deployedBytecodeSize:kn(s)}}import{groupBy as Hn}from"@latticexyz/common/utils";import{readFileSync as Mn}from"fs";import{globSync as Bn}from"glob";import Pn from"toposort";function Do(e,o,t){let r=Pn(e.flatMap(n=>t(n).map(a=>[o(n),a])));return[...e].sort((n,a)=>r.indexOf(o(n))-r.indexOf(o(a)))}function To(e){let t=Bn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(Mn(r,"utf8"))).flatMap(r=>{if(!r.metadata)return[];let n=Object.keys(r.metadata.settings.compilationTarget)[0],a=r.metadata.settings.compilationTarget[n],s=r.bytecode.linkReferences;return Object.entries(s).flatMap(([i,c])=>Object.keys(c).map(l=>({path:i,name:l,dependentPath:n,dependentName:a})))});return Do(t,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}async function Bo({rootDir:e,config:o,forgeOutDir:t}){let r=To(t).map(d=>{let y=F(On.basename(d.path),d.name,t);return{path:d.path,name:d.name,abi:y.abi,prepareDeploy:R(y.bytecode,y.placeholders),deployedBytecodeSize:y.deployedBytecodeSize}}),a=F("System.sol","System",t).abi.filter(d=>d.type==="function").map(Mo),s=await In({rootDir:e,config:o}),i=await Wn({rootDir:e,config:o}),c=s.filter(d=>!d.deploy.disabled).map(d=>{let y=i.systems.find(({systemId:g})=>g===d.systemId);if(!y)throw new Error(`System "${d.label}" not found in systems manifest. Run \`mud build\` before trying again.`);let b=F(`${d.label}.sol`,d.label,t),w=d.deploy.registerWorldFunctions?b.abi.filter(g=>g.type==="function").map(Mo).filter(g=>!a.includes(g)).map(g=>{let A=d.namespace===""?g:`${d.namespace}__${g}`;return{signature:A,selector:Po(A),systemId:d.systemId,systemFunctionSignature:g,systemFunctionSelector:Po(g)}}):[],v=d.accessList.filter(g=>ko(g)),S=d.accessList.filter(g=>!ko(g)).map(g=>s.find(p=>p.label===g).systemId);return{...d,allowAll:d.openAccess,allowedAddresses:v,allowedSystemIds:S,prepareDeploy:R(b.bytecode,b.placeholders),deployedBytecodeSize:b.deployedBytecodeSize,worldFunctions:w,abi:y.abi,worldAbi:y.worldAbi}}),l=Hn(c,d=>d.systemId),f=Array.from(l.values()).filter(d=>d.length>1).flat();if(f.length){let d=f.map(y=>y.name);throw new Error(`Found systems with overlapping system ID: ${d.join(", ")}.
17
+
18
+ System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}return{systems:c,libraries:r}}import{getChainId as ds}from"viem/actions";import{existsSync as Rn}from"fs";import jn from"path";import $n from"chalk";import{getScriptDirectory as Ln,forge as En}from"@latticexyz/common/foundry";async function Oo(e,o,t,r,n,a){let s=n?.replaceAll("\\","").split(" ")??[],i=jn.join(await Ln(),e+".s.sol");if(!Rn(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log($n.blue(`Executing post deploy script at ${i}`)),await En(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",a?"--aws":"",...s],{profile:r})}import{kmsKeyToAccount as ls}from"@latticexyz/common/kms";import Io from"node:path";import{encodeField as Nn}from"@latticexyz/protocol-parser/internal";import{bytesToHex as Vn}from"viem";import{createRequire as Fn}from"node:module";import{findUp as zn}from"find-up";async function Wo({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await zn("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=Fn(r)(o)}catch(r){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),r}return ie(t)}import{resolveWithContext as Un}from"@latticexyz/world/internal";var _n={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"};async function ce(e,o){return await Promise.all(e.modules.map(async r=>{let n=r.artifactPath;if(!n)if(r.name)n=_n[r.name]??Io.join(o,`${r.name}.sol`,`${r.name}.json`),console.warn(["","\u26A0\uFE0F Your `mud.config.ts` is using a module with a `name`, but this option is deprecated.","","To resolve this, you can replace this:","",` name: ${JSON.stringify(r.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(n)}`,""].join(`
19
+ `));else throw new Error("No `artifactPath` provided for module.");let a=Io.basename(n,".json"),s=await Wo({artifactPath:n}),i=r.args.map(c=>Un(c,{config:e})).map(c=>{let l=c.value instanceof Uint8Array?Vn(c.value):c.value;return Nn(c.type,l)});if(i.length>1)throw new Error(`${a} module should only have 0-1 args, but had ${i.length} args.`);return{name:a,installAsRoot:r.root,installData:i.length===0?"0x":i[0],prepareDeploy:R(s.bytecode,s.placeholders),deployedBytecodeSize:s.deployedBytecodeSize,abi:s.abi}}))}import{findContractArtifacts as cs}from"@latticexyz/world/node";import{getAutomine as Kn,getBlock as Ho,setAutomine as Jn,setIntervalMining as qn}from"viem/actions";import{getAction as q}from"viem/utils";async function jo(e){let o=await Yn(e).catch(()=>{});if(!(!o||o.type==="automine"))return H("Enabling automine"),await Ro(e,{type:"automine"}),{reset:()=>(H("Disabling automine"),Ro(e,o))}}async function Yn(e){let o={mode:"anvil",...e};return await q(o,Kn,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await Gn(e)}}async function Ro(e,o){o.type==="automine"?await q(e,Jn,"setAutomine")(!0):await q(e,qn,"setIntervalMining")({interval:o.blockTime})}async function Gn(e){let o=await q(e,Ho,"getBlock")({blockTag:"latest"}),t=await q(e,Ho,"getBlock")({blockNumber:o.number-1n}),r=o.timestamp-t.timestamp;return Number(r)}var M={configPath:{type:"string",desc:"Path to the MUD config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."},forgeScriptOptions:{type:"string",description:"Options to pass to forge script PostDeploy.s.sol"},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."},kms:{type:"boolean",desc:"Deploy the World with an AWS KMS key instead of local private key."}};async function N(e){let o=e.salt;if(o!=null&&!ts(o))throw new Ae("Expected hex string for salt");let t=e.profile??process.env.FOUNDRY_PROFILE,r=await ss(e.configPath),n=await ns(r),a=me.dirname(r);e.printConfig&&console.log(z.green(`
20
+ Resolved config:
21
+ `),JSON.stringify(n,null,2));let s=await as(t),i=e.rpc??await is(t);console.log(z.bgBlue(z.whiteBright(`
22
+ Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
23
+ `))),e.skipBuild||await Q({rootDir:a,config:n,foundryProfile:t});let{systems:c,libraries:l}=await Bo({rootDir:a,config:n,forgeOutDir:s}),f=await cs({forgeOutDir:s}),d=await ce(n,s),y=Object.values(n.namespaces).flatMap(p=>Object.values(p.tables)).filter(p=>!p.deploy.disabled),b=await(async()=>{if(e.kms){let p=process.env.AWS_KMS_KEY_ID;if(!p)throw new Ae("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await ls({keyId:p})}else{let p=process.env.PRIVATE_KEY;if(!p)throw new Ae(`Missing PRIVATE_KEY environment variable.
24
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
25
+ in your contracts directory to use the default anvil private key.`);return rs(p)}})(),w=es({transport:os(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:b});console.log("Deploying from",w.account.address);let v=await jo(w),S=Date.now(),g=await So({config:n,deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:w,tables:y,systems:c,libraries:l,modules:d,artifacts:f});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await Oo(n.deploy.postDeployScript,g.address,i,t,e.forgeScriptOptions,!!e.kms),await v?.reset(),console.log(z.green("Deployment completed in",(Date.now()-S)/1e3,"seconds"));let A={worldAddress:g.address,blockNumber:Number(g.deployBlock)};if(e.saveDeployment){let p=await ds(w),h=me.join(n.deploy.deploysDirectory,p.toString());Zn(h,{recursive:!0}),Ce(me.join(h,"latest.json"),JSON.stringify(A,null,2)),Ce(me.join(h,Date.now()+".json"),JSON.stringify(A,null,2));let k=[1337,31337],u=Qn(n.deploy.worldsFile)?JSON.parse(Xn(n.deploy.worldsFile,"utf-8")):{};u[p]={address:A.worldAddress,blockNumber:k.includes(p)?void 0:A.blockNumber},Ce(n.deploy.worldsFile,JSON.stringify(u,null,2)),console.log(z.bgGreen(z.whiteBright(`
26
+ Deployment result (written to ${n.deploy.worldsFile} and ${h}):
27
+ `)))}return console.log(A),g}var ms={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await N(e)}catch(o){G(o),process.exit(1)}process.exit(0)}},$o=ms;import ps from"node:path";import{loadConfig as fs,resolveConfigPath as ys}from"@latticexyz/config/node";import{worldgen as us}from"@latticexyz/world/node";var gs={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 bs(e),process.exit(0)}};async function bs(e){let o=await ys(e.configPath),t=await fs(o),r=ps.dirname(o);await us({rootDir:r,config:t,clean:e.clean})}var Lo=gs;import Y from"chalk";import{readFileSync as As,writeFileSync as vs}from"fs";import Se from"path";import{MUDError as V}from"@latticexyz/common/errors";var Eo={name:"@latticexyz/cli",version:"2.2.10",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},typesVersions:{"*":{index:["./dist/index.d.ts"]}},bin:{mud:"./bin/mud.js"},files:["bin","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":"shx rm -rf dist","clean:test-tables":"shx rm -rf src/**/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ark/util":"catalog:","@aws-sdk/client-kms":"^3.556.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/block-logs-stream":"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:*","@latticexyz/world-module-metadata":"workspace:*",abitype:"catalog:","asn1.js":"^5.4.1",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",execa:"^7.0.0","find-up":"^6.3.0",glob:"^10.4.2",openurl:"^1.1.1","p-queue":"^7.4.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",toposort:"^2.0.2",typescript:"5.4.2",viem:"catalog:",yargs:"^17.7.1",zod:"3.23.8","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/toposort":"^2.0.6","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.34.6"}};import{globSync as Ss}from"glob";import{ZodError as ws,z as Fo}from"zod";var xs=Fo.object({MUD_PACKAGES:Fo.string().transform(e=>JSON.parse(e))});function Cs(){try{return xs.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/explorer":{"localPath":"packages/explorer"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@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/stash":{"localPath":"packages/stash"},"@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-module-metadata":{"localPath":"packages/world-module-metadata"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof ws){let{...o}=e.format();console.error(`
28
+ Missing or invalid environment variables:
29
+
30
+ ${Object.keys(o).join(`
31
+ `)}
32
+ `),process.exit(1)}throw e}}var ve=Cs().MUD_PACKAGES;var Ds={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"],t=o.reduce((n,a)=>e[a]?n+1:n,0);if(t===0)throw new V(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new V(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Ts(e));let r=Ss("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)ks(n,e)}catch(o){G(o)}finally{process.exit(0)}}};async function Ts(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(Y.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Eo.name}`)).json()}catch{throw new V("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new V(`Could not find npm version with tag "${e.tag}"`);return console.log(Y.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new V(`Could not find npm version based on commit "${e.commit}"`);return console.log(Y.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function ks(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ps(e),a=Object.keys(ve),s={};for(let l in n.dependencies)a.includes(l)&&(s[l]=n.dependencies[l]);let i={};for(let l in n.devDependencies)a.includes(l)&&(i[l]=n.devDependencies[l]);for(let l in n.dependencies)a.includes(l)&&(n.dependencies[l]=c(l,"dependencies"));for(let l in n.devDependencies)a.includes(l)&&(n.devDependencies[l]=c(l,"devDependencies"));return vs(e,JSON.stringify(n,null,2)+`
33
+ `),console.log(`Updating ${e}`),zo(s,n.dependencies),zo(i,n.devDependencies),n;function c(l,f){return t&&(r=Ms(e,t,l)),r||n[f][l]}}function Ps(e){try{let o=As(e,"utf8");return JSON.parse(o)}catch{throw new V("Could not read JSON at "+e)}}function zo(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${Y.red(e[t])} -> ${Y.green(o[t])}`)}function Ms(e,o,t){let r=Se.relative(Se.dirname(e),process.cwd());return"link:"+Se.join(r,o,ve[t].localPath)}var No=Ds;import{anvil as Bs,forge as Os,getRpcUrl as Ws}from"@latticexyz/common/foundry";import Is from"chalk";var Hs={...M,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(Hs)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Bs(n)}let o=e.worldAddress?await Ws(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await N({...e,saveDeployment:!1,rpc:o})).address;console.log(Is.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Os(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},Vo=Rs;import js from"node:path";import Uo from"node:fs";import{loadConfig as $s,resolveConfigPath as Ls}from"@latticexyz/config/node";import{MUDError as _o}from"@latticexyz/common/errors";import{cast as Es,getRpcUrl as Fs}from"@latticexyz/common/foundry";import zs from"@latticexyz/world/mud.config";import{createClient as Ns,http as Vs}from"viem";import{getChainId as Us,readContract as _s}from"viem/actions";import{resolveSystems as Ks}from"@latticexyz/world/node";var Js=zs.namespaces.world.tables.Systems.tableId;function qs(e,o){if(!Uo.existsSync(e))throw new _o(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(Uo.readFileSync(e,"utf-8"));if(!t[o])throw new _o(`Missing chain ID ${o} in "${e}"`);return t[o].address}var Ys={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the MUD config file"},profile:{type:"string",description:"The foundry profile to use"},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){let o=await Ls(e.configPath),t=js.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await Fs(r),a=await $s(o),s=Ns({transport:Vs(n)}),i=await Us(s),c=e.worldAddress??qs(a.deploy.worldsFile,i),l=await Ks({rootDir:t,config:a}),f=await Promise.all(l.map(async y=>({label:y.label,address:await _s(s,{abi:C,address:c,functionName:"getField",args:[Js,[y.systemId],0]})}))),d=await Es(["run","--label",`${c}:World`,...f.map(({label:y,address:b})=>["--label",`${b}:${y}`]).flat(),`${e.tx}`]);console.log(d),process.exit(0)}},Ko=Ys;import{anvil as Gs,getScriptDirectory as Qs,getSrcDirectory as Zs}from"@latticexyz/common/foundry";import I from"chalk";import Xs from"chokidar";import{loadConfig as ea,resolveConfigPath as oa}from"@latticexyz/config/node";import ta from"path";import{homedir as ra}from"os";import{rmSync as na}from"fs";import{BehaviorSubject as sa,debounceTime as aa,exhaustMap as ia,filter as da}from"rxjs";import{isDefined as la}from"@latticexyz/common/utils";var ca={rpc:M.rpc,configPath:M.configPath,alwaysRunPostDeploy:M.alwaysRunPostDeploy,forgeScriptOptions:M.forgeScriptOptions,worldAddress:M.worldAddress},ma={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ca)},async handler(e){let o=e.rpc,t=e.configPath??await oa(e.configPath),r=await Zs(),n=await Qs(),a=await ea(t);if(!e.rpc){console.log(I.gray("Cleaning devnode cache"));let l=ra();na(ta.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Gs(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let s=new sa(Date.now());Xs.watch([t,r,n],{ignoreInitial:!0}).on("all",async(l,f)=>{f.includes(t)&&(console.log(I.blue("Config changed, queuing deploy\u2026")),s.next(Date.now())),(f.includes(r)||f.includes(n))&&(f.includes(a.codegen.outputDirectory)||(console.log(I.blue("Contracts changed, queuing deploy\u2026")),s.next(Date.now())))});let i=e.worldAddress;s.pipe(aa(200),ia(async l=>{i&&console.log(I.blue("Rebuilding and upgrading world\u2026"));try{let f=await N({...e,configPath:t,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:i,salt:"0x",kms:void 0});return i=f.address,l<s.value?s.next(s.value):console.log(I.gray(`
34
+ Waiting for file changes\u2026
35
+ `)),f}catch(f){console.error(I.bgRed(I.whiteBright(`
36
+ Error while attempting deploy
37
+ `))),console.error(f),console.log(I.gray(`
38
+ Waiting for file changes\u2026
39
+ `))}}),da(la)).subscribe()}},Jo=ma;import{getCreate2Address as qo,sliceHex as fa,zeroHash as ya}from"viem";import{forge as pa}from"@latticexyz/common/foundry";async function j(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 pa(o,{cwd:e.cwd})}import ua from"p-queue";import{MUDError as ga}from"@latticexyz/common/errors";import{getStorageAt as ba}from"viem/actions";import{execa as De}from"execa";var ha="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function Yo({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:a,verifier:s,verifierUrl:i}){let c=a??await X(e);if(!c)throw new ga("No deployer address provided or found.");let l=await ba(e,{address:n,slot:ha}),f=l&&l!==ya,d=new ua({concurrency:4});if(t.map(({name:y,bytecode:b})=>d.add(()=>j({name:y,rpc:o,verifier:s,verifierUrl:i,address:qo({from:c,bytecode:b,salt:x})}).catch(w=>{console.error(`Error verifying system contract ${y}:`,w)}))),s==="sourcify")if(await De("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await De("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await De("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(f?te(c):oe(c)).map(([y,{bytecode:b}])=>d.add(()=>j({cwd:"node_modules/@latticexyz/world",name:y,rpc:o,verifier:s,verifierUrl:i,address:qo({from:c,bytecode:b,salt:x})}).catch(w=>{console.error(`Error verifying world factory contract ${y}:`,w)}))),r.map(({name:y,prepareDeploy:b})=>{let{address:w}=b(c);return d.add(()=>j({cwd:"node_modules/@latticexyz/world-modules",name:y,rpc:o,verifier:s,verifierUrl:i,address:w}).catch(v=>{console.error(`Error verifying module contract ${y}:`,v)}))}),f){let y=fa(l,-20);d.add(()=>j({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(b=>{console.error("Error verifying WorldProxy contract:",b)})),d.add(()=>j({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:y}).catch(b=>{console.error("Error verifying World contract:",b)}))}else d.add(()=>j({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(y=>{console.error("Error verifying World contract:",y)}));else console.log(""),console.log(`Note: MUD is currently unable to verify store, world, and world-modules contracts with ${s}. We are planning to expand support in a future version.`),console.log("")}import{loadConfig as wa,resolveConfigPath as xa}from"@latticexyz/config/node";import{resolveSystems as Ca}from"@latticexyz/world/node";import{getOutDirectory as Aa,getRpcUrl as va}from"@latticexyz/common/foundry";import{createWalletClient as Sa,http as Da}from"viem";import Go from"chalk";import Ta from"node:path";var ka={deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",required:!0,desc:"Verify an existing World at the given address"},configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},verifier:{type:"string",desc:"The verifier to use. Defaults to blockscout",default:"blockscout"},verifierUrl:{type:"string",desc:"The verification provider."}},Pa={command:"verify",describe:"Verify contracts",builder(e){return e.options(ka)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await xa(e.configPath),r=Ta.dirname(t),n=await wa(t),a=await Aa(o),s=e.rpc??await va(o);console.log(Go.bgBlue(Go.whiteBright(`
40
+ Verifying MUD contracts${o?" with profile "+o:""} to RPC ${s}
41
+ `)));let i=Sa({transport:Da(s,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await Ca({rootDir:r,config:n})).map(d=>{let y=F(`${d.name}.sol`,d.name,a);return{name:d.name,bytecode:y.bytecode}}),f=await ce(n,a);await Yo({client:i,rpc:s,systems:l,modules:f,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},Qo=Pa;var au=[ke,$o,Pe,Ma,Me,Be,Lo,No,Vo,Ko,Jo,Ba,Qo];export{au as commands};
42
+ //# sourceMappingURL=commands-VJP7PW7P.js.map