@latticexyz/cli 2.0.0-main-c463c848 → 2.0.0-main-9c83adc0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/cli",
3
- "version": "2.0.0-main-c463c848",
3
+ "version": "2.0.0-main-9c83adc0",
4
4
  "description": "Command line interface for mud",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,17 +40,17 @@
40
40
  "yargs": "^17.7.1",
41
41
  "zod": "^3.21.4",
42
42
  "zod-validation-error": "^1.3.0",
43
- "@latticexyz/abi-ts": "2.0.0-main-c463c848",
44
- "@latticexyz/common": "2.0.0-main-c463c848",
45
- "@latticexyz/config": "2.0.0-main-c463c848",
46
- "@latticexyz/gas-report": "2.0.0-main-c463c848",
47
- "@latticexyz/protocol-parser": "2.0.0-main-c463c848",
48
- "@latticexyz/schema-type": "2.0.0-main-c463c848",
49
- "@latticexyz/services": "2.0.0-main-c463c848",
50
- "@latticexyz/store": "2.0.0-main-c463c848",
51
- "@latticexyz/utils": "2.0.0-main-c463c848",
52
- "@latticexyz/world": "2.0.0-main-c463c848",
53
- "@latticexyz/world-modules": "2.0.0-main-c463c848"
43
+ "@latticexyz/abi-ts": "2.0.0-main-9c83adc0",
44
+ "@latticexyz/common": "2.0.0-main-9c83adc0",
45
+ "@latticexyz/config": "2.0.0-main-9c83adc0",
46
+ "@latticexyz/gas-report": "2.0.0-main-9c83adc0",
47
+ "@latticexyz/protocol-parser": "2.0.0-main-9c83adc0",
48
+ "@latticexyz/schema-type": "2.0.0-main-9c83adc0",
49
+ "@latticexyz/services": "2.0.0-main-9c83adc0",
50
+ "@latticexyz/store": "2.0.0-main-9c83adc0",
51
+ "@latticexyz/utils": "2.0.0-main-9c83adc0",
52
+ "@latticexyz/world": "2.0.0-main-9c83adc0",
53
+ "@latticexyz/world-modules": "2.0.0-main-9c83adc0"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/debug": "^4.1.7",
@@ -87,6 +87,7 @@ const commandModule: CommandModule<typeof devOptions, InferredOptionTypes<typeof
87
87
  printConfig: false,
88
88
  profile: undefined,
89
89
  saveDeployment: true,
90
+ deployerAddress: undefined,
90
91
  worldAddress,
91
92
  srcDir,
92
93
  salt: "0x",
@@ -24,6 +24,7 @@ export const worldAbi = [...IBaseWorldAbi, ...IModuleAbi] as const;
24
24
  export const supportedStoreVersions = ["1.0.0-unaudited"];
25
25
  export const supportedWorldVersions = ["1.0.0-unaudited"];
26
26
 
