@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,61 @@
1
+ import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex, size } from "viem";
2
+ import { getBytecode } from "viem/actions";
3
+ import { deployer } from "./ensureDeployer";
4
+ import { contractSizeLimit, salt } from "./common";
5
+ import { sendTransaction } from "@latticexyz/common";
6
+ import { debug } from "./debug";
7
+ import pRetry from "p-retry";
8
+ import { wait } from "@latticexyz/common/utils";
9
+
10
+ export type Contract = {
11
+ bytecode: Hex;
12
+ deployedBytecodeSize: number;
13
+ label?: string;
14
+ };
15
+
16
+ export async function ensureContract({
17
+ client,
18
+ bytecode,
19
+ deployedBytecodeSize,
20
+ label = "contract",
21
+ }: {
22
+ readonly client: Client<Transport, Chain | undefined, Account>;
23
+ } & Contract): Promise<readonly Hex[]> {
24
+ const address = getCreate2Address({ from: deployer, salt, bytecode });
25
+
26
+ const contractCode = await getBytecode(client, { address, blockTag: "pending" });
27
+ if (contractCode) {
28
+ debug("found", label, "at", address);
29
+ return [];
30
+ }
31
+
32
+ if (deployedBytecodeSize > contractSizeLimit) {
33
+ console.warn(
34
+ `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`
35
+ );
36
+ } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {
37
+ console.warn(
38
+ `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`
39
+ );
40
+ }
41
+
42
+ debug("deploying", label, "at", address);
43
+ return [
44
+ await pRetry(
45
+ () =>
46
+ sendTransaction(client, {
47
+ chain: client.chain ?? null,
48
+ to: deployer,
49
+ data: concatHex([salt, bytecode]),
50
+ }),
51
+ {
52
+ retries: 3,
53
+ onFailedAttempt: async (error) => {
54
+ const delay = error.attemptNumber * 500;
55
+ debug(`failed to deploy ${label}, retrying in ${delay}ms...`);
56
+ await wait(delay);
57
+ },
58
+ }
59
+ ),
60
+ ];
61
+ }
@@ -0,0 +1,25 @@
1
+ import { Client, Transport, Chain, Account, Hex } from "viem";
2
+ import { waitForTransactionReceipt } from "viem/actions";
3
+ import { debug } from "./debug";
4
+ import { Contract, ensureContract } from "./ensureContract";
5
+
6
+ export async function ensureContractsDeployed({
7
+ client,
8
+ contracts,
9
+ }: {
10
+ readonly client: Client<Transport, Chain | undefined, Account>;
11
+ readonly contracts: readonly Contract[];
12
+ }): Promise<readonly Hex[]> {
13
+ const txs = (await Promise.all(contracts.map((contract) => ensureContract({ client, ...contract })))).flat();
14
+
15
+ if (txs.length) {
16
+ debug("waiting for contracts");
17
+ // wait for each tx separately/serially, because parallelizing results in RPC errors
18
+ for (const tx of txs) {
19
+ await waitForTransactionReceipt(client, { hash: tx });
20
+ // TODO: throw if there was a revert?
21
+ }
22
+ }
23
+
24
+ return txs;
25
+ }
@@ -0,0 +1,36 @@
1
+ import { Account, Chain, Client, Transport } from "viem";
2
+ import { getBytecode, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from "viem/actions";
3
+ import deployment from "./create2/deployment.json";
4
+ import { debug } from "./debug";
5
+
6
+ export const deployer = `0x${deployment.address}` as const;
7
+
8
+ export async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<void> {
9
+ const bytecode = await getBytecode(client, { address: deployer });
10
+ if (bytecode) {
11
+ debug("found create2 deployer at", deployer);
12
+ return;
13
+ }
14
+
15
+ // send gas to signer
16
+ debug("sending gas for create2 deployer to signer at", deployment.signerAddress);
17
+ const gasTx = await sendTransaction(client, {
18
+ chain: client.chain ?? null,
19
+ to: `0x${deployment.signerAddress}`,
20
+ value: BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice),
21
+ });
22
+ const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });
23
+ if (gasReceipt.status !== "success") {
24
+ console.error("failed to send gas to deployer signer", gasReceipt);
25
+ throw new Error("failed to send gas to deployer signer");
26
+ }
27
+
28
+ // deploy the deployer
29
+ debug("deploying create2 deployer at", deployer);
30
+ const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` });
31
+ const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });
32
+ if (deployReceipt.contractAddress !== deployer) {
33
+ console.error("unexpected contract address for deployer", deployReceipt);
34
+ throw new Error("unexpected contract address for deployer");
35
+ }
36
+ }
@@ -0,0 +1,86 @@
1
+ import { Client, Transport, Chain, Account, Hex } from "viem";
2
+ import { hexToResource, writeContract } from "@latticexyz/common";
3
+ import { WorldDeploy, WorldFunction, worldAbi } from "./common";
4
+ import { debug } from "./debug";
5
+ import { getFunctions } from "./getFunctions";
6
+ import pRetry from "p-retry";
7
+ import { wait } from "@latticexyz/common/utils";
8
+
9
+ export async function ensureFunctions({
10
+ client,
11
+ worldDeploy,
12
+ functions,
13
+ }: {
14
+ readonly client: Client<Transport, Chain | undefined, Account>;
15
+ readonly worldDeploy: WorldDeploy;
16
+ readonly functions: readonly WorldFunction[];
17
+ }): Promise<readonly Hex[]> {
18
+ const worldFunctions = await getFunctions({ client, worldDeploy });
19
+ const worldSelectorToFunction = Object.fromEntries(worldFunctions.map((func) => [func.selector, func]));
20
+
21
+ const toSkip = functions.filter((func) => worldSelectorToFunction[func.selector]);
22
+ const toAdd = functions.filter((func) => !toSkip.includes(func));
23
+
24
+ if (toSkip.length) {
25
+ debug("functions already registered:", toSkip.map((func) => func.signature).join(", "));
26
+ const wrongSystem = toSkip.filter((func) => func.systemId !== worldSelectorToFunction[func.selector]?.systemId);
27
+ if (wrongSystem.length) {
28
+ console.warn(
29
+ "found",
30
+ wrongSystem.length,
31
+ "functions already registered but pointing at a different system ID:",
32
+ wrongSystem.map((func) => func.signature).join(", ")
33
+ );
34
+ }
35
+ }
36
+
37
+ if (!toAdd.length) return [];
38
+
39
+ debug("registering functions:", toAdd.map((func) => func.signature).join(", "));
40
+
41
+ return Promise.all(
42
+ toAdd.map((func) => {
43
+ const { namespace } = hexToResource(func.systemId);
44
+ if (namespace === "") {
45
+ return pRetry(
46
+ () =>
47
+ writeContract(client, {
48
+ chain: client.chain ?? null,
49
+ address: worldDeploy.address,
50
+ abi: worldAbi,
51
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
52
+ functionName: "registerRootFunctionSelector",
53
+ args: [func.systemId, func.systemFunctionSignature, func.systemFunctionSelector],
54
+ }),
55
+ {
56
+ retries: 3,
57
+ onFailedAttempt: async (error) => {
58
+ const delay = error.attemptNumber * 500;
59
+ debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);
60
+ await wait(delay);
61
+ },
62
+ }
63
+ );
64
+ }
65
+ return pRetry(
66
+ () =>
67
+ writeContract(client, {
68
+ chain: client.chain ?? null,
69
+ address: worldDeploy.address,
70
+ abi: worldAbi,
71
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
72
+ functionName: "registerFunctionSelector",
73
+ args: [func.systemId, func.systemFunctionSignature],
74
+ }),
75
+ {
76
+ retries: 3,
77
+ onFailedAttempt: async (error) => {
78
+ const delay = error.attemptNumber * 500;
79
+ debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`);
80
+ await wait(delay);
81
+ },
82
+ }
83
+ );
84
+ })
85
+ );
86
+ }
@@ -0,0 +1,73 @@
1
+ import { Client, Transport, Chain, Account, Hex, BaseError, getAddress } from "viem";
2
+ import { writeContract } from "@latticexyz/common";
3
+ import { Module, WorldDeploy, worldAbi } from "./common";
4
+ import { debug } from "./debug";
5
+ import { isDefined, uniqueBy, wait } from "@latticexyz/common/utils";
6
+ import pRetry from "p-retry";
7
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
8
+
9
+ export async function ensureModules({
10
+ client,
11
+ worldDeploy,
12
+ modules,
13
+ }: {
14
+ readonly client: Client<Transport, Chain | undefined, Account>;
15
+ readonly worldDeploy: WorldDeploy;
16
+ readonly modules: readonly Module[];
17
+ }): Promise<readonly Hex[]> {
18
+ if (!modules.length) return [];
19
+
20
+ await ensureContractsDeployed({
21
+ client,
22
+ contracts: uniqueBy(modules, (mod) => getAddress(mod.address)).map((mod) => ({
23
+ bytecode: mod.bytecode,
24
+ deployedBytecodeSize: mod.deployedBytecodeSize,
25
+ label: `${mod.name} module`,
26
+ })),
27
+ });
28
+
29
+ debug("installing modules:", modules.map((mod) => mod.name).join(", "));
30
+ return (
31
+ await Promise.all(
32
+ modules.map((mod) =>
33
+ pRetry(
34
+ async () => {
35
+ try {
36
+ return mod.installAsRoot
37
+ ? await writeContract(client, {
38
+ chain: client.chain ?? null,
39
+ address: worldDeploy.address,
40
+ abi: worldAbi,
41
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
42
+ functionName: "installRootModule",
43
+ args: [mod.address, mod.installData],
44
+ })
45
+ : await writeContract(client, {
46
+ chain: client.chain ?? null,
47
+ address: worldDeploy.address,
48
+ abi: worldAbi,
49
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
50
+ functionName: "installModule",
51
+ args: [mod.address, mod.installData],
52
+ });
53
+ } catch (error) {
54
+ if (error instanceof BaseError && error.message.includes("Module_AlreadyInstalled")) {
55
+ debug(`module ${mod.name} already installed`);
56
+ return;
57
+ }
58
+ throw error;
59
+ }
60
+ },
61
+ {
62
+ retries: 3,
63
+ onFailedAttempt: async (error) => {
64
+ const delay = error.attemptNumber * 500;
65
+ debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);
66
+ await wait(delay);
67
+ },
68
+ }
69
+ )
70
+ )
71
+ )
72
+ ).filter(isDefined);
73
+ }
@@ -0,0 +1,162 @@
1
+ import { Client, Transport, Chain, Account, Hex, getAddress } from "viem";
2
+ import { writeContract } from "@latticexyz/common";
3
+ import { System, WorldDeploy, worldAbi } from "./common";
4
+ import { debug } from "./debug";
5
+ import { resourceLabel } from "./resourceLabel";
6
+ import { getSystems } from "./getSystems";
7
+ import { getResourceAccess } from "./getResourceAccess";
8
+ import { uniqueBy, wait } from "@latticexyz/common/utils";
9
+ import pRetry from "p-retry";
10
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
11
+
12
+ export async function ensureSystems({
13
+ client,
14
+ worldDeploy,
15
+ systems,
16
+ }: {
17
+ readonly client: Client<Transport, Chain | undefined, Account>;
18
+ readonly worldDeploy: WorldDeploy;
19
+ readonly systems: readonly System[];
20
+ }): Promise<readonly Hex[]> {
21
+ const [worldSystems, worldAccess] = await Promise.all([
22
+ getSystems({ client, worldDeploy }),
23
+ getResourceAccess({ client, worldDeploy }),
24
+ ]);
25
+ const systemIds = systems.map((system) => system.systemId);
26
+ const currentAccess = worldAccess.filter(({ resourceId }) => systemIds.includes(resourceId));
27
+ const desiredAccess = systems.flatMap((system) =>
28
+ system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address }))
29
+ );
30
+
31
+ const accessToAdd = desiredAccess.filter(
32
+ (access) =>
33
+ !currentAccess.some(
34
+ ({ resourceId, address }) =>
35
+ resourceId === access.resourceId && getAddress(address) === getAddress(access.address)
36
+ )
37
+ );
38
+
39
+ const accessToRemove = currentAccess.filter(
40
+ (access) =>
41
+ !desiredAccess.some(
42
+ ({ resourceId, address }) =>
43
+ resourceId === access.resourceId && getAddress(address) === getAddress(access.address)
44
+ )
45
+ );
46
+
47
+ // TODO: move each system access+registration to batch call to be atomic
48
+
49
+ if (accessToRemove.length) {
50
+ debug("revoking", accessToRemove.length, "access grants");
51
+ }
52
+ if (accessToAdd.length) {
53
+ debug("adding", accessToAdd.length, "access grants");
54
+ }
55
+
56
+ const accessTxs = [
57
+ ...accessToRemove.map((access) =>
58
+ pRetry(
59
+ () =>
60
+ writeContract(client, {
61
+ chain: client.chain ?? null,
62
+ address: worldDeploy.address,
63
+ abi: worldAbi,
64
+ functionName: "revokeAccess",
65
+ args: [access.resourceId, access.address],
66
+ }),
67
+ {
68
+ retries: 3,
69
+ onFailedAttempt: async (error) => {
70
+ const delay = error.attemptNumber * 500;
71
+ debug(`failed to revoke access, retrying in ${delay}ms...`);
72
+ await wait(delay);
73
+ },
74
+ }
75
+ )
76
+ ),
77
+ ...accessToAdd.map((access) =>
78
+ pRetry(
79
+ () =>
80
+ writeContract(client, {
81
+ chain: client.chain ?? null,
82
+ address: worldDeploy.address,
83
+ abi: worldAbi,
84
+ functionName: "grantAccess",
85
+ args: [access.resourceId, access.address],
86
+ }),
87
+ {
88
+ retries: 3,
89
+ onFailedAttempt: async (error) => {
90
+ const delay = error.attemptNumber * 500;
91
+ debug(`failed to grant access, retrying in ${delay}ms...`);
92
+ await wait(delay);
93
+ },
94
+ }
95
+ )
96
+ ),
97
+ ];
98
+
99
+ const existingSystems = systems.filter((system) =>
100
+ worldSystems.some(
101
+ (worldSystem) =>
102
+ worldSystem.systemId === system.systemId && getAddress(worldSystem.address) === getAddress(system.address)
103
+ )
104
+ );
105
+ if (existingSystems.length) {
106
+ debug("existing systems", existingSystems.map(resourceLabel).join(", "));
107
+ }
108
+ const existingSystemIds = existingSystems.map((system) => system.systemId);
109
+
110
+ const missingSystems = systems.filter((system) => !existingSystemIds.includes(system.systemId));
111
+ if (!missingSystems.length) return [];
112
+
113
+ const systemsToUpgrade = missingSystems.filter((system) =>
114
+ worldSystems.some(
115
+ (worldSystem) =>
116
+ worldSystem.systemId === system.systemId && getAddress(worldSystem.address) !== getAddress(system.address)
117
+ )
118
+ );
119
+ if (systemsToUpgrade.length) {
120
+ debug("upgrading systems", systemsToUpgrade.map(resourceLabel).join(", "));
121
+ }
122
+
123
+ const systemsToAdd = missingSystems.filter(
124
+ (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId)
125
+ );
126
+ if (systemsToAdd.length) {
127
+ debug("registering new systems", systemsToAdd.map(resourceLabel).join(", "));
128
+ }
129
+
130
+ await ensureContractsDeployed({
131
+ client,
132
+ contracts: uniqueBy(missingSystems, (system) => getAddress(system.address)).map((system) => ({
133
+ bytecode: system.bytecode,
134
+ deployedBytecodeSize: system.deployedBytecodeSize,
135
+ label: `${resourceLabel(system)} system`,
136
+ })),
137
+ });
138
+
139
+ const registerTxs = missingSystems.map((system) =>
140
+ pRetry(
141
+ () =>
142
+ writeContract(client, {
143
+ chain: client.chain ?? null,
144
+ address: worldDeploy.address,
145
+ abi: worldAbi,
146
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
147
+ functionName: "registerSystem",
148
+ args: [system.systemId, system.address, system.allowAll],
149
+ }),
150
+ {
151
+ retries: 3,
152
+ onFailedAttempt: async (error) => {
153
+ const delay = error.attemptNumber * 500;
154
+ debug(`failed to register system ${resourceLabel(system)}, retrying in ${delay}ms...`);
155
+ await wait(delay);
156
+ },
157
+ }
158
+ )
159
+ );
160
+
161
+ return await Promise.all([...accessTxs, ...registerTxs]);
162
+ }
@@ -0,0 +1,65 @@
1
+ import { Client, Transport, Chain, Account, Hex } from "viem";
2
+ import { Table } from "./configToTables";
3
+ import { writeContract } from "@latticexyz/common";
4
+ import { WorldDeploy, worldAbi } from "./common";
5
+ import { valueSchemaToFieldLayoutHex, keySchemaToHex, valueSchemaToHex } from "@latticexyz/protocol-parser";
6
+ import { debug } from "./debug";
7
+ import { resourceLabel } from "./resourceLabel";
8
+ import { getTables } from "./getTables";
9
+ import pRetry from "p-retry";
10
+ import { wait } from "@latticexyz/common/utils";
11
+
12
+ export async function ensureTables({
13
+ client,
14
+ worldDeploy,
15
+ tables,
16
+ }: {
17
+ readonly client: Client<Transport, Chain | undefined, Account>;
18
+ readonly worldDeploy: WorldDeploy;
19
+ readonly tables: readonly Table[];
20
+ }): Promise<readonly Hex[]> {
21
+ const worldTables = await getTables({ client, worldDeploy });
22
+ const worldTableIds = worldTables.map((table) => table.tableId);
23
+
24
+ const existingTables = tables.filter((table) => worldTableIds.includes(table.tableId));
25
+ if (existingTables.length) {
26
+ debug("existing tables", existingTables.map(resourceLabel).join(", "));
27
+ }
28
+
29
+ const missingTables = tables.filter((table) => !worldTableIds.includes(table.tableId));
30
+ if (missingTables.length) {
31
+ debug("registering tables", missingTables.map(resourceLabel).join(", "));
32
+ return await Promise.all(
33
+ missingTables.map((table) =>
34
+ pRetry(
35
+ () =>
36
+ writeContract(client, {
37
+ chain: client.chain ?? null,
38
+ address: worldDeploy.address,
39
+ abi: worldAbi,
40
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
41
+ functionName: "registerTable",
42
+ args: [
43
+ table.tableId,
44
+ valueSchemaToFieldLayoutHex(table.valueSchema),
45
+ keySchemaToHex(table.keySchema),
46
+ valueSchemaToHex(table.valueSchema),
47
+ Object.keys(table.keySchema),
48
+ Object.keys(table.valueSchema),
49
+ ],
50
+ }),
51
+ {
52
+ retries: 3,
53
+ onFailedAttempt: async (error) => {
54
+ const delay = error.attemptNumber * 500;
55
+ debug(`failed to register table ${resourceLabel(table)}, retrying in ${delay}ms...`);
56
+ await wait(delay);
57
+ },
58
+ }
59
+ )
60
+ )
61
+ );
62
+ }
63
+
64
+ return [];
65
+ }
@@ -0,0 +1,47 @@
1
+ import coreModuleBuild from "@latticexyz/world/out/CoreModule.sol/CoreModule.json" assert { type: "json" };
2
+ import worldFactoryBuild from "@latticexyz/world/out/WorldFactory.sol/WorldFactory.json" assert { type: "json" };
3
+ import { Client, Transport, Chain, Account, Hex, parseAbi, getCreate2Address, encodeDeployData, size } from "viem";
4
+ import { deployer } from "./ensureDeployer";
5
+ import { salt } from "./common";
6
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
7
+ import { Contract } from "./ensureContract";
8
+
9
+ export const coreModuleDeployedBytecodeSize = size(coreModuleBuild.deployedBytecode.object as Hex);
10
+ export const coreModuleBytecode = encodeDeployData({
11
+ bytecode: coreModuleBuild.bytecode.object as Hex,
12
+ abi: [],
13
+ });
14
+
15
+ export const coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });
16
+
17
+ export const worldFactoryDeployedBytecodeSize = size(worldFactoryBuild.deployedBytecode.object as Hex);
18
+ export const worldFactoryBytecode = encodeDeployData({
19
+ bytecode: worldFactoryBuild.bytecode.object as Hex,
20
+ abi: parseAbi(["constructor(address)"]),
21
+ args: [coreModule],
22
+ });
23
+
24
+ export const worldFactory = getCreate2Address({ from: deployer, bytecode: worldFactoryBytecode, salt });
25
+
26
+ export const worldFactoryContracts: readonly Contract[] = [
27
+ {
28
+ bytecode: coreModuleBytecode,
29
+ deployedBytecodeSize: coreModuleDeployedBytecodeSize,
30
+ label: "core module",
31
+ },
32
+ {
33
+ bytecode: worldFactoryBytecode,
34
+ deployedBytecodeSize: worldFactoryDeployedBytecodeSize,
35
+ label: "world factory",
36
+ },
37
+ ];
38
+
39
+ export async function ensureWorldFactory(
40
+ client: Client<Transport, Chain | undefined, Account>
41
+ ): Promise<readonly Hex[]> {
42
+ // WorldFactory constructor doesn't call CoreModule, only sets its address, so we can do these in parallel since the address is deterministic
43
+ return await ensureContractsDeployed({
44
+ client,
45
+ contracts: worldFactoryContracts,
46
+ });
47
+ }
@@ -0,0 +1,58 @@
1
+ import { Client, getFunctionSelector, parseAbiItem } from "viem";
2
+ import { WorldDeploy, WorldFunction, worldTables } from "./common";
3
+ import { debug } from "./debug";
4
+ import { storeSetRecordEvent } from "@latticexyz/store";
5
+ import { getLogs } from "viem/actions";
6
+ import { decodeValueArgs } from "@latticexyz/protocol-parser";
7
+ import { getTableValue } from "./getTableValue";
8
+ import { hexToResource } from "@latticexyz/common";
9
+
10
+ export async function getFunctions({
11
+ client,
12
+ worldDeploy,
13
+ }: {
14
+ readonly client: Client;
15
+ readonly worldDeploy: WorldDeploy;
16
+ }): Promise<readonly WorldFunction[]> {
17
+ // This assumes we only use `FunctionSelectors._set(...)`, which is true as of this writing.
18
+ debug("looking up function signatures for", worldDeploy.address);
19
+ const logs = await getLogs(client, {
20
+ strict: true,
21
+ fromBlock: worldDeploy.deployBlock,
22
+ toBlock: worldDeploy.stateBlock,
23
+ address: worldDeploy.address,
24
+ event: parseAbiItem(storeSetRecordEvent),
25
+ args: { tableId: worldTables.world_FunctionSignatures.tableId },
26
+ });
27
+
28
+ const signatures = logs.map((log) => {
29
+ const value = decodeValueArgs(worldTables.world_FunctionSignatures.valueSchema, log.args);
30
+ return value.functionSignature;
31
+ });
32
+ debug("found", signatures.length, "function signatures for", worldDeploy.address);
33
+
34
+ // TODO: parallelize with a bulk getRecords
35
+ const functions = await Promise.all(
36
+ signatures.map(async (signature) => {
37
+ const selector = getFunctionSelector(signature);
38
+ const { systemId, systemFunctionSelector } = await getTableValue({
39
+ client,
40
+ worldDeploy,
41
+ table: worldTables.world_FunctionSelectors,
42
+ key: { functionSelector: selector },
43
+ });
44
+ const { namespace, name } = hexToResource(systemId);
45
+ // TODO: find away around undoing contract logic (https://github.com/latticexyz/mud/issues/1708)
46
+ const systemFunctionSignature = namespace === "" ? signature : signature.replace(`${namespace}_${name}_`, "");
47
+ return {
48
+ signature,
49
+ selector,
50
+ systemId,
51
+ systemFunctionSignature,
52
+ systemFunctionSelector,
53
+ };
54
+ })
55
+ );
56
+
57
+ return functions;
58
+ }
@@ -0,0 +1,51 @@
1
+ import { Client, parseAbiItem, Hex, Address, getAddress } from "viem";
2
+ import { WorldDeploy, worldTables } from "./common";
3
+ import { debug } from "./debug";
4
+ import { storeSpliceStaticDataEvent } from "@latticexyz/store";
5
+ import { getLogs } from "viem/actions";
6
+ import { decodeKey } from "@latticexyz/protocol-parser";
7
+ import { getTableValue } from "./getTableValue";
8
+
9
+ export async function getResourceAccess({
10
+ client,
11
+ worldDeploy,
12
+ }: {
13
+ readonly client: Client;
14
+ readonly worldDeploy: WorldDeploy;
15
+ }): Promise<readonly { readonly resourceId: Hex; readonly address: Address }[]> {
16
+ // This assumes we only use `ResourceAccess._set(...)`, which is true as of this writing.
17
+ // 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
18
+
19
+ debug("looking up resource access for", worldDeploy.address);
20
+
21
+ const logs = await getLogs(client, {
22
+ strict: true,
23
+ fromBlock: worldDeploy.deployBlock,
24
+ toBlock: worldDeploy.stateBlock,
25
+ address: worldDeploy.address,
26
+ // our usage of `ResourceAccess._set(...)` emits a splice instead of set record
27
+ // TODO: https://github.com/latticexyz/mud/issues/479
28
+ event: parseAbiItem(storeSpliceStaticDataEvent),
29
+ args: { tableId: worldTables.world_ResourceAccess.tableId },
30
+ });
31
+
32
+ const keys = logs.map((log) => decodeKey(worldTables.world_ResourceAccess.keySchema, log.args.keyTuple));
33
+
34
+ const access = (
35
+ await Promise.all(
36
+ keys.map(
37
+ async (key) =>
38
+ [key, await getTableValue({ client, worldDeploy, table: worldTables.world_ResourceAccess, key })] as const
39
+ )
40
+ )
41
+ )
42
+ .filter(([, value]) => value.access)
43
+ .map(([key]) => ({
44
+ resourceId: key.resourceId,
45
+ address: getAddress(key.caller),
46
+ }));
47
+
48
+ debug("found", access.length, "resource<>address access pairs");
49
+
50
+ return access;
51
+ }