@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
@@ -1,518 +0,0 @@
1
- import { existsSync, readFileSync } from "fs";
2
- import path from "path";
3
- import { MUDConfig, resolveWithContext } from "@latticexyz/config";
4
- import { MUDError } from "@latticexyz/config";
5
- import { getOutDirectory, getScriptDirectory, cast, forge } from "./foundry.js";
6
- import { BigNumber, ContractInterface, ethers } from "ethers";
7
- import { IBaseWorld } from "@latticexyz/world/types/ethers-contracts/IBaseWorld.js";
8
- import chalk from "chalk";
9
- import { encodeSchema } from "@latticexyz/schema-type";
10
- import { resolveAbiOrUserType } from "../render-solidity/userType.js";
11
- import { defaultAbiCoder as abi, Fragment } from "ethers/lib/utils.js";
12
-
13
- import WorldData from "@latticexyz/world/abi/World.json" assert { type: "json" };
14
- import IBaseWorldData from "@latticexyz/world/abi/IBaseWorld.json" assert { type: "json" };
15
- import CoreModuleData from "@latticexyz/world/abi/CoreModule.json" assert { type: "json" };
16
- import RegistrationModuleData from "@latticexyz/world/abi/RegistrationModule.json" assert { type: "json" };
17
- import KeysWithValueModuleData from "@latticexyz/world/abi/KeysWithValueModule.json" assert { type: "json" };
18
- import UniqueEntityModuleData from "@latticexyz/world/abi/UniqueEntityModule.json" assert { type: "json" };
19
-
20
- export interface DeployConfig {
21
- profile?: string;
22
- rpc: string;
23
- privateKey: string;
24
- priorityFeeMultiplier: number;
25
- debug?: boolean;
26
- worldAddress?: string;
27
- }
28
-
29
- export interface DeploymentInfo {
30
- blockNumber: number;
31
- worldAddress: string;
32
- }
33
-
34
- export async function deploy(mudConfig: MUDConfig, deployConfig: DeployConfig): Promise<DeploymentInfo> {
35
- const startTime = Date.now();
36
- const { worldContractName, namespace, postDeployScript } = mudConfig;
37
- const { profile, rpc, privateKey, priorityFeeMultiplier, debug, worldAddress } = deployConfig;
38
- const forgeOutDirectory = await getOutDirectory(profile);
39
-
40
- // Set up signer for deployment
41
- const provider = new ethers.providers.StaticJsonRpcProvider(rpc);
42
- const signer = new ethers.Wallet(privateKey, provider);
43
-
44
- // Manual nonce handling to allow for faster sending of transactions without waiting for previous transactions
45
- let nonce = await signer.getTransactionCount();
46
- console.log("Initial nonce", nonce);
47
-
48
- // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions
49
- let maxPriorityFeePerGas: number;
50
- let maxFeePerGas: BigNumber;
51
- setInternalFeePerGas(priorityFeeMultiplier);
52
-
53
- // Catch all to await any promises before exiting the script
54
- let promises: Promise<unknown>[] = [];
55
-
56
- // Get block number before deploying
57
- const blockNumber = Number(await cast(["block-number", "--rpc-url", rpc], { profile }));
58
- console.log("Start deployment at block", blockNumber);
59
-
60
- // Deploy World
61
- const worldPromise = {
62
- World: worldAddress
63
- ? Promise.resolve(worldAddress)
64
- : worldContractName
65
- ? deployContractByName(worldContractName)
66
- : deployContract(IBaseWorldData.abi, WorldData.bytecode, "World"),
67
- };
68
-
69
- // Deploy Systems
70
- const systemPromises = Object.keys(mudConfig.systems).reduce<Record<string, Promise<string>>>((acc, systemName) => {
71
- acc[systemName] = deployContractByName(systemName);
72
- return acc;
73
- }, {});
74
-
75
- // Deploy default World modules
76
- const defaultModules: Record<string, Promise<string>> = {
77
- // TODO: these only need to be deployed once per chain, add a check if they exist already
78
- CoreModule: deployContract(CoreModuleData.abi, CoreModuleData.bytecode, "CoreModule"),
79
- RegistrationModule: deployContract(
80
- RegistrationModuleData.abi,
81
- RegistrationModuleData.bytecode,
82
- "RegistrationModule"
83
- ),
84
- KeysWithValueModule: deployContract(
85
- KeysWithValueModuleData.abi,
86
- KeysWithValueModuleData.bytecode,
87
- "KeysWithValueModule"
88
- ),
89
- UniqueEntityModule: deployContract(
90
- UniqueEntityModuleData.abi,
91
- UniqueEntityModuleData.bytecode,
92
- "UniqueEntityModule"
93
- ),
94
- };
95
-
96
- // Deploy user Modules
97
- const modulePromises = mudConfig.modules
98
- .filter((module) => !defaultModules[module.name]) // Only deploy user modules here, not default modules
99
- .reduce<Record<string, Promise<string>>>((acc, module) => {
100
- acc[module.name] = deployContractByName(module.name);
101
- return acc;
102
- }, defaultModules);
103
-
104
- // Combine all contracts into one object
105
- const contractPromises: Record<string, Promise<string>> = { ...worldPromise, ...systemPromises, ...modulePromises };
106
-
107
- // Create World contract instance from deployed address
108
- const WorldContract = new ethers.Contract(await contractPromises.World, IBaseWorldData.abi, signer) as IBaseWorld;
109
-
110
- // Install core Modules
111
- if (!worldAddress) {
112
- console.log(chalk.blue("Installing core World modules"));
113
- await fastTxExecute(WorldContract, "installRootModule", [await modulePromises.CoreModule, "0x"]);
114
- await fastTxExecute(WorldContract, "installRootModule", [await modulePromises.RegistrationModule, "0x"]);
115
- console.log(chalk.green("Installed core World modules"));
116
- }
117
-
118
- // Register namespace
119
- if (namespace) await fastTxExecute(WorldContract, "registerNamespace", [toBytes16(namespace)]);
120
-
121
- // Register tables
122
- const tableIds: { [tableName: string]: Uint8Array } = {};
123
- promises = [
124
- ...promises,
125
- ...Object.entries(mudConfig.tables).map(async ([tableName, { name, schema, primaryKeys }]) => {
126
- console.log(chalk.blue(`Registering table ${tableName} at ${namespace}/${name}`));
127
-
128
- // Store the tableId for later use
129
- tableIds[tableName] = toResourceSelector(namespace, name);
130
-
131
- // Register table
132
- const schemaTypes = Object.values(schema).map((abiOrUserType) => {
133
- const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);
134
- return schemaType;
135
- });
136
-
137
- const keyTypes = Object.values(primaryKeys).map((abiOrUserType) => {
138
- const { schemaType } = resolveAbiOrUserType(abiOrUserType, mudConfig);
139
- return schemaType;
140
- });
141
-
142
- await fastTxExecute(WorldContract, "registerTable", [
143
- toBytes16(namespace),
144
- toBytes16(name),
145
- encodeSchema(schemaTypes),
146
- encodeSchema(keyTypes),
147
- ]);
148
-
149
- // Register table metadata
150
- await fastTxExecute(WorldContract, "setMetadata(bytes16,bytes16,string,string[])", [
151
- toBytes16(namespace),
152
- toBytes16(name),
153
- tableName,
154
- Object.keys(schema),
155
- ]);
156
-
157
- console.log(chalk.green(`Registered table ${tableName} at ${name}`));
158
- }),
159
- ];
160
-
161
- // Register systems (using forEach instead of for..of to avoid blocking on async calls)
162
- promises = [
163
- ...promises,
164
- ...Object.entries(mudConfig.systems).map(async ([systemName, { name, openAccess, registerFunctionSelectors }]) => {
165
- // Register system at route
166
- console.log(chalk.blue(`Registering system ${systemName} at ${namespace}/${name}`));
167
- await fastTxExecute(WorldContract, "registerSystem", [
168
- toBytes16(namespace),
169
- toBytes16(name),
170
- await contractPromises[systemName],
171
- openAccess,
172
- ]);
173
- console.log(chalk.green(`Registered system ${systemName} at ${namespace}/${name}`));
174
-
175
- // Register function selectors for the system
176
- if (registerFunctionSelectors) {
177
- const functionSignatures: FunctionSignature[] = await loadFunctionSignatures(systemName);
178
- const isRoot = namespace === "";
179
- // Using Promise.all to avoid blocking on async calls
180
- await Promise.all(
181
- functionSignatures.map(async ({ functionName, functionArgs }) => {
182
- const functionSignature = isRoot
183
- ? functionName + functionArgs
184
- : `${namespace}_${name}_${functionName}${functionArgs}`;
185
-
186
- console.log(chalk.blue(`Registering function "${functionSignature}"`));
187
- if (isRoot) {
188
- const worldFunctionSelector = toFunctionSelector(
189
- functionSignature === ""
190
- ? { functionName: systemName, functionArgs } // Register the system's fallback function as `<systemName>(<args>)`
191
- : { functionName, functionArgs }
192
- );
193
- const systemFunctionSelector = toFunctionSelector({ functionName, functionArgs });
194
- await fastTxExecute(WorldContract, "registerRootFunctionSelector", [
195
- toBytes16(namespace),
196
- toBytes16(name),
197
- worldFunctionSelector,
198
- systemFunctionSelector,
199
- ]);
200
- } else {
201
- await fastTxExecute(WorldContract, "registerFunctionSelector", [
202
- toBytes16(namespace),
203
- toBytes16(name),
204
- functionName,
205
- functionArgs,
206
- ]);
207
- }
208
- console.log(chalk.green(`Registered function "${functionSignature}"`));
209
- })
210
- );
211
- }
212
- }),
213
- ];
214
-
215
- // Wait for resources to be registered before granting access to them
216
- await Promise.all(promises); // ----------------------------------------------------------------------------------------------
217
- promises = [];
218
-
219
- // Grant access to systems
220
- for (const [systemName, { name, accessListAddresses, accessListSystems }] of Object.entries(mudConfig.systems)) {
221
- const resourceSelector = `${namespace}/${name}`;
222
-
223
- // Grant access to addresses
224
- promises = [
225
- ...promises,
226
- ...accessListAddresses.map(async (address) => {
227
- console.log(chalk.blue(`Grant ${address} access to ${systemName} (${resourceSelector})`));
228
- await fastTxExecute(WorldContract, "grantAccess(bytes16,bytes16,address)", [
229
- toBytes16(namespace),
230
- toBytes16(name),
231
- address,
232
- ]);
233
- console.log(chalk.green(`Granted ${address} access to ${systemName} (${namespace}/${name})`));
234
- }),
235
- ];
236
-
237
- // Grant access to other systems
238
- promises = [
239
- ...promises,
240
- ...accessListSystems.map(async (granteeSystem) => {
241
- console.log(chalk.blue(`Grant ${granteeSystem} access to ${systemName} (${resourceSelector})`));
242
- await fastTxExecute(WorldContract, "grantAccess(bytes16,bytes16,address)", [
243
- toBytes16(namespace),
244
- toBytes16(name),
245
- await contractPromises[granteeSystem],
246
- ]);
247
- console.log(chalk.green(`Granted ${granteeSystem} access to ${systemName} (${resourceSelector})`));
248
- }),
249
- ];
250
- }
251
-
252
- // Wait for access to be granted before installing modules
253
- await Promise.all(promises); // ----------------------------------------------------------------------------------------------
254
- promises = [];
255
-
256
- // Install modules
257
- promises = [
258
- ...promises,
259
- ...mudConfig.modules.map(async (module) => {
260
- console.log(chalk.blue(`Installing${module.root ? " root " : " "}module ${module.name}`));
261
- // Resolve arguments
262
- const resolvedArgs = await Promise.all(
263
- module.args.map((arg) => resolveWithContext(arg, { tableIds, systemAddresses: contractPromises }))
264
- );
265
- const values = resolvedArgs.map((arg) => arg.value);
266
- const types = resolvedArgs.map((arg) => arg.type);
267
- const moduleAddress = await contractPromises[module.name];
268
- if (!moduleAddress) throw new Error(`Module ${module.name} not found`);
269
-
270
- // Send transaction to install module
271
- await fastTxExecute(WorldContract, module.root ? "installRootModule" : "installModule", [
272
- moduleAddress,
273
- abi.encode(types, values),
274
- ]);
275
-
276
- console.log(chalk.green(`Installed${module.root ? " root " : " "}module ${module.name}`));
277
- }),
278
- ];
279
-
280
- // Await all promises before executing PostDeploy script
281
- await Promise.all(promises); // ----------------------------------------------------------------------------------------------
282
- promises = [];
283
-
284
- // Execute postDeploy forge script
285
- const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + ".s.sol");
286
- if (existsSync(postDeployPath)) {
287
- console.log(chalk.blue(`Executing post deploy script at ${postDeployPath}`));
288
- await forge(
289
- [
290
- "script",
291
- postDeployScript,
292
- "--sig",
293
- "run(address)",
294
- await contractPromises.World,
295
- "--broadcast",
296
- "--rpc-url",
297
- rpc,
298
- "-vvv",
299
- ],
300
- {
301
- profile,
302
- }
303
- );
304
- } else {
305
- console.log(`No script at ${postDeployPath}, skipping post deploy hook`);
306
- }
307
-
308
- console.log(chalk.green("Deployment completed in", (Date.now() - startTime) / 1000, "seconds"));
309
-
310
- return { worldAddress: await contractPromises.World, blockNumber };
311
-
312
- // ------------------- INTERNAL FUNCTIONS -------------------
313
- // (Inlined to avoid having to pass around nonce, signer and forgeOutDir)
314
-
315
- /**
316
- * Deploy a contract and return the address
317
- * @param contractName Name of the contract to deploy (must exist in the file system)
318
- * @returns Address of the deployed contract
319
- */
320
- async function deployContractByName(contractName: string): Promise<string> {
321
- console.log(chalk.blue("Deploying", contractName));
322
-
323
- const { abi, bytecode } = await getContractData(contractName);
324
- return deployContract(abi, bytecode, contractName);
325
- }
326
-
327
- /**
328
- * Deploy a contract and return the address
329
- * @param abi The contract interface
330
- * @param bytecode The contract bytecode
331
- * @param contractName The contract name (optional, used for logs)
332
- * @returns Address of the deployed contract
333
- */
334
- async function deployContract(
335
- abi: ContractInterface,
336
- bytecode: string | { object: string },
337
- contractName?: string,
338
- retryCount = 0
339
- ): Promise<string> {
340
- try {
341
- const factory = new ethers.ContractFactory(abi, bytecode, signer);
342
- console.log(chalk.gray(`executing deployment of ${contractName} with nonce ${nonce}`));
343
- const deployPromise = factory.deploy({
344
- nonce: nonce++,
345
- maxPriorityFeePerGas,
346
- maxFeePerGas,
347
- });
348
- promises.push(deployPromise);
349
- const { address } = await deployPromise;
350
-
351
- console.log(chalk.green("Deployed", contractName, "to", address));
352
- return address;
353
- } catch (error: any) {
354
- if (debug) console.error(error);
355
- if (retryCount === 0 && error?.message.includes("transaction already imported")) {
356
- // If the deployment failed because the transaction was already imported,
357
- // retry with a higher priority fee
358
- setInternalFeePerGas(priorityFeeMultiplier * 1.1);
359
- return deployContract(abi, bytecode, contractName, retryCount++);
360
- } else if (error?.message.includes("invalid bytecode")) {
361
- throw new MUDError(
362
- `Error deploying ${contractName}: invalid bytecode. Note that linking of public libraries is not supported yet, make sure none of your libraries use "external" functions.`
363
- );
364
- } else if (error?.message.includes("CreateContractLimit")) {
365
- throw new MUDError(`Error deploying ${contractName}: CreateContractLimit exceeded.`);
366
- } else throw error;
367
- }
368
- }
369
-
370
- /**
371
- * Deploy a contract and return the address
372
- * @param contractName Name of the contract to deploy (must exist in the file system)
373
- * @returns Address of the deployed contract
374
- *
375
- * NOTE: Forge deploy seems to be slightly slower than ethers
376
- * (probably due to the extra overhead spawning a child process to run forge),
377
- * so we mostly use ethersDeployContract here.
378
- * However, for contracts not in the user directory (eg. the vanilla World contract),
379
- * using forge is more convenient because it automatically finds the contract in the @latticexyz/world package.
380
- */
381
- // async function forgeDeployContract(contractName: string): Promise<string> {
382
- // console.log(chalk.blue("Deploying", contractName));
383
-
384
- // const { deployedTo } = JSON.parse(
385
- // await forge(
386
- // ["create", contractName, "--rpc-url", rpc, "--private-key", privateKey, "--json", "--nonce", String(nonce++)],
387
- // { profile, silent: true }
388
- // )
389
- // );
390
- // return deployedTo;
391
- // }
392
-
393
- async function loadFunctionSignatures(contractName: string): Promise<FunctionSignature[]> {
394
- const { abi } = await getContractData(contractName);
395
-
396
- return abi
397
- .filter((item) => ["fallback", "function"].includes(item.type))
398
- .map((item) => {
399
- if (item.type === "fallback") return { functionName: "", functionArgs: "" };
400
-
401
- return { functionName: item.name, functionArgs: `(${item.inputs.map((arg) => arg.type).join(",")})` };
402
- });
403
- }
404
-
405
- /**
406
- * Only await gas estimation (for speed), only execute if gas estimation succeeds (for safety)
407
- */
408
- async function fastTxExecute<C extends { estimateGas: any; [key: string]: any }, F extends keyof C>(
409
- contract: C,
410
- func: F,
411
- args: Parameters<C[F]>,
412
- retryCount = 0,
413
- confirmations = 1
414
- ): Promise<Awaited<ReturnType<Awaited<ReturnType<C[F]>>["wait"]>>> {
415
- const functionName = `${func as string}(${args.map((arg) => `'${arg}'`).join(",")})`;
416
- try {
417
- const gasLimit = await contract.estimateGas[func].apply(null, args);
418
- console.log(chalk.gray(`executing transaction: ${functionName} with nonce ${nonce}`));
419
- const txPromise = contract[func]
420
- .apply(null, [...args, { gasLimit, nonce: nonce++, maxPriorityFeePerGas, maxFeePerGas }])
421
- .then((tx: any) => tx.wait(confirmations));
422
- promises.push(txPromise);
423
- return txPromise;
424
- } catch (error: any) {
425
- if (debug) console.error(error);
426
- if (retryCount === 0 && error?.message.includes("transaction already imported")) {
427
- // If the deployment failed because the transaction was already imported,
428
- // retry with a higher priority fee
429
- setInternalFeePerGas(priorityFeeMultiplier * 1.1);
430
- return fastTxExecute(contract, func, args, retryCount++, confirmations);
431
- } else throw new MUDError(`Gas estimation error for ${functionName}: ${error?.reason}`);
432
- }
433
- }
434
-
435
- /**
436
- * Load the contract's abi and bytecode from the file system
437
- * @param contractName: Name of the contract to load
438
- */
439
- async function getContractData(contractName: string): Promise<{ bytecode: string; abi: Fragment[] }> {
440
- let data: any;
441
- const contractDataPath = path.join(forgeOutDirectory, contractName + ".sol", contractName + ".json");
442
- try {
443
- data = JSON.parse(readFileSync(contractDataPath, "utf8"));
444
- } catch (error: any) {
445
- throw new MUDError(`Error reading file at ${contractDataPath}`);
446
- }
447
-
448
- const bytecode = data?.bytecode?.object;
449
- if (!bytecode) throw new MUDError(`No bytecode found in ${contractDataPath}`);
450
-
451
- const abi = data?.abi;
452
- if (!abi) throw new MUDError(`No ABI found in ${contractDataPath}`);
453
-
454
- return { abi, bytecode };
455
- }
456
-
457
- /**
458
- * Set the maxFeePerGas and maxPriorityFeePerGas based on the current base fee and the given multiplier.
459
- * The multiplier is used to allow replacing pending transactions.
460
- * @param multiplier Multiplier to apply to the base fee
461
- */
462
- async function setInternalFeePerGas(multiplier: number) {
463
- // Compute maxFeePerGas and maxPriorityFeePerGas like ethers, but allow for a multiplier to allow replacing pending transactions
464
- const feeData = await provider.getFeeData();
465
- if (!feeData.lastBaseFeePerGas) throw new MUDError("Can not fetch lastBaseFeePerGas from RPC");
466
-
467
- // Set the priority fee to 0 for development chains with no base fee, to allow transactions from unfunded wallets
468
- maxPriorityFeePerGas = feeData.lastBaseFeePerGas.eq(0) ? 0 : Math.floor(1_500_000_000 * multiplier);
469
- maxFeePerGas = feeData.lastBaseFeePerGas.mul(2).add(maxPriorityFeePerGas);
470
- }
471
- }
472
-
473
- // TODO: use stringToBytes16 from utils as soon as utils are usable inside cli
474
- // (see https://github.com/latticexyz/mud/issues/499)
475
- function toBytes16(input: string) {
476
- if (input.length > 16) throw new Error("String does not fit into 16 bytes");
477
-
478
- const result = new Uint8Array(16);
479
- // Set ascii bytes
480
- for (let i = 0; i < input.length; i++) {
481
- result[i] = input.charCodeAt(i);
482
- }
483
- // Set the remaining bytes to 0
484
- for (let i = input.length; i < 16; i++) {
485
- result[i] = 0;
486
- }
487
- return result;
488
- }
489
-
490
- // TODO: use TableId from utils as soon as utils are usable inside cli
491
- // (see https://github.com/latticexyz/mud/issues/499)
492
- function toResourceSelector(namespace: string, file: string): Uint8Array {
493
- const namespaceBytes = toBytes16(namespace);
494
- const fileBytes = toBytes16(file);
495
- const result = new Uint8Array(32);
496
- result.set(namespaceBytes);
497
- result.set(fileBytes, 16);
498
- return result;
499
- }
500
-
501
- interface FunctionSignature {
502
- functionName: string;
503
- functionArgs: string;
504
- }
505
-
506
- // TODO: move this to utils as soon as utils are usable inside cli
507
- // (see https://github.com/latticexyz/mud/issues/499)
508
- function toFunctionSelector({ functionName, functionArgs }: FunctionSignature): string {
509
- const functionSignature = functionName + functionArgs;
510
- if (functionSignature === "") return "0x";
511
- return sigHash(functionSignature);
512
- }
513
-
514
- // TODO: move this to utils as soon as utils are usable inside cli
515
- // (see https://github.com/latticexyz/mud/issues/499)
516
- function sigHash(signature: string) {
517
- return ethers.utils.hexDataSlice(ethers.utils.keccak256(ethers.utils.toUtf8Bytes(signature)), 0, 4);
518
- }
@@ -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";