@latticexyz/cli 2.0.0-alpha.94 → 2.0.0-foundry-js-c7b0289b

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.
Files changed (139) hide show
  1. package/dist/chunk-22IIKR4S.js +4 -0
  2. package/dist/chunk-22IIKR4S.js.map +1 -0
  3. package/dist/commands-UYAATBY6.js +27 -0
  4. package/dist/commands-UYAATBY6.js.map +1 -0
  5. package/dist/errors-XGN6V2Y3.js +2 -0
  6. package/dist/errors-XGN6V2Y3.js.map +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/mud.js +2 -8340
  10. package/dist/mud.js.map +1 -0
  11. package/package.json +54 -46
  12. package/src/commands/deploy.ts +26 -0
  13. package/src/commands/dev-contracts.ts +114 -0
  14. package/src/commands/devnode.ts +7 -2
  15. package/src/commands/faucet.ts +1 -1
  16. package/src/commands/index.ts +19 -14
  17. package/src/commands/set-version.ts +103 -81
  18. package/src/commands/tablegen.ts +7 -5
  19. package/src/commands/test.ts +65 -0
  20. package/src/commands/trace.ts +118 -0
  21. package/src/commands/worldgen.ts +29 -28
  22. package/src/common.ts +1 -0
  23. package/src/debug.ts +3 -0
  24. package/src/deploy/assertNamespaceOwner.ts +42 -0
  25. package/src/deploy/common.ts +76 -0
  26. package/src/deploy/configToTables.ts +68 -0
  27. package/src/deploy/create2/README.md +9 -0
  28. package/src/deploy/create2/deployment.json +7 -0
  29. package/src/deploy/debug.ts +3 -0
  30. package/src/deploy/deploy.ts +108 -0
  31. package/src/deploy/deployWorld.ts +33 -0
  32. package/src/deploy/ensureContract.ts +61 -0
  33. package/src/deploy/ensureContractsDeployed.ts +25 -0
  34. package/src/deploy/ensureDeployer.ts +36 -0
  35. package/src/deploy/ensureFunctions.ts +86 -0
  36. package/src/deploy/ensureModules.ts +73 -0
  37. package/src/deploy/ensureSystems.ts +162 -0
  38. package/src/deploy/ensureTables.ts +65 -0
  39. package/src/deploy/ensureWorldFactory.ts +47 -0
  40. package/src/deploy/getFunctions.ts +58 -0
  41. package/src/deploy/getResourceAccess.ts +51 -0
  42. package/src/deploy/getResourceIds.ts +31 -0
  43. package/src/deploy/getSystems.ts +48 -0
  44. package/src/deploy/getTableValue.ts +30 -0
  45. package/src/deploy/getTables.ts +59 -0
  46. package/src/deploy/getWorldDeploy.ts +39 -0
  47. package/src/deploy/logsToWorldDeploy.ts +49 -0
  48. package/src/deploy/resolveConfig.ts +151 -0
  49. package/src/deploy/resourceLabel.ts +3 -0
  50. package/src/index.ts +1 -1
  51. package/src/modules.d.ts +11 -0
  52. package/src/mud.ts +38 -23
  53. package/src/mudPackages.ts +24 -0
  54. package/src/runDeploy.ts +128 -0
  55. package/src/utils/errors.ts +1 -1
  56. package/src/utils/getExistingContracts.ts +12 -0
  57. package/src/utils/modules/constants.ts +26 -0
  58. package/src/utils/printMUD.ts +14 -0
  59. package/src/utils/utils/getContractData.ts +32 -0
  60. package/src/utils/utils/postDeploy.ts +25 -0
  61. package/dist/chunk-6V563IAZ.js +0 -283
  62. package/dist/chunk-FPG73MVN.js +0 -71
  63. package/dist/chunk-L4YLJHLJ.js +0 -30
  64. package/dist/chunk-SKNB74MT.js +0 -726
  65. package/dist/chunk-T2YHSEJD.js +0 -3842
  66. package/dist/chunk-VQTZJIFF.js +0 -353
  67. package/dist/chunk-WZFXLDPK.js +0 -761
  68. package/dist/chunk-YL4GJLLL.js +0 -26139
  69. package/dist/index.d.ts +0 -2
  70. package/dist/mud.d.ts +0 -1
  71. package/dist/mud2.d.ts +0 -1
  72. package/dist/mud2.js +0 -25
  73. package/dist/render-solidity/index.d.ts +0 -171
  74. package/dist/render-solidity/index.js +0 -49
  75. package/dist/render-ts/index.d.ts +0 -26
  76. package/dist/render-ts/index.js +0 -14
  77. package/dist/utils/deprecated/index.d.ts +0 -76
  78. package/dist/utils/deprecated/index.js +0 -36
  79. package/dist/utils/index.d.ts +0 -88
  80. package/dist/utils/index.js +0 -39
  81. package/src/commands/deploy-v2.ts +0 -112
  82. package/src/commands/deprecated/bulkupload.ts +0 -50
  83. package/src/commands/deprecated/call-system.ts +0 -70
  84. package/src/commands/deprecated/codegen-libdeploy.ts +0 -29
  85. package/src/commands/deprecated/deploy-contracts.ts +0 -120
  86. package/src/commands/deprecated/index.ts +0 -22
  87. package/src/commands/deprecated/system-types.ts +0 -29
  88. package/src/commands/deprecated/test.ts +0 -53
  89. package/src/commands/deprecated/trace.ts +0 -81
  90. package/src/commands/deprecated/types.ts +0 -33
  91. package/src/commands/gas-report.ts +0 -219
  92. package/src/commands/test-v2.ts +0 -71
  93. package/src/commands/tsgen.ts +0 -33
  94. package/src/contracts/BulkUpload.sol +0 -174
  95. package/src/contracts/Deploy.sol +0 -23
  96. package/src/contracts/LibDeploy.ejs +0 -121
  97. package/src/contracts/LibDeploy.sol +0 -23
  98. package/src/contracts/LibDeployStub.sol +0 -23
  99. package/src/mud2.ts +0 -29
  100. package/src/render-solidity/common.ts +0 -138
  101. package/src/render-solidity/field.ts +0 -160
  102. package/src/render-solidity/index.ts +0 -10
  103. package/src/render-solidity/record.ts +0 -158
  104. package/src/render-solidity/renderSystemInterface.ts +0 -31
  105. package/src/render-solidity/renderTable.ts +0 -164
  106. package/src/render-solidity/renderTableIndex.ts +0 -15
  107. package/src/render-solidity/renderTypeHelpers.ts +0 -99
  108. package/src/render-solidity/renderTypes.ts +0 -19
  109. package/src/render-solidity/renderTypesFromConfig.ts +0 -13
  110. package/src/render-solidity/renderWorld.ts +0 -24
  111. package/src/render-solidity/tableOptions.ts +0 -107
  112. package/src/render-solidity/tablegen.ts +0 -35
  113. package/src/render-solidity/types.ts +0 -111
  114. package/src/render-solidity/userType.ts +0 -131
  115. package/src/render-solidity/worldgen.ts +0 -59
  116. package/src/render-ts/index.ts +0 -5
  117. package/src/render-ts/recsV1TableOptions.ts +0 -39
  118. package/src/render-ts/renderRecsV1Tables.ts +0 -31
  119. package/src/render-ts/schemaTypesToRecsTypeStrings.ts +0 -202
  120. package/src/render-ts/tsgen.ts +0 -12
  121. package/src/render-ts/types.ts +0 -13
  122. package/src/utils/contractToInterface.ts +0 -132
  123. package/src/utils/deploy-v2.ts +0 -518
  124. package/src/utils/deprecated/build.ts +0 -55
  125. package/src/utils/deprecated/codegen.ts +0 -42
  126. package/src/utils/deprecated/constants.ts +0 -2
  127. package/src/utils/deprecated/deploy.ts +0 -111
  128. package/src/utils/deprecated/exec.ts +0 -18
  129. package/src/utils/deprecated/findLog.ts +0 -8
  130. package/src/utils/deprecated/hsr.ts +0 -71
  131. package/src/utils/deprecated/ids.ts +0 -14
  132. package/src/utils/deprecated/index.ts +0 -8
  133. package/src/utils/deprecated/typegen.ts +0 -133
  134. package/src/utils/execLog.ts +0 -22
  135. package/src/utils/format.ts +0 -39
  136. package/src/utils/formatAndWrite.ts +0 -21
  137. package/src/utils/foundry.ts +0 -103
  138. package/src/utils/getChainId.ts +0 -10
  139. package/src/utils/index.ts +0 -5
