@latticexyz/cli 2.0.0-alpha.94 → 2.0.0-main-0d434816

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 (100) hide show
  1. package/dist/chunk-LFIOIY67.js +30 -0
  2. package/dist/chunk-LFIOIY67.js.map +1 -0
  3. package/dist/index.js +2 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/mud.js +15 -8340
  6. package/dist/mud.js.map +1 -0
  7. package/package.json +45 -43
  8. package/src/commands/deploy.ts +49 -0
  9. package/src/commands/dev-contracts.ts +176 -0
  10. package/src/commands/devnode.ts +7 -2
  11. package/src/commands/faucet.ts +1 -1
  12. package/src/commands/index.ts +18 -13
  13. package/src/commands/set-version.ts +38 -10
  14. package/src/commands/tablegen.ts +5 -4
  15. package/src/commands/{test-v2.ts → test.ts} +5 -6
  16. package/src/commands/trace.ts +108 -0
  17. package/src/commands/tsgen.ts +4 -3
  18. package/src/commands/worldgen.ts +29 -28
  19. package/src/index.ts +2 -1
  20. package/src/modules.d.ts +11 -0
  21. package/src/mud.ts +10 -4
  22. package/src/render-ts/recsV1TableOptions.ts +4 -4
  23. package/src/render-ts/renderRecsV1Tables.ts +3 -3
  24. package/src/render-ts/schemaTypesToRecsTypeStrings.ts +33 -33
  25. package/src/render-ts/tsgen.ts +4 -4
  26. package/src/utils/{deploy-v2.ts → deploy.ts} +207 -123
  27. package/src/utils/deployHandler.ts +87 -0
  28. package/src/utils/errors.ts +1 -1
  29. package/src/utils/getExistingContracts.ts +12 -0
  30. package/src/utils/index.ts +7 -5
  31. package/src/utils/printMUD.ts +14 -0
  32. package/src/utils/worldtypes.ts +21 -0
  33. package/dist/chunk-6V563IAZ.js +0 -283
  34. package/dist/chunk-FPG73MVN.js +0 -71
  35. package/dist/chunk-L4YLJHLJ.js +0 -30
  36. package/dist/chunk-SKNB74MT.js +0 -726
  37. package/dist/chunk-T2YHSEJD.js +0 -3842
  38. package/dist/chunk-VQTZJIFF.js +0 -353
  39. package/dist/chunk-WZFXLDPK.js +0 -761
  40. package/dist/chunk-YL4GJLLL.js +0 -26139
  41. package/dist/index.d.ts +0 -2
  42. package/dist/mud.d.ts +0 -1
  43. package/dist/mud2.d.ts +0 -1
  44. package/dist/mud2.js +0 -25
  45. package/dist/render-solidity/index.d.ts +0 -171
  46. package/dist/render-solidity/index.js +0 -49
  47. package/dist/render-ts/index.d.ts +0 -26
  48. package/dist/render-ts/index.js +0 -14
  49. package/dist/utils/deprecated/index.d.ts +0 -76
  50. package/dist/utils/deprecated/index.js +0 -36
  51. package/dist/utils/index.d.ts +0 -88
  52. package/dist/utils/index.js +0 -39
  53. package/src/commands/deploy-v2.ts +0 -112
  54. package/src/commands/deprecated/bulkupload.ts +0 -50
  55. package/src/commands/deprecated/call-system.ts +0 -70
  56. package/src/commands/deprecated/codegen-libdeploy.ts +0 -29
  57. package/src/commands/deprecated/deploy-contracts.ts +0 -120
  58. package/src/commands/deprecated/index.ts +0 -22
  59. package/src/commands/deprecated/system-types.ts +0 -29
  60. package/src/commands/deprecated/test.ts +0 -53
  61. package/src/commands/deprecated/trace.ts +0 -81
  62. package/src/commands/deprecated/types.ts +0 -33
  63. package/src/commands/gas-report.ts +0 -219
  64. package/src/contracts/BulkUpload.sol +0 -174
  65. package/src/contracts/Deploy.sol +0 -23
  66. package/src/contracts/LibDeploy.ejs +0 -121
  67. package/src/contracts/LibDeploy.sol +0 -23
  68. package/src/contracts/LibDeployStub.sol +0 -23
  69. package/src/mud2.ts +0 -29
  70. package/src/render-solidity/common.ts +0 -138
  71. package/src/render-solidity/field.ts +0 -160
  72. package/src/render-solidity/index.ts +0 -10
  73. package/src/render-solidity/record.ts +0 -158
  74. package/src/render-solidity/renderSystemInterface.ts +0 -31
  75. package/src/render-solidity/renderTable.ts +0 -164
  76. package/src/render-solidity/renderTableIndex.ts +0 -15
  77. package/src/render-solidity/renderTypeHelpers.ts +0 -99
  78. package/src/render-solidity/renderTypes.ts +0 -19
  79. package/src/render-solidity/renderTypesFromConfig.ts +0 -13
  80. package/src/render-solidity/renderWorld.ts +0 -24
  81. package/src/render-solidity/tableOptions.ts +0 -107
  82. package/src/render-solidity/tablegen.ts +0 -35
  83. package/src/render-solidity/types.ts +0 -111
  84. package/src/render-solidity/userType.ts +0 -131
  85. package/src/render-solidity/worldgen.ts +0 -59
  86. package/src/utils/contractToInterface.ts +0 -132
  87. package/src/utils/deprecated/build.ts +0 -55
  88. package/src/utils/deprecated/codegen.ts +0 -42
  89. package/src/utils/deprecated/constants.ts +0 -2
  90. package/src/utils/deprecated/deploy.ts +0 -111
  91. package/src/utils/deprecated/exec.ts +0 -18
  92. package/src/utils/deprecated/findLog.ts +0 -8
  93. package/src/utils/deprecated/hsr.ts +0 -71
  94. package/src/utils/deprecated/ids.ts +0 -14
  95. package/src/utils/deprecated/index.ts +0 -8
  96. package/src/utils/deprecated/typegen.ts +0 -133
  97. package/src/utils/execLog.ts +0 -22
  98. package/src/utils/format.ts +0 -39
  99. package/src/utils/formatAndWrite.ts +0 -21
  100. package/src/utils/foundry.ts +0 -103
