@latticexyz/cli 2.0.9-account-kit-e3d101f9 → 2.0.9-main-074ed66e

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