@@ -0,0 +1,65 @@
1
+ import type { CommandModule, InferredOptionTypes, Options } from "yargs";
2
+ import { anvil, forge, getRpcUrl } from "@latticexyz/common/foundry";
3
+ import chalk from "chalk";
4
+ import { deployOptions, runDeploy } from "../runDeploy";
5
+
6
+ const testOptions = {
7
+ ...deployOptions,
8
+ port: { type: "number", description: "Port to run internal node for fork testing on", default: 4242 },
9
+ worldAddress: {
10
+ type: "string",
11
+ description:
12
+ "Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing.",
13
+ },
14
+ forgeOptions: { type: "string", description: "Options to pass to forge test" },
15
+ } as const satisfies Record<string, Options>;
16
+
17
+ type TestOptions = InferredOptionTypes<typeof testOptions>;
18
+
19
+ const commandModule: CommandModule<typeof testOptions, TestOptions> = {
20
+ command: "test",
21
+
22
+ describe: "Run tests in MUD contracts",
23
+
24
+ builder(yargs) {
25
+ return yargs.options(testOptions);
26
+ },
27
+
28
+ async handler(opts) {
29
+ // Start an internal anvil process if no world address is provided
30
+ if (!opts.worldAddress) {
31
+ const anvilArgs = ["--block-base-fee-per-gas", "0", "--port", String(opts.port)];
32
+ anvil(anvilArgs);
33
+ }
34
+
35
+ const forkRpc = opts.worldAddress ? await getRpcUrl(opts.profile) : `http://127.0.0.1:${opts.port}`;
36
+
37
+ const worldAddress =
38
+ opts.worldAddress ??
39
+ (
40
+ await runDeploy({
41
+ ...opts,
42
+ saveDeployment: false,
43
+ rpc: forkRpc,
44
+ })
45
+ ).address;
46
+
47
+ console.log(chalk.blue("World address", worldAddress));
48
+
49
+ const userOptions = opts.forgeOptions?.replaceAll("\\", "").split(" ") ?? [];
50
+ try {
51
+ await forge(["test", "--fork-url", forkRpc, ...userOptions], {
52
+ profile: opts.profile,
53
+ env: {
54
+ WORLD_ADDRESS: worldAddress,
55
+ },
56
+ });
57
+ process.exit(0);
58
+ } catch (e) {
59
+ console.error(e);
60
+ process.exit(1);
61
+ }
62
+ },
63
+ };
64
+
65
+ export default commandModule;
@@ -0,0 +1,118 @@
1
+ import { existsSync, readFileSync } from "fs";
2
+ import type { CommandModule } from "yargs";
3
+ import { ethers } from "ethers";
4
+
5
+ import { loadConfig } from "@latticexyz/config/node";
6
+ import { MUDError } from "@latticexyz/common/errors";
7
+ import { cast, getRpcUrl, getSrcDirectory } from "@latticexyz/common/foundry";
8
+ import { StoreConfig } from "@latticexyz/store";
9
+ import { resolveWorldConfig, WorldConfig } from "@latticexyz/world";
10
+ import IBaseWorldAbi from "@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json" assert { type: "json" };
11
+ import worldConfig from "@latticexyz/world/mud.config";
12
+ import { resourceToHex } from "@latticexyz/common";
13
+ import { getExistingContracts } from "../utils/getExistingContracts";
14
+ import { createClient, http } from "viem";
15
+ import { getChainId } from "viem/actions";
16
+
17
+ // TODO account for multiple namespaces (https://github.com/latticexyz/mud/issues/994)
18
+ const systemsTableId = resourceToHex({
19
+ type: "system",
20
+ namespace: worldConfig.namespace,
21
+ name: worldConfig.tables.Systems.name,
22
+ });
23
+
24
+ type Options = {
25
+ tx: string;
26
+ worldAddress?: string;
27
+ configPath?: string;
28
+ profile?: string;
29
+ srcDir?: string;
30
+ rpc?: string;
31
+ };
32
+
33
+ const commandModule: CommandModule<Options, Options> = {
34
+ command: "trace",
35
+
36
+ describe: "Display the trace of a transaction",
37
+
38
+ builder(yargs) {
39
+ return yargs.options({
40
+ tx: { type: "string", required: true, description: "Transaction hash to replay" },
41
+ worldAddress: {
42
+ type: "string",
43
+ description: "World contract address. Defaults to the value from worlds.json, based on rpc's chainId",
44
+ },
45
+ configPath: { type: "string", description: "Path to the config file" },
46
+ profile: { type: "string", description: "The foundry profile to use" },
47
+ srcDir: { type: "string", description: "Source directory. Defaults to foundry src directory." },
48
+ rpc: { type: "string", description: "json rpc endpoint. Defaults to foundry's configured eth_rpc_url" },
49
+ });
50
+ },
51
+
52
+ async handler(args) {
53
+ args.profile ??= process.env.FOUNDRY_PROFILE;
54
+ const { profile } = args;
55
+ args.srcDir ??= await getSrcDirectory(profile);
56
+ args.rpc ??= await getRpcUrl(profile);
57
+ const { tx, configPath, srcDir, rpc } = args;
58
+
59
+ const existingContracts = getExistingContracts(srcDir);
60
+
61
+ // Load the config
62
+ const mudConfig = (await loadConfig(configPath)) as StoreConfig & WorldConfig;
63
+
64
+ const resolvedConfig = resolveWorldConfig(
65
+ mudConfig,
66
+ existingContracts.map(({ basename }) => basename)
67
+ );
68
+
69
+ // Get worldAddress either from args or from worldsFile
70
+ const worldAddress = args.worldAddress ?? (await getWorldAddress(mudConfig.worldsFile, rpc));
71
+
72
+ // Create World contract instance from deployed address
73
+ const provider = new ethers.providers.StaticJsonRpcProvider(rpc);
74
+ const WorldContract = new ethers.Contract(worldAddress, IBaseWorldAbi, provider);
75
+
76
+ // TODO account for multiple namespaces (https://github.com/latticexyz/mud/issues/994)
77
+ const namespace = mudConfig.namespace;
78
+ const names = Object.values(resolvedConfig.systems).map(({ name }) => name);
79
+
80
+ // Fetch system table field layout from chain
81
+ const systemTableFieldLayout = await WorldContract.getFieldLayout(systemsTableId);
82
+ const labels: { name: string; address: string }[] = [];
83
+ for (const name of names) {
84
+ const systemSelector = resourceToHex({ type: "system", namespace, name });
85
+ // Get the first field of `Systems` table (the table maps system name to its address and other data)
86
+ const address = await WorldContract.getField(systemsTableId, [systemSelector], 0, systemTableFieldLayout);
87
+ labels.push({ name, address });
88
+ }
89
+
90
+ const result = await cast([
91
+ "run",
92
+ "--label",
93
+ `${worldAddress}:World`,
94
+ ...labels.map(({ name, address }) => ["--label", `${address}:${name}`]).flat(),
95
+ `${tx}`,
96
+ ]);
97
+ console.log(result);
98
+
99
+ process.exit(0);
100
+ },
101
+ };
102
+
103
+ export default commandModule;
104
+
105
+ async function getWorldAddress(worldsFile: string, rpc: string) {
106
+ if (existsSync(worldsFile)) {
107
+ const client = createClient({ transport: http(rpc) });
108
+ const chainId = await getChainId(client);
109
+ const deploys = JSON.parse(readFileSync(worldsFile, "utf-8"));
110
+
111
+ if (!deploys[chainId]) {
112
+ throw new MUDError(`chainId ${chainId} is missing in worldsFile "${worldsFile}"`);
113
+ }
114
+ return deploys[chainId].address as string;
115
+ } else {
116
+ throw new MUDError("worldAddress is not specified and worldsFile is missing");
117
+ }
118
+ }
@@ -1,14 +1,18 @@
1
1
  import type { CommandModule } from "yargs";
