@aztec/aztec 0.0.0-test.1 → 0.0.1-commit.1142ef1

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 (156) hide show
  1. package/README.md +1 -1
  2. package/dest/bin/index.d.ts +1 -1
  3. package/dest/bin/index.js +23 -12
  4. package/dest/cli/aztec_start_action.d.ts +1 -1
  5. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  6. package/dest/cli/aztec_start_action.js +40 -40
  7. package/dest/cli/aztec_start_options.d.ts +5 -3
  8. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  9. package/dest/cli/aztec_start_options.js +143 -224
  10. package/dest/cli/cli.d.ts +1 -1
  11. package/dest/cli/cli.d.ts.map +1 -1
  12. package/dest/cli/cli.js +12 -7
  13. package/dest/cli/cmds/migrate_ha_db.d.ts +3 -0
  14. package/dest/cli/cmds/migrate_ha_db.d.ts.map +1 -0
  15. package/dest/cli/cmds/migrate_ha_db.js +27 -0
  16. package/dest/cli/cmds/start_archiver.d.ts +1 -1
  17. package/dest/cli/cmds/start_archiver.d.ts.map +1 -1
  18. package/dest/cli/cmds/start_archiver.js +20 -12
  19. package/dest/cli/cmds/start_bot.d.ts +4 -7
  20. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  21. package/dest/cli/cmds/start_bot.js +25 -14
  22. package/dest/cli/cmds/start_node.d.ts +2 -2
  23. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  24. package/dest/cli/cmds/start_node.js +68 -81
  25. package/dest/cli/cmds/start_p2p_bootstrap.d.ts +1 -1
  26. package/dest/cli/cmds/start_p2p_bootstrap.d.ts.map +1 -1
  27. package/dest/cli/cmds/start_p2p_bootstrap.js +9 -4
  28. package/dest/cli/cmds/start_prover_agent.d.ts +1 -1
  29. package/dest/cli/cmds/start_prover_agent.d.ts.map +1 -1
  30. package/dest/cli/cmds/start_prover_agent.js +33 -4
  31. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  32. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  33. package/dest/cli/cmds/start_prover_broker.js +10 -4
  34. package/dest/cli/cmds/start_prover_node.d.ts +1 -1
  35. package/dest/cli/cmds/start_prover_node.d.ts.map +1 -1
  36. package/dest/cli/cmds/start_prover_node.js +44 -46
  37. package/dest/cli/cmds/start_txe.d.ts +1 -1
  38. package/dest/cli/index.d.ts +1 -1
  39. package/dest/cli/preload_crs.d.ts +3 -0
  40. package/dest/cli/preload_crs.d.ts.map +1 -0
  41. package/dest/cli/preload_crs.js +6 -0
  42. package/dest/cli/release_version.d.ts +2 -0
  43. package/dest/cli/release_version.d.ts.map +1 -0
  44. package/dest/cli/release_version.js +14 -0
  45. package/dest/cli/util.d.ts +38 -7
  46. package/dest/cli/util.d.ts.map +1 -1
  47. package/dest/cli/util.js +198 -28
  48. package/dest/cli/versioning.d.ts +1 -1
  49. package/dest/cli/versioning.js +3 -3
  50. package/dest/examples/token.d.ts +1 -1
  51. package/dest/examples/token.js +31 -18
  52. package/dest/examples/util.d.ts +5 -6
  53. package/dest/examples/util.d.ts.map +1 -1
  54. package/dest/examples/util.js +5 -6
  55. package/dest/index.d.ts +2 -2
  56. package/dest/index.d.ts.map +1 -1
  57. package/dest/index.js +1 -1
  58. package/dest/local-network/banana_fpc.d.ts +10 -0
  59. package/dest/local-network/banana_fpc.d.ts.map +1 -0
  60. package/dest/{sandbox → local-network}/banana_fpc.js +20 -22
  61. package/dest/local-network/index.d.ts +4 -0
  62. package/dest/local-network/index.d.ts.map +1 -0
  63. package/dest/local-network/index.js +3 -0
  64. package/dest/local-network/local-network.d.ts +72 -0
  65. package/dest/local-network/local-network.d.ts.map +1 -0
  66. package/dest/local-network/local-network.js +195 -0
  67. package/dest/local-network/sponsored_fpc.d.ts +5 -0
  68. package/dest/local-network/sponsored_fpc.d.ts.map +1 -0
  69. package/dest/local-network/sponsored_fpc.js +18 -0
  70. package/dest/mnemonic.d.ts +1 -1
  71. package/dest/splash.d.ts +1 -1
  72. package/dest/testing/anvil_test_watcher.d.ts +34 -0
  73. package/dest/testing/anvil_test_watcher.d.ts.map +1 -0
  74. package/dest/testing/anvil_test_watcher.js +144 -0
  75. package/dest/testing/cheat_codes.d.ts +41 -0
  76. package/dest/testing/cheat_codes.d.ts.map +1 -0
  77. package/dest/testing/cheat_codes.js +62 -0
  78. package/dest/testing/epoch_test_settler.d.ts +17 -0
  79. package/dest/testing/epoch_test_settler.d.ts.map +1 -0
  80. package/dest/testing/epoch_test_settler.js +52 -0
  81. package/dest/testing/index.d.ts +5 -0
  82. package/dest/testing/index.d.ts.map +1 -0
  83. package/dest/testing/index.js +4 -0
  84. package/package.json +55 -45
  85. package/scripts/aztec.sh +63 -0
  86. package/scripts/compile.sh +44 -0
  87. package/scripts/extract_function.js +47 -0
  88. package/scripts/flamegraph.sh +59 -0
  89. package/scripts/init.sh +35 -0
  90. package/scripts/new.sh +59 -0
  91. package/scripts/setup_project.sh +31 -0
  92. package/src/bin/index.ts +28 -12
  93. package/src/cli/aztec_start_action.ts +36 -38
  94. package/src/cli/aztec_start_options.ts +159 -222
  95. package/src/cli/cli.ts +20 -11
  96. package/src/cli/cmds/migrate_ha_db.ts +43 -0
  97. package/src/cli/cmds/start_archiver.ts +21 -15
  98. package/src/cli/cmds/start_bot.ts +36 -13
  99. package/src/cli/cmds/start_node.ts +91 -86
  100. package/src/cli/cmds/start_p2p_bootstrap.ts +12 -4
  101. package/src/cli/cmds/start_prover_agent.ts +24 -12
  102. package/src/cli/cmds/start_prover_broker.ts +24 -4
  103. package/src/cli/cmds/start_prover_node.ts +54 -51
  104. package/src/cli/preload_crs.ts +7 -0
  105. package/src/cli/release_version.ts +21 -0
  106. package/src/cli/util.ts +208 -34
  107. package/src/cli/versioning.ts +3 -3
  108. package/src/examples/token.ts +23 -19
  109. package/src/examples/util.ts +6 -8
  110. package/src/index.ts +5 -6
  111. package/src/{sandbox → local-network}/banana_fpc.ts +21 -26
  112. package/src/local-network/index.ts +7 -0
  113. package/src/local-network/local-network.ts +238 -0
  114. package/src/local-network/sponsored_fpc.ts +26 -0
  115. package/src/testing/anvil_test_watcher.ts +166 -0
  116. package/src/testing/cheat_codes.ts +79 -0
  117. package/src/testing/epoch_test_settler.ts +59 -0
  118. package/src/testing/index.ts +4 -0
  119. package/dest/cli/chain_l2_config.d.ts +0 -19
  120. package/dest/cli/chain_l2_config.d.ts.map +0 -1
  121. package/dest/cli/chain_l2_config.js +0 -56
  122. package/dest/cli/cmds/start_blob_sink.d.ts +0 -3
  123. package/dest/cli/cmds/start_blob_sink.d.ts.map +0 -1
  124. package/dest/cli/cmds/start_blob_sink.js +0 -17
  125. package/dest/cli/cmds/start_faucet.d.ts +0 -4
  126. package/dest/cli/cmds/start_faucet.d.ts.map +0 -1
  127. package/dest/cli/cmds/start_faucet.js +0 -20
  128. package/dest/cli/cmds/start_pxe.d.ts +0 -16
  129. package/dest/cli/cmds/start_pxe.d.ts.map +0 -1
  130. package/dest/cli/cmds/start_pxe.js +0 -95
  131. package/dest/cli/get_l1_config.d.ts +0 -7
  132. package/dest/cli/get_l1_config.d.ts.map +0 -1
  133. package/dest/cli/get_l1_config.js +0 -13
  134. package/dest/sandbox/banana_fpc.d.ts +0 -11
  135. package/dest/sandbox/banana_fpc.d.ts.map +0 -1
  136. package/dest/sandbox/index.d.ts +0 -5
  137. package/dest/sandbox/index.d.ts.map +0 -1
  138. package/dest/sandbox/index.js +0 -4
  139. package/dest/sandbox/sandbox.d.ts +0 -76
  140. package/dest/sandbox/sandbox.d.ts.map +0 -1
  141. package/dest/sandbox/sandbox.js +0 -181
  142. package/dest/sandbox/sponsored_fee_payment_method.d.ts +0 -23
  143. package/dest/sandbox/sponsored_fee_payment_method.d.ts.map +0 -1
  144. package/dest/sandbox/sponsored_fee_payment_method.js +0 -36
  145. package/dest/sandbox/sponsored_fpc.d.ts +0 -6
  146. package/dest/sandbox/sponsored_fpc.d.ts.map +0 -1
  147. package/dest/sandbox/sponsored_fpc.js +0 -26
  148. package/src/cli/chain_l2_config.ts +0 -74
  149. package/src/cli/cmds/start_blob_sink.ts +0 -31
  150. package/src/cli/cmds/start_faucet.ts +0 -34
  151. package/src/cli/cmds/start_pxe.ts +0 -129
  152. package/src/cli/get_l1_config.ts +0 -18
  153. package/src/sandbox/index.ts +0 -5
  154. package/src/sandbox/sandbox.ts +0 -229
  155. package/src/sandbox/sponsored_fee_payment_method.ts +0 -46
  156. package/src/sandbox/sponsored_fpc.ts +0 -38
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env -S node --no-warnings
2
+ import { getInitialTestAccountsData } from '@aztec/accounts/testing';
3
+ import { AztecNodeService } from '@aztec/aztec-node';
4
+ import { type AztecNodeConfig, getConfigEnvVars } from '@aztec/aztec-node/config';
5
+ import { Fr } from '@aztec/aztec.js/fields';
6
+ import { createLogger } from '@aztec/aztec.js/log';
7
+ import { type BlobClientInterface, createBlobClient } from '@aztec/blob-client/client';
8
+ import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
9
+ import { createEthereumChain } from '@aztec/ethereum/chain';
10
+ import { waitForPublicClient } from '@aztec/ethereum/client';
11
+ import { getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
12
+ import { NULL_KEY } from '@aztec/ethereum/constants';
13
+ import { deployAztecL1Contracts } from '@aztec/ethereum/deploy-aztec-l1-contracts';
14
+ import { EthCheatCodes } from '@aztec/ethereum/test';
15
+ import { SecretValue } from '@aztec/foundation/config';
16
+ import { EthAddress } from '@aztec/foundation/eth-address';
17
+ import type { LogFn } from '@aztec/foundation/log';
18
+ import { DateProvider, TestDateProvider } from '@aztec/foundation/timer';
19
+ import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
20
+ import { protocolContractsHash } from '@aztec/protocol-contracts';
21
+ import type { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
22
+ import {
23
+ type TelemetryClient,
24
+ getConfigEnvVars as getTelemetryClientConfig,
25
+ initTelemetryClient,
26
+ } from '@aztec/telemetry-client';
27
+ import { TestWallet, deployFundedSchnorrAccounts } from '@aztec/test-wallet/server';
28
+ import { getGenesisValues } from '@aztec/world-state/testing';
29
+
30
+ import { type Hex, createPublicClient, fallback, http as httpViemTransport } from 'viem';
31
+ import { mnemonicToAccount, privateKeyToAddress } from 'viem/accounts';
32
+ import { foundry } from 'viem/chains';
33
+
34
+ import { createAccountLogs } from '../cli/util.js';
35
+ import { DefaultMnemonic } from '../mnemonic.js';
36
+ import { AnvilTestWatcher } from '../testing/anvil_test_watcher.js';
37
+ import { EpochTestSettler } from '../testing/epoch_test_settler.js';
38
+ import { getBananaFPCAddress, setupBananaFPC } from './banana_fpc.js';
39
+ import { getSponsoredFPCAddress } from './sponsored_fpc.js';
40
+
41
+ const logger = createLogger('local-network');
42
+
43
+ const localAnvil = foundry;
44
+
45
+ /**
46
+ * Function to deploy our L1 contracts to the local network L1
47
+ * @param aztecNodeConfig - The Aztec Node Config
48
+ * @param hdAccount - Account for publishing L1 contracts
49
+ */
50
+ export async function deployContractsToL1(
51
+ aztecNodeConfig: AztecNodeConfig,
52
+ privateKey: Hex,
53
+ opts: {
54
+ assumeProvenThroughBlockNumber?: number;
55
+ genesisArchiveRoot?: Fr;
56
+ feeJuicePortalInitialBalance?: bigint;
57
+ } = {},
58
+ ) {
59
+ await waitForPublicClient(aztecNodeConfig);
60
+
61
+ const l1Contracts = await deployAztecL1Contracts(aztecNodeConfig.l1RpcUrls[0], privateKey, foundry.id, {
62
+ ...getL1ContractsConfigEnvVars(), // TODO: We should not need to be loading config from env again, caller should handle this
63
+ ...aztecNodeConfig,
64
+ vkTreeRoot: getVKTreeRoot(),
65
+ protocolContractsHash,
66
+ genesisArchiveRoot: opts.genesisArchiveRoot ?? new Fr(GENESIS_ARCHIVE_ROOT),
67
+ feeJuicePortalInitialBalance: opts.feeJuicePortalInitialBalance,
68
+ aztecTargetCommitteeSize: 0, // no committee in local network
69
+ slasherFlavor: 'none', // no slashing in local network
70
+ realVerifier: false,
71
+ });
72
+
73
+ aztecNodeConfig.l1Contracts = l1Contracts.l1ContractAddresses;
74
+ aztecNodeConfig.rollupVersion = l1Contracts.rollupVersion;
75
+
76
+ return aztecNodeConfig.l1Contracts;
77
+ }
78
+
79
+ /** Local network settings. */
80
+ export type LocalNetworkConfig = AztecNodeConfig & {
81
+ /** Mnemonic used to derive the L1 deployer private key.*/
82
+ l1Mnemonic: string;
83
+ /** Whether to deploy test accounts on local network start.*/
84
+ testAccounts: boolean;
85
+ };
86
+
87
+ /**
88
+ * Create and start a new Aztec Node and PXE. Deploys L1 contracts.
89
+ * Does not start any HTTP services nor populate any initial accounts.
90
+ * @param config - Optional local network settings.
91
+ */
92
+ export async function createLocalNetwork(config: Partial<LocalNetworkConfig> = {}, userLog: LogFn) {
93
+ // local network is meant for test envs. We should only need one l1RpcUrl
94
+ const l1RpcUrl = config.l1RpcUrls?.[0];
95
+ if (!l1RpcUrl) {
96
+ throw new Error('An L1 RPC URL is required');
97
+ }
98
+ if ((config.l1RpcUrls?.length || 0) > 1) {
99
+ logger.warn(`Multiple L1 RPC URLs provided. Local networks will only use the first one: ${l1RpcUrl}`);
100
+ }
101
+
102
+ const aztecNodeConfig: AztecNodeConfig = {
103
+ ...getConfigEnvVars(),
104
+ ...config,
105
+ };
106
+ const hdAccount = mnemonicToAccount(config.l1Mnemonic || DefaultMnemonic);
107
+ if (
108
+ aztecNodeConfig.publisherPrivateKeys == undefined ||
109
+ !aztecNodeConfig.publisherPrivateKeys.length ||
110
+ aztecNodeConfig.publisherPrivateKeys[0].getValue() === NULL_KEY
111
+ ) {
112
+ const privKey = hdAccount.getHdKey().privateKey;
113
+ aztecNodeConfig.publisherPrivateKeys = [new SecretValue(`0x${Buffer.from(privKey!).toString('hex')}` as const)];
114
+ }
115
+ if (!aztecNodeConfig.validatorPrivateKeys?.getValue().length) {
116
+ const privKey = hdAccount.getHdKey().privateKey;
117
+ aztecNodeConfig.validatorPrivateKeys = new SecretValue([`0x${Buffer.from(privKey!).toString('hex')}`]);
118
+ }
119
+ aztecNodeConfig.coinbase = EthAddress.fromString(
120
+ privateKeyToAddress(aztecNodeConfig.validatorPrivateKeys.getValue()[0]),
121
+ );
122
+
123
+ const initialAccounts = await (async () => {
124
+ if (config.testAccounts === true || config.testAccounts === undefined) {
125
+ if (aztecNodeConfig.p2pEnabled) {
126
+ userLog(`Not setting up test accounts as we are connecting to a network`);
127
+ } else {
128
+ userLog(`Setting up test accounts`);
129
+ return await getInitialTestAccountsData();
130
+ }
131
+ }
132
+ return [];
133
+ })();
134
+
135
+ const bananaFPC = await getBananaFPCAddress(initialAccounts);
136
+ const sponsoredFPC = await getSponsoredFPCAddress();
137
+ const fundedAddresses = initialAccounts.length
138
+ ? [...initialAccounts.map(a => a.address), bananaFPC, sponsoredFPC]
139
+ : [];
140
+ const { genesisArchiveRoot, prefilledPublicData, fundingNeeded } = await getGenesisValues(fundedAddresses);
141
+
142
+ const dateProvider = new TestDateProvider();
143
+
144
+ let cheatcodes: EthCheatCodes | undefined;
145
+ let rollupAddress: EthAddress | undefined;
146
+ let watcher: AnvilTestWatcher | undefined;
147
+ if (!aztecNodeConfig.p2pEnabled) {
148
+ ({ rollupAddress } = await deployContractsToL1(
149
+ aztecNodeConfig,
150
+ aztecNodeConfig.validatorPrivateKeys.getValue()[0],
151
+ {
152
+ assumeProvenThroughBlockNumber: Number.MAX_SAFE_INTEGER,
153
+ genesisArchiveRoot,
154
+ feeJuicePortalInitialBalance: fundingNeeded,
155
+ },
156
+ ));
157
+
158
+ const chain =
159
+ aztecNodeConfig.l1RpcUrls.length > 0
160
+ ? createEthereumChain([l1RpcUrl], aztecNodeConfig.l1ChainId)
161
+ : { chainInfo: localAnvil };
162
+
163
+ const publicClient = createPublicClient({
164
+ chain: chain.chainInfo,
165
+ transport: fallback([httpViemTransport(l1RpcUrl)]) as any,
166
+ });
167
+
168
+ cheatcodes = new EthCheatCodes([l1RpcUrl], dateProvider);
169
+
170
+ watcher = new AnvilTestWatcher(cheatcodes, rollupAddress, publicClient, dateProvider);
171
+ watcher.setisLocalNetwork(true);
172
+ watcher.setIsMarkingAsProven(false); // Do not mark as proven in the watcher. It's marked in the epochTestSettler after the out hash is set.
173
+
174
+ await watcher.start();
175
+ }
176
+
177
+ const telemetry = await initTelemetryClient(getTelemetryClientConfig());
178
+ // Create a local blob client client inside the local network, no http connectivity
179
+ const blobClient = createBlobClient();
180
+ const node = await createAztecNode(aztecNodeConfig, { telemetry, blobClient, dateProvider }, { prefilledPublicData });
181
+
182
+ let epochTestSettler: EpochTestSettler | undefined;
183
+ if (!aztecNodeConfig.p2pEnabled) {
184
+ epochTestSettler = new EpochTestSettler(cheatcodes!, rollupAddress!, node.getBlockSource(), {
185
+ pollingIntervalMs: 200,
186
+ });
187
+ await epochTestSettler.start();
188
+ }
189
+
190
+ if (initialAccounts.length) {
191
+ const PXEConfig = { proverEnabled: aztecNodeConfig.realProofs };
192
+ const wallet = await TestWallet.create(node, PXEConfig);
193
+
194
+ userLog('Setting up funded test accounts...');
195
+ const accountManagers = await deployFundedSchnorrAccounts(wallet, node, initialAccounts);
196
+ const accountsWithSecrets = accountManagers.map((manager, i) => ({
197
+ account: manager,
198
+ secretKey: initialAccounts[i].secret,
199
+ }));
200
+ const accLogs = await createAccountLogs(accountsWithSecrets, wallet);
201
+ userLog(accLogs.join(''));
202
+
203
+ await setupBananaFPC(initialAccounts, wallet, userLog);
204
+
205
+ userLog(`SponsoredFPC: ${await getSponsoredFPCAddress()}`);
206
+
207
+ // We no longer need the wallet once we've setup the accounts so we stop the underlying PXE job queue
208
+ await wallet.stop();
209
+ }
210
+
211
+ const stop = async () => {
212
+ await node.stop();
213
+ await watcher?.stop();
214
+ await epochTestSettler?.stop();
215
+ };
216
+
217
+ return { node, stop };
218
+ }
219
+
220
+ /**
221
+ * Create and start a new Aztec RPC HTTP Server
222
+ * @param config - Optional Aztec node settings.
223
+ */
224
+ export async function createAztecNode(
225
+ config: Partial<AztecNodeConfig> = {},
226
+ deps: { telemetry?: TelemetryClient; blobClient?: BlobClientInterface; dateProvider?: DateProvider } = {},
227
+ options: { prefilledPublicData?: PublicDataTreeLeaf[] } = {},
228
+ ) {
229
+ // TODO(#12272): will clean this up. This is criminal.
230
+ const { l1Contracts, ...rest } = getConfigEnvVars();
231
+ const aztecNodeConfig: AztecNodeConfig = {
232
+ ...rest,
233
+ ...config,
234
+ l1Contracts: { ...l1Contracts, ...config.l1Contracts },
235
+ };
236
+ const node = await AztecNodeService.createAndSync(aztecNodeConfig, deps, options);
237
+ return node;
238
+ }
@@ -0,0 +1,26 @@
1
+ import type { AztecAddress } from '@aztec/aztec.js/addresses';
2
+ import {
3
+ type ContractInstanceWithAddress,
4
+ getContractInstanceFromInstantiationParams,
5
+ } from '@aztec/aztec.js/contracts';
6
+ import { Fr } from '@aztec/aztec.js/fields';
7
+ import type { Wallet } from '@aztec/aztec.js/wallet';
8
+ import { SPONSORED_FPC_SALT } from '@aztec/constants';
9
+ import { SponsoredFPCContract } from '@aztec/noir-contracts.js/SponsoredFPC';
10
+
11
+ async function getSponsoredFPCInstance(): Promise<ContractInstanceWithAddress> {
12
+ return await getContractInstanceFromInstantiationParams(SponsoredFPCContract.artifact, {
13
+ salt: new Fr(SPONSORED_FPC_SALT),
14
+ });
15
+ }
16
+
17
+ export async function getSponsoredFPCAddress(): Promise<AztecAddress> {
18
+ return (await getSponsoredFPCInstance()).address;
19
+ }
20
+
21
+ export async function registerDeployedSponsoredFPCInWalletAndGetAddress(wallet: Wallet): Promise<AztecAddress> {
22
+ const fpc = await getSponsoredFPCInstance();
23
+ // The following is no-op if the contract is already registered
24
+ await wallet.registerContract(fpc, SponsoredFPCContract.artifact);
25
+ return fpc.address;
26
+ }
@@ -0,0 +1,166 @@
1
+ import { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
2
+ import type { ViemClient } from '@aztec/ethereum/types';
3
+ import { SlotNumber } from '@aztec/foundation/branded-types';
4
+ import type { EthAddress } from '@aztec/foundation/eth-address';
5
+ import { type Logger, createLogger } from '@aztec/foundation/log';
6
+ import { RunningPromise } from '@aztec/foundation/running-promise';
7
+ import type { TestDateProvider } from '@aztec/foundation/timer';
8
+ import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
9
+
10
+ import { type GetContractReturnType, getAddress, getContract } from 'viem';
11
+
12
+ /**
13
+ * Represents a watcher for a rollup contract.
14
+ *
15
+ * It started on a network like anvil where time traveling is allowed, and auto-mine is turned on
16
+ * it will periodically check if the current slot have already been filled, e.g., there was an L2
17
+ * block within the slot. And if so, it will time travel into the next slot.
18
+ */
19
+ export class AnvilTestWatcher {
20
+ private isLocalNetwork: boolean = false;
21
+
22
+ private rollup: GetContractReturnType<typeof RollupAbi, ViemClient>;
23
+ private rollupCheatCodes: RollupCheatCodes;
24
+ private l2SlotDuration!: number;
25
+
26
+ private filledRunningPromise?: RunningPromise;
27
+ private syncDateProviderPromise?: RunningPromise;
28
+ private markingAsProvenRunningPromise?: RunningPromise;
29
+
30
+ private logger: Logger = createLogger(`aztecjs:utils:watcher`);
31
+
32
+ private isMarkingAsProven = true;
33
+
34
+ constructor(
35
+ private cheatcodes: EthCheatCodes,
36
+ rollupAddress: EthAddress,
37
+ l1Client: ViemClient,
38
+ private dateProvider?: TestDateProvider,
39
+ ) {
40
+ this.rollup = getContract({
41
+ address: getAddress(rollupAddress.toString()),
42
+ abi: RollupAbi,
43
+ client: l1Client,
44
+ });
45
+
46
+ this.rollupCheatCodes = new RollupCheatCodes(this.cheatcodes, {
47
+ rollupAddress,
48
+ });
49
+
50
+ this.logger.debug(`Watcher created for rollup at ${rollupAddress}`);
51
+ }
52
+
53
+ setIsMarkingAsProven(isMarkingAsProven: boolean) {
54
+ this.logger.warn(`Watcher is now ${isMarkingAsProven ? 'marking' : 'not marking'} blocks as proven`);
55
+ this.isMarkingAsProven = isMarkingAsProven;
56
+ }
57
+
58
+ setisLocalNetwork(isLocalNetwork: boolean) {
59
+ this.isLocalNetwork = isLocalNetwork;
60
+ }
61
+
62
+ async start() {
63
+ if (this.filledRunningPromise) {
64
+ throw new Error('Watcher already watching for filled slot');
65
+ }
66
+
67
+ const config = await this.rollupCheatCodes.getConfig();
68
+ this.l2SlotDuration = config.slotDuration;
69
+
70
+ // If auto mining is not supported (e.g., we are on a real network), then we
71
+ // will simple do nothing. But if on an anvil or the like, this make sure that
72
+ // the local network and tests don't break because time is frozen and we never get to
73
+ // the next slot.
74
+ const isAutoMining = await this.cheatcodes.isAutoMining();
75
+
76
+ if (isAutoMining) {
77
+ this.filledRunningPromise = new RunningPromise(() => this.warpTimeIfNeeded(), this.logger, 200);
78
+ this.filledRunningPromise.start();
79
+ this.syncDateProviderPromise = new RunningPromise(() => this.syncDateProviderToL1IfBehind(), this.logger, 200);
80
+ this.syncDateProviderPromise.start();
81
+ this.markingAsProvenRunningPromise = new RunningPromise(() => this.markAsProven(), this.logger, 200);
82
+ this.markingAsProvenRunningPromise.start();
83
+ this.logger.info(`Watcher started for rollup at ${this.rollup.address}`);
84
+ } else {
85
+ this.logger.info(`Watcher not started because not auto mining`);
86
+ }
87
+ }
88
+
89
+ async stop() {
90
+ await this.filledRunningPromise?.stop();
91
+ await this.syncDateProviderPromise?.stop();
92
+ await this.markingAsProvenRunningPromise?.stop();
93
+ }
94
+
95
+ async trigger() {
96
+ await this.filledRunningPromise?.trigger();
97
+ await this.syncDateProviderPromise?.trigger();
98
+ await this.markingAsProvenRunningPromise?.trigger();
99
+ }
100
+
101
+ async markAsProven() {
102
+ if (!this.isMarkingAsProven) {
103
+ return;
104
+ }
105
+ await this.rollupCheatCodes.markAsProven();
106
+ }
107
+
108
+ async syncDateProviderToL1IfBehind() {
109
+ // this doesn't apply to the local network, because we don't have a date provider in the local network
110
+ if (!this.dateProvider) {
111
+ return;
112
+ }
113
+
114
+ const l1Time = (await this.cheatcodes.timestamp()) * 1000;
115
+ const wallTime = this.dateProvider.now();
116
+ if (l1Time > wallTime) {
117
+ this.logger.warn(`L1 is ahead of wall time. Syncing wall time to L1 time`);
118
+ this.dateProvider.setTime(l1Time);
119
+ } else if (l1Time + Number(this.l2SlotDuration) * 1000 < wallTime) {
120
+ this.logger.warn(`L1 is more than 1 L2 slot behind wall time. Warping to wall time`);
121
+ await this.cheatcodes.warp(Math.ceil(wallTime / 1000));
122
+ }
123
+ }
124
+
125
+ async warpTimeIfNeeded() {
126
+ try {
127
+ const currentSlot = SlotNumber.fromBigInt(await this.rollup.read.getCurrentSlot());
128
+ const pendingCheckpointNumber = await this.rollup.read.getPendingCheckpointNumber();
129
+ const checkpointLog = await this.rollup.read.getCheckpoint([pendingCheckpointNumber]);
130
+ const nextSlot = SlotNumber(currentSlot + 1);
131
+ const nextSlotTimestamp = Number(await this.rollup.read.getTimestampForSlot([BigInt(nextSlot)]));
132
+
133
+ if (BigInt(currentSlot) === checkpointLog.slotNumber) {
134
+ // We should jump to the next slot
135
+ try {
136
+ await this.cheatcodes.warp(nextSlotTimestamp, {
137
+ resetBlockInterval: true,
138
+ });
139
+ } catch (e) {
140
+ this.logger.error(`Failed to warp to timestamp ${nextSlotTimestamp}: ${e}`);
141
+ }
142
+
143
+ this.logger.info(`Slot ${currentSlot} was filled, jumped to next slot`);
144
+ return;
145
+ }
146
+
147
+ // If we are not in local network, we don't need to warp time
148
+ if (!this.isLocalNetwork) {
149
+ return;
150
+ }
151
+
152
+ const currentTimestamp = this.dateProvider?.now() ?? Date.now();
153
+ if (currentTimestamp > nextSlotTimestamp * 1000) {
154
+ try {
155
+ await this.cheatcodes.warp(nextSlotTimestamp, { resetBlockInterval: true });
156
+ } catch (e) {
157
+ this.logger.error(`Failed to warp to timestamp ${nextSlotTimestamp}: ${e}`);
158
+ }
159
+
160
+ this.logger.info(`Slot ${currentSlot} was missed, jumped to next slot`);
161
+ }
162
+ } catch {
163
+ this.logger.error('mineIfSlotFilled failed');
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,79 @@
1
+ import { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { retryUntil } from '@aztec/foundation/retry';
4
+ import type { DateProvider } from '@aztec/foundation/timer';
5
+ import type { SequencerClient } from '@aztec/sequencer-client';
6
+ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
7
+
8
+ /**
9
+ * A class that provides utility functions for interacting with the chain.
10
+ * @deprecated There used to be 3 kinds of cheat codes: eth, rollup and aztec. We have nuked the Aztec ones because
11
+ * they became unused (we now have better testing tools). If you are introducing a new functionality to the cheat
12
+ * codes, please consider whether it makes sense to just introduce new utils in your tests instead.
13
+ */
14
+ export class CheatCodes {
15
+ constructor(
16
+ /** Cheat codes for L1.*/
17
+ public eth: EthCheatCodes,
18
+ /** Cheat codes for the Aztec Rollup contract on L1. */
19
+ public rollup: RollupCheatCodes,
20
+ ) {}
21
+
22
+ static async create(rpcUrls: string[], node: AztecNode, dateProvider: DateProvider): Promise<CheatCodes> {
23
+ const ethCheatCodes = new EthCheatCodes(rpcUrls, dateProvider);
24
+ const rollupCheatCodes = new RollupCheatCodes(
25
+ ethCheatCodes,
26
+ await node.getNodeInfo().then(n => n.l1ContractAddresses),
27
+ );
28
+ return new CheatCodes(ethCheatCodes, rollupCheatCodes);
29
+ }
30
+
31
+ /**
32
+ * Warps the L1 timestamp to a target timestamp and mines an L2 block that advances the L2 timestamp to at least
33
+ * the target timestamp. L2 timestamp is not advanced exactly to the target timestamp because it is determined
34
+ * by the slot number, which advances in fixed intervals.
35
+ * This is useful for testing time-dependent contract behavior.
36
+ * @param sequencerClient - The sequencer client to use to force an empty block to be mined.
37
+ * @param node - The Aztec node used to query if a new block has been mined.
38
+ * @param targetTimestamp - The target timestamp to warp to (in seconds)
39
+ */
40
+ async warpL2TimeAtLeastTo(sequencerClient: SequencerClient, node: AztecNode, targetTimestamp: bigint | number) {
41
+ const currentL2BlockNumber: BlockNumber = await node.getBlockNumber();
42
+
43
+ // We warp the L1 timestamp
44
+ await this.eth.warp(targetTimestamp, { resetBlockInterval: true });
45
+
46
+ // Wait until an L2 block is mined
47
+ const sequencer = sequencerClient.getSequencer();
48
+ const minTxsPerBlock = sequencer.getConfig().minTxsPerBlock;
49
+ sequencer.updateConfig({ minTxsPerBlock: 0 });
50
+
51
+ await retryUntil(
52
+ async () => {
53
+ const newL2BlockNumber: BlockNumber = await node.getBlockNumber();
54
+ return newL2BlockNumber > currentL2BlockNumber;
55
+ },
56
+ 'new block after warping L2 time',
57
+ 36,
58
+ 1,
59
+ );
60
+
61
+ // Restore original minTxsPerBlock
62
+ sequencer.updateConfig({ minTxsPerBlock });
63
+ }
64
+
65
+ /**
66
+ * Warps the L1 timestamp forward by a specified duration and mines an L2 block that advances the L2 timestamp at
67
+ * least by the duration. L2 timestamp is not advanced exactly by the duration because it is determined by the slot
68
+ * number, which advances in fixed intervals.
69
+ * This is useful for testing time-dependent contract behavior.
70
+ * @param sequencerClient - The sequencer client to use to force an empty block to be mined.
71
+ * @param node - The Aztec node used to query if a new block has been mined.
72
+ * @param duration - The duration to advance time by (in seconds)
73
+ */
74
+ async warpL2TimeAtLeastBy(sequencerClient: SequencerClient, node: AztecNode, duration: bigint | number) {
75
+ const currentTimestamp = await this.eth.timestamp();
76
+ const targetTimestamp = BigInt(currentTimestamp) + BigInt(duration);
77
+ await this.warpL2TimeAtLeastTo(sequencerClient, node, targetTimestamp);
78
+ }
79
+ }
@@ -0,0 +1,59 @@
1
+ import { Fr } from '@aztec/aztec.js/fields';
2
+ import { type EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
3
+ import { type EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { EpochMonitor } from '@aztec/prover-node';
5
+ import type { EthAddress, L2BlockSource } from '@aztec/stdlib/block';
6
+ import { computeL2ToL1MembershipWitnessFromMessagesInEpoch } from '@aztec/stdlib/messaging';
7
+
8
+ export class EpochTestSettler {
9
+ private rollupCheatCodes: RollupCheatCodes;
10
+ private epochMonitor?: EpochMonitor;
11
+
12
+ constructor(
13
+ cheatcodes: EthCheatCodes,
14
+ rollupAddress: EthAddress,
15
+ private l2BlockSource: L2BlockSource,
16
+ private options: { pollingIntervalMs: number; provingDelayMs?: number },
17
+ ) {
18
+ this.rollupCheatCodes = new RollupCheatCodes(cheatcodes, { rollupAddress });
19
+ }
20
+
21
+ async start() {
22
+ const { epochDuration } = await this.rollupCheatCodes.getConfig();
23
+ this.epochMonitor = new EpochMonitor(this.l2BlockSource, { epochDuration: Number(epochDuration) }, this.options);
24
+ this.epochMonitor.start(this);
25
+ }
26
+
27
+ async stop() {
28
+ await this.epochMonitor?.stop();
29
+ }
30
+
31
+ async handleEpochReadyToProve(epoch: EpochNumber): Promise<boolean> {
32
+ const blocks = await this.l2BlockSource.getBlocksForEpoch(epoch);
33
+ const messagesInEpoch: Fr[][][][] = [];
34
+ let previousSlotNumber = SlotNumber.ZERO;
35
+ let checkpointIndex = -1;
36
+ for (const block of blocks) {
37
+ const slotNumber = block.header.globalVariables.slotNumber;
38
+ if (slotNumber !== previousSlotNumber) {
39
+ checkpointIndex++;
40
+ messagesInEpoch[checkpointIndex] = [];
41
+ previousSlotNumber = slotNumber;
42
+ }
43
+ messagesInEpoch[checkpointIndex].push(block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs));
44
+ }
45
+
46
+ const [firstMessage] = messagesInEpoch.flat(3);
47
+ if (firstMessage) {
48
+ const { root: outHash } = computeL2ToL1MembershipWitnessFromMessagesInEpoch(messagesInEpoch, firstMessage);
49
+ await this.rollupCheatCodes.insertOutbox(epoch, outHash.toBigInt());
50
+ }
51
+
52
+ // Mark the blocks as proven.
53
+ for (const block of blocks) {
54
+ await this.rollupCheatCodes.markAsProven(block.number);
55
+ }
56
+
57
+ return true;
58
+ }
59
+ }
@@ -0,0 +1,4 @@
1
+ export { AnvilTestWatcher } from './anvil_test_watcher.js';
2
+ export { EthCheatCodes, RollupCheatCodes } from '@aztec/ethereum/test';
3
+ export { CheatCodes } from './cheat_codes.js';
4
+ export { EpochTestSettler } from './epoch_test_settler.js';
@@ -1,19 +0,0 @@
1
- export type NetworkNames = 'testnet-ignition';
2
- export type L2ChainConfig = {
3
- l1ChainId: number;
4
- ethereumSlotDuration: number;
5
- aztecSlotDuration: number;
6
- aztecEpochDuration: number;
7
- aztecProofSubmissionWindow: number;
8
- testAccounts: boolean;
9
- p2pEnabled: boolean;
10
- p2pBootstrapNodes: string[];
11
- registryAddress: string;
12
- seqMinTxsPerBlock: number;
13
- seqMaxTxsPerBlock: number;
14
- };
15
- export declare const testnetIgnitionL2ChainConfig: L2ChainConfig;
16
- export declare function getBootnodes(networkName: NetworkNames): Promise<any>;
17
- export declare function getL2ChainConfig(networkName: NetworkNames): Promise<L2ChainConfig | undefined>;
18
- export declare function enrichEnvironmentWithChainConfig(networkName: NetworkNames): Promise<void>;
19
- //# sourceMappingURL=chain_l2_config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"chain_l2_config.d.ts","sourceRoot":"","sources":["../../src/cli/chain_l2_config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAE9C,MAAM,MAAM,aAAa,GAAG;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,0BAA0B,EAAE,MAAM,CAAC;IACnC,YAAY,EAAE,OAAO,CAAC;IACtB,UAAU,EAAE,OAAO,CAAC;IACpB,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,eAAO,MAAM,4BAA4B,EAAE,aAY1C,CAAC;AAEF,wBAAsB,YAAY,CAAC,WAAW,EAAE,YAAY,gBAQ3D;AAED,wBAAsB,gBAAgB,CAAC,WAAW,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAOpG;AAUD,wBAAsB,gCAAgC,CAAC,WAAW,EAAE,YAAY,iBAgB/E"}
@@ -1,56 +0,0 @@
1
- export const testnetIgnitionL2ChainConfig = {
2
- l1ChainId: 11155111,
3
- ethereumSlotDuration: 12,
4
- aztecSlotDuration: 36,
5
- aztecEpochDuration: 32,
6
- aztecProofSubmissionWindow: 64,
7
- testAccounts: true,
8
- p2pEnabled: true,
9
- p2pBootstrapNodes: [],
10
- registryAddress: '0x12b3ebc176a1646b911391eab3760764f2e05fe3',
11
- seqMinTxsPerBlock: 0,
12
- seqMaxTxsPerBlock: 0
13
- };
14
- export async function getBootnodes(networkName) {
15
- const url = `http://static.aztec.network/${networkName}/bootnodes.json`;
16
- const response = await fetch(url);
17
- if (!response.ok) {
18
- throw new Error(`Failed to fetch basic contract addresses from ${url}`);
19
- }
20
- const json = await response.json();
21
- return json['bootnodes'];
22
- }
23
- export async function getL2ChainConfig(networkName) {
24
- if (networkName === 'testnet-ignition') {
25
- const config = {
26
- ...testnetIgnitionL2ChainConfig
27
- };
28
- config.p2pBootstrapNodes = await getBootnodes(networkName);
29
- return config;
30
- }
31
- return undefined;
32
- }
33
- function enrichVar(envVar, value) {
34
- // Don't override
35
- if (process.env[envVar]) {
36
- return;
37
- }
38
- process.env[envVar] = value;
39
- }
40
- export async function enrichEnvironmentWithChainConfig(networkName) {
41
- const config = await getL2ChainConfig(networkName);
42
- if (!config) {
43
- throw new Error(`Unknown network name: ${networkName}`);
44
- }
45
- enrichVar('ETHEREUM_SLOT_DURATION', config.ethereumSlotDuration.toString());
46
- enrichVar('AZTEC_SLOT_DURATION', config.aztecSlotDuration.toString());
47
- enrichVar('AZTEC_EPOCH_DURATION', config.aztecEpochDuration.toString());
48
- enrichVar('AZTEC_PROOF_SUBMISSION_WINDOW', config.aztecProofSubmissionWindow.toString());
49
- enrichVar('P2P_BOOTSTRAP_NODES', config.p2pBootstrapNodes.join(','));
50
- enrichVar('TEST_ACCOUNTS', config.testAccounts.toString());
51
- enrichVar('P2P_ENABLED', config.p2pEnabled.toString());
52
- enrichVar('L1_CHAIN_ID', config.l1ChainId.toString());
53
- enrichVar('REGISTRY_CONTRACT_ADDRESS', config.registryAddress);
54
- enrichVar('SEQ_MIN_TX_PER_BLOCK', config.seqMinTxsPerBlock.toString());
55
- enrichVar('SEQ_MAX_TX_PER_BLOCK', config.seqMaxTxsPerBlock.toString());
56
- }
@@ -1,3 +0,0 @@
1
- import type { LogFn } from '@aztec/foundation/log';
2
- export declare function startBlobSink(options: any, signalHandlers: (() => Promise<void>)[], userLog: LogFn): Promise<void>;
3
- //# sourceMappingURL=start_blob_sink.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"start_blob_sink.d.ts","sourceRoot":"","sources":["../../../src/cli/cmds/start_blob_sink.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAKnD,wBAAsB,aAAa,CAAC,OAAO,EAAE,GAAG,EAAE,cAAc,EAAE,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,iBAmBxG"}