@latticexyz/cli 2.0.0-snapshot-test-32d38619 → 2.0.0-transaction-context-324984c5

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 (75) hide show
  1. package/dist/chunk-22IIKR4S.js +4 -0
  2. package/dist/chunk-22IIKR4S.js.map +1 -0
  3. package/dist/commands-3JV3U43E.js +27 -0
  4. package/dist/commands-3JV3U43E.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 -14
  9. package/dist/mud.js.map +1 -1
  10. package/package.json +18 -13
  11. package/src/build.ts +44 -0
  12. package/src/commands/build.ts +36 -0
  13. package/src/commands/deploy.ts +7 -30
  14. package/src/commands/dev-contracts.ts +76 -138
  15. package/src/commands/index.ts +2 -0
  16. package/src/commands/set-version.ts +23 -61
  17. package/src/commands/test.ts +30 -36
  18. package/src/commands/trace.ts +8 -6
  19. package/src/common.ts +1 -0
  20. package/src/debug.ts +10 -0
  21. package/src/deploy/common.ts +76 -0
  22. package/src/deploy/configToTables.ts +68 -0
  23. package/src/deploy/create2/README.md +9 -0
  24. package/src/deploy/create2/deployment.json +7 -0
  25. package/src/deploy/debug.ts +10 -0
  26. package/src/deploy/deploy.ts +116 -0
  27. package/src/deploy/deployWorld.ts +37 -0
  28. package/src/deploy/ensureContract.ts +61 -0
  29. package/src/deploy/ensureContractsDeployed.ts +25 -0
  30. package/src/deploy/ensureDeployer.ts +36 -0
  31. package/src/deploy/ensureFunctions.ts +86 -0
  32. package/src/deploy/ensureModules.ts +73 -0
  33. package/src/deploy/ensureNamespaceOwner.ts +71 -0
  34. package/src/deploy/ensureSystems.ts +162 -0
  35. package/src/deploy/ensureTables.ts +65 -0
  36. package/src/deploy/ensureWorldFactory.ts +118 -0
  37. package/src/deploy/getFunctions.ts +58 -0
  38. package/src/deploy/getResourceAccess.ts +51 -0
  39. package/src/deploy/getResourceIds.ts +31 -0
  40. package/src/deploy/getSystems.ts +48 -0
  41. package/src/deploy/getTableValue.ts +30 -0
  42. package/src/deploy/getTables.ts +59 -0
  43. package/src/deploy/getWorldDeploy.ts +39 -0
  44. package/src/deploy/logsToWorldDeploy.ts +49 -0
  45. package/src/deploy/resolveConfig.ts +151 -0
  46. package/src/deploy/resourceLabel.ts +3 -0
  47. package/src/index.ts +1 -1
  48. package/src/mud.ts +37 -31
  49. package/src/mudPackages.ts +24 -0
  50. package/src/runDeploy.ts +131 -0
  51. package/src/utils/modules/constants.ts +11 -8
  52. package/src/utils/utils/getContractData.ts +6 -3
  53. package/dist/chunk-WERDORTY.js +0 -11
  54. package/dist/chunk-WERDORTY.js.map +0 -1
  55. package/src/utils/deploy.ts +0 -255
  56. package/src/utils/deployHandler.ts +0 -93
  57. package/src/utils/modules/getInstallModuleCallData.ts +0 -27
  58. package/src/utils/modules/getUserModules.ts +0 -5
  59. package/src/utils/modules/types.ts +0 -14
  60. package/src/utils/systems/getGrantAccessCallData.ts +0 -29
  61. package/src/utils/systems/getRegisterFunctionSelectorsCallData.ts +0 -57
  62. package/src/utils/systems/getRegisterSystemCallData.ts +0 -17
  63. package/src/utils/systems/types.ts +0 -9
  64. package/src/utils/systems/utils.ts +0 -42
  65. package/src/utils/tables/getRegisterTableCallData.ts +0 -49
  66. package/src/utils/tables/getTableIds.ts +0 -21
  67. package/src/utils/tables/types.ts +0 -12
  68. package/src/utils/utils/confirmNonce.ts +0 -24
  69. package/src/utils/utils/deployContract.ts +0 -33
  70. package/src/utils/utils/fastTxExecute.ts +0 -56
  71. package/src/utils/utils/getChainId.ts +0 -10
  72. package/src/utils/utils/setInternalFeePerGas.ts +0 -49
  73. package/src/utils/utils/toBytes16.ts +0 -16
  74. package/src/utils/utils/types.ts +0 -21
  75. package/src/utils/world.ts +0 -28
