@latticexyz/cli 2.0.8-not-npmignore-cache-2d3a1a18 → 2.0.8-not-npmignore-cache-a91bf9e0

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