@latticexyz/cli 2.0.11-main-6f858726 → 2.0.11

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