27
+ // TODO: extend this to include factory+deployer address? so we can reuse the deployer for a world?
27
28
  export type WorldDeploy = {
28
29
  readonly address: Address;
29
30
  readonly worldVersion: string;
@@ -47,7 +48,7 @@ export type WorldFunction = {
47
48
  };
48
49
 
49
50
  export type DeterministicContract = {
50
- readonly address: Address;
51
+ readonly getAddress: (deployer: Address) => Address;
51
52
  readonly bytecode: Hex;
52
53
  readonly deployedBytecodeSize: number;
53
54
  readonly abi: Abi;
@@ -59,9 +60,17 @@ export type System = DeterministicContract & {
59
60
  readonly systemId: Hex;
60
61
  readonly allowAll: boolean;
61
62
  readonly allowedAddresses: readonly Hex[];
63
+ readonly allowedSystemIds: readonly Hex[];
62
64
  readonly functions: readonly WorldFunction[];
63
65
  };
64
66
 
67
+ export type DeployedSystem = Omit<
68
+ System,
69
+ "getAddress" | "abi" | "bytecode" | "deployedBytecodeSize" | "allowedSystemIds"
70
+ > & {
71
+ address: Address;
72
+ };
73
+
65
74
  export type Module = DeterministicContract & {
66
75
  readonly name: string;
67
76
  readonly installAsRoot: boolean;
@@ -6,4 +6,8 @@ cd deterministic-deployment-proxy
6
6
  git checkout b3bb19c
7
7
  npm install
8
8
  npm run build
9
+ cd output
10
+ jq --arg bc "$(cat bytecode.txt)" '. + {bytecode: $bc}' deployment.json > deployment-with-bytecode.json
11
+ mv deployment-with-bytecode.json deployment.json
12
+ cp deployment.json ../path/to/this/dir
9
13
  ```
@@ -3,5 +3,6 @@
3
3
  "gasLimit": 100000,
4
4
  "signerAddress": "3fab184622dc19b6109349b94811493bf2a45362",
5
5
  "transaction": "f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",
6
- "address": "4e59b44847b379578588920ca78fbf26c0b4956c"
6
+ "address": "4e59b44847b379578588920ca78fbf26c0b4956c",
7
+ "bytecode": "604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"
7
8
  }
@@ -11,17 +11,24 @@ import { ensureModules } from "./ensureModules";
11
11
  import { Table } from "./configToTables";
12
12
  import { ensureNamespaceOwner } from "./ensureNamespaceOwner";
13
13
  import { debug } from "./debug";
14
- import { resourceLabel } from "./resourceLabel";
14
+ import { resourceToLabel } from "@latticexyz/common";
15
15
  import { uniqueBy } from "@latticexyz/common/utils";
16
16
  import { ensureContractsDeployed } from "./ensureContractsDeployed";
17
- import { worldFactoryContracts } from "./ensureWorldFactory";
18
17
  import { randomBytes } from "crypto";
18
+ import { ensureWorldFactory } from "./ensureWorldFactory";
19
19
 
20
20
  type DeployOptions<configInput extends ConfigInput> = {
21
21
  client: Client<Transport, Chain | undefined, Account>;
22
22
  config: Config<configInput>;
23
23
  salt?: Hex;
24
24
  worldAddress?: Address;
25
+ /**
26
+ * Address of determinstic deployment proxy: https://github.com/Arachnid/deterministic-deployment-proxy
27
+ * By default, we look for a deployment at 0x4e59b44847b379578588920ca78fbf26c0b4956c and, if not, deploy one.
28
+ * If the target chain does not support legacy transactions, we deploy the proxy bytecode anyway, but it will
29
+ * not have a deterministic address.
30
+ */
31
+ deployerAddress?: Hex;
25
32
  };
26
33
 
27
34
  /**
@@ -35,23 +42,25 @@ export async function deploy<configInput extends ConfigInput>({
35
42
  config,
36
43
  salt,
37
44
  worldAddress: existingWorldAddress,
45
+ deployerAddress: initialDeployerAddress,
38
46
  }: DeployOptions<configInput>): Promise<WorldDeploy> {
39
47
  const tables = Object.values(config.tables) as Table[];
40
- const systems = Object.values(config.systems);
41
48
 
42
- await ensureDeployer(client);
49
+ const deployerAddress = initialDeployerAddress ?? (await ensureDeployer(client));
50
+
51
+ await ensureWorldFactory(client, deployerAddress);
43
52
 
44
53
  // deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.
45
54
  await ensureContractsDeployed({
46
55
  client,
56
+ deployerAddress,
47
57
  contracts: [
48
- ...worldFactoryContracts,
49
- ...uniqueBy(systems, (system) => getAddress(system.address)).map((system) => ({
58
+ ...uniqueBy(config.systems, (system) => getAddress(system.getAddress(deployerAddress))).map((system) => ({
50
59
  bytecode: system.bytecode,
51
60
  deployedBytecodeSize: system.deployedBytecodeSize,
52
- label: `${resourceLabel(system)} system`,
61
+ label: `${resourceToLabel(system)} system`,
53
62
  })),
54
- ...uniqueBy(config.modules, (mod) => getAddress(mod.address)).map((mod) => ({
63
+ ...uniqueBy(config.modules, (mod) => getAddress(mod.getAddress(deployerAddress))).map((mod) => ({
55
64
  bytecode: mod.bytecode,
56
65
  deployedBytecodeSize: mod.deployedBytecodeSize,
57
66
  label: `${mod.name} module`,
@@ -61,7 +70,7 @@ export async function deploy<configInput extends ConfigInput>({
61
70
 
62
71
  const worldDeploy = existingWorldAddress
63
72
  ? await getWorldDeploy(client, existingWorldAddress)
64
- : await deployWorld(client, salt ? salt : `0x${randomBytes(32).toString("hex")}`);
73
+ : await deployWorld(client, deployerAddress, salt ?? `0x${randomBytes(32).toString("hex")}`);
65
74
 
66
75
  if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {
67
76
  throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);
@@ -73,7 +82,7 @@ export async function deploy<configInput extends ConfigInput>({
73
82
  const namespaceTxs = await ensureNamespaceOwner({
74
83
  client,
75
84
  worldDeploy,
76
- resourceIds: [...tables.map((table) => table.tableId), ...systems.map((system) => system.systemId)],
85
+ resourceIds: [...tables.map((table) => table.tableId), ...config.systems.map((system) => system.systemId)],
77
86
  });
78
87
 
79
88
  debug("waiting for all namespace registration transactions to confirm");
@@ -88,16 +97,18 @@ export async function deploy<configInput extends ConfigInput>({
88
97
  });
89
98
  const systemTxs = await ensureSystems({
90
99
  client,
100
+ deployerAddress,
91
101
  worldDeploy,
92
- systems,
102
+ systems: config.systems,
93
103
  });
94
104
  const functionTxs = await ensureFunctions({
95
105
  client,
96
106
  worldDeploy,
97
- functions: systems.flatMap((system) => system.functions),
107
+ functions: config.systems.flatMap((system) => system.functions),
98
108
  });
99
109
  const moduleTxs = await ensureModules({
100
110
  client,
111
+ deployerAddress,
101
112
  worldDeploy,
102
113
  modules: config.modules,
103
114
  });
@@ -1,6 +1,6 @@
1
1
  import { Account, Chain, Client, Hex, Log, Transport } from "viem";
2
2
  import { waitForTransactionReceipt } from "viem/actions";
3
- import { ensureWorldFactory, worldFactory } from "./ensureWorldFactory";
3
+ import { ensureWorldFactory } from "./ensureWorldFactory";
4
4
  import WorldFactoryAbi from "@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json" assert { type: "json" };
5
5
  import { writeContract } from "@latticexyz/common";
6
6
  import { debug } from "./debug";
@@ -9,9 +9,10 @@ import { WorldDeploy } from "./common";
9
9
 
10
10
  export async function deployWorld(
11
11
  client: Client<Transport, Chain | undefined, Account>,
12
+ deployerAddress: Hex,
12
13
  salt: Hex
13
14
  ): Promise<WorldDeploy> {
14
- await ensureWorldFactory(client);
15
+ const worldFactory = await ensureWorldFactory(client, deployerAddress);
15
16
 
16
17
  debug("deploying world");
17
18
  const tx = await writeContract(client, {
@@ -1,6 +1,5 @@
1
- import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex, size } from "viem";
1
+ import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from "viem";
2
2
  import { getBytecode } from "viem/actions";
3
- import { deployer } from "./ensureDeployer";
4
3
  import { contractSizeLimit, salt } from "./common";
5
4
  import { sendTransaction } from "@latticexyz/common";
6
5
  import { debug } from "./debug";
@@ -15,13 +14,15 @@ export type Contract = {
15
14
 
16
15
  export async function ensureContract({
17
16
  client,
17
+ deployerAddress,
18
18
  bytecode,
19
19
  deployedBytecodeSize,
20
20
  label = "contract",
21
21
  }: {
22
22
  readonly client: Client<Transport, Chain | undefined, Account>;
23
+ readonly deployerAddress: Hex;
23
24
  } & Contract): Promise<readonly Hex[]> {
24
- const address = getCreate2Address({ from: deployer, salt, bytecode });
25
+ const address = getCreate2Address({ from: deployerAddress, salt, bytecode });
25
26
 
26
27
  const contractCode = await getBytecode(client, { address, blockTag: "pending" });
27
28
  if (contractCode) {
@@ -45,7 +46,7 @@ export async function ensureContract({
45
46
  () =>
46
47
  sendTransaction(client, {
47
48
  chain: client.chain ?? null,
48
- to: deployer,
49
+ to: deployerAddress,
49
50
  data: concatHex([salt, bytecode]),
50
51
  }),
51
52
  {
@@ -5,12 +5,16 @@ import { Contract, ensureContract } from "./ensureContract";
5
5
 
6
6
  export async function ensureContractsDeployed({
7
7
  client,
8
+ deployerAddress,
8
9
  contracts,
9
10
  }: {
10
11
  readonly client: Client<Transport, Chain | undefined, Account>;
12
+ readonly deployerAddress: Hex;
11
13
  readonly contracts: readonly Contract[];
12
14
  }): Promise<readonly Hex[]> {
13
- const txs = (await Promise.all(contracts.map((contract) => ensureContract({ client, ...contract })))).flat();
15
+ const txs = (
16
+ await Promise.all(contracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))
17
+ ).flat();
14
18
 
15
19
  if (txs.length) {
16
20
  debug("waiting for contracts");
@@ -1,36 +1,75 @@
1
- import { Account, Chain, Client, Transport } from "viem";
2
- import { getBytecode, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from "viem/actions";
1
+ import { Account, Address, Chain, Client, Transport } from "viem";
2
+ import { getBalance, getBytecode, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from "viem/actions";
3
3
  import deployment from "./create2/deployment.json";
4
4
  import { debug } from "./debug";
5
5
 
6
- export const deployer = `0x${deployment.address}` as const;
6
+ const deployer = `0x${deployment.address}` as const;
7
+ const deployerBytecode = `0x${deployment.bytecode}` as const;
7
8
 
8
- export async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<void> {
9
+ export async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {
9
10
  const bytecode = await getBytecode(client, { address: deployer });
10
11
  if (bytecode) {
11
- debug("found create2 deployer at", deployer);
12
- return;
12
+ debug("found CREATE2 deployer at", deployer);
13
+ if (bytecode !== deployerBytecode) {
14
+ console.warn(
15
+ `\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\n`
16
+ );
17
+ }
18
+ return deployer;
13
19
  }
14
20
 
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");
21
+ // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,
22
+ // so we have to attempt to create the deployer first and, if it fails, fall back
23
+ // to a regular deploy.
24
+
25
+ // Send gas to deployment signer
26
+ const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);
27
+ const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });
28
+ const gasNeeded = gasRequired - currentBalance;
29
+ if (gasNeeded > 0) {
30
+ debug("sending gas for CREATE2 deployer to signer at", deployment.signerAddress);
31
+ const gasTx = await sendTransaction(client, {
32
+ chain: client.chain ?? null,
33
+ to: `0x${deployment.signerAddress}`,
34
+ value: gasNeeded,
35
+ });
36
+ const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });
37
+ if (gasReceipt.status !== "success") {
38
+ console.error("failed to send gas to deployer signer", gasReceipt);
39
+ throw new Error("failed to send gas to deployer signer");
40
+ }
26
41
  }
27
42
 
28
- // deploy the deployer
29
- debug("deploying create2 deployer at", deployer);
30
- const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` });
43
+ // Deploy the deployer
44
+ debug("deploying CREATE2 deployer at", deployer);
45
+ const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(
46
+ (error) => {
47
+ // Do a regular contract create if the presigned transaction doesn't work due to replay protection
48
+ if (String(error).includes("only replay-protected (EIP-155) transactions allowed over RPC")) {
49
+ console.warn(
50
+ // eslint-disable-next-line max-len
51
+ `\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\n\n We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.\n`
52
+ );
53
+ debug("deploying CREATE2 deployer");
54
+ return sendTransaction(client, {
55
+ chain: client.chain ?? null,
56
+ data: deployerBytecode,
57
+ });
58
+ }
59
+ throw error;
60
+ }
61
+ );
62
+
31
63
  const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });
