@latticexyz/cli 2.0.0-next.11 → 2.0.0-next.13

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 (68) hide show
  1. package/dist/chunk-22IIKR4S.js +4 -0
  2. package/dist/chunk-22IIKR4S.js.map +1 -0
  3. package/dist/commands-AAHOIIJW.js +23 -0
  4. package/dist/commands-AAHOIIJW.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 +0 -1
  8. package/dist/mud.js +1 -18
  9. package/dist/mud.js.map +1 -1
  10. package/package.json +16 -12
  11. package/src/commands/deploy.ts +7 -30
  12. package/src/commands/dev-contracts.ts +74 -138
  13. package/src/commands/test.ts +30 -36
  14. package/src/commands/trace.ts +7 -5
  15. package/src/debug.ts +3 -0
  16. package/src/deploy/assertNamespaceOwner.ts +42 -0
  17. package/src/deploy/common.ts +72 -0
  18. package/src/deploy/configToTables.ts +68 -0
  19. package/src/deploy/create2/README.md +9 -0
  20. package/src/deploy/create2/deployment.json +7 -0
  21. package/src/deploy/debug.ts +3 -0
  22. package/src/deploy/deploy.ts +108 -0
  23. package/src/deploy/deployWorld.ts +33 -0
  24. package/src/deploy/ensureContract.ts +49 -0
  25. package/src/deploy/ensureContractsDeployed.ts +25 -0
  26. package/src/deploy/ensureDeployer.ts +36 -0
  27. package/src/deploy/ensureFunctions.ts +86 -0
  28. package/src/deploy/ensureModules.ts +72 -0
  29. package/src/deploy/ensureSystems.ts +161 -0
  30. package/src/deploy/ensureTables.ts +65 -0
  31. package/src/deploy/ensureWorldFactory.ts +34 -0
  32. package/src/deploy/getFunctions.ts +58 -0
  33. package/src/deploy/getResourceAccess.ts +51 -0
  34. package/src/deploy/getResourceIds.ts +31 -0
  35. package/src/deploy/getSystems.ts +48 -0
  36. package/src/deploy/getTableValue.ts +30 -0
  37. package/src/deploy/getTables.ts +59 -0
  38. package/src/deploy/getWorldDeploy.ts +39 -0
  39. package/src/deploy/logsToWorldDeploy.ts +49 -0
  40. package/src/deploy/resolveConfig.ts +154 -0
  41. package/src/deploy/resourceLabel.ts +3 -0
  42. package/src/index.ts +1 -1
  43. package/src/mud.ts +37 -31
  44. package/src/runDeploy.ts +128 -0
  45. package/src/utils/modules/constants.ts +1 -2
  46. package/src/utils/utils/getContractData.ts +2 -5
  47. package/dist/chunk-TW3YGZ4D.js +0 -11
  48. package/dist/chunk-TW3YGZ4D.js.map +0 -1
  49. package/src/utils/deploy.ts +0 -254
  50. package/src/utils/deployHandler.ts +0 -93
  51. package/src/utils/modules/getInstallModuleCallData.ts +0 -27
  52. package/src/utils/modules/getUserModules.ts +0 -5
  53. package/src/utils/modules/types.ts +0 -14
  54. package/src/utils/systems/getGrantAccessCallData.ts +0 -29
  55. package/src/utils/systems/getRegisterFunctionSelectorsCallData.ts +0 -57
  56. package/src/utils/systems/getRegisterSystemCallData.ts +0 -17
  57. package/src/utils/systems/types.ts +0 -9
  58. package/src/utils/systems/utils.ts +0 -42
  59. package/src/utils/tables/getRegisterTableCallData.ts +0 -49
  60. package/src/utils/tables/getTableIds.ts +0 -18
  61. package/src/utils/tables/types.ts +0 -12
  62. package/src/utils/utils/confirmNonce.ts +0 -24
  63. package/src/utils/utils/deployContract.ts +0 -33
  64. package/src/utils/utils/fastTxExecute.ts +0 -56
  65. package/src/utils/utils/getChainId.ts +0 -10
  66. package/src/utils/utils/setInternalFeePerGas.ts +0 -49
  67. package/src/utils/utils/types.ts +0 -21
  68. package/src/utils/world.ts +0 -28