@@ -1,132 +0,0 @@
1
- import { parse, visit } from "@solidity-parser/parser";
2
- import { TypeName, VariableDeclaration } from "@solidity-parser/parser/dist/src/ast-types.js";
3
- import { MUDError } from "@latticexyz/config";
4
- import { RenderSystemInterfaceFunction } from "../render-solidity/types.js";
5
-
6
- /**
7
- * Parse the contract data to get the functions necessary to generate an interface,
8
- * and symbols to import from the original contract.
9
- * @param data contents of a file with the solidity contract
10
- * @param contractName name of the contract
11
- * @returns interface data
12
- */
13
- export function contractToInterface(data: string, contractName: string) {
14
- const ast = parse(data);
15
-
16
- let withContract = false;
17
- let symbols: string[] = [];
18
- const functions: RenderSystemInterfaceFunction[] = [];
19
-
20
- visit(ast, {
21
- ContractDefinition({ name }) {
22
- if (name === contractName) {
23
- withContract = true;
24
- }
25
- },
26
- FunctionDefinition(
27
- { name, visibility, parameters, stateMutability, returnParameters, isConstructor, isFallback, isReceiveEther },
28
- parent
29
- ) {
30
- if (parent !== undefined && parent.type === "ContractDefinition" && parent.name === contractName) {
31
- try {
32
- // skip constructor and fallbacks
33
- if (isConstructor || isFallback || isReceiveEther) return;
34
- // forbid default visibility (this check might be unnecessary, modern solidity already disallows this)
35
- if (visibility === "default") throw new MUDError(`Visibility is not specified`);
36
-
37
- if (visibility === "external" || visibility === "public") {
38
- functions.push({
39
- name: name === null ? "" : name,
40
- parameters: parameters.map(parseParameter),
41
- stateMutability: stateMutability || "",
42
- returnParameters: returnParameters === null ? [] : returnParameters.map(parseParameter),
43
- });
44
-
45
- for (const { typeName } of parameters.concat(returnParameters ?? [])) {
46
- symbols = symbols.concat(typeNameToExternalSymbols(typeName));
47
- }
48
- }
49
- } catch (error: unknown) {
50
- if (error instanceof MUDError) {
51
- error.message = `Function "${name}" in contract "${contractName}": ${error.message}`;
52
- }
53
- throw error;
54
- }
55
- }
56
- },
57
- });
58
-
59
- if (!withContract) {
60
- throw new MUDError(`Contract not found: ${contractName}`);
61
- }
62
-
63
- return {
64
- functions,
65
- symbols,
66
- };
67
- }
68
-
69
- function parseParameter({ name, typeName, storageLocation }: VariableDeclaration): string {
70
- let typedNameWithLocation = "";
71
-
72
- const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);
73
- // type name (e.g. uint256)
74
- typedNameWithLocation += flattenedTypeName;
75
- // optional mutability (e.g. address payable)
76
- if (stateMutability !== null) {
77
- typedNameWithLocation += ` ${stateMutability}`;
78
- }
79
- // location, when relevant (e.g. string memory)
80
- if (storageLocation !== null) {
81
- typedNameWithLocation += ` ${storageLocation}`;
82
- }
83
- // optional variable name
84
- if (name !== null) {
85
- typedNameWithLocation += ` ${name}`;
86
- }
87
-
88
- return typedNameWithLocation;
89
- }
90
-
91
- function flattenTypeName(typeName: TypeName | null): { name: string; stateMutability: string | null } {
92
- if (typeName === null) {
93
- return {
94
- name: "",
95
- stateMutability: null,
96
- };
97
- }
98
- if (typeName.type === "ElementaryTypeName") {
99
- return {
100
- name: typeName.name,
101
- stateMutability: typeName.stateMutability,
102
- };
103
- } else if (typeName.type === "UserDefinedTypeName") {
104
- return {
105
- name: typeName.namePath,
106
- stateMutability: null,
107
- };
108
- } else if (typeName.type === "ArrayTypeName") {
109
- const length = typeName.length?.type === "NumberLiteral" ? typeName.length.number : "";
110
- const { name, stateMutability } = flattenTypeName(typeName.baseTypeName);
111
- return {
112
- name: `${name}[${length}]`,
113
- stateMutability,
114
- };
115
- } else {
116
- // TODO function types are unsupported but could be useful
117
- throw new MUDError(`Invalid typeName.type ${typeName.type}`);
118
- }
119
- }
120
-
121
- // Get symbols that need to be imported for given typeName
122
- function typeNameToExternalSymbols(typeName: TypeName | null): string[] {
123
- if (typeName?.type === "UserDefinedTypeName") {
124
- // split is needed to get a library, if types are internal to it
125
- const symbol = typeName.namePath.split(".")[0];
126
- return [symbol];
127
- } else if (typeName?.type === "ArrayTypeName") {
128
- return typeNameToExternalSymbols(typeName.baseTypeName);
129
- } else {
130
- return [];
131
- }
132
- }
@@ -1,55 +0,0 @@
1
- import { execa } from "execa";
2
- import { copyFileSync, mkdirSync, readdirSync, rmSync } from "fs";
3
- import path from "path";
4
- import { getOutDirectory } from "../foundry.js";
5
-
6
- export async function forgeBuild(options?: { clear?: boolean }) {
7
- if (options?.clear) {
8
- const out = await getOutDirectory();
9
- console.log("Clearing forge build output directory", out);
10
- rmSync(out, { recursive: true, force: true });
11
- }
12
-
13
- console.log("Running forge build");
14
- const child = execa("forge", ["build"], {
15
- stdio: ["inherit", "pipe", "inherit"],
16
- });
17
-
18
- return (await child).stdout;
19
- }
20
-
21
- function getContractsInDirectory(dir: string, exclude?: string[]) {
22
- return readdirSync(dir)
23
- .filter((item) => item.includes(".sol"))
24
- .map((item) => item.replace(".sol", ""))
25
- .filter((item) => !exclude?.includes(item));
26
- }
27
-
28
- function copyAbi(inDir: string, outDir: string, contract: string) {
29
- try {
30
- return copyFileSync(path.join(inDir, contract + ".sol", contract + ".json"), path.join(outDir, contract + ".json"));
31
- } catch (e) {
32
- console.log("Skipping", contract);
33
- }
34
- }
35
-
36
- export function filterAbi(abiIn = "./out", abiOut = "./abi", exclude: string[] = ["Component", "IComponent"]) {
37
- // Clean our dir
38
- console.log(`Cleaning output directory (${abiOut}})`);
39
- rmSync(abiOut, { recursive: true, force: true });
40
- mkdirSync(abiOut);
41
-
42
- // Only include World, LibQuery, *Component, *System
43
- const include = ["Component", "System", "World", "LibQuery"];
44
- const contracts = getContractsInDirectory(abiIn, exclude).filter((item) => include.find((i) => item.includes(i)));
45
-
46
- console.log("Selected ABIs: ", contracts);
47
-
48
- // Move selected ABIs to ./abi
49
- for (const contract of contracts) {
50
- if (contract.includes(".t")) continue;
51
- copyAbi(abiIn, abiOut, contract);
52
- }
53
-
54
- console.log("Successfully moved selected ABIs to ./abi");
55
- }
@@ -1,42 +0,0 @@
1
- import { readFile, writeFile } from "fs/promises";
2
- import ejs from "ejs";
3
- import path from "path";
4
-
5
- const contractsDirectory = new URL("../src/contracts", import.meta.url).pathname;
6
-
7
- const stubLibDeploy = readFile(path.join(contractsDirectory, "LibDeployStub.sol"));
8
-
9
- /**
10
- * Generate LibDeploy.sol from deploy.json
11
- * @param configPath path to deploy.json
12
- * @param out output directory for LibDeploy.sol
13
- * @param systems optional, only generate deploy code for the given systems
14
- * @returns path to generated LibDeploy.sol
15
- */
16
- export async function generateLibDeploy(configPath: string, out: string, systems?: string | string[]) {
17
- // Parse config
18
- const config = JSON.parse(await readFile(configPath, { encoding: "utf8" }));
19
-
20
- // Initializers are optional
21
- config.initializers ??= [];
22
-
23
- // Filter systems
24
- if (systems) {
25
- const systemsArray = Array.isArray(systems) ? systems : [systems];
26
- config.systems = config.systems.filter((system: { name: string }) => systemsArray.includes(system.name));
27
- }
28
-
29
- console.log(`Deploy config: \n`, JSON.stringify(config, null, 2));
30
-
31
- // Generate LibDeploy
32
- console.log("Generating deployment script");
33
- const LibDeploy = await ejs.renderFile(path.join(contractsDirectory, "LibDeploy.ejs"), config, { async: true });
34
- const libDeployPath = path.join(out, "LibDeploy.sol");
35
- await writeFile(libDeployPath, LibDeploy);
36
-
37
- return libDeployPath;
38
- }
39
-
40
- export async function resetLibDeploy(out: string) {
41
- await writeFile(path.join(out, "LibDeploy.sol"), await stubLibDeploy);
42
- }
@@ -1,2 +0,0 @@
1
- export const systemsDir = "systems";
2
- export const componentsDir = "components";
@@ -1,111 +0,0 @@
1
- import { constants, Wallet } from "ethers";
2
- import { generateLibDeploy, resetLibDeploy } from "./codegen.js";
3
- import { findLog } from "./findLog.js";
4
- import { generateTypes } from "./typegen.js";
5
- import { execa } from "execa";
6
- import { StaticJsonRpcProvider } from "@ethersproject/providers";
7
- import path from "path";
8
-
9
- const contractsDirectory = new URL("../src/contracts", import.meta.url).pathname;
10
-
11
- /**
12
- * Deploy world, components and systems from deploy.json
13
- * @param deployerPrivateKey private key of deployer
14
- * @param rpc rpc url
15
- * @param worldAddress optional, address of existing world
16
- * @param reuseComponents optional, reuse existing components
17
- * @returns address of deployed world
18
- */
19
- export async function deploy(
20
- deployerPrivateKey?: string,
21
- rpc = "http://localhost:8545",
22
- worldAddress?: string,
23
- reuseComponents?: boolean,
24
- gasPrice?: number
25
- ) {
26
- const address = deployerPrivateKey ? new Wallet(deployerPrivateKey).address : constants.AddressZero;
27
-
28
- if (gasPrice == null) {
29
- try {
30
- console.log("Fetching gas price...");
31
- const provider = new StaticJsonRpcProvider(rpc, { name: "AnyNetwork", chainId: 1234 });
32
- gasPrice = (await provider.getGasPrice()).toNumber() * 1.3; // 30% multiplier for faster inclusion
33
- console.log("Gas price:", gasPrice);
34
- } catch (e) {
35
- console.log("Could not fetch gas price");
36
- }
37
- }
38
-
39
- const child = execa(
40
- "forge",
41
- [
42
- "script",
43
- path.join(contractsDirectory, "/Deploy.sol"),
44
- "--target-contract",
45
- "Deploy",
46
- "-vvv",
47
- ...(!deployerPrivateKey ? [] : ["--broadcast", "--private-keys", deployerPrivateKey]),
48
- "--sig",
49
- "broadcastDeploy(address,address,bool)",
50
- address, // Deployer
51
- worldAddress || constants.AddressZero, // World address (0 = deploy a new world)
52
- reuseComponents ? "true" : "false", // Reuse components?
53
- "--fork-url",
54
- rpc,
55
- ...(gasPrice != null ? ["--with-gas-price", String(Math.round(gasPrice))] : []),
56
- ],
57
- { stdio: ["inherit", "pipe", "pipe"] }
58
- );
59
-
60
- child.stderr?.on("data", (data) => console.log("stderr:", data.toString()));
61
- child.stdout?.on("data", (data) => console.log(data.toString()));
62
-
63
- // Extract world address from deploy script
64
- const lines = (await child).stdout?.split("\n");
65
- const deployedWorldAddress = findLog(lines, "world: address");
66
- const initialBlockNumber = findLog(lines, "initialBlockNumber: uint256");
67
-
68
- return { child: await child, deployedWorldAddress, initialBlockNumber };
69
- }
70
-
71
- export type DeployOptions = {
72
- config: string;
73
- deployerPrivateKey?: string;
74
- worldAddress?: string;
75
- rpc: string;
76
- systems?: string | string[];
77
- reuseComponents?: boolean;
78
- clear?: boolean;
79
- gasPrice?: number;
80
- };
81
-
82
- export async function generateAndDeploy(args: DeployOptions) {
83
- let libDeployPath: string | undefined;
84
- let deployedWorldAddress: string | undefined;
85
- let initialBlockNumber: string | undefined;
86
-
87
- try {
88
- // Generate LibDeploy
89
- libDeployPath = await generateLibDeploy(args.config, contractsDirectory, args.systems);
90
-
91
- // Build and generate fresh types
92
- await generateTypes(undefined, "./types", { clear: args.clear });
93
-
94
- // Call deploy script
95
- const result = await deploy(
96
- args.deployerPrivateKey,
97
- args.rpc,
98
- args.worldAddress,
99
- Boolean(args.reuseComponents),
100
- args.gasPrice
101
- );
102
- deployedWorldAddress = result.deployedWorldAddress;
103
- initialBlockNumber = result.initialBlockNumber;
104
- } finally {
105
- // Remove generated LibDeploy
106
- console.log("Cleaning up deployment script");
107
- if (libDeployPath) await resetLibDeploy(contractsDirectory);
108
- }
109
-
110
- return { deployedWorldAddress, initialBlockNumber };
111
- }
@@ -1,18 +0,0 @@
1
- import { execa } from "execa";
2
-
3
- /**
4
- * Wrapper for execa that logs the full command.
5
- * @param command - The program/script to execute.
6
- * @param options - Arguments to pass to `command` on execution.
7
- * @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
8
- */
9
- export function execLog(command: string, options: string[]) {
10
- console.log("Cmd:");
11
- console.log([command, ...options].join(" "));
12
-
13
- // TODO piping outputs and doing custom logging would be better for readability
14
- // (see https://github.com/latticexyz/mud/issues/446)
15
- return execa(command, options, {
16
- stdio: ["inherit", "inherit", "inherit"],
17
- });
18
- }
@@ -1,8 +0,0 @@
1
- export function findLog(deployLogLines: string[], log: string): string {
2
- for (const logLine of deployLogLines) {
3
- if (logLine.includes(log)) {
4
- return logLine.split(log)[1].trim();
5
- }
6
- }
7
- throw new Error("Can not find log");
8
- }
@@ -1,71 +0,0 @@
1
- import chokidar from "chokidar";
2
- import { readFileSync } from "fs";
3
-
4
- const ImportsRegex = new RegExp(/(?<=import ").*(?=";)|(?<=from ").*(?=";)/g);
5
-
6
- /**
7
- * Extract file imports from a given file
8
- * @param path File to extracts imports from
9
- * @returns Array of imported filenames
10
- */
11
- function extractImports(path: string): string[] {
12
- const content = readFileSync(path).toString();
13
- const regexResult = [...content.matchAll(ImportsRegex)]
14
- .map((match) => match[0])
15
- .map((path) => path.split("/").at(-1)!);
16
- return regexResult;
17
- }
18
-
19
- function findDependencies(
20
- file: string,
21
- dependencyGraph: { [file: string]: string[] },
22
- visited: string[] = []
23
- ): string[] {
24
- const dependencies = dependencyGraph[file] ?? [];
25
- const subDependencies = dependencies.flatMap((d) => {
26
- if (visited.includes(d)) {
27
- console.warn("Circular dependency detected: ", d, dependencyGraph[d]);
28
- return [];
29
- }
30
- return findDependencies(d, dependencyGraph, [...visited, d]);
31
- });
32
- return [...new Set([...dependencies, ...subDependencies])];
33
- }
34
-
35
- // Hot System Replacement
36
- export function hsr(root: string, replaceSystems: (systems: string[]) => Promise<unknown>) {
37
- const dependencyGraph: { [file: string]: string[] } = {};
38
- const systems = new Set<string>();
39
-
40
- console.log("Watching system file changes...");
41
-
42
- chokidar.watch(root).on("all", async (event, path) => {
43
- console.log(`[${event}]: ${path}`);
44
-
45
- // Find changed file
46
- const changedFile = path.split("/").at(-1)!;
47
-
48
- if (["add", "change"].includes(event)) {
49
- // Construct dependency graph based in file imports
50
- const imports = extractImports(path);
51
- for (const importedFile of imports) {
52
- dependencyGraph[importedFile] ??= [];
53
- dependencyGraph[importedFile].push(changedFile);
54
- }
55
-
56
- // Track system files
57
- if (path.includes("systems") && path.includes(".sol")) systems.add(changedFile);
58
- }
59
-
60
- if (event === "change") {
61
- // Find all files depending on the changed file
62
- const dependencies = findDependencies(changedFile, dependencyGraph);
63
- const changedSystems = [
64
- ...new Set([changedFile, ...dependencies].filter((f) => systems.has(f)).map((f) => f.replace(".sol", ""))),
65
- ];
66
- console.log("Systems to replace", changedSystems);
67
- if (changedSystems.length > 0) await replaceSystems(changedSystems);
68
- console.log("Watching system file changes...");
69
- }
70
- });
71
- }
@@ -1,14 +0,0 @@
1
- import { keccak256 as keccak256Bytes, toUtf8Bytes } from "ethers/lib/utils.js";
2
- import { readFileSync } from "fs";
3
-
4
- export const IDregex = new RegExp(/(?<=uint256 constant ID = uint256\(keccak256\(")(.*)(?="\))/);
5
-
6
- export function extractIdFromFile(path: string): string | null {
7
- const content = readFileSync(path).toString();
8
- const regexResult = IDregex.exec(content);
9
- return regexResult && regexResult[0];
10
- }
11
-
12
- export function keccak256(data: string) {
13
- return keccak256Bytes(toUtf8Bytes(data));
14
- }
@@ -1,8 +0,0 @@
1
- export * from "./exec.js";
2
- export * from "./ids.js";
3
- export * from "./codegen.js";
4
- export * from "./deploy.js";
5
- export * from "./hsr.js";
6
- export * from "./findLog.js";
7
- export * from "./typegen.js";
8
- export * from "./build.js";
@@ -1,133 +0,0 @@
1
- import { runTypeChain, glob as typechainGlob } from "typechain";
2
- import glob from "glob";
3
- import { extractIdFromFile } from "./ids.js";
4
- import { rmSync, writeFileSync } from "fs";
5
- import path from "path";
6
- import { filterAbi, forgeBuild } from "./build.js";
7
- import { getOutDirectory, getSrcDirectory } from "../foundry.js";
8
- import { systemsDir } from "./constants.js";
9
-
10
- export async function generateAbiTypes(
11
- inputDir: string,
12
- outputDir: string,
13
- options?: { clear?: boolean; cwd?: string }
14
- ) {
15
- if (options?.clear) {
16
- console.log("Clearing typechain output directory", outputDir);
17
- rmSync(outputDir, { recursive: true, force: true });
18
- }
19
-
20
- const cwd = options?.cwd ?? process.cwd();
21
-
22
- const allFiles = typechainGlob(cwd, [`${inputDir}/**/+([a-zA-Z0-9_]).json`]);
23
-
24
- const result = await runTypeChain({
25
- cwd,
26
- filesToProcess: allFiles,
27
- allFiles,
28
- outDir: outputDir,
29
- target: "ethers-v5",
30
- });
31
-
32
- console.log(`Successfully generated ${result.filesGenerated} files`);
33
- }
34
-
35
- export async function generateSystemTypes(outputDir: string, options?: { clear?: boolean }) {
36
- if (options?.clear) {
37
- console.log("Clearing system type output files", outputDir);
38
- rmSync(path.join(outputDir, "/SystemTypes.ts"), { force: true });
39
- rmSync(path.join(outputDir, "/SystemAbis.mts"), { force: true });
40
- rmSync(path.join(outputDir, "/SystemAbis.mjs"), { force: true });
41
- rmSync(path.join(outputDir, "/SystemMappings.ts"), { force: true });
42
- }
43
-
44
- let abis: string[] = [];
45
- let systems: string[] = [];
46
- let ids: string[] = [];
47
- let typePaths: string[] = [];
48
-
49
- const srcDir = await getSrcDirectory();
50
- const systemsPath = path.join(srcDir, systemsDir, "*.sol");
51
-
52
- const matches = glob.sync(systemsPath);
53
-
54
- systems = matches.map((path) => {
55
- const fragments = path.split("/");
56
- return fragments[fragments.length - 1].split(".sol")[0];
57
- });
58
-
59
- ids = matches.map((path, index) => {
60
- const id = extractIdFromFile(path);
61
- if (!id) {
62
- console.log("Path:", path);
63
- console.log("ID:", id);
64
- throw new Error(
65
- "No ID found for" +
66
- matches[index] +
67
- ". Make sure your system source file includes a ID definition (uint256 constant ID = uint256(keccak256(<ID>));)"
68
- );
69
- }
70
- return id;
71
- });
72
-
73
- abis = systems.map((system) => `../abi/${system}.json`);
74
-
75
- typePaths = systems.map((system) => `./ethers-contracts/${system}.ts`);
76
-
77
- console.log("Matches", systems);
78
- console.log("Solidity", ids);
79
- console.log("Type paths", typePaths);
80
- console.log("ABIs", abis);
81
-
82
- const SystemMappings = `// Autogenerated using mud system-types
83
- export const systemToId = {
84
- ${systems.map((system, index) => ` ${system}: "${ids[index]}",`).join("\n")}
85
- };
86
-
87
- export const idToSystem = {
88
- ${ids.map((id, index) => ` "${id}": "${systems[index]}",`).join("\n")}
89
- };
90
- `;
91
-
92
- const SystemTypes = `// Autogenerated using mud system-types
93
- ${typePaths.map((path, index) => `import { ${systems[index]} } from "${path.replace(".ts", "")}";`).join("\n")}
94
-
95
- export type SystemTypes = {
96
- ${systems.map((system, index) => ` "${ids[index]}": ${system};`).join("\n")}
97
- };
98
- `;
99
-
100
- const SystemAbis = `// Autogenerated using mud system-types
101
- ${abis.map((path, index) => `import ${systems[index]} from "${path}";`).join("\n")}
102
-
103
- export const SystemAbis = {
104
- ${systems.map((system, index) => ` "${ids[index]}": ${system}.abi,`).join("\n")}
105
- };
106
- `;
107
-
108
- console.log("Generating files:");
109
- console.log("SystemTypes.ts", SystemTypes);
110
- console.log("SystemAbis.mts", SystemAbis);
111
- console.log("SystemMappings.ts", SystemMappings);
112
-
113
- writeFileSync(`${outputDir}/SystemTypes.ts`, SystemTypes);
114
- writeFileSync(`${outputDir}/SystemAbis.mts`, SystemAbis);
115
- writeFileSync(`${outputDir}/SystemAbis.mjs`, SystemAbis);
116
- writeFileSync(`${outputDir}/SystemMappings.ts`, SystemMappings);
117
- }
118
-
119
- /**
120
- * @param abiDir If not provided, the contracts are built and abis are exported to ./abi
121
- */
122
- export async function generateTypes(abiDir?: string, outputDir = "./types", options?: { clear?: boolean }) {
123
- if (!abiDir) {
124
- console.log("Compiling contracts");
125
- const buildOutput = await getOutDirectory();
126
- abiDir = "./abi";
127
- await forgeBuild(options);
128
- filterAbi(buildOutput, abiDir);
129
- }
130
-
131
- await generateAbiTypes(abiDir, path.join(outputDir, "ethers-contracts"), options);
132
- await generateSystemTypes(outputDir, options);
133
- }
@@ -1,22 +0,0 @@
1
- import chalk from "chalk";
2
- import { execa, Options } from "execa";
3
-
4
- /**
5
- * Executes the given command, returns the stdout, and logs the command to the console.
6
- * Throws an error if the command fails.
7
- * @param command The command to execute
8
- * @param args The arguments to pass to the command
9
- * @returns The stdout of the command
10
- */
11
- export async function execLog(command: string, args: string[], options?: Options<string>): Promise<string> {
12
- const commandString = `${command} ${args.join(" ")}`;
13
- try {
14
- console.log(chalk.gray(`running "${commandString}"`));
15
- const { stdout } = await execa(command, args, { stdout: "pipe", stderr: "pipe", ...options });
16
- return stdout;
17
- } catch (error: any) {
18
- let errorMessage = error?.stderr || error?.message || "";
19
- errorMessage += chalk.red(`\nError running "${commandString}"`);
20
- throw new Error(errorMessage);
21
- }
22
- }
@@ -1,39 +0,0 @@
1
- import chalk from "chalk";
2
- import prettier from "prettier";
3
- import prettierPluginSolidity from "prettier-plugin-solidity";
4
-
5
- export async function formatSolidity(content: string, prettierConfigPath?: string) {
6
- let config;
7
- if (prettierConfigPath) {
8
- config = await prettier.resolveConfig(prettierConfigPath);
9
- }
10
- try {
11
- return prettier.format(content, {
12
- plugins: [prettierPluginSolidity],
13
- parser: "solidity-parse",
14
-
15
- printWidth: 120,
16
- semi: true,
17
- tabWidth: 2,
18
- useTabs: false,
19
- bracketSpacing: true,
20
-
21
- ...config,
22
- });
23
- } catch (error) {
24
- let message;
25
- if (error instanceof Error) {
26
- message = error.message;
27
- } else {
28
- message = error;
29
- }
30
- console.log(chalk.yellow(`Error during output formatting: ${message}`));
31
- return content;
32
- }
33
- }
34
-
35
- export async function formatTypescript(content: string) {
36
- return prettier.format(content, {
37
- parser: "typescript",
38
- });
39
- }