64
+ if (!deployReceipt.contractAddress) {
65
+ throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");
66
+ }
67
+
32
68
  if (deployReceipt.contractAddress !== deployer) {
33
- console.error("unexpected contract address for deployer", deployReceipt);
34
- throw new Error("unexpected contract address for deployer");
69
+ console.warn(
70
+ `\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`
71
+ );
35
72
  }
73
+
74
+ return deployReceipt.contractAddress;
36
75
  }
@@ -8,10 +8,12 @@ import { ensureContractsDeployed } from "./ensureContractsDeployed";
8
8
 
9
9
  export async function ensureModules({
10
10
  client,
11
+ deployerAddress,
11
12
  worldDeploy,
12
13
  modules,
13
14
  }: {
14
15
  readonly client: Client<Transport, Chain | undefined, Account>;
16
+ readonly deployerAddress: Hex; // TODO: move this into WorldDeploy to reuse a world's deployer?
15
17
  readonly worldDeploy: WorldDeploy;
16
18
  readonly modules: readonly Module[];
17
19
  }): Promise<readonly Hex[]> {
@@ -19,7 +21,8 @@ export async function ensureModules({
19
21
 
20
22
  await ensureContractsDeployed({
21
23
  client,
22
- contracts: uniqueBy(modules, (mod) => getAddress(mod.address)).map((mod) => ({
24
+ deployerAddress,
25
+ contracts: uniqueBy(modules, (mod) => getAddress(mod.getAddress(deployerAddress))).map((mod) => ({
23
26
  bytecode: mod.bytecode,
24
27
  deployedBytecodeSize: mod.deployedBytecodeSize,
25
28
  label: `${mod.name} module`,
@@ -40,7 +43,7 @@ export async function ensureModules({
40
43
  abi: worldAbi,
41
44
  // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
42
45
  functionName: "installRootModule",
43
- args: [mod.address, mod.installData],
46
+ args: [mod.getAddress(deployerAddress), mod.installData],
44
47
  })
45
48
  : await writeContract(client, {
46
49
  chain: client.chain ?? null,
@@ -48,7 +51,7 @@ export async function ensureModules({
48
51
  abi: worldAbi,
49
52
  // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
50
53
  functionName: "installModule",
51
- args: [mod.address, mod.installData],
54
+ args: [mod.getAddress(deployerAddress), mod.installData],
52
55
  });
53
56
  } catch (error) {
54
57
  if (error instanceof BaseError && error.message.includes("Module_AlreadyInstalled")) {
@@ -1,20 +1,23 @@
1
- import { Client, Transport, Chain, Account, Hex, getAddress } from "viem";
2
- import { writeContract } from "@latticexyz/common";
1
+ import { Client, Transport, Chain, Account, Hex, getAddress, Address } from "viem";
2
+ import { writeContract, resourceToLabel } from "@latticexyz/common";
3
3
  import { System, WorldDeploy, worldAbi } from "./common";
4
4
  import { debug } from "./debug";
5
- import { resourceLabel } from "./resourceLabel";
6
5
  import { getSystems } from "./getSystems";
7
6
  import { getResourceAccess } from "./getResourceAccess";
8
7
  import { uniqueBy, wait } from "@latticexyz/common/utils";
9
8
  import pRetry from "p-retry";
10
9
  import { ensureContractsDeployed } from "./ensureContractsDeployed";
11
10
 
11
+ // TODO: move each system registration+access to batch call to be atomic
12
+
12
13
  export async function ensureSystems({
13
14
  client,
15
+ deployerAddress,
14
16
  worldDeploy,
15
17
  systems,
16
18
  }: {
17
19
  readonly client: Client<Transport, Chain | undefined, Account>;
20
+ readonly deployerAddress: Hex; // TODO: move this into WorldDeploy to reuse a world's deployer?
18
21
  readonly worldDeploy: WorldDeploy;
19
22
  readonly systems: readonly System[];
20
23
  }): Promise<readonly Hex[]> {
@@ -22,11 +25,95 @@ export async function ensureSystems({
22
25
  getSystems({ client, worldDeploy }),
23
26
  getResourceAccess({ client, worldDeploy }),
24
27
  ]);
28
+
29
+ // Register or replace systems
30
+
31
+ const existingSystems = systems.filter((system) =>
32
+ worldSystems.some(
33
+ (worldSystem) =>
34
+ worldSystem.systemId === system.systemId &&
35
+ getAddress(worldSystem.address) === getAddress(system.getAddress(deployerAddress))
36
+ )
37
+ );
38
+ if (existingSystems.length) {
39
+ debug("existing systems", existingSystems.map(resourceToLabel).join(", "));
40
+ }
41
+ const existingSystemIds = existingSystems.map((system) => system.systemId);
42
+
43
+ const missingSystems = systems.filter((system) => !existingSystemIds.includes(system.systemId));
44
+ if (!missingSystems.length) return [];
45
+
46
+ const systemsToUpgrade = missingSystems.filter((system) =>
47
+ worldSystems.some(
48
+ (worldSystem) =>
49
+ worldSystem.systemId === system.systemId &&
50
+ getAddress(worldSystem.address) !== getAddress(system.getAddress(deployerAddress))
51
+ )
52
+ );
53
+ if (systemsToUpgrade.length) {
54
+ debug("upgrading systems", systemsToUpgrade.map(resourceToLabel).join(", "));
55
+ }
56
+
57
+ const systemsToAdd = missingSystems.filter(
58
+ (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId)
59
+ );
60
+ if (systemsToAdd.length) {
61
+ debug("registering new systems", systemsToAdd.map(resourceToLabel).join(", "));
62
+ }
63
+
64
+ await ensureContractsDeployed({
65
+ client,
66
+ deployerAddress,
67
+ contracts: uniqueBy(missingSystems, (system) => getAddress(system.getAddress(deployerAddress))).map((system) => ({
68
+ bytecode: system.bytecode,
69
+ deployedBytecodeSize: system.deployedBytecodeSize,
70
+ label: `${resourceToLabel(system)} system`,
71
+ })),
72
+ });
73
+
74
+ const registerTxs = await Promise.all(
75
+ missingSystems.map((system) =>
76
+ pRetry(
77
+ () =>
78
+ writeContract(client, {
79
+ chain: client.chain ?? null,
80
+ address: worldDeploy.address,
81
+ abi: worldAbi,
82
+ // TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
83
+ functionName: "registerSystem",
84
+ args: [system.systemId, system.getAddress(deployerAddress), system.allowAll],
85
+ }),
86
+ {
87
+ retries: 3,
88
+ onFailedAttempt: async (error) => {
89
+ const delay = error.attemptNumber * 500;
90
+ debug(`failed to register system ${resourceToLabel(system)}, retrying in ${delay}ms...`);
91
+ await wait(delay);
92
+ },
93
+ }
94
+ )
95
+ )
96
+ );
97
+
98
+ // Adjust system access
99
+
25
100
  const systemIds = systems.map((system) => system.systemId);
26
101
  const currentAccess = worldAccess.filter(({ resourceId }) => systemIds.includes(resourceId));
27
- const desiredAccess = systems.flatMap((system) =>
28
- system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address }))
29
- );
102
+ const desiredAccess = [
103
+ ...systems.flatMap((system) =>
104
+ system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address }))
105
+ ),
106
+ ...systems.flatMap((system) =>
107
+ system.allowedSystemIds
108
+ .map((systemId) => ({
109
+ resourceId: system.systemId,
110
+ address:
111
+ worldSystems.find((s) => s.systemId === systemId)?.address ??
112
+ systems.find((s) => s.systemId === systemId)?.getAddress(deployerAddress),
113
+ }))
114
+ .filter((access): access is typeof access & { address: Address } => access.address != null)
115
+ ),
116
+ ];
30
117
 
31
118
  const accessToAdd = desiredAccess.filter(
32
119
  (access) =>
@@ -44,8 +131,6 @@ export async function ensureSystems({
44
131
  )
45
132
  );
46
133
 
47
- // TODO: move each system access+registration to batch call to be atomic
48
-
49
134
  if (accessToRemove.length) {
50
135
  debug("revoking", accessToRemove.length, "access grants");
51
136
  }
@@ -53,7 +138,7 @@ export async function ensureSystems({
53
138
  debug("adding", accessToAdd.length, "access grants");
54
139
  }
55
140
 
56
- const accessTxs = [
141
+ const accessTxs = await Promise.all([
57
142
  ...accessToRemove.map((access) =>
58
143
  pRetry(
59
144
  () =>
@@ -94,69 +179,7 @@ export async function ensureSystems({
94
179
  }
95
180
  )
96
181
  ),
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
- );
182
+ ]);
160
183
 
161
- return await Promise.all([...accessTxs, ...registerTxs]);
184
+ return [...registerTxs, ...accessTxs];
162
185
  }
@@ -1,10 +1,9 @@
1
1
  import { Client, Transport, Chain, Account, Hex } from "viem";
2
2
  import { Table } from "./configToTables";
3
- import { writeContract } from "@latticexyz/common";
3
+ import { resourceToLabel, writeContract } from "@latticexyz/common";
4
4
  import { WorldDeploy, worldAbi } from "./common";
5
5
  import { valueSchemaToFieldLayoutHex, keySchemaToHex, valueSchemaToHex } from "@latticexyz/protocol-parser";
6
6
  import { debug } from "./debug";
7
- import { resourceLabel } from "./resourceLabel";
8
7
  import { getTables } from "./getTables";
9
8
  import pRetry from "p-retry";
10
9
  import { wait } from "@latticexyz/common/utils";
@@ -23,12 +22,12 @@ export async function ensureTables({
23
22
 
24
23
  const existingTables = tables.filter((table) => worldTableIds.includes(table.tableId));
25
24
  if (existingTables.length) {
26
- debug("existing tables", existingTables.map(resourceLabel).join(", "));
25
+ debug("existing tables", existingTables.map(resourceToLabel).join(", "));
27
26
  }
28
27
 
29
28
  const missingTables = tables.filter((table) => !worldTableIds.includes(table.tableId));
30
29
  if (missingTables.length) {
31
- debug("registering tables", missingTables.map(resourceLabel).join(", "));
30
+ debug("registering tables", missingTables.map(resourceToLabel).join(", "));
32
31
  return await Promise.all(
33
32
  missingTables.map((table) =>
34
33
  pRetry(
@@ -52,7 +51,7 @@ export async function ensureTables({
52
51
  retries: 3,
53
52
  onFailedAttempt: async (error) => {
54
53
  const delay = error.attemptNumber * 500;
55
- debug(`failed to register table ${resourceLabel(table)}, retrying in ${delay}ms...`);
54
+ debug(`failed to register table ${resourceToLabel(table)}, retrying in ${delay}ms...`);
56
55
  await wait(delay);
57
56
  },
58
57
  }