@latticexyz/cli 2.0.0-alpha.93 → 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-P5YXGXRI.js +0 -3842
  65. package/dist/chunk-SKNB74MT.js +0 -726
  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,31 @@
1
+ import { Client, parseAbiItem, Hex } from "viem";
2
+ import { getLogs } from "viem/actions";
3
+ import { storeSpliceStaticDataEvent } from "@latticexyz/store";
4
+ import { WorldDeploy, storeTables } from "./common";
5
+ import { debug } from "./debug";
6
+
7
+ export async function getResourceIds({
8
+ client,
9
+ worldDeploy,
10
+ }: {
11
+ readonly client: Client;
12
+ readonly worldDeploy: WorldDeploy;
13
+ }): Promise<readonly Hex[]> {
14
+ // This assumes we only use `ResourceIds._setExists(true)`, which is true as of this writing.
15
+ // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state
16
+
17
+ debug("looking up resource IDs for", worldDeploy.address);
18
+ const logs = await getLogs(client, {
19
+ strict: true,
20
+ address: worldDeploy.address,
21
+ fromBlock: worldDeploy.deployBlock,
22
+ toBlock: worldDeploy.stateBlock,
23
+ event: parseAbiItem(storeSpliceStaticDataEvent),
24
+ args: { tableId: storeTables.store_ResourceIds.tableId },
25
+ });
26
+
27
+ const resourceIds = logs.map((log) => log.args.keyTuple[0]);
28
+ debug("found", resourceIds.length, "resource IDs for", worldDeploy.address);
29
+
30
+ return resourceIds;
31
+ }
@@ -0,0 +1,48 @@
1
+ import { System, WorldDeploy, worldTables } from "./common";
2
+ import { Client } from "viem";
3
+ import { getResourceIds } from "./getResourceIds";
4
+ import { hexToResource } from "@latticexyz/common";
5
+ import { getTableValue } from "./getTableValue";
6
+ import { debug } from "./debug";
7
+ import { resourceLabel } from "./resourceLabel";
8
+ import { getFunctions } from "./getFunctions";
9
+ import { getResourceAccess } from "./getResourceAccess";
10
+
11
+ export async function getSystems({
12
+ client,
13
+ worldDeploy,
14
+ }: {
15
+ readonly client: Client;
16
+ readonly worldDeploy: WorldDeploy;
17
+ }): Promise<readonly Omit<System, "abi" | "bytecode" | "deployedBytecodeSize">[]> {
18
+ const [resourceIds, functions, resourceAccess] = await Promise.all([
19
+ getResourceIds({ client, worldDeploy }),
20
+ getFunctions({ client, worldDeploy }),
21
+ getResourceAccess({ client, worldDeploy }),
22
+ ]);
23
+ const systems = resourceIds.map(hexToResource).filter((resource) => resource.type === "system");
24
+
25
+ debug("looking up systems", systems.map(resourceLabel).join(", "));
26
+ return await Promise.all(
27
+ systems.map(async (system) => {
28
+ const { system: address, publicAccess } = await getTableValue({
29
+ client,
30
+ worldDeploy,
31
+ table: worldTables.world_Systems,
32
+ key: { systemId: system.resourceId },
33
+ });
34
+ const systemFunctions = functions.filter((func) => func.systemId === system.resourceId);
35
+ return {
36
+ address,
37
+ namespace: system.namespace,
38
+ name: system.name,
39
+ systemId: system.resourceId,
40
+ allowAll: publicAccess,
41
+ allowedAddresses: resourceAccess
42
+ .filter(({ resourceId }) => resourceId === system.resourceId)
43
+ .map(({ address }) => address),
44
+ functions: systemFunctions,
45
+ };
46
+ })
47
+ );
48
+ }
@@ -0,0 +1,30 @@
1
+ import { SchemaToPrimitives, decodeValueArgs, encodeKey } from "@latticexyz/protocol-parser";
2
+ import { WorldDeploy, worldAbi } from "./common";
3
+ import { Client } from "viem";
4
+ import { readContract } from "viem/actions";
5
+ import { Table } from "./configToTables";
6
+
7
+ export async function getTableValue<table extends Table>({
8
+ client,
9
+ worldDeploy,
10
+ table,
11
+ key,
12
+ }: {
13
+ readonly client: Client;
14
+ readonly worldDeploy: WorldDeploy;
15
+ readonly table: table;
16
+ readonly key: SchemaToPrimitives<table["keySchema"]>;
17
+ }): Promise<SchemaToPrimitives<table["valueSchema"]>> {
18
+ const [staticData, encodedLengths, dynamicData] = await readContract(client, {
19
+ blockNumber: worldDeploy.stateBlock,
20
+ address: worldDeploy.address,
21
+ abi: worldAbi,
22
+ functionName: "getRecord",
23
+ args: [table.tableId, encodeKey(table.keySchema, key)],
24
+ });
25
+ return decodeValueArgs(table.valueSchema, {
26
+ staticData,
27
+ encodedLengths,
28
+ dynamicData,
29
+ });
30
+ }
@@ -0,0 +1,59 @@
1
+ import { Client, parseAbiItem, decodeAbiParameters, parseAbiParameters } from "viem";
2
+ import { Table } from "./configToTables";
3
+ import { hexToResource } from "@latticexyz/common";
4
+ import { WorldDeploy, storeTables } from "./common";
5
+ import { debug } from "./debug";
6
+ import { storeSetRecordEvent } from "@latticexyz/store";
7
+ import { getLogs } from "viem/actions";
8
+ import { KeySchema, ValueSchema, decodeKey, decodeValueArgs, hexToSchema } from "@latticexyz/protocol-parser";
9
+
10
+ export async function getTables({
11
+ client,
12
+ worldDeploy,
13
+ }: {
14
+ readonly client: Client;
15
+ readonly worldDeploy: WorldDeploy;
16
+ }): Promise<readonly Table[]> {
17
+ // This assumes we only use `Tables._set(...)`, which is true as of this writing.
18
+ // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state
19
+ // TODO: consider moving this to a batched getRecord for Tables table
20
+
21
+ debug("looking up tables for", worldDeploy.address);
22
+ const logs = await getLogs(client, {
23
+ strict: true,
24
+ // this may fail for certain RPC providers with block range limits
25
+ // if so, could potentially use our fetchLogs helper (which does pagination)
26
+ fromBlock: worldDeploy.deployBlock,
27
+ toBlock: worldDeploy.stateBlock,
28
+ address: worldDeploy.address,
29
+ event: parseAbiItem(storeSetRecordEvent),
30
+ args: { tableId: storeTables.store_Tables.tableId },
31
+ });
32
+
33
+ // TODO: combine with store-sync logToTable and export from somewhere
34
+ const tables = logs.map((log) => {
35
+ const { tableId } = decodeKey(storeTables.store_Tables.keySchema, log.args.keyTuple);
36
+ const { namespace, name } = hexToResource(tableId);
37
+ const value = decodeValueArgs(storeTables.store_Tables.valueSchema, log.args);
38
+
39
+ // TODO: migrate to better helper
40
+ const keySchemaFields = hexToSchema(value.keySchema);
41
+ const valueSchemaFields = hexToSchema(value.valueSchema);
42
+ const keyNames = decodeAbiParameters(parseAbiParameters("string[]"), value.abiEncodedKeyNames)[0];
43
+ const fieldNames = decodeAbiParameters(parseAbiParameters("string[]"), value.abiEncodedFieldNames)[0];
44
+
45
+ const valueAbiTypes = [...valueSchemaFields.staticFields, ...valueSchemaFields.dynamicFields];
46
+
47
+ const keySchema = Object.fromEntries(
48
+ keySchemaFields.staticFields.map((abiType, i) => [keyNames[i], abiType])
49
+ ) as KeySchema;
50
+ const valueSchema = Object.fromEntries(valueAbiTypes.map((abiType, i) => [fieldNames[i], abiType])) as ValueSchema;
51
+
52
+ return { namespace, name, tableId, keySchema, valueSchema } as const;
53
+ });
54
+ // TODO: filter/detect duplicates?
55
+
56
+ debug("found", tables.length, "tables for", worldDeploy.address);
57
+
58
+ return tables;
59
+ }
@@ -0,0 +1,39 @@
1
+ import { Client, Address, getAddress, parseAbi } from "viem";
2
+ import { getBlockNumber, getLogs } from "viem/actions";
3
+ import { WorldDeploy, worldDeployEvents } from "./common";
4
+ import { debug } from "./debug";
5
+ import { logsToWorldDeploy } from "./logsToWorldDeploy";
6
+
7
+ const deploys = new Map<Address, WorldDeploy>();
8
+
9
+ export async function getWorldDeploy(client: Client, worldAddress: Address): Promise<WorldDeploy> {
10
+ const address = getAddress(worldAddress);
11
+
12
+ let deploy = deploys.get(address);
13
+ if (deploy != null) {
14
+ return deploy;
15
+ }
16
+
17
+ debug("looking up world deploy for", address);
18
+
19
+ const stateBlock = await getBlockNumber(client);
20
+ const logs = await getLogs(client, {
21
+ strict: true,
22
+ address,
23
+ events: parseAbi(worldDeployEvents),
24
+ // this may fail for certain RPC providers with block range limits
25
+ // if so, could potentially use our fetchLogs helper (which does pagination)
26
+ fromBlock: "earliest",
27
+ toBlock: stateBlock,
28
+ });
29
+
30
+ deploy = {
31
+ ...logsToWorldDeploy(logs),
32
+ stateBlock,
33
+ };
34
+ deploys.set(address, deploy);
35
+
36
+ debug("found world deploy for", address, "at block", deploy.deployBlock);
37
+
38
+ return deploy;
39
+ }
@@ -0,0 +1,49 @@
1
+ import { AbiEventSignatureNotFoundError, Log, decodeEventLog, hexToString, parseAbi, trim } from "viem";
2
+ import { WorldDeploy, worldDeployEvents } from "./common";
3
+ import { isDefined } from "@latticexyz/common/utils";
4
+
5
+ export function logsToWorldDeploy(logs: readonly Log<bigint, number, false>[]): Omit<WorldDeploy, "stateBlock"> {
6
+ const deployLogs = logs
7
+ .map((log) => {
8
+ try {
9
+ return {
10
+ ...log,
11
+ ...decodeEventLog({
12
+ strict: true,
13
+ abi: parseAbi(worldDeployEvents),
14
+ topics: log.topics,
15
+ data: log.data,
16
+ }),
17
+ };
18
+ } catch (error: unknown) {
19
+ if (error instanceof AbiEventSignatureNotFoundError) {
20
+ return;
21
+ }
22
+ throw error;
23
+ }
24
+ })
25
+ .filter(isDefined);
26
+
27
+ // TODO: should this test for/validate that only one of each of these events is present? and that the address/block number don't change between each?
28
+ const { address, deployBlock, worldVersion, storeVersion } = deployLogs.reduce<Partial<WorldDeploy>>(
29
+ (deploy, log) => ({
30
+ ...deploy,
31
+ address: log.address,
32
+ deployBlock: log.blockNumber,
33
+ ...(log.eventName === "HelloWorld"
34
+ ? { worldVersion: hexToString(trim(log.args.worldVersion, { dir: "right" })) }
35
+ : null),
36
+ ...(log.eventName === "HelloStore"
37
+ ? { storeVersion: hexToString(trim(log.args.storeVersion, { dir: "right" })) }
38
+ : null),
39
+ }),
40
+ {}
41
+ );
42
+
43
+ if (address == null) throw new Error("could not find world address");
44
+ if (deployBlock == null) throw new Error("could not find world deploy block number");
45
+ if (worldVersion == null) throw new Error("could not find world version");
46
+ if (storeVersion == null) throw new Error("could not find store version");
47
+
48
+ return { address, deployBlock, worldVersion, storeVersion };
49
+ }
@@ -0,0 +1,151 @@
1
+ import { resolveWorldConfig } from "@latticexyz/world";
2
+ import { Config, ConfigInput, WorldFunction, salt } from "./common";
3
+ import { resourceToHex, hexToResource } from "@latticexyz/common";
4
+ import { resolveWithContext } from "@latticexyz/config";
5
+ import { encodeField } from "@latticexyz/protocol-parser";
6
+ import { SchemaAbiType, SchemaAbiTypeToPrimitiveType } from "@latticexyz/schema-type";
7
+ import {
8
+ getFunctionSelector,
9
+ Hex,
10
+ getCreate2Address,
11
+ getAddress,
12
+ hexToBytes,
13
+ Abi,
14
+ bytesToHex,
15
+ getFunctionSignature,
16
+ } from "viem";
17
+ import { getExistingContracts } from "../utils/getExistingContracts";
18
+ import { defaultModuleContracts } from "../utils/modules/constants";
19
+ import { getContractData } from "../utils/utils/getContractData";
20
+ import { configToTables } from "./configToTables";
21
+ import { deployer } from "./ensureDeployer";
22
+ import { resourceLabel } from "./resourceLabel";
23
+
24
+ // TODO: this should be replaced by https://github.com/latticexyz/mud/issues/1668
25
+
26
+ export function resolveConfig<config extends ConfigInput>({
27
+ config,
28
+ forgeSourceDir,
29
+ forgeOutDir,
30
+ }: {
31
+ config: config;
32
+ forgeSourceDir: string;
33
+ forgeOutDir: string;
34
+ }): Config<config> {
35
+ const tables = configToTables(config);
36
+
37
+ // TODO: should the config parser/loader help with resolving systems?
38
+ const contractNames = getExistingContracts(forgeSourceDir).map(({ basename }) => basename);
39
+ const resolvedConfig = resolveWorldConfig(config, contractNames);
40
+ const baseSystemContractData = getContractData("System", forgeOutDir);
41
+ const baseSystemFunctions = baseSystemContractData.abi
42
+ .filter((item): item is typeof item & { type: "function" } => item.type === "function")
43
+ .map(getFunctionSignature);
44
+
45
+ const systems = Object.entries(resolvedConfig.systems).map(([systemName, system]) => {
46
+ const namespace = config.namespace;
47
+ const name = system.name;
48
+ const systemId = resourceToHex({ type: "system", namespace, name });
49
+ const contractData = getContractData(systemName, forgeOutDir);
50
+
51
+ const systemFunctions = contractData.abi
52
+ .filter((item): item is typeof item & { type: "function" } => item.type === "function")
53
+ .map(getFunctionSignature)
54
+ .filter((sig) => !baseSystemFunctions.includes(sig))
55
+ .map((sig): WorldFunction => {
56
+ // TODO: figure out how to not duplicate contract behavior (https://github.com/latticexyz/mud/issues/1708)
57
+ const worldSignature = namespace === "" ? sig : `${namespace}_${name}_${sig}`;
58
+ return {
59
+ signature: worldSignature,
60
+ selector: getFunctionSelector(worldSignature),
61
+ systemId,
62
+ systemFunctionSignature: sig,
63
+ systemFunctionSelector: getFunctionSelector(sig),
64
+ };
65
+ });
66
+
67
+ return {
68
+ namespace,
69
+ name,
70
+ systemId,
71
+ allowAll: system.openAccess,
72
+ allowedAddresses: system.accessListAddresses as Hex[],
73
+ allowedSystemIds: system.accessListSystems.map((name) =>
74
+ resourceToHex({ type: "system", namespace, name: resolvedConfig.systems[name].name })
75
+ ),
76
+ address: getCreate2Address({ from: deployer, bytecode: contractData.bytecode, salt }),
77
+ bytecode: contractData.bytecode,
78
+ deployedBytecodeSize: contractData.deployedBytecodeSize,
79
+ abi: contractData.abi,
80
+ functions: systemFunctions,
81
+ };
82
+ });
83
+
84
+ // resolve allowedSystemIds
85
+ // TODO: resolve this at deploy time so we can allow for arbitrary system IDs registered in the world as the source-of-truth rather than config
86
+ const systemsWithAccess = systems.map(({ allowedAddresses, allowedSystemIds, ...system }) => {
87
+ const allowedSystemAddresses = allowedSystemIds.map((systemId) => {
88
+ const targetSystem = systems.find((s) => s.systemId === systemId);
89
+ if (!targetSystem) {
90
+ throw new Error(
91
+ `System ${resourceLabel(system)} wanted access to ${resourceLabel(
92
+ hexToResource(systemId)
93
+ )}, but it wasn't found in the config.`
94
+ );
95
+ }
96
+ return targetSystem.address;
97
+ });
98
+ return {
99
+ ...system,
100
+ allowedAddresses: Array.from(
101
+ new Set([...allowedAddresses, ...allowedSystemAddresses].map((addr) => getAddress(addr)))
102
+ ),
103
+ };
104
+ });
105
+
106
+ // ugh (https://github.com/latticexyz/mud/issues/1668)
107
+ const resolveContext = {
108
+ tableIds: Object.fromEntries(
109
+ Object.entries(config.tables).map(([tableName, table]) => [
110
+ tableName,
111
+ hexToBytes(
112
+ resourceToHex({
113
+ type: table.offchainOnly ? "offchainTable" : "table",
114
+ namespace: config.namespace,
115
+ name: table.name,
116
+ })
117
+ ),
118
+ ])
119
+ ),
120
+ };
121
+
122
+ const modules = config.modules.map((mod) => {
123
+ const contractData =
124
+ defaultModuleContracts.find((defaultMod) => defaultMod.name === mod.name) ??
125
+ getContractData(mod.name, forgeOutDir);
126
+ const installArgs = mod.args
127
+ .map((arg) => resolveWithContext(arg, resolveContext))
128
+ .map((arg) => {
129
+ const value = arg.value instanceof Uint8Array ? bytesToHex(arg.value) : arg.value;
130
+ return encodeField(arg.type as SchemaAbiType, value as SchemaAbiTypeToPrimitiveType<SchemaAbiType>);
131
+ });
132
+ if (installArgs.length > 1) {
133
+ throw new Error(`${mod.name} module should only have 0-1 args, but had ${installArgs.length} args.`);
134
+ }
135
+ return {
136
+ name: mod.name,
137
+ installAsRoot: mod.root,
138
+ installData: installArgs.length === 0 ? "0x" : installArgs[0],
139
+ address: getCreate2Address({ from: deployer, bytecode: contractData.bytecode, salt }),
140
+ bytecode: contractData.bytecode,
141
+ deployedBytecodeSize: contractData.deployedBytecodeSize,
142
+ abi: contractData.abi,
143
+ };
144
+ });
145
+
146
+ return {
147
+ tables,
148
+ systems: systemsWithAccess,
149
+ modules,
150
+ };
151
+ }
@@ -0,0 +1,3 @@
1
+ export function resourceLabel({ namespace, name }: { readonly namespace: string; readonly name: string }): string {
2
+ return `${namespace}:${name}`;
3
+ }
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export {};
1
+ // nothing to export
@@ -0,0 +1,11 @@
1
+ // adding .js to minimal would break clients down the line because it probably won't get a synthetic default import
2
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ declare module "protobufjs/minimal" {
4
+ export const configure: any;
5
+ export const util: any;
6
+ export const Reader: any;
7
+ export type Reader = any;
8
+ export const Writer: any;
9
+ export type Writer = any;
10
+ }
11
+ declare module "rollup-plugin-preserve-shebang";
package/src/mud.ts CHANGED
@@ -1,30 +1,45 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import yargs from "yargs";
4
- import { hideBin } from "yargs/helpers";
5
- import { commands as v2 } from "./commands/index.js";
6
- import { commands as v1 } from "./commands/deprecated/index.js";
7
- import { logError } from "./utils/errors.js";
8
-
9
3
  // Load .env file into process.env
