@latticexyz/cli 2.0.0-snapshot-test-32d38619 → 2.0.0
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/dist/chunk-QXUPZVZL.js +4 -0
- package/dist/chunk-QXUPZVZL.js.map +1 -0
- package/dist/commands-WWEJJZV4.js +36 -0
- package/dist/commands-WWEJJZV4.js.map +1 -0
- package/dist/errors-MZURIB7V.js +2 -0
- package/dist/errors-MZURIB7V.js.map +1 -0
- package/dist/index.js +0 -1
- package/dist/mud.js +1 -14
- package/dist/mud.js.map +1 -1
- package/package.json +21 -15
- package/src/build.ts +48 -0
- package/src/commands/build.ts +35 -0
- package/src/commands/deploy.ts +8 -31
- package/src/commands/dev-contracts.ts +80 -141
- package/src/commands/index.ts +2 -0
- package/src/commands/set-version.ts +24 -62
- package/src/commands/tablegen.ts +2 -2
- package/src/commands/test.ts +30 -36
- package/src/commands/trace.ts +15 -11
- package/src/commands/worldgen.ts +7 -6
- package/src/common.ts +1 -0
- package/src/debug.ts +10 -0
- package/src/deploy/common.ts +122 -0
- package/src/deploy/configToTables.ts +70 -0
- package/src/deploy/create2/README.md +13 -0
- package/src/deploy/create2/deployment.json +8 -0
- package/src/deploy/createPrepareDeploy.ts +28 -0
- package/src/deploy/debug.ts +10 -0
- package/src/deploy/deploy.ts +133 -0
- package/src/deploy/deployWorld.ts +38 -0
- package/src/deploy/ensureContract.ts +66 -0
- package/src/deploy/ensureContractsDeployed.ts +33 -0
- package/src/deploy/ensureDeployer.ts +75 -0
- package/src/deploy/ensureFunctions.ts +86 -0
- package/src/deploy/ensureModules.ts +79 -0
- package/src/deploy/ensureNamespaceOwner.ts +71 -0
- package/src/deploy/ensureSystems.ts +187 -0
- package/src/deploy/ensureTables.ts +64 -0
- package/src/deploy/ensureWorldFactory.ts +105 -0
- package/src/deploy/findLibraries.ts +36 -0
- package/src/deploy/getFunctions.ts +58 -0
- package/src/deploy/getResourceAccess.ts +51 -0
- package/src/deploy/getResourceIds.ts +31 -0
- package/src/deploy/getSystems.ts +47 -0
- package/src/deploy/getTableValue.ts +30 -0
- package/src/deploy/getTables.ts +59 -0
- package/src/deploy/getWorldDeploy.ts +39 -0
- package/src/deploy/logsToWorldDeploy.ts +49 -0
- package/src/deploy/orderByDependencies.ts +12 -0
- package/src/deploy/resolveConfig.ts +148 -0
- package/src/index.ts +1 -1
- package/src/mud.ts +37 -31
- package/src/mudPackages.ts +24 -0
- package/src/runDeploy.ts +149 -0
- package/src/utils/defaultModuleContracts.ts +30 -0
- package/src/utils/errors.ts +1 -1
- package/src/utils/findPlaceholders.ts +27 -0
- package/src/utils/getContractData.ts +38 -0
- package/src/utils/{utils/postDeploy.ts → postDeploy.ts} +2 -2
- package/src/utils/printMUD.ts +1 -1
- package/dist/chunk-WERDORTY.js +0 -11
- package/dist/chunk-WERDORTY.js.map +0 -1
- package/src/utils/deploy.ts +0 -255
- package/src/utils/deployHandler.ts +0 -93
- package/src/utils/modules/constants.ts +0 -23
- package/src/utils/modules/getInstallModuleCallData.ts +0 -27
- package/src/utils/modules/getUserModules.ts +0 -5
- package/src/utils/modules/types.ts +0 -14
- package/src/utils/systems/getGrantAccessCallData.ts +0 -29
- package/src/utils/systems/getRegisterFunctionSelectorsCallData.ts +0 -57
- package/src/utils/systems/getRegisterSystemCallData.ts +0 -17
- package/src/utils/systems/types.ts +0 -9
- package/src/utils/systems/utils.ts +0 -42
- package/src/utils/tables/getRegisterTableCallData.ts +0 -49
- package/src/utils/tables/getTableIds.ts +0 -21
- package/src/utils/tables/types.ts +0 -12
- package/src/utils/utils/confirmNonce.ts +0 -24
- package/src/utils/utils/deployContract.ts +0 -33
- package/src/utils/utils/fastTxExecute.ts +0 -56
- package/src/utils/utils/getChainId.ts +0 -10
- package/src/utils/utils/getContractData.ts +0 -29
- package/src/utils/utils/setInternalFeePerGas.ts +0 -49
- package/src/utils/utils/toBytes16.ts +0 -16
- package/src/utils/utils/types.ts +0 -21
- package/src/utils/world.ts +0 -28
@@ -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,133 @@
|
|
1
|
+
import { Account, Address, Chain, Client, Hex, Transport } 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 { resourceToLabel } from "@latticexyz/common";
|
15
|
+
import { ensureContractsDeployed } from "./ensureContractsDeployed";
|
16
|
+
import { randomBytes } from "crypto";
|
17
|
+
import { ensureWorldFactory } from "./ensureWorldFactory";
|
18
|
+
|
19
|
+
type DeployOptions<configInput extends ConfigInput> = {
|
20
|
+
client: Client<Transport, Chain | undefined, Account>;
|
21
|
+
config: Config<configInput>;
|
22
|
+
salt?: Hex;
|
23
|
+
worldAddress?: Address;
|
24
|
+
/**
|
25
|
+
* Address of determinstic deployment proxy: https://github.com/Arachnid/deterministic-deployment-proxy
|
26
|
+
* By default, we look for a deployment at 0x4e59b44847b379578588920ca78fbf26c0b4956c and, if not, deploy one.
|
27
|
+
* If the target chain does not support legacy transactions, we deploy the proxy bytecode anyway, but it will
|
28
|
+
* not have a deterministic address.
|
29
|
+
*/
|
30
|
+
deployerAddress?: Hex;
|
31
|
+
};
|
32
|
+
|
33
|
+
/**
|
34
|
+
* Given a viem client and MUD config, we attempt to introspect the world
|
35
|
+
* (or deploy a new one if no world address is provided) and do the minimal
|
36
|
+
* amount of work to make the world match the config (e.g. deploy new tables,
|
37
|
+
* replace systems, etc.)
|
38
|
+
*/
|
39
|
+
export async function deploy<configInput extends ConfigInput>({
|
40
|
+
client,
|
41
|
+
config,
|
42
|
+
salt,
|
43
|
+
worldAddress: existingWorldAddress,
|
44
|
+
deployerAddress: initialDeployerAddress,
|
45
|
+
}: DeployOptions<configInput>): Promise<WorldDeploy> {
|
46
|
+
const tables = Object.values(config.tables) as Table[];
|
47
|
+
|
48
|
+
const deployerAddress = initialDeployerAddress ?? (await ensureDeployer(client));
|
49
|
+
|
50
|
+
await ensureWorldFactory(client, deployerAddress);
|
51
|
+
|
52
|
+
// deploy all dependent contracts, because system registration, module install, etc. all expect these contracts to be callable.
|
53
|
+
await ensureContractsDeployed({
|
54
|
+
client,
|
55
|
+
deployerAddress,
|
56
|
+
contracts: [
|
57
|
+
...config.libraries.map((library) => ({
|
58
|
+
bytecode: library.prepareDeploy(deployerAddress, config.libraries).bytecode,
|
59
|
+
deployedBytecodeSize: library.deployedBytecodeSize,
|
60
|
+
label: `${library.path}:${library.name} library`,
|
61
|
+
})),
|
62
|
+
...config.systems.map((system) => ({
|
63
|
+
bytecode: system.prepareDeploy(deployerAddress, config.libraries).bytecode,
|
64
|
+
deployedBytecodeSize: system.deployedBytecodeSize,
|
65
|
+
label: `${resourceToLabel(system)} system`,
|
66
|
+
})),
|
67
|
+
...config.modules.map((mod) => ({
|
68
|
+
bytecode: mod.prepareDeploy(deployerAddress, config.libraries).bytecode,
|
69
|
+
deployedBytecodeSize: mod.deployedBytecodeSize,
|
70
|
+
label: `${mod.name} module`,
|
71
|
+
})),
|
72
|
+
],
|
73
|
+
});
|
74
|
+
|
75
|
+
const worldDeploy = existingWorldAddress
|
76
|
+
? await getWorldDeploy(client, existingWorldAddress)
|
77
|
+
: await deployWorld(client, deployerAddress, salt ?? `0x${randomBytes(32).toString("hex")}`);
|
78
|
+
|
79
|
+
if (!supportedStoreVersions.includes(worldDeploy.storeVersion)) {
|
80
|
+
throw new Error(`Unsupported Store version: ${worldDeploy.storeVersion}`);
|
81
|
+
}
|
82
|
+
if (!supportedWorldVersions.includes(worldDeploy.worldVersion)) {
|
83
|
+
throw new Error(`Unsupported World version: ${worldDeploy.worldVersion}`);
|
84
|
+
}
|
85
|
+
|
86
|
+
const namespaceTxs = await ensureNamespaceOwner({
|
87
|
+
client,
|
88
|
+
worldDeploy,
|
89
|
+
resourceIds: [...tables.map((table) => table.tableId), ...config.systems.map((system) => system.systemId)],
|
90
|
+
});
|
91
|
+
|
92
|
+
debug("waiting for all namespace registration transactions to confirm");
|
93
|
+
for (const tx of namespaceTxs) {
|
94
|
+
await waitForTransactionReceipt(client, { hash: tx });
|
95
|
+
}
|
96
|
+
|
97
|
+
const tableTxs = await ensureTables({
|
98
|
+
client,
|
99
|
+
worldDeploy,
|
100
|
+
tables,
|
101
|
+
});
|
102
|
+
const systemTxs = await ensureSystems({
|
103
|
+
client,
|
104
|
+
deployerAddress,
|
105
|
+
libraries: config.libraries,
|
106
|
+
worldDeploy,
|
107
|
+
systems: config.systems,
|
108
|
+
});
|
109
|
+
const functionTxs = await ensureFunctions({
|
110
|
+
client,
|
111
|
+
worldDeploy,
|
112
|
+
functions: config.systems.flatMap((system) => system.functions),
|
113
|
+
});
|
114
|
+
const moduleTxs = await ensureModules({
|
115
|
+
client,
|
116
|
+
deployerAddress,
|
117
|
+
libraries: config.libraries,
|
118
|
+
worldDeploy,
|
119
|
+
modules: config.modules,
|
120
|
+
});
|
121
|
+
|
122
|
+
const txs = [...tableTxs, ...systemTxs, ...functionTxs, ...moduleTxs];
|
123
|
+
|
124
|
+
// wait for each tx separately/serially, because parallelizing results in RPC errors
|
125
|
+
debug("waiting for all transactions to confirm");
|
126
|
+
for (const tx of txs) {
|
127
|
+
await waitForTransactionReceipt(client, { hash: tx });
|
128
|
+
// TODO: throw if there was a revert?
|
129
|
+
}
|
130
|
+
|
131
|
+
debug("deploy complete");
|
132
|
+
return worldDeploy;
|
133
|
+
}
|
@@ -0,0 +1,38 @@
|
|
1
|
+
import { Account, Chain, Client, Hex, Log, Transport } from "viem";
|
2
|
+
import { waitForTransactionReceipt } from "viem/actions";
|
3
|
+
import { ensureWorldFactory } 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
|
+
deployerAddress: Hex,
|
13
|
+
salt: Hex,
|
14
|
+
): Promise<WorldDeploy> {
|
15
|
+
const worldFactory = await ensureWorldFactory(client, deployerAddress);
|
16
|
+
|
17
|
+
debug("deploying world");
|
18
|
+
const tx = await writeContract(client, {
|
19
|
+
chain: client.chain ?? null,
|
20
|
+
address: worldFactory,
|
21
|
+
abi: WorldFactoryAbi,
|
22
|
+
functionName: "deployWorld",
|
23
|
+
args: [salt],
|
24
|
+
});
|
25
|
+
|
26
|
+
debug("waiting for world deploy");
|
27
|
+
const receipt = await waitForTransactionReceipt(client, { hash: tx });
|
28
|
+
if (receipt.status !== "success") {
|
29
|
+
console.error("world deploy failed", receipt);
|
30
|
+
throw new Error("world deploy failed");
|
31
|
+
}
|
32
|
+
|
33
|
+
// TODO: remove type casting once https://github.com/wagmi-dev/viem/pull/1330 is merged
|
34
|
+
const deploy = logsToWorldDeploy(receipt.logs.map((log) => log as Log<bigint, number, false>));
|
35
|
+
debug("deployed world to", deploy.address, "at block", deploy.deployBlock);
|
36
|
+
|
37
|
+
return { ...deploy, stateBlock: deploy.deployBlock };
|
38
|
+
}
|
@@ -0,0 +1,66 @@
|
|
1
|
+
import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from "viem";
|
2
|
+
import { getBytecode } from "viem/actions";
|
3
|
+
import { contractSizeLimit, salt } from "./common";
|
4
|
+
import { sendTransaction } from "@latticexyz/common";
|
5
|
+
import { debug } from "./debug";
|
6
|
+
import pRetry from "p-retry";
|
7
|
+
import { wait } from "@latticexyz/common/utils";
|
8
|
+
|
9
|
+
export type Contract = {
|
10
|
+
bytecode: Hex;
|
11
|
+
deployedBytecodeSize: number;
|
12
|
+
label?: string;
|
13
|
+
};
|
14
|
+
|
15
|
+
export async function ensureContract({
|
16
|
+
client,
|
17
|
+
deployerAddress,
|
18
|
+
bytecode,
|
19
|
+
deployedBytecodeSize,
|
20
|
+
label = "contract",
|
21
|
+
}: {
|
22
|
+
readonly client: Client<Transport, Chain | undefined, Account>;
|
23
|
+
readonly deployerAddress: Hex;
|
24
|
+
} & Contract): Promise<readonly Hex[]> {
|
25
|
+
if (bytecode.includes("__$")) {
|
26
|
+
throw new Error(`Found unlinked public library in ${label} bytecode`);
|
27
|
+
}
|
28
|
+
|
29
|
+
const address = getCreate2Address({ from: deployerAddress, salt, bytecode });
|
30
|
+
|
31
|
+
const contractCode = await getBytecode(client, { address, blockTag: "pending" });
|
32
|
+
if (contractCode) {
|
33
|
+
debug("found", label, "at", address);
|
34
|
+
return [];
|
35
|
+
}
|
36
|
+
|
37
|
+
if (deployedBytecodeSize > contractSizeLimit) {
|
38
|
+
console.warn(
|
39
|
+
`\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`,
|
40
|
+
);
|
41
|
+
} else if (deployedBytecodeSize > contractSizeLimit * 0.95) {
|
42
|
+
console.warn(
|
43
|
+
`\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`,
|
44
|
+
);
|
45
|
+
}
|
46
|
+
|
47
|
+
debug("deploying", label, "at", address);
|
48
|
+
return [
|
49
|
+
await pRetry(
|
50
|
+
() =>
|
51
|
+
sendTransaction(client, {
|
52
|
+
chain: client.chain ?? null,
|
53
|
+
to: deployerAddress,
|
54
|
+
data: concatHex([salt, bytecode]),
|
55
|
+
}),
|
56
|
+
{
|
57
|
+
retries: 3,
|
58
|
+
onFailedAttempt: async (error) => {
|
59
|
+
const delay = error.attemptNumber * 500;
|
60
|
+
debug(`failed to deploy ${label}, retrying in ${delay}ms...`);
|
61
|
+
await wait(delay);
|
62
|
+
},
|
63
|
+
},
|
64
|
+
),
|
65
|
+
];
|
66
|
+
}
|
@@ -0,0 +1,33 @@
|
|
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
|
+
import { uniqueBy } from "@latticexyz/common/utils";
|
6
|
+
|
7
|
+
export async function ensureContractsDeployed({
|
8
|
+
client,
|
9
|
+
deployerAddress,
|
10
|
+
contracts,
|
11
|
+
}: {
|
12
|
+
readonly client: Client<Transport, Chain | undefined, Account>;
|
13
|
+
readonly deployerAddress: Hex;
|
14
|
+
readonly contracts: readonly Contract[];
|
15
|
+
}): Promise<readonly Hex[]> {
|
16
|
+
// Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode
|
17
|
+
const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);
|
18
|
+
|
19
|
+
const txs = (
|
20
|
+
await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))
|
21
|
+
).flat();
|
22
|
+
|
23
|
+
if (txs.length) {
|
24
|
+
debug("waiting for contracts");
|
25
|
+
// wait for each tx separately/serially, because parallelizing results in RPC errors
|
26
|
+
for (const tx of txs) {
|
27
|
+
await waitForTransactionReceipt(client, { hash: tx });
|
28
|
+
// TODO: throw if there was a revert?
|
29
|
+
}
|
30
|
+
}
|
31
|
+
|
32
|
+
return txs;
|
33
|
+
}
|
@@ -0,0 +1,75 @@
|
|
1
|
+
import { Account, Address, Chain, Client, Transport } from "viem";
|
2
|
+
import { getBalance, getBytecode, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from "viem/actions";
|
3
|
+
import deployment from "./create2/deployment.json";
|
4
|
+
import { debug } from "./debug";
|
5
|
+
|
6
|
+
const deployer = `0x${deployment.address}` as const;
|
7
|
+
const deployerBytecode = `0x${deployment.bytecode}` as const;
|
8
|
+
|
9
|
+
export async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {
|
10
|
+
const bytecode = await getBytecode(client, { address: deployer });
|
11
|
+
if (bytecode) {
|
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;
|
19
|
+
}
|
20
|
+
|
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
|
+
}
|
41
|
+
}
|
42
|
+
|
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
|
+
|
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
|
+
|
68
|
+
if (deployReceipt.contractAddress !== deployer) {
|
69
|
+
console.warn(
|
70
|
+
`\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,
|
71
|
+
);
|
72
|
+
}
|
73
|
+
|
74
|
+
return deployReceipt.contractAddress;
|
75
|
+
}
|
@@ -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.systemFunctionSignature],
|
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,79 @@
|
|
1
|
+
import { Client, Transport, Chain, Account, Hex, BaseError } from "viem";
|
2
|
+
import { writeContract } from "@latticexyz/common";
|
3
|
+
import { Library, Module, WorldDeploy, worldAbi } from "./common";
|
4
|
+
import { debug } from "./debug";
|
5
|
+
import { isDefined, 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
|
+
deployerAddress,
|
12
|
+
libraries,
|
13
|
+
worldDeploy,
|
14
|
+
modules,
|
15
|
+
}: {
|
16
|
+
readonly client: Client<Transport, Chain | undefined, Account>;
|
17
|
+
readonly deployerAddress: Hex;
|
18
|
+
readonly libraries: readonly Library[];
|
19
|
+
readonly worldDeploy: WorldDeploy;
|
20
|
+
readonly modules: readonly Module[];
|
21
|
+
}): Promise<readonly Hex[]> {
|
22
|
+
if (!modules.length) return [];
|
23
|
+
|
24
|
+
await ensureContractsDeployed({
|
25
|
+
client,
|
26
|
+
deployerAddress,
|
27
|
+
contracts: modules.map((mod) => ({
|
28
|
+
bytecode: mod.prepareDeploy(deployerAddress, libraries).bytecode,
|
29
|
+
deployedBytecodeSize: mod.deployedBytecodeSize,
|
30
|
+
label: `${mod.name} module`,
|
31
|
+
})),
|
32
|
+
});
|
33
|
+
|
34
|
+
debug("installing modules:", modules.map((mod) => mod.name).join(", "));
|
35
|
+
return (
|
36
|
+
await Promise.all(
|
37
|
+
modules.map((mod) =>
|
38
|
+
pRetry(
|
39
|
+
async () => {
|
40
|
+
try {
|
41
|
+
const moduleAddress = mod.prepareDeploy(deployerAddress, libraries).address;
|
42
|
+
return mod.installAsRoot
|
43
|
+
? await writeContract(client, {
|
44
|
+
chain: client.chain ?? null,
|
45
|
+
address: worldDeploy.address,
|
46
|
+
abi: worldAbi,
|
47
|
+
// TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
|
48
|
+
functionName: "installRootModule",
|
49
|
+
args: [moduleAddress, mod.installData],
|
50
|
+
})
|
51
|
+
: await writeContract(client, {
|
52
|
+
chain: client.chain ?? null,
|
53
|
+
address: worldDeploy.address,
|
54
|
+
abi: worldAbi,
|
55
|
+
// TODO: replace with batchCall (https://github.com/latticexyz/mud/issues/1645)
|
56
|
+
functionName: "installModule",
|
57
|
+
args: [moduleAddress, mod.installData],
|
58
|
+
});
|
59
|
+
} catch (error) {
|
60
|
+
if (error instanceof BaseError && error.message.includes("Module_AlreadyInstalled")) {
|
61
|
+
debug(`module ${mod.name} already installed`);
|
62
|
+
return;
|
63
|
+
}
|
64
|
+
throw error;
|
65
|
+
}
|
66
|
+
},
|
67
|
+
{
|
68
|
+
retries: 3,
|
69
|
+
onFailedAttempt: async (error) => {
|
70
|
+
const delay = error.attemptNumber * 500;
|
71
|
+
debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`);
|
72
|
+
await wait(delay);
|
73
|
+
},
|
74
|
+
},
|
75
|
+
),
|
76
|
+
),
|
77
|
+
)
|
78
|
+
).filter(isDefined);
|
79
|
+
}
|
@@ -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
|
+
}
|