2
- import { loadStoreConfig, loadWorldConfig } from "@latticexyz/config";
3
- import { getSrcDirectory } from "../utils/foundry.js";
4
- import glob from "glob";
5
- import path, { basename } from "path";
6
- import { worldgen } from "../render-solidity/worldgen.js";
2
+ import { loadConfig } from "@latticexyz/config/node";
3
+ import { StoreConfig } from "@latticexyz/store";
4
+ import { WorldConfig } from "@latticexyz/world";
5
+ import { worldgen } from "@latticexyz/world/node";
6
+ import { getSrcDirectory } from "@latticexyz/common/foundry";
7
+ import path from "path";
7
8
  import { rmSync } from "fs";
9
+ import { getExistingContracts } from "../utils/getExistingContracts";
8
10
 
9
11
  type Options = {
10
12
  configPath?: string;
11
13
  clean?: boolean;
14
+ srcDir?: string;
15
+ config?: StoreConfig & WorldConfig;
12
16
  };
13
17
 
14
18
  const commandModule: CommandModule<Options, Options> = {
@@ -19,38 +23,35 @@ const commandModule: CommandModule<Options, Options> = {
19
23
  builder(yargs) {
20
24
  return yargs.options({
21
25
  configPath: { type: "string", desc: "Path to the config file" },
22
- clean: { type: "boolean", desc: "Clear the worldgen directory before generating new interfaces" },
26
+ clean: {
27
+ type: "boolean",
28
+ desc: "Clear the worldgen directory before generating new interfaces (defaults to true)",
29
+ default: true,
30
+ },
23
31
  });
24
32
  },
25
33
 
26
34
  async handler(args) {
27
- const { configPath, clean } = args;
28
- const srcDir = await getSrcDirectory();
35
+ await worldgenHandler(args);
36
+ process.exit(0);
37
+ },
38
+ };
29
39
 
30
- // Get a list of all contract names
31
- const existingContracts = glob.sync(`${srcDir}/**/*.sol`).map((path) => ({
32
- path,
33
- basename: basename(path, ".sol"),
34
- }));
40
+ export async function worldgenHandler(args: Options) {
41
+ const srcDir = args.srcDir ?? (await getSrcDirectory());
35
42
 
36
- // Load and resolve the config
37
- const worldConfig = await loadWorldConfig(
38
- configPath,
39
- existingContracts.map(({ basename }) => basename)
40
- );
41
- const storeConfig = await loadStoreConfig(configPath);
42
- const mudConfig = { ...worldConfig, ...storeConfig };
43
+ const existingContracts = getExistingContracts(srcDir);
43
44
 
44
- const outputBaseDirectory = path.join(srcDir, mudConfig.codegenDirectory);
45
+ // Load the config
46
+ const mudConfig = args.config ?? ((await loadConfig(args.configPath)) as StoreConfig & WorldConfig);
45
47
 
46
- // clear the worldgen directory
47
- if (clean) rmSync(path.join(outputBaseDirectory, mudConfig.worldgenDirectory), { recursive: true, force: true });
48
+ const outputBaseDirectory = path.join(srcDir, mudConfig.codegenDirectory);
48
49
 
49
- // generate new interfaces
50
- await worldgen(mudConfig, existingContracts, outputBaseDirectory);
50
+ // clear the worldgen directory
51
+ if (args.clean) rmSync(path.join(outputBaseDirectory, mudConfig.worldgenDirectory), { recursive: true, force: true });
51
52
 
52
- process.exit(0);
53
- },
54
- };
53
+ // generate new interfaces
54
+ await worldgen(mudConfig, existingContracts, outputBaseDirectory);
55
+ }
55
56
 