@@ -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,72 @@
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
+ label: `${mod.name} module`,
25
+ })),
26
+ });
27
+
28
+ debug("installing modules:", modules.map((mod) => mod.name).join(", "));
29
+ return (
30
+ await Promise.all(
31
+ modules.map((mod) =>
32
+ pRetry(
33
+ async () => {
34
+ try {
35
+ return mod.installAsRoot
36
+ ? await 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: "installRootModule",
42
+ args: [mod.address, mod.installData],
43
+ })
44
+ : await writeContract(client, {
45
+ chain: client.chain ?? null,
46
+ address: worldDeploy.address,
47
+ abi: worldAbi,
48
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
49
+ functionName: "installModule",
50
+ args: [mod.address, mod.installData],
51
+ });
52
+ } catch (error) {
53
+ if (error instanceof BaseError && error.message.includes("Module_AlreadyInstalled")) {
54
+ debug(`module ${mod.name} already installed`);
55
+ return;
56
+ }
57
+ throw error;
58
+ }
59
+ },
60
+ {
61
+ retries: 3,
62
+ onFailedAttempt: async (error) => {
63
+ const delay = error.attemptNumber * 500;
64
+ debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);
65
+ await wait(delay);
66
+ },
67
+ }
68
+ )
69
+ )
70
+ )
71
+ ).filter(isDefined);
72
+ }
@@ -0,0 +1,161 @@
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
+ label: `${resourceLabel(system)} system`,
135
+ })),
136
+ });
137
+
138
+ const registerTxs = missingSystems.map((system) =>
139
+ pRetry(
140
+ () =>
141
+ writeContract(client, {
142
+ chain: client.chain ?? null,
143
+ address: worldDeploy.address,
144
+ abi: worldAbi,
145
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
146
+ functionName: "registerSystem",
147
+ args: [system.systemId, system.address, system.allowAll],
148
+ }),
149
+ {
150
+ retries: 3,
151
+ onFailedAttempt: async (error) => {
152
+ const delay = error.attemptNumber * 500;
153
+ debug(`failed to register system ${resourceLabel(system)}, retrying in ${delay}ms...`);
154
+ await wait(delay);
155
+ },
156
+ }
157
+ )
158
+ );
159
+
160
+ return await Promise.all([...accessTxs, ...registerTxs]);
161
+ }
@@ -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,34 @@
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 } from "viem";
4
+ import { deployer } from "./ensureDeployer";
5
+ import { salt } from "./common";
6
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
7
+
8
+ export const coreModuleBytecode = encodeDeployData({
9
+ bytecode: coreModuleBuild.bytecode.object as Hex,
10
+ abi: [],
11
+ });
12
+
13
+ export const coreModule = getCreate2Address({ from: deployer, bytecode: coreModuleBytecode, salt });
14
+
15
+ export const worldFactoryBytecode = encodeDeployData({
16
+ bytecode: worldFactoryBuild.bytecode.object as Hex,
17
+ abi: parseAbi(["constructor(address)"]),
18
+ args: [coreModule],
19
+ });
20
+
21
+ export const worldFactory = getCreate2Address({ from: deployer, bytecode: worldFactoryBytecode, salt });
22
+
23
+ export async function ensureWorldFactory(
24
+ client: Client<Transport, Chain | undefined, Account>
25
+ ): Promise<readonly Hex[]> {
26
+ // WorldFactory constructor doesn't call CoreModule, only sets its address, so we can do these in parallel since the address is deterministic
27
+ return await ensureContractsDeployed({
28
+ client,
29
+ contracts: [
30
+ { bytecode: coreModuleBytecode, label: "core module" },
31
+ { bytecode: worldFactoryBytecode, label: "world factory" },
32
+ ],
33
+ });
34
+ }
@@ -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
+ }
@@ -0,0 +1,31 @@
1
+ import { Client, parseAbiItem, Hex } from "viem";
2
+ import { getLogs } from "viem/actions";
3
+ import { storeSpliceStaticDataEvent } from "@latticexyz/store";
4
+ import { WorldDeploy, storeTables } from "./common";
5
+ import { debug } from "./debug";
6
+
7
+ export async function getResourceIds({
8
+ client,
9
+ worldDeploy,
10
+ }: {
11
+ readonly client: Client;
12
+ readonly worldDeploy: WorldDeploy;
13
+ }): Promise<readonly Hex[]> {
14
+ // This assumes we only use `ResourceIds._setExists(true)`, which is true as of this writing.
15
+ // TODO: PR to viem's getLogs to accept topics array so we can filter on all store events and quickly recreate this table's current state
16
+
17
+ debug("looking up resource IDs for", worldDeploy.address);
18
+ const logs = await getLogs(client, {
19
+ strict: true,
20
+ address: worldDeploy.address,
21
+ fromBlock: worldDeploy.deployBlock,
22
+ toBlock: worldDeploy.stateBlock,
23
+ event: parseAbiItem(storeSpliceStaticDataEvent),
24
+ args: { tableId: storeTables.store_ResourceIds.tableId },
25
+ });
26
+
27
+ const resourceIds = logs.map((log) => log.args.keyTuple[0]);
28
+ debug("found", resourceIds.length, "resource IDs for", worldDeploy.address);
29
+
30
+ return resourceIds;
31
+ }
@@ -0,0 +1,48 @@
1
+ import { System, WorldDeploy, worldTables } from "./common";
2
+ import { Client } from "viem";
3
+ import { getResourceIds } from "./getResourceIds";
4
+ import { hexToResource } from "@latticexyz/common";
5
+ import { getTableValue } from "./getTableValue";
6
+ import { debug } from "./debug";
7
+ import { resourceLabel } from "./resourceLabel";
8
+ import { getFunctions } from "./getFunctions";
9
+ import { getResourceAccess } from "./getResourceAccess";
10
+
11
+ export async function getSystems({
12
+ client,
13
+ worldDeploy,
14
+ }: {
15
+ readonly client: Client;
16
+ readonly worldDeploy: WorldDeploy;
17
+ }): Promise<readonly Omit<System, "abi" | "bytecode">[]> {
18
+ const [resourceIds, functions, resourceAccess] = await Promise.all([
19
+ getResourceIds({ client, worldDeploy }),
20
+ getFunctions({ client, worldDeploy }),
21
+ getResourceAccess({ client, worldDeploy }),
22
+ ]);
23
+ const systems = resourceIds.map(hexToResource).filter((resource) => resource.type === "system");
24
+
25
+ debug("looking up systems", systems.map(resourceLabel).join(", "));
26
+ return await Promise.all(
27
+ systems.map(async (system) => {
28
+ const { system: address, publicAccess } = await getTableValue({
29
+ client,
30
+ worldDeploy,
31
+ table: worldTables.world_Systems,
32
+ key: { systemId: system.resourceId },
33
+ });
34
+ const systemFunctions = functions.filter((func) => func.systemId === system.resourceId);
35
+ return {
36
+ address,
37
+ namespace: system.namespace,
38
+ name: system.name,
39
+ systemId: system.resourceId,
40
+ allowAll: publicAccess,
41
+ allowedAddresses: resourceAccess
42
+ .filter(({ resourceId }) => resourceId === system.resourceId)
43
+ .map(({ address }) => address),
44
+ functions: systemFunctions,
45
+ };
46
+ })
47
+ );
48
+ }
@@ -0,0 +1,30 @@
1
+ import { SchemaToPrimitives, decodeValueArgs, encodeKey } from "@latticexyz/protocol-parser";
2
+ import { WorldDeploy, worldAbi } from "./common";
3
+ import { Client } from "viem";
4
+ import { readContract } from "viem/actions";
5
+ import { Table } from "./configToTables";
6
+
7
+ export async function getTableValue<table extends Table>({
8
+ client,
9
+ worldDeploy,
10
+ table,
11
+ key,
12
+ }: {
13
+ readonly client: Client;
14
+ readonly worldDeploy: WorldDeploy;
15
+ readonly table: table;
16
+ readonly key: SchemaToPrimitives<table["keySchema"]>;
17
+ }): Promise<SchemaToPrimitives<table["valueSchema"]>> {
18
+ const [staticData, encodedLengths, dynamicData] = await readContract(client, {
19
+ blockNumber: worldDeploy.stateBlock,
20
+ address: worldDeploy.address,
21
+ abi: worldAbi,
22
+ functionName: "getRecord",
23
+ args: [table.tableId, encodeKey(table.keySchema, key)],
24
+ });
25
+ return decodeValueArgs(table.valueSchema, {
26
+ staticData,
27
+ encodedLengths,
28
+ dynamicData,
29
+ });
30
+ }