@@ -0,0 +1,68 @@
1
+ import { resourceToHex } from "@latticexyz/common";
2
+ import { KeySchema, ValueSchema } from "@latticexyz/protocol-parser";
3
+ import { SchemaAbiType, StaticAbiType } from "@latticexyz/schema-type";
4
+ import { StoreConfig, resolveUserTypes } from "@latticexyz/store";
5
+ import { Hex } from "viem";
6
+
7
+ // TODO: we shouldn't need this file once our config parsing returns nicely formed tables
8
+
9
+ type UserTypes<config extends StoreConfig = StoreConfig> = config["userTypes"];
10
+ // TODO: fix strong enum types and avoid every schema getting `{ [k: string]: "uint8" }`
11
+ // type UserTypes<config extends StoreConfig = StoreConfig> = config["userTypes"] & {
12
+ // [k in keyof config["enums"]]: { internalType: "uint8" };
13
+ // };
14
+
15
+ export type TableKey<
16
+ config extends StoreConfig = StoreConfig,
17
+ table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]]
18
+ > = `${config["namespace"]}_${table["name"]}`;
19
+
20
+ export type Table<
21
+ config extends StoreConfig = StoreConfig,
22
+ table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]]
23
+ > = {
24
+ readonly namespace: config["namespace"];
25
+ readonly name: table["name"];
26
+ readonly tableId: Hex;
27
+ readonly keySchema: table["keySchema"] extends KeySchema<UserTypes<config>>
28
+ ? KeySchema & {
29
+ readonly [k in keyof table["keySchema"]]: UserTypes<config>[table["keySchema"][k]]["internalType"] extends StaticAbiType
30
+ ? UserTypes<config>[table["keySchema"][k]]["internalType"]
31
+ : table["keySchema"][k];
32
+ }
33
+ : KeySchema;
34
+ readonly valueSchema: table["valueSchema"] extends ValueSchema<UserTypes<config>>
35
+ ? {
36
+ readonly [k in keyof table["valueSchema"]]: UserTypes<config>[table["valueSchema"][k]]["internalType"] extends SchemaAbiType
37
+ ? UserTypes<config>[table["valueSchema"][k]]["internalType"]
38
+ : table["valueSchema"][k];
39
+ }
40
+ : ValueSchema;
41
+ };
42
+
43
+ export type Tables<config extends StoreConfig = StoreConfig> = {
44
+ readonly [k in keyof config["tables"] as TableKey<config, config["tables"][k]>]: Table<config, config["tables"][k]>;
45
+ };
46
+
47
+ export function configToTables<config extends StoreConfig>(config: config): Tables<config> {
48
+ const userTypes = {
49
+ ...config.userTypes,
50
+ ...Object.fromEntries(Object.entries(config.enums).map(([key]) => [key, { internalType: "uint8" }] as const)),
51
+ };
52
+ return Object.fromEntries(
53
+ Object.entries(config.tables).map(([tableName, table]) => [
54
+ `${config.namespace}_${tableName}` satisfies TableKey<config, config["tables"][keyof config["tables"]]>,
55
+ {
56
+ namespace: config.namespace,
57
+ name: table.name,
58
+ tableId: resourceToHex({
59
+ type: table.offchainOnly ? "offchainTable" : "table",
60
+ namespace: config.namespace,
61
+ name: table.name,
62
+ }),
63
+ keySchema: resolveUserTypes(table.keySchema, userTypes) as any,
64
+ valueSchema: resolveUserTypes(table.valueSchema, userTypes) as any,
65
+ } satisfies Table<config, config["tables"][keyof config["tables"]]>,
66
+ ])
67
+ ) as Tables<config>;
68
+ }
@@ -0,0 +1,9 @@
1
+ Files generated by
2
+
3
+ ```
4
+ git clone https://github.com/Arachnid/deterministic-deployment-proxy.git
5
+ cd deterministic-deployment-proxy
6
+ git checkout b3bb19c
7
+ npm install
8
+ npm run build
9
+ ```
@@ -0,0 +1,7 @@
1
+ {
2
+ "gasPrice": 100000000000,
3
+ "gasLimit": 100000,
4
+ "signerAddress": "3fab184622dc19b6109349b94811493bf2a45362",
5
+ "transaction": "f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",
6
+ "address": "4e59b44847b379578588920ca78fbf26c0b4956c"
7
+ }
@@ -0,0 +1,10 @@
1
+ import { debug as parentDebug } from "../debug";
2
+
3
+ export const debug = parentDebug.extend("deploy");
4
+ export const error = parentDebug.extend("deploy");
5
+
6
+ // Pipe debug output to stdout instead of stderr
7
+ debug.log = console.debug.bind(console);
8
+
9
+ // Pipe error output to stderr
10
+ error.log = console.error.bind(console);
@@ -0,0 +1,116 @@
1
+ import { Account, Address, Chain, Client, Hex, Transport, getAddress } from "viem";
2
+ import { ensureDeployer } from "./ensureDeployer";
3
+ import { deployWorld } from "./deployWorld";
4
+ import { ensureTables } from "./ensureTables";
5
+ import { Config, ConfigInput, WorldDeploy, supportedStoreVersions, supportedWorldVersions } from "./common";
6
+ import { ensureSystems } from "./ensureSystems";
7
+ import { waitForTransactionReceipt } from "viem/actions";
8
+ import { getWorldDeploy } from "./getWorldDeploy";
9
+ import { ensureFunctions } from "./ensureFunctions";
10
+ import { ensureModules } from "./ensureModules";
11
+ import { Table } from "./configToTables";
12
+ import { ensureNamespaceOwner } from "./ensureNamespaceOwner";
13
+ import { debug } from "./debug";
14
+ import { resourceLabel } from "./resourceLabel";
15
+ import { uniqueBy } from "@latticexyz/common/utils";
16
+ import { ensureContractsDeployed } from "./ensureContractsDeployed";
17
+ import { worldFactoryContracts } from "./ensureWorldFactory";
18
+ import { randomBytes } from "crypto";
19
+
20
+ type DeployOptions<configInput extends ConfigInput> = {
21
+ client: Client<Transport, Chain | undefined, Account>;
22
+ config: Config<configInput>;
23
+ salt?: Hex;
24
+ worldAddress?: Address;
25
+ };
26
+
27
+ /**
28
+ * Given a viem client and MUD config, we attempt to introspect the world
29
+ * (or deploy a new one if no world address is provided) and do the minimal
30
+ * amount of work to make the world match the config (e.g. deploy new tables,
31
+ * replace systems, etc.)
32
+ */
33
+ export async function deploy<configInput extends ConfigInput>({
34
+ client,
35
+ config,
36
+ salt,
37
+ worldAddress: existingWorldAddress,
38
+ }: DeployOptions<configInput>): Promise<WorldDeploy> {
39
+ const tables = Object.values(config.tables) as Table[];
40
+ const systems = Object.values(config.systems);
41
+
42
+ await ensureDeployer(client);
43
+
44
+ // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.
45
+ await ensureContractsDeployed({
46
+ client,
47
+ contracts: [
48
+ ...worldFactoryContracts,
49
+ ...uniqueBy(systems, (system) => getAddress(system.address)).map((system) => ({
50
+ bytecode: system.bytecode,
51
+ deployedBytecodeSize: system.deployedBytecodeSize,
52
+ label: `${resourceLabel(system)} system`,
53
+ })),
54
+ ...uniqueBy(config.modules, (mod) => getAddress(mod.address)).map((mod) => ({
55
+ bytecode: mod.bytecode,
56
+ deployedBytecodeSize: mod.deployedBytecodeSize,
57
+ label: `${mod.name} module`,
58
+ })),
59
+ ],
60
+ });
61
+
62
+ const worldDeploy = existingWorldAddress
63
+ ? await getWorldDeploy(client, existingWorldAddress)
64
+ : await deployWorld(client, salt ? salt : `0x${randomBytes(32).toString("hex")}`);
65
+
66
+ if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {
67
+ throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);
68
+ }
69
+ if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {
70
+ throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);
71
+ }
72
+
73
+ const namespaceTxs = await ensureNamespaceOwner({
74
+ client,
75
+ worldDeploy,
76
+ resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],
77
+ });
78
+
79
+ debug("waiting for all namespace registration transactions to confirm");
80
+ for (const tx of namespaceTxs) {
81
+ await waitForTransactionReceipt(client, { hash: tx });
82
+ }
83
+
84
+ const tableTxs = await ensureTables({
85
+ client,
86
+ worldDeploy,
87
+ tables,
88
+ });
89
+ const systemTxs = await ensureSystems({
90
+ client,
91
+ worldDeploy,
92
+ systems,
93
+ });
94
+ const functionTxs = await ensureFunctions({
95
+ client,
96
+ worldDeploy,
97
+ functions: systems.flatMap((system) => system.functions),
98
+ });
99
+ const moduleTxs = await ensureModules({
100
+ client,
101
+ worldDeploy,
102
+ modules: config.modules,
103
+ });
104
+
105
+ const txs = [...tableTxs, ...systemTxs, ...functionTxs, ...moduleTxs];
106
+
107
+ // wait for each tx separately/serially, because parallelizing results in RPC errors
108
+ debug("waiting for all transactions to confirm");
109
+ for (const tx of txs) {
110
+ await waitForTransactionReceipt(client, { hash: tx });
111
+ // TODO: throw if there was a revert?
112
+ }
113
+
114
+ debug("deploy complete");
115
+ return worldDeploy;
116
+ }
@@ -0,0 +1,37 @@
1
+ import { Account, Chain, Client, Hex, Log, Transport } from "viem";
2
+ import { waitForTransactionReceipt } from "viem/actions";
3
+ import { ensureWorldFactory, worldFactory } from "./ensureWorldFactory";
4
+ import WorldFactoryAbi from "@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json" assert { type: "json" };
5
+ import { writeContract } from "@latticexyz/common";
6
+ import { debug } from "./debug";
7
+ import { logsToWorldDeploy } from "./logsToWorldDeploy";
8
+ import { WorldDeploy } from "./common";
9
+
10
+ export async function deployWorld(
11
+ client: Client<Transport, Chain | undefined, Account>,
12
+ salt: Hex
13
+ ): Promise<WorldDeploy> {
14
+ await ensureWorldFactory(client);
15
+
16
+ debug("deploying world");
17
+ const tx = await writeContract(client, {
18
+ chain: client.chain ?? null,
19
+ address: worldFactory,
20
+ abi: WorldFactoryAbi,
21
+ functionName: "deployWorld",
22
+ args: [salt],
23
+ });
24
+
25
+ debug("waiting for world deploy");
26
+ const receipt = await waitForTransactionReceipt(client, { hash: tx });
27
+ if (receipt.status !== "success") {
28
+ console.error("world deploy failed", receipt);
29
+ throw new Error("world deploy failed");
30
+ }
31
+
32
+ // TODO: remove type casting once https://github.com/wagmi-dev/viem/pull/1330 is merged
33
+ const deploy = logsToWorldDeploy(receipt.logs.map((log) => log as Log<bigint, number, false>));
34
+ debug("deployed world to", deploy.address, "at block", deploy.deployBlock);
35
+
36
+ return { ...deploy, stateBlock: deploy.deployBlock };
37
+ }
@@ -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,71 @@
1
+ import { Account, Chain, Client, Hex, Transport, getAddress } from "viem";
2
+ import { WorldDeploy, worldAbi, worldTables } from "./common";
3
+ import { hexToResource, resourceToHex, writeContract } from "@latticexyz/common";
4
+ import { getResourceIds } from "./getResourceIds";
5
+ import { getTableValue } from "./getTableValue";
6
+ import { debug } from "./debug";
7
+
8
+ export async function ensureNamespaceOwner({
9
+ client,
10
+ worldDeploy,
11
+ resourceIds,
12
+ }: {
13
+ readonly client: Client<Transport, Chain | undefined, Account>;
14
+ readonly worldDeploy: WorldDeploy;
15
+ readonly resourceIds: readonly Hex[];
16
+ }): Promise<readonly Hex[]> {
17
+ const desiredNamespaces = Array.from(new Set(resourceIds.map((resourceId) => hexToResource(resourceId).namespace)));
18
+ const existingResourceIds = await getResourceIds({ client, worldDeploy });
19
+ const existingNamespaces = new Set(existingResourceIds.map((resourceId) => hexToResource(resourceId).namespace));
20
+ if (existingNamespaces.size) {
21
+ debug(
22
+ "found",
23
+ existingNamespaces.size,
24
+ "existing namespaces:",
25
+ Array.from(existingNamespaces)
26
+ .map((namespace) => (namespace === "" ? "<root>" : namespace))
27
+ .join(", ")
28
+ );
29
+ }
30
+
31
+ // Assert ownership of existing namespaces
32
+ const existingDesiredNamespaces = desiredNamespaces.filter((namespace) => existingNamespaces.has(namespace));
33
+ const namespaceOwners = await Promise.all(
34
+ existingDesiredNamespaces.map(async (namespace) => {
35
+ const { owner } = await getTableValue({
36
+ client,
37
+ worldDeploy,
38
+ table: worldTables.world_NamespaceOwner,
39
+ key: { namespaceId: resourceToHex({ type: "namespace", namespace, name: "" }) },
40
+ });
41
+ return [namespace, owner];
42
+ })
43
+ );
44
+
45
+ const unauthorizedNamespaces = namespaceOwners
46
+ .filter(([, owner]) => getAddress(owner) !== getAddress(client.account.address))
47
+ .map(([namespace]) => namespace);
48
+
49
+ if (unauthorizedNamespaces.length) {
50
+ throw new Error(`You are attempting to deploy to namespaces you do not own: ${unauthorizedNamespaces.join(", ")}`);
51
+ }
52
+
53
+ // Register missing namespaces
54
+ const missingNamespaces = desiredNamespaces.filter((namespace) => !existingNamespaces.has(namespace));
55
+ if (missingNamespaces.length > 0) {
56
+ debug("registering namespaces", Array.from(missingNamespaces).join(", "));
57
+ }
58
+ const registrationTxs = Promise.all(
59
+ missingNamespaces.map((namespace) =>
60
+ writeContract(client, {
61
+ chain: client.chain ?? null,
62
+ address: worldDeploy.address,
63
+ abi: worldAbi,
64
+ functionName: "registerNamespace",
65
+ args: [resourceToHex({ namespace, type: "namespace", name: "" })],
66
+ })
67
+ )
68
+ );
69
+
70
+ return registrationTxs;
71
+ }