56
57
  export default commandModule;
package/src/common.ts ADDED
@@ -0,0 +1 @@
1
+ export type MudPackages = Record<string, { localPath: string }>;
package/src/debug.ts ADDED
@@ -0,0 +1,3 @@
1
+ import createDebug from "debug";
2
+
3
+ export const debug = createDebug("mud:cli");
@@ -0,0 +1,42 @@
1
+ import { Account, Chain, Client, Hex, Transport, getAddress } from "viem";
2
+ import { WorldDeploy, worldTables } from "./common";
3
+ import { hexToResource, resourceToHex } from "@latticexyz/common";
4
+ import { getResourceIds } from "./getResourceIds";
5
+ import { getTableValue } from "./getTableValue";
6
+
7
+ export async function assertNamespaceOwner({
8
+ client,
9
+ worldDeploy,
10
+ resourceIds,
11
+ }: {
12
+ readonly client: Client<Transport, Chain | undefined, Account>;
13
+ readonly worldDeploy: WorldDeploy;
14
+ readonly resourceIds: readonly Hex[];
15
+ }): Promise<void> {
16
+ const desiredNamespaces = Array.from(new Set(resourceIds.map((resourceId) => hexToResource(resourceId).namespace)));
17
+ const existingResourceIds = await getResourceIds({ client, worldDeploy });
18
+ const existingNamespaces = Array.from(
19
+ new Set(existingResourceIds.map((resourceId) => hexToResource(resourceId).namespace))
20
+ );
21
+
22
+ const namespaces = desiredNamespaces.filter((namespace) => existingNamespaces.includes(namespace));
23
+ const namespaceOwners = await Promise.all(
24
+ namespaces.map(async (namespace) => {
25
+ const { owner } = await getTableValue({
26
+ client,
27
+ worldDeploy,
28
+ table: worldTables.world_NamespaceOwner,
29
+ key: { namespaceId: resourceToHex({ type: "namespace", namespace, name: "" }) },
30
+ });
31
+ return [namespace, owner];
32
+ })
33
+ );
34
+
35
+ const unauthorizedNamespaces = namespaceOwners
36
+ .filter(([, owner]) => getAddress(owner) !== getAddress(client.account.address))
37
+ .map(([namespace]) => namespace);
38
+
39
+ if (unauthorizedNamespaces.length) {
40
+ throw new Error(`You are attempting to deploy to namespaces you do not own: ${unauthorizedNamespaces.join(", ")}`);
41
+ }
42
+ }
@@ -0,0 +1,76 @@
1
+ import { Abi, Address, Hex, padHex } from "viem";
2
+ import storeConfig from "@latticexyz/store/mud.config";
3
+ import worldConfig from "@latticexyz/world/mud.config";
4
+ import IBaseWorldAbi from "@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json" assert { type: "json" };
5
+ import IModuleAbi from "@latticexyz/world-modules/out/IModule.sol/IModule.abi.json" assert { type: "json" };
6
+ import { Tables, configToTables } from "./configToTables";
7
+ import { StoreConfig, helloStoreEvent } from "@latticexyz/store";
8
+ import { WorldConfig, helloWorldEvent } from "@latticexyz/world";
9
+
10
+ export const salt = padHex("0x", { size: 32 });
11
+
12
+ // https://eips.ethereum.org/EIPS/eip-170
13
+ export const contractSizeLimit = parseInt("6000", 16);
14
+
15
+ // TODO: add `as const` to mud config so these get more strongly typed (blocked by current config parsing not using readonly)
16
+ export const storeTables = configToTables(storeConfig);
17
+ export const worldTables = configToTables(worldConfig);
18
+
19
+ export const worldDeployEvents = [helloStoreEvent, helloWorldEvent] as const;
20
+
21
+ export const worldAbi = [...IBaseWorldAbi, ...IModuleAbi] as const;
22
+
23
+ // Ideally, this should be an append-only list. Before adding more versions here, be sure to add backwards-compatible support for old Store/World versions.
24
+ export const supportedStoreVersions = ["1.0.0-unaudited"];
25
+ export const supportedWorldVersions = ["1.0.0-unaudited"];
26
+
27
+ export type WorldDeploy = {
28
+ readonly address: Address;
29
+ readonly worldVersion: string;
30
+ readonly storeVersion: string;
31
+ /** Block number where the world was deployed */
32
+ readonly deployBlock: bigint;
33
+ /**
34
+ * Block number at the time of fetching world deploy.
35
+ * We use this block number when requesting data from the chain to align chain state
36
+ * with the same block during the introspection steps of the deploy.
37
+ */
38
+ readonly stateBlock: bigint;
39
+ };
40
+
41
+ export type WorldFunction = {
42
+ readonly signature: string;
43
+ readonly selector: Hex;
44
+ readonly systemId: Hex;
45
+ readonly systemFunctionSignature: string;
46
+ readonly systemFunctionSelector: Hex;
47
+ };
48
+
49
+ export type DeterministicContract = {
50
+ readonly address: Address;
51
+ readonly bytecode: Hex;
52
+ readonly deployedBytecodeSize: number;
53
+ readonly abi: Abi;
54
+ };
55
+
56
+ export type System = DeterministicContract & {
57
+ readonly namespace: string;
58
+ readonly name: string;
59
+ readonly systemId: Hex;
60
+ readonly allowAll: boolean;
61
+ readonly allowedAddresses: readonly Hex[];
62
+ readonly functions: readonly WorldFunction[];
63
+ };
64
+
65
+ export type Module = DeterministicContract & {
66
+ readonly name: string;
67
+ readonly installAsRoot: boolean;
68
+ readonly installData: Hex; // TODO: figure out better naming for this
69
+ };
70
+
71
+ export type ConfigInput = StoreConfig & WorldConfig;
72
+ export type Config<config extends ConfigInput> = {
73
+ readonly tables: Tables<config>;
74
+ readonly systems: readonly System[];
75
+ readonly modules: readonly Module[];
76
+ };
@@ -0,0 +1,68 @@
1
+ import { resourceToHex } from "@latticexyz/common";
2
+ import { KeySchema, ValueSchema } from "@latticexyz/protocol-parser";
3
+ import { SchemaAbiType, StaticAbiType } from "@latticexyz/schema-type";
4
+ import { StoreConfig, resolveUserTypes } from "@latticexyz/store";
5
+ import { Hex } from "viem";
6
+
7
+ // TODO: we shouldn't need this file once our config parsing returns nicely formed tables
8
+
9
+ type UserTypes<config extends StoreConfig = StoreConfig> = config["userTypes"];
10
+ // TODO: fix strong enum types and avoid every schema getting `{ [k: string]: "uint8" }`
11
+ // type UserTypes<config extends StoreConfig = StoreConfig> = config["userTypes"] & {
12
+ // [k in keyof config["enums"]]: { internalType: "uint8" };
13
+ // };
14
+
15
+ export type TableKey<
16
+ config extends StoreConfig = StoreConfig,
17
+ table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]]
18
+ > = `${config["namespace"]}_${table["name"]}`;
19
+
20
+ export type Table<
21
+ config extends StoreConfig = StoreConfig,
22
+ table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]]
23
+ > = {
24
+ readonly namespace: config["namespace"];
25
+ readonly name: table["name"];
26
+ readonly tableId: Hex;
27
+ readonly keySchema: table["keySchema"] extends KeySchema<UserTypes<config>>
28
+ ? KeySchema & {
29
+ readonly [k in keyof table["keySchema"]]: UserTypes<config>[table["keySchema"][k]]["internalType"] extends StaticAbiType
30
+ ? UserTypes<config>[table["keySchema"][k]]["internalType"]
31
+ : table["keySchema"][k];
32
+ }
33
+ : KeySchema;
34
+ readonly valueSchema: table["valueSchema"] extends ValueSchema<UserTypes<config>>
35
+ ? {
36
+ readonly [k in keyof table["valueSchema"]]: UserTypes<config>[table["valueSchema"][k]]["internalType"] extends SchemaAbiType
37
+ ? UserTypes<config>[table["valueSchema"][k]]["internalType"]
38
+ : table["valueSchema"][k];
39
+ }
40
+ : ValueSchema;
41
+ };
42
+
43
+ export type Tables<config extends StoreConfig = StoreConfig> = {
44
+ readonly [k in keyof config["tables"] as TableKey<config, config["tables"][k]>]: Table<config, config["tables"][k]>;
45
+ };
46
+
47
+ export function configToTables<config extends StoreConfig>(config: config): Tables<config> {
48
+ const userTypes = {
49
+ ...config.userTypes,
50
+ ...Object.fromEntries(Object.entries(config.enums).map(([key]) => [key, { internalType: "uint8" }] as const)),
51
+ };
52
+ return Object.fromEntries(
53
+ Object.entries(config.tables).map(([tableName, table]) => [
54
+ `${config.namespace}_${tableName}` satisfies TableKey<config, config["tables"][keyof config["tables"]]>,
55
+ {
56
+ namespace: config.namespace,
57
+ name: table.name,
58
+ tableId: resourceToHex({
59
+ type: table.offchainOnly ? "offchainTable" : "table",
60
+ namespace: config.namespace,
61
+ name: table.name,
62
+ }),
63
+ keySchema: resolveUserTypes(table.keySchema, userTypes) as any,
64
+ valueSchema: resolveUserTypes(table.valueSchema, userTypes) as any,
65
+ } satisfies Table<config, config["tables"][keyof config["tables"]]>,
66
+ ])
67
+ ) as Tables<config>;
68
+ }
@@ -0,0 +1,9 @@
1
+ Files generated by
2
+
3
+ ```
4
+ git clone https://github.com/Arachnid/deterministic-deployment-proxy.git
5
+ cd deterministic-deployment-proxy
6
+ git checkout b3bb19c
7
+ npm install
8
+ npm run build
9
+ ```
@@ -0,0 +1,7 @@
1
+ {
2
+ "gasPrice": 100000000000,
3
+ "gasLimit": 100000,
4
+ "signerAddress": "3fab184622dc19b6109349b94811493bf2a45362",
5
+ "transaction": "f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",
6
+ "address": "4e59b44847b379578588920ca78fbf26c0b4956c"
7
+ }
@@ -0,0 +1,3 @@
1
+ import { debug as parentDebug } from "../debug";
2
+
3
+ export const debug = parentDebug.extend("deploy");
@@ -0,0 +1,108 @@
1
+ import { Account, Address, Chain, Client, Transport, getAddress } from "viem";
2
+ import { ensureDeployer } from "./ensureDeployer";
3
+ import { deployWorld } from "./deployWorld";
4
+ import { ensureTables } from "./ensureTables";
5
+ import { Config, ConfigInput, WorldDeploy, supportedStoreVersions, supportedWorldVersions } from "./common";
6
+ import { ensureSystems } from "./ensureSystems";
7
+ import { waitForTransactionReceipt } from "viem/actions";
8
+ import { getWorldDeploy } from "./getWorldDeploy";
9
+ import { ensureFunctions } from "./ensureFunctions";
10
+ import { ensureModules } from "./ensureModules";
11
+ import { Table } from "./configToTables";
12
+ import { assertNamespaceOwner } from "./assertNamespaceOwner";
13
+ import { debug } from "./debug";
14
+ import { resourceLabel } from "./resourceLabel";
15
+ import { uniqueBy } from "@latticexyz/common/utils";
16
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
17
+ import { coreModuleBytecode, worldFactoryBytecode, worldFactoryContracts } from "./ensureWorldFactory";
18
+
19
+ type DeployOptions<configInput extends ConfigInput> = {
20
+ client: Client<Transport, Chain | undefined, Account>;
21
+ config: Config<configInput>;
22
+ worldAddress?: Address;
23
+ };
24
+
25
+ /**
26
+ * Given a viem client and MUD config, we attempt to introspect the world
27
+ * (or deploy a new one if no world address is provided) and do the minimal
28
+ * amount of work to make the world match the config (e.g. deploy new tables,
29
+ * replace systems, etc.)
30
+ */
31
+ export async function deploy<configInput extends ConfigInput>({
32
+ client,
33
+ config,
34
+ worldAddress: existingWorldAddress,
35
+ }: DeployOptions<configInput>): Promise<WorldDeploy> {
36
+ const tables = Object.values(config.tables) as Table[];
37
+ const systems = Object.values(config.systems);
38
+
39
+ await ensureDeployer(client);
40
+
41
+ // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.
42
+ await ensureContractsDeployed({
43
+ client,
44
+ contracts: [
45
+ ...worldFactoryContracts,
46
+ ...uniqueBy(systems, (system) => getAddress(system.address)).map((system) => ({
47
+ bytecode: system.bytecode,
48
+ deployedBytecodeSize: system.deployedBytecodeSize,
49
+ label: `${resourceLabel(system)} system`,
50
+ })),
51
+ ...uniqueBy(config.modules, (mod) => getAddress(mod.address)).map((mod) => ({
52
+ bytecode: mod.bytecode,
53
+ deployedBytecodeSize: mod.deployedBytecodeSize,
54
+ label: `${mod.name} module`,
55
+ })),
56
+ ],
57
+ });
58
+
59
+ const worldDeploy = existingWorldAddress
60
+ ? await getWorldDeploy(client, existingWorldAddress)
61
+ : await deployWorld(client);
62
+
63
+ if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {
64
+ throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);
65
+ }
66
+ if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {
67
+ throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);
68
+ }
69
+
70
+ await assertNamespaceOwner({
71
+ client,
72
+ worldDeploy,
73
+ resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],
74
+ });
75
+
76
+ const tableTxs = await ensureTables({
77
+ client,
78
+ worldDeploy,
79
+ tables,
80
+ });
81
+ const systemTxs = await ensureSystems({
82
+ client,
83
+ worldDeploy,
84
+ systems,
85
+ });
86
+ const functionTxs = await ensureFunctions({
87
+ client,
88
+ worldDeploy,
89
+ functions: systems.flatMap((system) => system.functions),
90
+ });
91
+ const moduleTxs = await ensureModules({
92
+ client,
93
+ worldDeploy,
94
+ modules: config.modules,
95
+ });
96
+
97
+ const txs = [...tableTxs, ...systemTxs, ...functionTxs, ...moduleTxs];
98
+
99
+ // wait for each tx separately/serially, because parallelizing results in RPC errors
100
+ debug("waiting for all transactions to confirm");
101
+ for (const tx of txs) {
102
+ await waitForTransactionReceipt(client, { hash: tx });
103
+ // TODO: throw if there was a revert?
104
+ }
105
+
106
+ debug("deploy complete");
107
+ return worldDeploy;
108
+ }
@@ -0,0 +1,33 @@
1
+ import { Account, Chain, Client, Log, Transport } from "viem";
2
+ import { waitForTransactionReceipt } from "viem/actions";
3
+ import { ensureWorldFactory, worldFactory } from "./ensureWorldFactory";
4
+ import WorldFactoryAbi from "@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json" assert { type: "json" };
5
+ import { writeContract } from "@latticexyz/common";
6
+ import { debug } from "./debug";
7
+ import { logsToWorldDeploy } from "./logsToWorldDeploy";
8
+ import { WorldDeploy } from "./common";
9
+
10
+ export async function deployWorld(client: Client<Transport, Chain | undefined, Account>): Promise<WorldDeploy> {
11
+ await ensureWorldFactory(client);
12
+
13
+ debug("deploying world");
14
+ const tx = await writeContract(client, {
15
+ chain: client.chain ?? null,
16
+ address: worldFactory,
17
+ abi: WorldFactoryAbi,
18
+ functionName: "deployWorld",
19
+ });
20
+
21
+ debug("waiting for world deploy");
22
+ const receipt = await waitForTransactionReceipt(client, { hash: tx });
23
+ if (receipt.status !== "success") {
24
+ console.error("world deploy failed", receipt);
25
+ throw new Error("world deploy failed");
26
+ }
27
+
28
+ // TODO: remove type casting once https://github.com/wagmi-dev/viem/pull/1330 is merged
29
+ const deploy = logsToWorldDeploy(receipt.logs.map((log) => log as Log<bigint, number, false>));
30
+ debug("deployed world to", deploy.address, "at block", deploy.deployBlock);
31
+
32
+ return { ...deploy, stateBlock: deploy.deployBlock };
33
+ }