@latticexyz/cli 2.0.7-main-375d902e → 2.0.7-main-fce741b0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ import type { CommandModule, InferredOptionTypes } from "yargs";
2
+ import { verify } from "../verify";
3
+ import { loadConfig } from "@latticexyz/config/node";
4
+ import { World as WorldConfig } from "@latticexyz/world";
5
+ import { resolveWorldConfig } from "@latticexyz/world/internal";
6
+ import { worldToV1 } from "@latticexyz/world/config/v2";
7
+ import { getOutDirectory, getRpcUrl, getSrcDirectory } from "@latticexyz/common/foundry";
8
+ import { getExistingContracts } from "../utils/getExistingContracts";
9
+ import { getContractData } from "../utils/getContractData";
10
+ import { defaultModuleContracts } from "../utils/defaultModuleContracts";
11
+ import { Hex, createWalletClient, http } from "viem";
12
+ import chalk from "chalk";
13
+
14
+ const verifyOptions = {
15
+ deployerAddress: {
16
+ type: "string",
17
+ desc: "Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)",
18
+ },
19
+ worldAddress: { type: "string", required: true, desc: "Verify an existing World at the given address" },
20
+ configPath: { type: "string", desc: "Path to the MUD config file" },
21
+ profile: { type: "string", desc: "The foundry profile to use" },
22
+ rpc: { type: "string", desc: "The RPC URL to use. Defaults to the RPC url from the local foundry.toml" },
23
+ rpcBatch: {
24
+ type: "boolean",
25
+ desc: "Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)",
26
+ },
27
+ srcDir: { type: "string", desc: "Source directory. Defaults to foundry src directory." },
28
+ verifier: { type: "string", desc: "The verifier to use" },
29
+ verifierUrl: {
30
+ type: "string",
31
+ desc: "The verification provider.",
32
+ },
33
+ } as const;
34
+
35
+ type Options = InferredOptionTypes<typeof verifyOptions>;
36
+
37
+ const commandModule: CommandModule<Options, Options> = {
38
+ command: "verify",
39
+
40
+ describe: "Verify contracts",
41
+
42
+ builder(yargs) {
43
+ return yargs.options(verifyOptions);
44
+ },
45
+
46
+ async handler(opts) {
47
+ const profile = opts.profile ?? process.env.FOUNDRY_PROFILE;
48
+
49
+ const configV2 = (await loadConfig(opts.configPath)) as WorldConfig;
50
+ const config = worldToV1(configV2);
51
+
52
+ const srcDir = opts.srcDir ?? (await getSrcDirectory(profile));
53
+ const outDir = await getOutDirectory(profile);
54
+
55
+ const rpc = opts.rpc ?? (await getRpcUrl(profile));
56
+ console.log(
57
+ chalk.bgBlue(
58
+ chalk.whiteBright(`\n Verifying MUD contracts${profile ? " with profile " + profile : ""} to RPC ${rpc} \n`),
59
+ ),
60
+ );
61
+
62
+ const client = createWalletClient({
63
+ transport: http(rpc, {
64
+ batch: opts.rpcBatch
65
+ ? {
66
+ batchSize: 100,
67
+ wait: 1000,
68
+ }
69
+ : undefined,
70
+ }),
71
+ });
72
+
73
+ const contractNames = getExistingContracts(srcDir).map(({ basename }) => basename);
74
+ const resolvedWorldConfig = resolveWorldConfig(config, contractNames);
75
+
76
+ const systems = Object.keys(resolvedWorldConfig.systems).map((name) => {
77
+ const contractData = getContractData(`${name}.sol`, name, outDir);
78
+
79
+ return {
80
+ name,
81
+ bytecode: contractData.bytecode,
82
+ };
83
+ });
84
+
85
+ // Get modules
86
+ const modules = config.modules.map((mod) => {
87
+ const contractData =
88
+ defaultModuleContracts.find((defaultMod) => defaultMod.name === mod.name) ??
89
+ getContractData(`${mod.name}.sol`, mod.name, outDir);
90
+
91
+ return {
92
+ name: mod.name,
93
+ bytecode: contractData.bytecode,
94
+ };
95
+ });
96
+
97
+ await verify({
98
+ client,
99
+ rpc,
100
+ foundryProfile: profile,
101
+ systems,
102
+ modules,
103
+ deployerAddress: opts.deployerAddress as Hex | undefined,
104
+ worldAddress: opts.worldAddress as Hex,
105
+ verifier: opts.verifier,
106
+ verifierUrl: opts.verifierUrl,
107
+ });
108
+ },
109
+ };
110
+
111
+ export default commandModule;
@@ -0,0 +1,24 @@
1
+ import { forge } from "@latticexyz/common/foundry";
2
+ import { Address } from "viem";
3
+
4
+ type VerifyContractOptions = {
5
+ name: string;
6
+ rpc: string;
7
+ verifier?: string;
8
+ verifierUrl?: string;
9
+ address: Address;
10
+ };
11
+
12
+ type ForgeOptions = { profile?: string; silent?: boolean; env?: NodeJS.ProcessEnv; cwd?: string };
13
+
14
+ export async function verifyContract(options: VerifyContractOptions, forgeOptions?: ForgeOptions) {
15
+ const args = ["verify-contract", options.address, options.name, "--rpc-url", options.rpc];
16
+
17
+ if (options.verifier) {
18
+ args.push("--verifier", options.verifier);
19
+ }
20
+ if (options.verifierUrl) {
21
+ args.push("--verifier-url", options.verifierUrl);
22
+ }
23
+ await forge(args, forgeOptions);
24
+ }
package/src/verify.ts ADDED
@@ -0,0 +1,166 @@
1
+ import { Chain, Client, Hex, Transport, getCreate2Address, sliceHex, zeroHash } from "viem";
2
+ import { getWorldFactoryContracts } from "./deploy/getWorldFactoryContracts";
3
+ import { verifyContract } from "./verify/verifyContract";
4
+ import PQueue from "p-queue";
5
+ import { getWorldProxyFactoryContracts } from "./deploy/getWorldProxyFactoryContracts";
6
+ import { getDeployer } from "./deploy/getDeployer";
7
+ import { MUDError } from "@latticexyz/common/errors";
8
+ import { salt } from "./deploy/common";
9
+ import { getStorageAt } from "viem/actions";
10
+
11
+ type VerifyOptions = {
12
+ client: Client<Transport, Chain | undefined>;
13
+ rpc: string;
14
+ foundryProfile?: string;
15
+ verifier?: string;
16
+ verifierUrl?: string;
17
+ systems: { name: string; bytecode: Hex }[];
18
+ modules: { name: string; bytecode: Hex }[];
19
+ worldAddress: Hex;
20
+ /**
21
+ * Address of determinstic deployment proxy: https://github.com/Arachnid/deterministic-deployment-proxy
22
+ * By default, we look for a deployment at 0x4e59b44847b379578588920ca78fbf26c0b4956c.
23
+ * If it is not deployed or the target chain does not support legacy transactions, the user must set the deployer manually.
24
+ */
25
+ deployerAddress?: Hex;
26
+ };
27
+
28
+ const ERC1967_IMPLEMENTATION_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";
29
+
30
+ export async function verify({
31
+ client,
32
+ rpc,
33
+ foundryProfile = process.env.FOUNDRY_PROFILE,
34
+ systems,
35
+ modules,
36
+ worldAddress,
37
+ deployerAddress: initialDeployerAddress,
38
+ verifier,
39
+ verifierUrl,
40
+ }: VerifyOptions): Promise<void> {
41
+ const deployerAddress = initialDeployerAddress ?? (await getDeployer(client));
42
+ if (!deployerAddress) {
43
+ throw new MUDError(`No deployer`);
44
+ }
45
+
46
+ // If the proxy implementation storage slot is set on the World, the World was deployed as a proxy.
47
+ const implementationStorage = await getStorageAt(client, {
48
+ address: worldAddress,
49
+ slot: ERC1967_IMPLEMENTATION_SLOT,
50
+ });
51
+ const usesProxy = implementationStorage && implementationStorage !== zeroHash;
52
+
53
+ const verifyQueue = new PQueue({ concurrency: 1 });
54
+
55
+ systems.map(({ name, bytecode }) =>
56
+ verifyQueue.add(() =>
57
+ verifyContract(
58
+ {
59
+ name,
60
+ rpc,
61
+ verifier,
62
+ verifierUrl,
63
+ address: getCreate2Address({
64
+ from: deployerAddress,
65
+ bytecode: bytecode,
66
+ salt,
67
+ }),
68
+ },
69
+ { profile: foundryProfile },
70
+ ).catch((error) => {
71
+ console.error(`Error verifying system contract ${name}:`, error);
72
+ }),
73
+ ),
74
+ );
75
+
76
+ Object.entries(
77
+ usesProxy ? getWorldProxyFactoryContracts(deployerAddress) : getWorldFactoryContracts(deployerAddress),
78
+ ).map(([name, { bytecode }]) =>
79
+ verifyQueue.add(() =>
80
+ verifyContract(
81
+ {
82
+ name,
83
+ rpc,
84
+ verifier,
85
+ verifierUrl,
86
+ address: getCreate2Address({
87
+ from: deployerAddress,
88
+ bytecode: bytecode,
89
+ salt,
90
+ }),
91
+ },
92
+ {
93
+ profile: foundryProfile,
94
+ cwd: "node_modules/@latticexyz/world",
95
+ },
96
+ ).catch((error) => {
97
+ console.error(`Error verifying world factory contract ${name}:`, error);
98
+ }),
99
+ ),
100
+ );
101
+
102
+ modules.map(({ name, bytecode }) =>
103
+ verifyQueue.add(() =>
104
+ verifyContract(
105
+ {
106
+ name: name,
107
+ rpc,
108
+ verifier,
109
+ verifierUrl,
110
+ address: getCreate2Address({
111
+ from: deployerAddress,
112
+ bytecode: bytecode,
113
+ salt,
114
+ }),
115
+ },
116
+ {
117
+ profile: foundryProfile,
118
+ cwd: "node_modules/@latticexyz/world-modules",
119
+ },
120
+ ).catch((error) => {
121
+ console.error(`Error verifying module contract ${name}:`, error);
122
+ }),
123
+ ),
124
+ );
125
+
126
+ // If the world was deployed as a Proxy, verify the proxy and implementation.
127
+ if (usesProxy) {
128
+ const implementationAddress = sliceHex(implementationStorage, -20);
129
+
130
+ verifyQueue.add(() =>
131
+ verifyContract(
132
+ { name: "WorldProxy", rpc, verifier, verifierUrl, address: worldAddress },
133
+ {
134
+ profile: foundryProfile,
135
+ cwd: "node_modules/@latticexyz/world",
136
+ },
137
+ ).catch((error) => {
138
+ console.error(`Error verifying WorldProxy contract:`, error);
139
+ }),
140
+ );
141
+
142
+ verifyQueue.add(() =>
143
+ verifyContract(
144
+ { name: "World", rpc, verifier, verifierUrl, address: implementationAddress },
145
+ {
146
+ profile: foundryProfile,
147
+ cwd: "node_modules/@latticexyz/world",
148
+ },
149
+ ).catch((error) => {
150
+ console.error(`Error verifying World contract:`, error);
151
+ }),
152
+ );
153
+ } else {
154
+ verifyQueue.add(() =>
155
+ verifyContract(
156
+ { name: "World", rpc, verifier, verifierUrl, address: worldAddress },
157
+ {
158
+ profile: foundryProfile,
159
+ cwd: "node_modules/@latticexyz/world",
160
+ },
161
+ ).catch((error) => {
162
+ console.error(`Error verifying World contract:`, error);
163
+ }),
164
+ );
165
+ }
166
+ }
@@ -1,36 +0,0 @@
1
- import{a as _}from"./chunk-QXUPZVZL.js";import Ps from"@latticexyz/gas-report";import Bs from"@latticexyz/abi-ts";import{loadConfig as Jo}from"@latticexyz/config/node";import{getSrcDirectory as qo}from"@latticexyz/common/foundry";import No from"node:path";import{tablegen as zo}from"@latticexyz/store/codegen";import{worldgen as Lo}from"@latticexyz/world/node";import{worldToV1 as Uo}from"@latticexyz/world/config/v2";import{forge as Vo,getRemappings as _o}from"@latticexyz/common/foundry";import $o from"glob";import{basename as Eo}from"path";function P(e){return $o.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:Eo(o,".sol")}))}import{execa as Ko}from"execa";async function K({config:e,srcDir:o,foundryProfile:n=process.env.FOUNDRY_PROFILE}){let r=Uo(e),t=No.join(o,r.codegenDirectory),s=await _o(n);await Promise.all([zo(e,t,s),Lo(e,P(o),t)]),await Vo(["build"],{profile:n}),await Ko("mud",["abi-ts"],{stdio:"inherit"})}var Go={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 Jo(e),r=await qo();await K({config:n,srcDir:r,foundryProfile:o}),process.exit(0)}},xe=Go;import{rmSync as Yo}from"fs";import{homedir as Zo}from"os";import Qo from"path";import{execa as Xo}from"execa";var et={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=Zo();Yo(Qo.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let n=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${n.join(" ")}`);let r=Xo("anvil",n,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
2
- gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},Se=et;import{FaucetServiceDefinition as ot}from"@latticexyz/services/faucet";import{createChannel as tt,createClient as rt}from"nice-grpc-web";import Ce from"chalk";import{NodeHttpTransport as nt}from"@improbable-eng/grpc-web-node-http-transport";function st(e){return rt(ot,tt(e,nt()))}var at={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 r=st(o);e&&(console.log(Ce.yellow("Dripping to",n)),await r.dripDev({address:n}),console.log(Ce.yellow("Success"))),process.exit(0)}},De=at;var it={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)}},Te=it;import dt from"path";import{loadConfig as ct}from"@latticexyz/config/node";import{tablegen as lt}from"@latticexyz/store/codegen";import{getRemappings as mt,getSrcDirectory as pt}from"@latticexyz/common/foundry";var ft={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 ct(e),n=await pt(),r=await mt();await lt(o,dt.join(n,o.codegen.outputDirectory),r),process.exit(0)}},ve=ft;import ue from"node:path";import{existsSync as un,mkdirSync as gn,readFileSync as bn,writeFileSync as ge}from"node:fs";import{getBalance as wt,sendRawTransaction as xt,sendTransaction as Ie,waitForTransactionReceipt as Pe}from"viem/actions";var v={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Ae from"debug";var J=Ae("mud:cli"),ut=Ae("mud:cli");J.log=console.debug.bind(console);ut.log=console.error.bind(console);var c=J.extend("deploy"),gt=J.extend("deploy");c.log=console.debug.bind(console);gt.log=console.error.bind(console);import{sliceHex as bt}from"viem";import{getBytecode as ht}from"viem/actions";var q=`0x${v.address}`;async function ke(e){let o=await ht(e,{address:q});if(o)return c("found CREATE2 deployer at",q),o!==bt(`0x${v.creationCode}`,14)&&console.warn(`
3
- \u26A0\uFE0F Bytecode for deployer at ${q} did not match the expected CREATE2 bytecode. You may have unexpected results.
4
- `),q}var ce=`0x${v.address}`;async function Be(e){let o=await ke(e);if(o!==void 0)return o;let n=BigInt(v.gasLimit)*BigInt(v.gasPrice),r=await wt(e,{address:`0x${v.signerAddress}`}),t=n-r;if(t>0){c("sending gas for CREATE2 deployer to signer at",v.signerAddress);let a=await Ie(e,{chain:e.chain??null,to:`0x${v.signerAddress}`,value:t}),d=await Pe(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")}c("deploying CREATE2 deployer at",ce);let s=await xt(e,{serializedTransaction:`0x${v.transaction}`}).catch(a=>{if(String(a).includes("only replay-protected (EIP-155) transactions allowed over RPC"))return console.warn(`
5
- \u26A0\uFE0F Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.
6
-
7
- We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.
8
- `),c("deploying CREATE2 deployer"),Ie(e,{chain:e.chain??null,data:`0x${v.creationCode}`});throw a}),i=await Pe(e,{hash:s});if(!i.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return i.contractAddress!==ce&&console.warn(`
9
- \u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${ce})`),i.contractAddress}import{waitForTransactionReceipt as Xt}from"viem/actions";import{waitForTransactionReceipt as Ft}from"viem/actions";import{concatHex as jt,getCreate2Address as Ot}from"viem";import{getBytecode as Mt}from"viem/actions";import{padHex as Ct}from"viem";import Dt from"@latticexyz/store/mud.config";import Tt from"@latticexyz/world/mud.config";import vt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import At from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as St}from"@latticexyz/common";import{resolveUserTypes as je}from"@latticexyz/store/internal";function $(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([n])=>[n,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([n,r])=>[`${e.namespace}_${n}`,{namespace:e.namespace,name:r.name,tableId:St({type:r.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:r.name}),keySchema:je(r.keySchema,o),valueSchema:je(r.valueSchema,o)}]))}import{helloStoreEvent as kt}from"@latticexyz/store";import{helloWorldEvent as It}from"@latticexyz/world";import{storeToV1 as Pt}from"@latticexyz/store/config/v2";import{worldToV1 as Bt}from"@latticexyz/world/config/v2";var T=Ct("0x",{size:32}),E=parseInt("6000",16),R=$(Pt(Dt)),A=$(Bt(Tt)),G=[kt,It],C=[...vt,...At],Oe=["2.0.0","2.0.1"],Me=["2.0.0","2.0.1"];import{sendTransaction as Rt}from"@latticexyz/common";import Wt from"p-retry";import{wait as Ht}from"@latticexyz/common/utils";async function Re({client:e,deployerAddress:o,bytecode:n,deployedBytecodeSize:r,label:t="contract"}){if(n.includes("__$"))throw new Error(`Found unlinked public library in ${t} bytecode`);let s=Ot({from:o,salt:T,bytecode:n});return await Mt(e,{address:s,blockTag:"pending"})?(c("found",t,"at",s),[]):(r>E?console.warn(`
10
- Bytecode for ${t} (${r} bytes) is over the contract size limit (${E} bytes). Run \`forge build --sizes\` for more info.
11
- `):r>E*.95&&console.warn(`
12
- Bytecode for ${t} (${r} bytes) is almost over the contract size limit (${E} bytes). Run \`forge build --sizes\` for more info.
13
- `),c("deploying",t,"at",s),[await Wt(()=>Rt(e,{chain:e.chain??null,to:o,data:jt([T,n])}),{retries:3,onFailedAttempt:async a=>{let d=a.attemptNumber*500;c(`failed to deploy ${t}, retrying in ${d}ms...`),await Ht(d)}})])}import{uniqueBy as $t}from"@latticexyz/common/utils";async function k({client:e,deployerAddress:o,contracts:n}){let r=$t(n,s=>s.bytecode),t=(await Promise.all(r.map(s=>Re({client:e,deployerAddress:o,...s})))).flat();if(t.length){c("waiting for contracts");for(let s of t)await Ft(e,{hash:s})}return t}import Ne from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import zt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as Lt,encodeDeployData as Ut,size as Vt}from"viem";import We from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import He from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Fe from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import $e from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import Ee from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Et from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as N,encodeDeployData as Nt,size as z}from"viem";function Y(e){let o=z(We.deployedBytecode.object),n=We.bytecode.object,r=N({from:e,bytecode:n,salt:T}),t=z(He.deployedBytecode.object),s=He.bytecode.object,i=N({from:e,bytecode:s,salt:T}),a=z(Fe.deployedBytecode.object),d=Fe.bytecode.object,l=N({from:e,bytecode:d,salt:T}),f=z($e.deployedBytecode.object),u=$e.bytecode.object,x=N({from:e,bytecode:u,salt:T}),S=z(Ee.deployedBytecode.object),y=Nt({bytecode:Ee.bytecode.object,abi:Et,args:[r,i,l,x]}),m=N({from:e,bytecode:y,salt:T});return{AccessManagementSystem:{bytecode:n,deployedBytecodeSize:o,label:"access management system",address:r},BalanceTransferSystem:{bytecode:s,deployedBytecodeSize:t,label:"balance transfer system",address:i},BatchCallSystem:{bytecode:d,deployedBytecodeSize:a,label:"batch call system",address:l},RegistrationSystem:{bytecode:u,deployedBytecodeSize:f,label:"core registration system",address:x},InitModule:{bytecode:y,deployedBytecodeSize:S,label:"core module",address:m}}}function ze(e){let o=Y(e),n=Vt(Ne.deployedBytecode.object),r=Ut({bytecode:Ne.bytecode.object,abi:zt,args:[o.InitModule.address]}),t=Lt({from:e,bytecode:r,salt:T});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:n,label:"world factory",address:t}}}import Le from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import _t from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as Kt,encodeDeployData as Jt,size as qt}from"viem";function Ue(e){let o=Y(e),n=qt(Le.deployedBytecode.object),r=Jt({bytecode:Le.bytecode.object,abi:_t,args:[o.InitModule.address]}),t=Kt({from:e,bytecode:r,salt:T});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:n,label:"world proxy factory",address:t}}}async function Z(e,o,n){if(n){let t=Ue(o);return await k({client:e,deployerAddress:o,contracts:Object.values(t)}),t.WorldProxyFactory.address}let r=ze(o);return await k({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import er from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as or}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as Gt,decodeEventLog as Yt,hexToString as Ve,parseAbi as Zt}from"viem";import{isDefined as Qt}from"@latticexyz/common/utils";function Q(e){let o=e.map(i=>{try{return{...i,...Yt({strict:!0,abi:Zt(G),topics:i.topics,data:i.data})}}catch(a){if(a instanceof Gt)return;throw a}}).filter(Qt),{address:n,deployBlock:r,worldVersion:t,storeVersion:s}=o.reduce((i,a)=>({...i,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:Ve(a.args.worldVersion).replace(/\0+$/,"")}:null,...a.eventName==="HelloStore"?{storeVersion:Ve(a.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(n==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(t==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:n,deployBlock:r,worldVersion:t,storeVersion:s}}async function _e(e,o,n,r){let t=await Z(e,o,r);c("deploying world");let s=await or(e,{chain:e.chain??null,address:t,abi:er,functionName:"deployWorld",args:[n]});c("waiting for world deploy");let i=await Xt(e,{hash:s});if(i.status!=="success")throw console.error("world deploy failed",i),new Error("world deploy failed");let a=Q(i.logs);return c("deployed world to",a.address,"at block",a.deployBlock),{...a,stateBlock:a.deployBlock}}import{resourceToLabel as le,writeContract as dr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as lr,valueSchemaToHex as mr}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as tr,decodeAbiParameters as Ke,parseAbiParameters as Je}from"viem";import{hexToResource as rr}from"@latticexyz/common";import{storeSetRecordEvent as nr}from"@latticexyz/store";import{getLogs as sr}from"viem/actions";import{decodeKey as ar,decodeValueArgs as ir,hexToSchema as qe}from"@latticexyz/protocol-parser/internal";async function Ge({client:e,worldDeploy:o}){c("looking up tables for",o.address);let r=(await sr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:tr(nr),args:{tableId:R.store_Tables.tableId}})).map(t=>{let{tableId:s}=ar(R.store_Tables.keySchema,t.args.keyTuple),{namespace:i,name:a}=rr(s),d=ir(R.store_Tables.valueSchema,t.args),l=qe(d.keySchema),f=qe(d.valueSchema),u=Ke(Je("string[]"),d.abiEncodedKeyNames)[0],x=Ke(Je("string[]"),d.abiEncodedFieldNames)[0],S=[...f.staticFields,...f.dynamicFields],y=Object.fromEntries(l.staticFields.map((w,h)=>[u[h],w])),m=Object.fromEntries(S.map((w,h)=>[x[h],w]));return{namespace:i,name:a,tableId:s,keySchema:y,valueSchema:m}});return c("found",r.length,"tables for",o.address),r}import pr from"p-retry";import{wait as fr}from"@latticexyz/common/utils";async function Ye({client:e,worldDeploy:o,tables:n}){let t=(await Ge({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>t.includes(a.tableId));s.length&&c("existing tables",s.map(le).join(", "));let i=n.filter(a=>!t.includes(a.tableId));return i.length?(c("registering tables",i.map(le).join(", ")),await Promise.all(i.map(a=>pr(()=>dr(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerTable",args:[a.tableId,cr(a.valueSchema),lr(a.keySchema),mr(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async d=>{let l=d.attemptNumber*500;c(`failed to register table ${le(a)}, retrying in ${l}ms...`),await fr(l)}})))):[]}import{getAddress as j}from"viem";import{writeContract as me,resourceToLabel as L}from"@latticexyz/common";import{parseAbiItem as yr,HttpRequestError as ur}from"viem";import{getLogs as gr}from"viem/actions";import{storeSpliceStaticDataEvent as br}from"@latticexyz/store";import hr from"p-retry";async function X({client:e,worldDeploy:o}){c("looking up resource IDs for",o.address);let r=(await hr(()=>gr(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:yr(br),args:{tableId:R.store_ResourceIds.tableId}}),{retries:3,onFailedAttempt:async t=>{if(!(t instanceof ur&&t.status===400&&t.message.includes("block is out of range")))throw t}})).map(t=>t.args.keyTuple[0]);return c("found",r.length,"resource IDs for",o.address),r}import{hexToResource as Mr,resourceToLabel as Rr}from"@latticexyz/common";import{decodeValueArgs as wr,encodeKey as xr}from"@latticexyz/protocol-parser/internal";import{readContract as Sr}from"viem/actions";async function B({client:e,worldDeploy:o,table:n,key:r}){let[t,s,i]=await Sr(e,{blockNumber:o.stateBlock,address:o.address,abi:C,functionName:"getRecord",args:[n.tableId,xr(n.keySchema,r)]});return wr(n.valueSchema,{staticData:t,encodedLengths:s,dynamicData:i})}import{toFunctionSelector as Cr,parseAbiItem as Dr}from"viem";import{storeSetRecordEvent as Tr}from"@latticexyz/store";import{getLogs as vr}from"viem/actions";import{decodeValueArgs as Ar}from"@latticexyz/protocol-parser/internal";import{hexToResource as kr}from"@latticexyz/common";async function ee({client:e,worldDeploy:o}){c("looking up function signatures for",o.address);let r=(await vr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Dr(Tr),args:{tableId:A.world_FunctionSignatures.tableId}})).map(s=>Ar(A.world_FunctionSignatures.valueSchema,s.args).functionSignature);return c("found",r.length,"function signatures for",o.address),await Promise.all(r.map(async s=>{let i=Cr(s),{systemId:a,systemFunctionSelector:d}=await B({client:e,worldDeploy:o,table:A.world_FunctionSelectors,key:{worldFunctionSelector:i}}),{namespace:l,name:f}=kr(a),u=l===""?s:s.replace(`${l}_${f}_`,"");return{signature:s,selector:i,systemId:a,systemFunctionSignature:u,systemFunctionSelector:d}}))}import{parseAbiItem as Ir,getAddress as Pr}from"viem";import{storeSpliceStaticDataEvent as Br}from"@latticexyz/store";import{getLogs as jr}from"viem/actions";import{decodeKey as Or}from"@latticexyz/protocol-parser/internal";async function oe({client:e,worldDeploy:o}){c("looking up resource access for",o.address);let r=(await jr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Ir(Br),args:{tableId:A.world_ResourceAccess.tableId}})).map(s=>Or(A.world_ResourceAccess.keySchema,s.args.keyTuple)),t=(await Promise.all(r.map(async s=>[s,await B({client:e,worldDeploy:o,table:A.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Pr(s.caller)}));return c("found",t.length,"resource<>address access pairs"),t}async function Ze({client:e,worldDeploy:o}){let[n,r,t]=await Promise.all([X({client:e,worldDeploy:o}),ee({client:e,worldDeploy:o}),oe({client:e,worldDeploy:o})]),s=n.map(Mr).filter(i=>i.type==="system");return c("looking up systems",s.map(Rr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:d}=await B({client:e,worldDeploy:o,table:A.world_Systems,key:{systemId:i.resourceId}}),l=r.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:d,allowedAddresses:t.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:l}}))}import{wait as pe}from"@latticexyz/common/utils";import fe from"p-retry";async function Qe({client:e,deployerAddress:o,libraries:n,worldDeploy:r,systems:t}){let[s,i]=await Promise.all([Ze({client:e,worldDeploy:r}),oe({client:e,worldDeploy:r})]),a=t.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)===j(p.prepareDeploy(o,n).address)));a.length&&c("existing systems",a.map(L).join(", "));let d=a.map(p=>p.systemId),l=t.filter(p=>!d.includes(p.systemId));if(!l.length)return[];let f=l.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)!==j(p.prepareDeploy(o,n).address)));f.length&&c("upgrading systems",f.map(L).join(", "));let u=l.filter(p=>!s.some(g=>g.systemId===p.systemId));u.length&&c("registering new systems",u.map(L).join(", ")),await k({client:e,deployerAddress:o,contracts:l.map(p=>({bytecode:p.prepareDeploy(o,n).bytecode,deployedBytecodeSize:p.deployedBytecodeSize,label:`${L(p)} system`}))});let x=await Promise.all(l.map(p=>fe(()=>me(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"registerSystem",args:[p.systemId,p.prepareDeploy(o,n).address,p.allowAll]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to register system ${L(p)}, retrying in ${b}ms...`),await pe(b)}}))),S=t.map(p=>p.systemId),y=i.filter(({resourceId:p})=>S.includes(p)),m=[...t.flatMap(p=>p.allowedAddresses.map(g=>({resourceId:p.systemId,address:g}))),...t.flatMap(p=>p.allowedSystemIds.map(g=>({resourceId:p.systemId,address:s.find(b=>b.systemId===g)?.address??t.find(b=>b.systemId===g)?.prepareDeploy(o,n).address})).filter(g=>g.address!=null))],w=m.filter(p=>!y.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address))),h=y.filter(p=>!m.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address)));h.length&&c("revoking",h.length,"access grants"),w.length&&c("adding",w.length,"access grants");let D=await Promise.all([...h.map(p=>fe(()=>me(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"revokeAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to revoke access, retrying in ${b}ms...`),await pe(b)}})),...w.map(p=>fe(()=>me(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"grantAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;c(`failed to grant access, retrying in ${b}ms...`),await pe(b)}}))]);return[...x,...D]}import{waitForTransactionReceipt as po}from"viem/actions";import{getAddress as Wr,parseAbi as Hr}from"viem";import{getBlockNumber as Fr,getLogs as $r}from"viem/actions";var Xe=new Map;async function eo(e,o){let n=Wr(o),r=Xe.get(n);if(r!=null)return r;c("looking up world deploy for",n);let t=await Fr(e),s=await $r(e,{strict:!0,address:n,events:Hr(G),fromBlock:"earliest",toBlock:t});return r={...Q(s),stateBlock:t},Xe.set(n,r),c("found world deploy for",n,"at block",r.deployBlock),r}import{hexToResource as Er,writeContract as oo}from"@latticexyz/common";import to from"p-retry";import{wait as ro}from"@latticexyz/common/utils";async function no({client:e,worldDeploy:o,functions:n}){let r=await ee({client:e,worldDeploy:o}),t=Object.fromEntries(r.map(a=>[a.selector,a])),s=n.filter(a=>t[a.selector]),i=n.filter(a=>!s.includes(a));if(s.length){c("functions already registered:",s.map(d=>d.signature).join(", "));let a=s.filter(d=>d.systemId!==t[d.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(d=>d.signature).join(", "))}return i.length?(c("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:d}=Er(a.systemId);return d===""?to(()=>oo(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;c(`failed to register function ${a.signature}, retrying in ${f}ms...`),await ro(f)}}):to(()=>oo(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async l=>{let f=l.attemptNumber*500;c(`failed to register function ${a.signature}, retrying in ${f}ms...`),await ro(f)}})}))):[]}import{BaseError as Nr}from"viem";import{writeContract as so}from"@latticexyz/common";import{isDefined as zr,wait as Lr}from"@latticexyz/common/utils";import Ur from"p-retry";async function ao({client:e,deployerAddress:o,libraries:n,worldDeploy:r,modules:t}){return t.length?(await k({client:e,deployerAddress:o,contracts:t.map(s=>({bytecode:s.prepareDeploy(o,n).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,label:`${s.name} module`}))}),c("installing modules:",t.map(s=>s.name).join(", ")),(await Promise.all(t.map(s=>Ur(async()=>{try{let i=s.prepareDeploy(o,n).address;return s.installAsRoot?await so(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"installRootModule",args:[i,s.installData]}):await so(e,{chain:e.chain??null,address:r.address,abi:C,functionName:"installModule",args:[i,s.installData]})}catch(i){if(i instanceof Nr&&i.message.includes("Module_AlreadyInstalled")){c(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;c(`failed to install module ${s.name}, retrying in ${a}ms...`),await Lr(a)}})))).filter(zr)):[]}import{getAddress as io}from"viem";import{hexToResource as co,resourceToHex as lo,writeContract as Vr}from"@latticexyz/common";async function mo({client:e,worldDeploy:o,resourceIds:n}){let r=Array.from(new Set(n.map(u=>co(u).namespace))),t=await X({client:e,worldDeploy:o}),s=new Set(t.map(u=>co(u).namespace));s.size&&c("found",s.size,"existing namespaces:",Array.from(s).map(u=>u===""?"<root>":u).join(", "));let i=r.filter(u=>s.has(u)),d=(await Promise.all(i.map(async u=>{let{owner:x}=await B({client:e,worldDeploy:o,table:A.world_NamespaceOwner,key:{namespaceId:lo({type:"namespace",namespace:u,name:""})}});return[u,x]}))).filter(([,u])=>io(u)!==io(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 l=r.filter(u=>!s.has(u));return l.length>0&&c("registering namespaces",Array.from(l).join(", ")),Promise.all(l.map(u=>Vr(e,{chain:e.chain??null,address:o.address,abi:C,functionName:"registerNamespace",args:[lo({namespace:u,type:"namespace",name:""})]})))}import{resourceToLabel as _r}from"@latticexyz/common";import{randomBytes as Kr}from"crypto";async function fo({client:e,config:o,salt:n,worldAddress:r,deployerAddress:t,withWorldProxy:s}){let i=Object.values(o.tables),a=t??await Be(e);await Z(e,a,s),await k({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:`${_r(m)} system`})),...o.modules.map(m=>({bytecode:m.prepareDeploy(a,o.libraries).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${m.name} module`}))]});let d=r?await eo(e,r):await _e(e,a,n??`0x${Kr(32).toString("hex")}`,s);if(!Oe.includes(d.storeVersion))throw new Error(`Unsupported Store version: ${d.storeVersion}`);if(!Me.includes(d.worldVersion))throw new Error(`Unsupported World version: ${d.worldVersion}`);let l=await mo({client:e,worldDeploy:d,resourceIds:[...i.map(m=>m.tableId),...o.systems.map(m=>m.systemId)]});c("waiting for all namespace registration transactions to confirm");for(let m of l)await po(e,{hash:m});let f=await Ye({client:e,worldDeploy:d,tables:i}),u=await Qe({client:e,deployerAddress:a,libraries:o.libraries,worldDeploy:d,systems:o.systems}),x=await no({client:e,worldDeploy:d,functions:o.systems.flatMap(m=>m.functions)}),S=await ao({client:e,deployerAddress:a,libraries:o.libraries,worldDeploy:d,modules:o.modules}),y=[...f,...u,...x,...S];c("waiting for all transactions to confirm");for(let m of y)await po(e,{hash:m});return c("deploy complete"),d}import{createWalletClient as hn,http as wn,isHex as xn}from"viem";import{privateKeyToAccount as Sn}from"viem/accounts";import{loadConfig as Cn}from"@latticexyz/config/node";import{worldToV1 as Dn}from"@latticexyz/world/config/v2";import{getOutDirectory as Tn,getRpcUrl as vn,getSrcDirectory as An}from"@latticexyz/common/foundry";import W from"chalk";import{MUDError as Co}from"@latticexyz/common/errors";import on from"path";import{resolveWorldConfig as tn}from"@latticexyz/world/internal";import{resourceToHex as ye}from"@latticexyz/common";import{resolveWithContext as rn}from"@latticexyz/config/library";import{encodeField as nn}from"@latticexyz/protocol-parser/internal";import{hexToBytes as sn,bytesToHex as an,toFunctionSelector as bo,toFunctionSignature as ho}from"viem";import te from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import re from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import ne from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import se from"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"assert{type:"json"};import{size as ae}from"viem";function M(e){return Object.entries(e).flatMap(([o,n])=>Object.entries(n).flatMap(([r,t])=>t.map(s=>({path:o,name:r,start:s.start,length:s.length}))))}var yo=[{name:"KeysWithValueModule",abi:te.abi,bytecode:te.bytecode.object,placeholders:M(te.bytecode.linkReferences),deployedBytecodeSize:ae(te.deployedBytecode.object)},{name:"KeysInTableModule",abi:re.abi,bytecode:re.bytecode.object,placeholders:M(re.bytecode.linkReferences),deployedBytecodeSize:ae(re.deployedBytecode.object)},{name:"UniqueEntityModule",abi:ne.abi,bytecode:ne.bytecode.object,placeholders:M(ne.bytecode.linkReferences),deployedBytecodeSize:ae(ne.deployedBytecode.object)},{name:"Unstable_CallWithSignatureModule",abi:se.abi,bytecode:se.bytecode.object,placeholders:M(se.bytecode.linkReferences),deployedBytecodeSize:ae(se.deployedBytecode.object)}];import{readFileSync as Jr}from"fs";import qr from"path";import{MUDError as ie}from"@latticexyz/common/errors";import{size as Gr}from"viem";function U(e,o,n){let r,t=qr.join(n,e,o+".json");try{r=JSON.parse(Jr(t,"utf8"))}catch{throw new ie(`Error reading file at ${t}`)}let s=r?.bytecode?.object;if(!s)throw new ie(`No bytecode found in ${t}`);let i=r?.deployedBytecode?.object;if(!i)throw new ie(`No deployed bytecode found in ${t}`);let a=r?.abi;if(!a)throw new ie(`No ABI found in ${t}`);let d=M(r?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:d,deployedBytecodeSize:Gr(i)}}import{groupBy as dn}from"@latticexyz/common/utils";import{readFileSync as Zr}from"fs";import Qr from"glob";import Yr from"toposort";function uo(e,o,n){let r=Yr(e.flatMap(t=>n(t).map(s=>[o(t),s])));return[...e].sort((t,s)=>r.indexOf(o(t))-r.indexOf(o(s)))}function go(e){let n=Qr.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(r=>JSON.parse(Zr(r,"utf8"))).flatMap(r=>{if(!r.metadata)return[];let t=Object.keys(r.metadata.settings.compilationTarget)[0],s=r.metadata.settings.compilationTarget[t],i=r.bytecode.linkReferences;return Object.entries(i).flatMap(([a,d])=>Object.keys(d).map(l=>({path:a,name:l,dependentPath:t,dependentName:s})))});return uo(n,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{spliceHex as Xr}from"@latticexyz/common";import{getCreate2Address as en}from"viem";function de(e,o){return function(r,t){let s=e;for(let i of o){let a=t.find(d=>d.path===i.path&&d.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=Xr(s,i.start,i.length,a.prepareDeploy(r,t).address)}return{bytecode:s,address:en({from:r,bytecode:s,salt:T})}}}function wo({config:e,forgeSourceDir:o,forgeOutDir:n}){let r=go(n).map(y=>{let m=U(on.basename(y.path),y.name,n);return{path:y.path,name:y.name,abi:m.abi,prepareDeploy:de(m.bytecode,m.placeholders),deployedBytecodeSize:m.deployedBytecodeSize}}),t=$(e),s=P(o).map(({basename:y})=>y),i=tn(e,s),d=U("System.sol","System",n).abi.filter(y=>y.type==="function").map(ho),l=Object.entries(i.systems).map(([y,m])=>{let w=e.namespace,h=m.name,D=ye({type:"system",namespace:w,name:h}),p=U(`${y}.sol`,y,n),g=p.abi.filter(b=>b.type==="function").map(ho).filter(b=>!d.includes(b)).map(b=>{let we=w===""?b:`${w}__${b}`;return{signature:we,selector:bo(we),systemId:D,systemFunctionSignature:b,systemFunctionSelector:bo(b)}});return{namespace:w,name:h,systemId:D,allowAll:m.openAccess,allowedAddresses:m.accessListAddresses,allowedSystemIds:m.accessListSystems.map(b=>ye({type:"system",namespace:w,name:i.systems[b].name})),prepareDeploy:de(p.bytecode,p.placeholders),deployedBytecodeSize:p.deployedBytecodeSize,abi:p.abi,functions:g}}),f=dn(l,y=>y.systemId),u=Array.from(f.values()).filter(y=>y.length>1).flat();if(u.length){let y=u.map(m=>m.name);throw new Error(`Found systems with overlapping system ID: ${y.join(", ")}.
14
-
15
- System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}let x={tableIds:Object.fromEntries(Object.entries(e.tables).map(([y,m])=>[y,sn(ye({type:m.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:m.name}))]))},S=e.modules.map(y=>{let m=yo.find(h=>h.name===y.name)??U(`${y.name}.sol`,y.name,n),w=y.args.map(h=>rn(h,x)).map(h=>{let D=h.value instanceof Uint8Array?an(h.value):h.value;return nn(h.type,D)});if(w.length>1)throw new Error(`${y.name} module should only have 0-1 args, but had ${w.length} args.`);return{name:y.name,installAsRoot:y.root,installData:w.length===0?"0x":w[0],prepareDeploy:de(m.bytecode,m.placeholders),deployedBytecodeSize:m.deployedBytecodeSize,abi:m.abi}});return{tables:t,systems:l,modules:S,libraries:r}}import{getChainId as kn}from"viem/actions";import{existsSync as cn}from"fs";import ln from"path";import xo from"chalk";import{getScriptDirectory as mn,forge as pn}from"@latticexyz/common/foundry";import{execSync as fn}from"child_process";import{formatGwei as yn}from"viem";async function So(e,o,n,r){let t=ln.join(await mn(),e+".s.sol");if(!cn(t)){console.log(`No script at ${t}, skipping post deploy hook`);return}let s=BigInt(fn(`cast gas-price --rpc-url ${n}`,{encoding:"utf-8"}).trim());console.log(xo.blue(`Executing post deploy script at ${t}`)),console.log(xo.blue(` using gas price of ${yn(s)} gwei`)),await pn(["script",e,"--broadcast","--sig","run(address)",o,"--with-gas-price",s.toString(),"--rpc-url",n,"-vvv"],{profile:r})}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."},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."}};async function H(e){let o=e.salt;if(o!=null&&!xn(o))throw new Co("Expected hex string for salt");let n=e.profile??process.env.FOUNDRY_PROFILE,r=await Cn(e.configPath),t=Dn(r);e.printConfig&&console.log(W.green(`
16
- Resolved config:
17
- `),JSON.stringify(t,null,2));let s=e.srcDir??await An(n),i=await Tn(n),a=e.rpc??await vn(n);console.log(W.bgBlue(W.whiteBright(`
18
- Deploying MUD contracts${n?" with profile "+n:""} to RPC ${a}
19
- `))),e.skipBuild||await K({config:r,srcDir:s,foundryProfile:n});let d=process.env.PRIVATE_KEY;if(!d)throw new Co(`Missing PRIVATE_KEY environment variable.
20
- Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
21
- in your contracts directory to use the default anvil private key.`);let l=wo({config:t,forgeSourceDir:s,forgeOutDir:i}),f=hn({transport:wn(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:Sn(d)});console.log("Deploying from",f.account.address);let u=Date.now(),x=await fo({deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:f,config:l,withWorldProxy:r.deploy.useProxy});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await So(t.postDeployScript,x.address,a,n),console.log(W.green("Deployment completed in",(Date.now()-u)/1e3,"seconds"));let S={worldAddress:x.address,blockNumber:Number(x.deployBlock)};if(e.saveDeployment){let y=await kn(f),m=ue.join(t.deploysDirectory,y.toString());gn(m,{recursive:!0}),ge(ue.join(m,"latest.json"),JSON.stringify(S,null,2)),ge(ue.join(m,Date.now()+".json"),JSON.stringify(S,null,2));let w=[1337,31337],h=un(t.worldsFile)?JSON.parse(bn(t.worldsFile,"utf-8")):{};h[y]={address:S.worldAddress,blockNumber:w.includes(y)?void 0:S.blockNumber},ge(t.worldsFile,JSON.stringify(h,null,2)),console.log(W.bgGreen(W.whiteBright(`
22
- Deployment result (written to ${t.worldsFile} and ${m}):
23
- `)))}return console.log(S),x}var In={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(I)},async handler(e){try{await H(e)}catch(o){_(o),process.exit(1)}process.exit(0)}},Do=In;import{loadConfig as Pn}from"@latticexyz/config/node";import{worldgen as Bn}from"@latticexyz/world/node";import{getSrcDirectory as jn}from"@latticexyz/common/foundry";import To from"path";import{rmSync as On}from"fs";var Mn={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await Rn(e),process.exit(0)}};async function Rn(e){let o=e.srcDir??await jn(),n=P(o),r=e.config??await Pn(e.configPath),t=To.join(o,r.codegen.outputDirectory);e.clean&&On(To.join(t,r.codegen.worldgenDirectory),{recursive:!0,force:!0}),await Bn(r,n,t)}var vo=Mn;import V from"chalk";import{readFileSync as En,writeFileSync as Nn}from"fs";import he from"path";import{MUDError as F}from"@latticexyz/common/errors";var Ao={name:"@latticexyz/cli",version:"2.0.6",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:{"@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:*",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-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 zn from"glob";import{ZodError as Hn,z as ko}from"zod";var Fn=ko.object({MUD_PACKAGES:ko.string().transform(e=>JSON.parse(e))});function $n(){try{return Fn.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 Hn){let{...o}=e.format();console.error(`
24
- Missing or invalid environment variables:
25
-
26
- ${Object.keys(o).join(`
27
- `)}
28
- `),process.exit(1)}throw e}}var be=$n().MUD_PACKAGES;var Ln={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],n=o.reduce((t,s)=>e[s]?t+1:t,0);if(n===0)throw new F(`You need to provide one these options: ${o.join(", ")}`);if(n>1)throw new F(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Un(e));let r=zn.sync("**/package.json").filter(t=>!t.includes("node_modules"));for(let t of r)Vn(t,e)}catch(o){_(o)}finally{process.exit(0)}}};async function Un(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(V.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Ao.name}`)).json()}catch{throw new F("Could not fetch available MUD versions")}if(e.tag){let n=o["dist-tags"][e.tag];if(!n)throw new F(`Could not find npm version with tag "${e.tag}"`);return console.log(V.green(`Latest version with tag ${e.tag}: ${n}`)),n}if(e.commit){let n=e.commit.substring(0,8),r=Object.keys(o.versions).find(t=>t.includes(n));if(!r)throw new F(`Could not find npm version based on commit "${e.commit}"`);return console.log(V.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Vn(e,o){let{link:n}=o,{mudVersion:r}=o,t=_n(e),s=Object.keys(be),i={};for(let l in t.dependencies)s.includes(l)&&(i[l]=t.dependencies[l]);let a={};for(let l in t.devDependencies)s.includes(l)&&(a[l]=t.devDependencies[l]);for(let l in t.dependencies)s.includes(l)&&(t.dependencies[l]=d(l,"dependencies"));for(let l in t.devDependencies)s.includes(l)&&(t.devDependencies[l]=d(l,"devDependencies"));return Nn(e,JSON.stringify(t,null,2)+`
29
- `),console.log(`Updating ${e}`),Io(i,t.dependencies),Io(a,t.devDependencies),t;function d(l,f){return n&&(r=Kn(e,n,l)),r||t[f][l]}}function _n(e){try{let o=En(e,"utf8");return JSON.parse(o)}catch{throw new F("Could not read JSON at "+e)}}function Io(e,o){for(let n in e)e[n]!==o[n]&&console.log(`${n}: ${V.red(e[n])} -> ${V.green(o[n])}`)}function Kn(e,o,n){let r=he.relative(he.dirname(e),process.cwd());return"link:"+he.join(r,o,be[n].localPath)}var Po=Ln;import{anvil as Jn,forge as qn,getRpcUrl as Gn}from"@latticexyz/common/foundry";import Yn from"chalk";var Zn={...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"}},Qn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Zn)},async handler(e){if(!e.worldAddress){let t=["--block-base-fee-per-gas","0","--port",String(e.port)];Jn(t)}let o=e.worldAddress?await Gn(e.profile):`http://127.0.0.1:${e.port}`,n=e.worldAddress??(await H({...e,saveDeployment:!1,rpc:o})).address;console.log(Yn.blue("World address",n));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await qn(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:n}}),process.exit(0)}catch(t){console.error(t),process.exit(1)}}},Bo=Qn;import{existsSync as Xn,readFileSync as es}from"fs";import{ethers as jo}from"ethers";import{loadConfig as os}from"@latticexyz/config/node";import{MUDError as Oo}from"@latticexyz/common/errors";import{cast as ts,getRpcUrl as rs,getSrcDirectory as ns}from"@latticexyz/common/foundry";import{resolveWorldConfig as ss}from"@latticexyz/world/internal";import as from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Mo from"@latticexyz/world/mud.config";import{resourceToHex as Wo}from"@latticexyz/common";import{createClient as is,http as ds}from"viem";import{getChainId as cs}from"viem/actions";import{worldToV1 as ls}from"@latticexyz/world/config/v2";var Ro=Wo({type:"system",namespace:Mo.namespace,name:Mo.tables.world__Systems.name}),ms={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the MUD config file"},profile:{type:"string",description:"The foundry profile to use"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await ns(o),e.rpc??=await rs(o);let{tx:n,configPath:r,srcDir:t,rpc:s}=e,i=P(t),a=await os(r),d=ls(a),l=ss(d,i.map(({basename:D})=>D)),f=e.worldAddress??await ps(d.worldsFile,s),u=new jo.providers.StaticJsonRpcProvider(s),x=new jo.Contract(f,as,u),S=d.namespace,y=Object.values(l.systems).map(({name:D})=>D),m=await x.getFieldLayout(Ro),w=[];for(let D of y){let p=Wo({type:"system",namespace:S,name:D}),g=await x.getField(Ro,[p],0,m);w.push({name:D,address:g})}let h=await ts(["run","--label",`${f}:World`,...w.map(({name:D,address:p})=>["--label",`${p}:${D}`]).flat(),`${n}`]);console.log(h),process.exit(0)}},Ho=ms;async function ps(e,o){if(Xn(e)){let n=is({transport:ds(o)}),r=await cs(n),t=JSON.parse(es(e,"utf-8"));if(!t[r])throw new Oo(`chainId ${r} is missing in worldsFile "${e}"`);return t[r].address}else throw new Oo("worldAddress is not specified and worldsFile is missing")}import{anvil as fs,getScriptDirectory as ys,getSrcDirectory as us}from"@latticexyz/common/foundry";import O from"chalk";import gs from"chokidar";import{loadConfig as bs,resolveConfigPath as hs}from"@latticexyz/config/node";import ws from"path";import{homedir as xs}from"os";import{rmSync as Ss}from"fs";import{BehaviorSubject as Cs,debounceTime as Ds,exhaustMap as Ts,filter as vs}from"rxjs";import{isDefined as As}from"@latticexyz/common/utils";var ks={rpc:I.rpc,configPath:I.configPath,alwaysRunPostDeploy:I.alwaysRunPostDeploy,worldAddress:I.worldAddress},Is={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ks)},async handler(e){let o=e.rpc,n=e.configPath??await hs(e.configPath),r=await us(),t=await ys(),s=await bs(n);if(!e.rpc){console.log(O.gray("Cleaning devnode cache"));let l=xs();Ss(ws.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),fs(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let i=new Cs(Date.now());gs.watch([n,r,t],{ignoreInitial:!0}).on("all",async(l,f)=>{f.includes(n)&&(console.log(O.blue("Config changed, queuing deploy\u2026")),i.next(Date.now())),(f.includes(r)||f.includes(t))&&(f.includes(s.codegen.outputDirectory)||(console.log(O.blue("Contracts changed, queuing deploy\u2026")),i.next(Date.now())))});let a=e.worldAddress;i.pipe(Ds(200),Ts(async l=>{a&&console.log(O.blue("Rebuilding and upgrading world\u2026"));try{let f=await H({...e,configPath:n,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:a,srcDir:r,salt:"0x"});return a=f.address,l<i.value?i.next(i.value):console.log(O.gray(`
30
- Waiting for file changes\u2026
31
- `)),f}catch(f){console.error(O.bgRed(O.whiteBright(`
32
- Error while attempting deploy
33
- `))),console.error(f),console.log(O.gray(`
34
- Waiting for file changes\u2026
35
- `))}}),vs(As)).subscribe()}},Fo=Is;var Sf=[xe,Do,Se,De,Ps,Te,ve,vo,Po,Bo,Ho,Fo,Bs];export{Sf as commands};
36
- //# sourceMappingURL=commands-DBHY7GFM.js.map