10
4
  import * as dotenv from "dotenv";
11
5
  dotenv.config();
12
6
 
13
- yargs(hideBin(process.argv))
14
- // Explicit name to display in help (by default it's the entry file, which may not be "mud" for e.g. ts-node)
15
- .scriptName("mud")
16
- // Use the commands directory to scaffold
17
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy
18
- .command([...v1, ...v2] as any)
19
- // Enable strict mode.
20
- .strict()
21
- // Custom error handler
22
- .fail((msg, err) => {
23
- console.log("");
24
- logError(err);
25
- console.log("");
7
+ async function run() {
8
+ // Import everything else async so they can pick up env vars in .env
9
+ const { default: yargs } = await import("yargs");
10
+ const { default: chalk } = await import("chalk");
11
+ const { hideBin } = await import("yargs/helpers");
12
+ const { logError } = await import("./utils/errors");
13
+ const { commands } = await import("./commands");
14
+
15
+ yargs(hideBin(process.argv))
16
+ // Explicit name to display in help (by default it's the entry file, which may not be "mud" for e.g. ts-node)
17
+ .scriptName("mud")
18
+ // Use the commands directory to scaffold
19
+ // command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ .command(commands as any)
22
+ // Enable strict mode.
23
+ .strict()
24
+ // Custom error handler
25
+ .fail((msg, err) => {
26
+ console.error(chalk.red(msg));
27
+ if (msg.includes("Missing required argument")) {
28
+ console.log(
29
+ chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)
30
+ );
31
+ }
32
+ console.log("");
33
+ // Even though `.fail` type says we should get an `Error`, this can sometimes be undefined
34
+ if (err != null) {
35
+ logError(err);
36
+ console.log("");
37
+ }
38
+
39
+ process.exit(1);
40
+ })
41
+ // Useful aliases.
42
+ .alias({ h: "help" }).argv;
43
+ }
26
44
 
27
- process.exit(1);
28
- })
29
- // Useful aliases.
30
- .alias({ h: "help" }).argv;
45
+ run();
@@ -0,0 +1,24 @@
1
+ import { ZodError, z } from "zod";
2
+ import { MudPackages } from "./common";
3
+
4
+ const envSchema = z.object({
5
+ MUD_PACKAGES: z.string().transform((value) => JSON.parse(value) as MudPackages),
6
+ });
7
+
8
+ function parseEnv(): z.infer<typeof envSchema> {
9
+ try {
10
+ return envSchema.parse({
11
+ // tsup replaces the env vars with their values at compile time
12
+ MUD_PACKAGES: process.env.MUD_PACKAGES,
13
+ });
14
+ } catch (error) {
15
+ if (error instanceof ZodError) {
16
+ const { _errors, ...invalidEnvVars } = error.format();
17
+ console.error(`\nMissing or invalid environment variables:\n\n ${Object.keys(invalidEnvVars).join("\n ")}\n`);
18
+ process.exit(1);
19
+ }
20
+ throw error;
21
+ }
22
+ }
23
+
24
+ export const mudPackages = parseEnv().MUD_PACKAGES;
@@ -0,0 +1,128 @@
1
+ import path from "node:path";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { InferredOptionTypes, Options } from "yargs";
4
+ import { deploy } from "./deploy/deploy";
5
+ import { createWalletClient, http, Hex } from "viem";
6
+ import { privateKeyToAccount } from "viem/accounts";
7
+ import { loadConfig } from "@latticexyz/config/node";
8
+ import { StoreConfig } from "@latticexyz/store";
9
+ import { WorldConfig } from "@latticexyz/world";
10
+ import { forge, getOutDirectory, getRemappings, getRpcUrl, getSrcDirectory } from "@latticexyz/common/foundry";
11
+ import chalk from "chalk";
12
+ import { execa } from "execa";
13
+ import { MUDError } from "@latticexyz/common/errors";
14
+ import { resolveConfig } from "./deploy/resolveConfig";
15
+ import { getChainId } from "viem/actions";
16
+ import { postDeploy } from "./utils/utils/postDeploy";
17
+ import { WorldDeploy } from "./deploy/common";
18
+ import { tablegen } from "@latticexyz/store/codegen";
19
+ import { worldgen } from "@latticexyz/world/node";
20
+ import { getExistingContracts } from "./utils/getExistingContracts";
21
+
22
+ export const deployOptions = {
23
+ configPath: { type: "string", desc: "Path to the config file" },
24
+ printConfig: { type: "boolean", desc: "Print the resolved config" },
25
+ profile: { type: "string", desc: "The foundry profile to use" },
26
+ saveDeployment: { type: "boolean", desc: "Save the deployment info to a file", default: true },
27
+ rpc: { type: "string", desc: "The RPC URL to use. Defaults to the RPC url from the local foundry.toml" },
28
+ worldAddress: { type: "string", desc: "Deploy to an existing World at the given address" },
29
+ srcDir: { type: "string", desc: "Source directory. Defaults to foundry src directory." },
30
+ skipBuild: { type: "boolean", desc: "Skip rebuilding the contracts before deploying" },
31
+ alwaysRunPostDeploy: {
32
+ type: "boolean",
33
+ 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.",
34
+ },
35
+ } as const satisfies Record<string, Options>;
36
+
37
+ export type DeployOptions = InferredOptionTypes<typeof deployOptions>;
38
+
39
+ /**
40
+ * Given some CLI arguments, finds and resolves a MUD config, foundry profile, and runs a deploy.
41
+ * This is used by the deploy, test, and dev-contracts CLI commands.
42
+ */
43
+ export async function runDeploy(opts: DeployOptions): Promise<WorldDeploy> {
44
+ const profile = opts.profile ?? process.env.FOUNDRY_PROFILE;
45
+
46
+ const config = (await loadConfig(opts.configPath)) as StoreConfig & WorldConfig;
47
+ if (opts.printConfig) {
48
+ console.log(chalk.green("\nResolved config:\n"), JSON.stringify(config, null, 2));
49
+ }
50
+
51
+ const srcDir = opts.srcDir ?? (await getSrcDirectory(profile));
52
+ const outDir = await getOutDirectory(profile);
53
+ const remappings = await getRemappings();
54
+
55
+ const rpc = opts.rpc ?? (await getRpcUrl(profile));
56
+ console.log(
57
+ chalk.bgBlue(
58
+ chalk.whiteBright(`\n Deploying MUD contracts${profile ? " with profile " + profile : ""} to RPC ${rpc} \n`)
59
+ )
60
+ );
61
+
62
+ // Run build
63
+ if (!opts.skipBuild) {
64
+ const outPath = path.join(srcDir, config.codegenDirectory);
65
+ await Promise.all([tablegen(config, outPath, remappings), worldgen(config, getExistingContracts(srcDir), outPath)]);
66
+ await forge(["build"], { profile });
67
+ await execa("mud", ["abi-ts"], { stdio: "inherit" });
68
+ }
69
+
70
+ const privateKey = process.env.PRIVATE_KEY as Hex;
71
+ if (!privateKey) {
72
+ throw new MUDError(
73
+ `Missing PRIVATE_KEY environment variable.
74
+ Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
75
+ in your contracts directory to use the default anvil private key.`
76
+ );
77
+ }
78
+
79
+ const resolvedConfig = resolveConfig({ config, forgeSourceDir: srcDir, forgeOutDir: outDir });
80
+
81
+ const client = createWalletClient({
82
+ transport: http(rpc),
83
+ account: privateKeyToAccount(privateKey),
84
+ });
85
+ console.log("Deploying from", client.account.address);
86
+
87
+ const startTime = Date.now();
88
+ const worldDeploy = await deploy({
89
+ worldAddress: opts.worldAddress as Hex | undefined,
90
+ client,
91
+ config: resolvedConfig,
92
+ });
93
+ if (opts.worldAddress == null || opts.alwaysRunPostDeploy) {
94
+ await postDeploy(config.postDeployScript, worldDeploy.address, rpc, profile);
95
+ }
96
+ console.log(chalk.green("Deployment completed in", (Date.now() - startTime) / 1000, "seconds"));
97
+
98
+ const deploymentInfo = {
99
+ worldAddress: worldDeploy.address,
100
+ blockNumber: Number(worldDeploy.deployBlock),
101
+ };
102
+
103
+ if (opts.saveDeployment) {
104
+ const chainId = await getChainId(client);
105
+ const deploysDir = path.join(config.deploysDirectory, chainId.toString());
106
+ mkdirSync(deploysDir, { recursive: true });
107
+ writeFileSync(path.join(deploysDir, "latest.json"), JSON.stringify(deploymentInfo, null, 2));
108
+ writeFileSync(path.join(deploysDir, Date.now() + ".json"), JSON.stringify(deploymentInfo, null, 2));
109
+
110
+ const localChains = [1337, 31337];
111
+ const deploys = existsSync(config.worldsFile) ? JSON.parse(readFileSync(config.worldsFile, "utf-8")) : {};
112
+ deploys[chainId] = {
113
+ address: deploymentInfo.worldAddress,
114
+ // We expect the worlds file to be committed and since local deployments are often
115
+ // a consistent address but different block number, we'll ignore the block number.
116
+ blockNumber: localChains.includes(chainId) ? undefined : deploymentInfo.blockNumber,
117
+ };
118
+ writeFileSync(config.worldsFile, JSON.stringify(deploys, null, 2));
119
+
120
+ console.log(
121
+ chalk.bgGreen(chalk.whiteBright(`\n Deployment result (written to ${config.worldsFile} and ${deploysDir}): \n`))
122
+ );
123
+ }
124
+
125
+ console.log(deploymentInfo);
126
+
127
+ return worldDeploy;
128
+ }
@@ -2,7 +2,7 @@ import chalk from "chalk";
2
2
  import { ZodError } from "zod";
3
3
  import { fromZodError, ValidationError } from "zod-validation-error";
4
4
  import { NotInsideProjectError } from "@latticexyz/config";
5
- import { MUDError } from "@latticexyz/config";
5
+ import { MUDError } from "@latticexyz/common/errors";
6
6
 
7
7
  export function logError(error: unknown) {
8
8
  if (error instanceof ValidationError) {