@aztec/end-to-end 4.0.0-nightly.20260113 → 4.0.0-nightly.20260115

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 (80) hide show
  1. package/dest/bench/client_flows/client_flows_benchmark.d.ts +12 -13
  2. package/dest/bench/client_flows/client_flows_benchmark.d.ts.map +1 -1
  3. package/dest/bench/client_flows/client_flows_benchmark.js +104 -134
  4. package/dest/bench/utils.d.ts +1 -1
  5. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.d.ts +6 -7
  6. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.d.ts.map +1 -1
  7. package/dest/e2e_blacklist_token_contract/blacklist_token_contract_test.js +98 -113
  8. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.d.ts +6 -7
  9. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.d.ts.map +1 -1
  10. package/dest/e2e_cross_chain_messaging/cross_chain_messaging_test.js +65 -62
  11. package/dest/e2e_deploy_contract/deploy_test.d.ts +4 -3
  12. package/dest/e2e_deploy_contract/deploy_test.d.ts.map +1 -1
  13. package/dest/e2e_deploy_contract/deploy_test.js +18 -13
  14. package/dest/e2e_epochs/epochs_test.js +1 -1
  15. package/dest/e2e_fees/bridging_race.notest.js +2 -4
  16. package/dest/e2e_fees/fees_test.d.ts +13 -13
  17. package/dest/e2e_fees/fees_test.d.ts.map +1 -1
  18. package/dest/e2e_fees/fees_test.js +122 -140
  19. package/dest/e2e_l1_publisher/write_json.d.ts +1 -1
  20. package/dest/e2e_l1_publisher/write_json.d.ts.map +1 -1
  21. package/dest/e2e_l1_publisher/write_json.js +1 -0
  22. package/dest/e2e_nested_contract/nested_contract_test.d.ts +6 -9
  23. package/dest/e2e_nested_contract/nested_contract_test.d.ts.map +1 -1
  24. package/dest/e2e_nested_contract/nested_contract_test.js +32 -40
  25. package/dest/e2e_p2p/inactivity_slash_test.d.ts +3 -3
  26. package/dest/e2e_p2p/inactivity_slash_test.d.ts.map +1 -1
  27. package/dest/e2e_p2p/inactivity_slash_test.js +3 -3
  28. package/dest/e2e_p2p/p2p_network.d.ts +7 -6
  29. package/dest/e2e_p2p/p2p_network.d.ts.map +1 -1
  30. package/dest/e2e_p2p/p2p_network.js +106 -103
  31. package/dest/e2e_token_contract/token_contract_test.d.ts +16 -9
  32. package/dest/e2e_token_contract/token_contract_test.d.ts.map +1 -1
  33. package/dest/e2e_token_contract/token_contract_test.js +90 -92
  34. package/dest/fixtures/e2e_prover_test.d.ts +8 -14
  35. package/dest/fixtures/e2e_prover_test.d.ts.map +1 -1
  36. package/dest/fixtures/e2e_prover_test.js +82 -93
  37. package/dest/fixtures/setup.d.ts +216 -0
  38. package/dest/fixtures/setup.d.ts.map +1 -0
  39. package/dest/fixtures/setup.js +683 -0
  40. package/dest/fixtures/utils.d.ts +5 -191
  41. package/dest/fixtures/utils.d.ts.map +1 -1
  42. package/dest/fixtures/utils.js +4 -615
  43. package/dest/quality_of_service/prometheus_client.d.ts +38 -0
  44. package/dest/quality_of_service/prometheus_client.d.ts.map +1 -0
  45. package/dest/quality_of_service/prometheus_client.js +67 -0
  46. package/dest/shared/cross_chain_test_harness.d.ts +12 -1
  47. package/dest/shared/cross_chain_test_harness.d.ts.map +1 -1
  48. package/dest/shared/gas_portal_test_harness.d.ts +11 -1
  49. package/dest/shared/gas_portal_test_harness.d.ts.map +1 -1
  50. package/dest/simulators/lending_simulator.d.ts +5 -1
  51. package/dest/simulators/lending_simulator.d.ts.map +1 -1
  52. package/dest/spartan/tx_metrics.d.ts +4 -1
  53. package/dest/spartan/tx_metrics.d.ts.map +1 -1
  54. package/dest/spartan/tx_metrics.js +21 -1
  55. package/dest/spartan/utils.d.ts +5 -1
  56. package/dest/spartan/utils.d.ts.map +1 -1
  57. package/dest/spartan/utils.js +25 -8
  58. package/package.json +39 -39
  59. package/src/bench/client_flows/client_flows_benchmark.ts +142 -195
  60. package/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts +107 -142
  61. package/src/e2e_cross_chain_messaging/cross_chain_messaging_test.ts +99 -106
  62. package/src/e2e_deploy_contract/deploy_test.ts +21 -14
  63. package/src/e2e_epochs/epochs_test.ts +1 -1
  64. package/src/e2e_fees/bridging_race.notest.ts +2 -5
  65. package/src/e2e_fees/fees_test.ts +171 -213
  66. package/src/e2e_l1_publisher/write_json.ts +1 -0
  67. package/src/e2e_nested_contract/nested_contract_test.ts +35 -56
  68. package/src/e2e_p2p/inactivity_slash_test.ts +5 -5
  69. package/src/e2e_p2p/p2p_network.ts +165 -167
  70. package/src/e2e_token_contract/token_contract_test.ts +105 -118
  71. package/src/fixtures/e2e_prover_test.ts +107 -136
  72. package/src/fixtures/setup.ts +1009 -0
  73. package/src/fixtures/utils.ts +27 -901
  74. package/src/quality_of_service/prometheus_client.ts +113 -0
  75. package/src/spartan/tx_metrics.ts +21 -1
  76. package/src/spartan/utils.ts +26 -8
  77. package/dest/fixtures/snapshot_manager.d.ts +0 -93
  78. package/dest/fixtures/snapshot_manager.d.ts.map +0 -1
  79. package/dest/fixtures/snapshot_manager.js +0 -488
  80. package/src/fixtures/snapshot_manager.ts +0 -646
@@ -0,0 +1,683 @@
1
+ import { SchnorrAccountContractArtifact } from '@aztec/accounts/schnorr';
2
+ import { generateSchnorrAccounts, getInitialTestAccountsData } from '@aztec/accounts/testing';
3
+ import { createArchiver } from '@aztec/archiver';
4
+ import { AztecNodeService, getConfigEnvVars } from '@aztec/aztec-node';
5
+ import { AztecAddress, EthAddress } from '@aztec/aztec.js/addresses';
6
+ import { BatchCall, getContractClassFromArtifact, waitForProven } from '@aztec/aztec.js/contracts';
7
+ import { publishContractClass, publishInstance } from '@aztec/aztec.js/deployment';
8
+ import { Fr } from '@aztec/aztec.js/fields';
9
+ import { createLogger } from '@aztec/aztec.js/log';
10
+ import { createAztecNodeClient, waitForNode } from '@aztec/aztec.js/node';
11
+ import { AnvilTestWatcher, CheatCodes } from '@aztec/aztec/testing';
12
+ import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
13
+ import { SPONSORED_FPC_SALT } from '@aztec/constants';
14
+ import { isAnvilTestChain } from '@aztec/ethereum/chain';
15
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
16
+ import { getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
17
+ import { NULL_KEY } from '@aztec/ethereum/constants';
18
+ import { deployMulticall3 } from '@aztec/ethereum/contracts';
19
+ import { deployAztecL1Contracts } from '@aztec/ethereum/deploy-aztec-l1-contracts';
20
+ import { DelayedTxUtils, EthCheatCodes, EthCheatCodesWithState, createDelayedL1TxUtilsFromViemWallet, startAnvil } from '@aztec/ethereum/test';
21
+ import { EpochNumber } from '@aztec/foundation/branded-types';
22
+ import { SecretValue } from '@aztec/foundation/config';
23
+ import { randomBytes } from '@aztec/foundation/crypto/random';
24
+ import { tryRmDir } from '@aztec/foundation/fs';
25
+ import { withLogNameSuffix } from '@aztec/foundation/log';
26
+ import { retryUntil } from '@aztec/foundation/retry';
27
+ import { sleep } from '@aztec/foundation/sleep';
28
+ import { DateProvider, TestDateProvider } from '@aztec/foundation/timer';
29
+ import { SponsoredFPCContract } from '@aztec/noir-contracts.js/SponsoredFPC';
30
+ import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
31
+ import { MockGossipSubNetwork, getMockPubSubP2PServiceFactory } from '@aztec/p2p/test-helpers';
32
+ import { protocolContractsHash } from '@aztec/protocol-contracts';
33
+ import { createProverNode } from '@aztec/prover-node';
34
+ import { getPXEConfig } from '@aztec/pxe/server';
35
+ import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract';
36
+ import { tryStop } from '@aztec/stdlib/interfaces/server';
37
+ import { getConfigEnvVars as getTelemetryConfig, initTelemetryClient } from '@aztec/telemetry-client';
38
+ import { BenchmarkTelemetryClient } from '@aztec/telemetry-client/bench';
39
+ import { TestWallet, deployFundedSchnorrAccounts } from '@aztec/test-wallet/server';
40
+ import { getGenesisValues } from '@aztec/world-state/testing';
41
+ import fs from 'fs/promises';
42
+ import { tmpdir } from 'os';
43
+ import path from 'path';
44
+ import { generatePrivateKey, mnemonicToAccount, privateKeyToAccount } from 'viem/accounts';
45
+ import { foundry } from 'viem/chains';
46
+ import { MNEMONIC, TEST_MAX_PENDING_TX_POOL_COUNT, TEST_PEER_CHECK_INTERVAL_MS } from './fixtures.js';
47
+ import { getACVMConfig } from './get_acvm_config.js';
48
+ import { getBBConfig } from './get_bb_config.js';
49
+ import { isMetricsLoggingRequested, setupMetricsLogger } from './logging.js';
50
+ import { getEndToEndTestTelemetryClient } from './with_telemetry_utils.js';
51
+ export { startAnvil };
52
+ const { AZTEC_NODE_URL = '' } = process.env;
53
+ const getAztecUrl = ()=>AZTEC_NODE_URL;
54
+ let telemetry = undefined;
55
+ async function getTelemetryClient(partialConfig = {}) {
56
+ if (!telemetry) {
57
+ const config = {
58
+ ...getTelemetryConfig(),
59
+ ...partialConfig
60
+ };
61
+ telemetry = config.benchmark ? new BenchmarkTelemetryClient() : await initTelemetryClient(config);
62
+ }
63
+ return telemetry;
64
+ }
65
+ if (typeof afterAll === 'function') {
66
+ afterAll(async ()=>{
67
+ await telemetry?.stop();
68
+ });
69
+ }
70
+ export const getPrivateKeyFromIndex = (index)=>{
71
+ const hdAccount = mnemonicToAccount(MNEMONIC, {
72
+ addressIndex: index
73
+ });
74
+ const privKeyRaw = hdAccount.getHdKey().privateKey;
75
+ return privKeyRaw === null ? null : Buffer.from(privKeyRaw);
76
+ };
77
+ /**
78
+ * Sets up shared blob storage using FileStore in the data directory.
79
+ */ export async function setupSharedBlobStorage(config) {
80
+ const sharedBlobPath = path.join(config.dataDirectory, 'shared-blobs');
81
+ await fs.mkdir(sharedBlobPath, {
82
+ recursive: true
83
+ });
84
+ config.blobFileStoreUrls = [
85
+ `file://${sharedBlobPath}`
86
+ ];
87
+ config.blobFileStoreUploadUrl = `file://${sharedBlobPath}`;
88
+ }
89
+ /**
90
+ * Sets up Private eXecution Environment (PXE) and returns the corresponding test wallet.
91
+ * @param aztecNode - An instance of Aztec Node.
92
+ * @param opts - Partial configuration for the PXE.
93
+ * @param logger - The logger to be used.
94
+ * @param useLogSuffix - Whether to add a randomly generated suffix to the PXE debug logs.
95
+ * @returns A test wallet, logger and teardown function.
96
+ */ export async function setupPXEAndGetWallet(aztecNode, opts = {}, logger = getLogger(), useLogSuffix = false) {
97
+ const PXEConfig = {
98
+ ...getPXEConfig(),
99
+ ...opts
100
+ };
101
+ // For tests we only want proving enabled if specifically requested
102
+ PXEConfig.proverEnabled = !!opts.proverEnabled;
103
+ // If no data directory provided, create a temp directory and clean up afterwards
104
+ const configuredDataDirectory = PXEConfig.dataDirectory;
105
+ if (!configuredDataDirectory) {
106
+ PXEConfig.dataDirectory = path.join(tmpdir(), randomBytes(8).toString('hex'));
107
+ }
108
+ const teardown = configuredDataDirectory ? ()=>Promise.resolve() : ()=>tryRmDir(PXEConfig.dataDirectory);
109
+ const wallet = await TestWallet.create(aztecNode, PXEConfig, {
110
+ useLogSuffix
111
+ });
112
+ return {
113
+ wallet,
114
+ logger,
115
+ teardown
116
+ };
117
+ }
118
+ /**
119
+ * Function to setup the test against a remote deployment. It is assumed that L1 contract are already deployed
120
+ */ async function setupWithRemoteEnvironment(account, config, logger, numberOfAccounts) {
121
+ const aztecNodeUrl = getAztecUrl();
122
+ logger.verbose(`Creating Aztec Node client to remote host ${aztecNodeUrl}`);
123
+ const aztecNode = createAztecNodeClient(aztecNodeUrl);
124
+ await waitForNode(aztecNode, logger);
125
+ logger.verbose('JSON RPC client connected to Aztec Node');
126
+ logger.verbose(`Retrieving contract addresses from ${aztecNodeUrl}`);
127
+ const { l1ContractAddresses, rollupVersion } = await aztecNode.getNodeInfo();
128
+ const l1Client = createExtendedL1Client(config.l1RpcUrls, account, foundry);
129
+ const deployL1ContractsValues = {
130
+ l1ContractAddresses,
131
+ l1Client,
132
+ rollupVersion
133
+ };
134
+ const ethCheatCodes = new EthCheatCodes(config.l1RpcUrls, new DateProvider());
135
+ const wallet = await TestWallet.create(aztecNode);
136
+ const cheatCodes = await CheatCodes.create(config.l1RpcUrls, aztecNode, new DateProvider());
137
+ const teardown = ()=>Promise.resolve();
138
+ logger.verbose('Populating wallet from already registered accounts...');
139
+ const initialFundedAccounts = await getInitialTestAccountsData();
140
+ if (initialFundedAccounts.length < numberOfAccounts) {
141
+ throw new Error(`Required ${numberOfAccounts} accounts. Found ${initialFundedAccounts.length}.`);
142
+ }
143
+ const testAccounts = await Promise.all(initialFundedAccounts.slice(0, numberOfAccounts).map(async (account)=>{
144
+ const accountManager = await wallet.createSchnorrAccount(account.secret, account.salt, account.signingKey);
145
+ return accountManager.address;
146
+ }));
147
+ return {
148
+ anvil: undefined,
149
+ aztecNode,
150
+ aztecNodeService: undefined,
151
+ aztecNodeAdmin: undefined,
152
+ sequencer: undefined,
153
+ proverNode: undefined,
154
+ deployL1ContractsValues,
155
+ config,
156
+ aztecNodeConfig: config,
157
+ initialFundedAccounts,
158
+ wallet,
159
+ accounts: testAccounts,
160
+ logger,
161
+ cheatCodes,
162
+ ethCheatCodes,
163
+ prefilledPublicData: undefined,
164
+ mockGossipSubNetwork: undefined,
165
+ watcher: undefined,
166
+ dateProvider: undefined,
167
+ telemetryClient: undefined,
168
+ acvmConfig: undefined,
169
+ bbConfig: undefined,
170
+ directoryToCleanup: undefined,
171
+ teardown
172
+ };
173
+ }
174
+ /**
175
+ * Sets up the environment for the end-to-end tests.
176
+ * @param numberOfAccounts - The number of new accounts to be created once the PXE is initiated.
177
+ * @param opts - Options to pass to the node initialization and to the setup script.
178
+ * @param pxeOpts - Options to pass to the PXE initialization.
179
+ */ export async function setup(numberOfAccounts = 1, opts = {}, pxeOpts = {}, chain = foundry) {
180
+ let anvil;
181
+ try {
182
+ opts.aztecTargetCommitteeSize ??= 0;
183
+ opts.slasherFlavor ??= 'none';
184
+ const config = {
185
+ ...getConfigEnvVars(),
186
+ ...opts
187
+ };
188
+ // use initialValidators for the node config
189
+ config.validatorPrivateKeys = new SecretValue(opts.initialValidators?.map((v)=>v.privateKey) ?? []);
190
+ config.peerCheckIntervalMS = TEST_PEER_CHECK_INTERVAL_MS;
191
+ config.maxPendingTxCount = opts.maxPendingTxCount ?? TEST_MAX_PENDING_TX_POOL_COUNT;
192
+ // For tests we only want proving enabled if specifically requested
193
+ config.realProofs = !!opts.realProofs;
194
+ // Only enforce the time table if requested
195
+ config.enforceTimeTable = !!opts.enforceTimeTable;
196
+ config.listenAddress = '127.0.0.1';
197
+ const logger = getLogger();
198
+ // Create a temp directory for any services that need it and cleanup later
199
+ const directoryToCleanup = path.join(tmpdir(), randomBytes(8).toString('hex'));
200
+ await fs.mkdir(directoryToCleanup, {
201
+ recursive: true
202
+ });
203
+ if (!config.dataDirectory) {
204
+ config.dataDirectory = directoryToCleanup;
205
+ }
206
+ if (!config.l1RpcUrls?.length) {
207
+ if (!isAnvilTestChain(chain.id)) {
208
+ throw new Error(`No ETHEREUM_HOSTS set but non anvil chain requested`);
209
+ }
210
+ if (AZTEC_NODE_URL) {
211
+ throw new Error(`AZTEC_NODE_URL provided but no ETHEREUM_HOSTS set. Refusing to run, please set both variables so tests can deploy L1 contracts to the same Anvil instance`);
212
+ }
213
+ const res = await startAnvil({
214
+ l1BlockTime: opts.ethereumSlotDuration,
215
+ accounts: opts.anvilAccounts,
216
+ port: opts.anvilPort
217
+ });
218
+ anvil = res.anvil;
219
+ config.l1RpcUrls = [
220
+ res.rpcUrl
221
+ ];
222
+ }
223
+ // Enable logging metrics to a local file named after the test suite
224
+ if (isMetricsLoggingRequested()) {
225
+ const filename = path.join('log', getJobName() + '.jsonl');
226
+ logger.info(`Logging metrics to ${filename}`);
227
+ setupMetricsLogger(filename);
228
+ }
229
+ const dateProvider = new TestDateProvider();
230
+ const ethCheatCodes = new EthCheatCodesWithState(config.l1RpcUrls, dateProvider);
231
+ if (opts.stateLoad) {
232
+ await ethCheatCodes.loadChainState(opts.stateLoad);
233
+ }
234
+ if (opts.l1StartTime) {
235
+ await ethCheatCodes.warp(opts.l1StartTime, {
236
+ resetBlockInterval: true
237
+ });
238
+ }
239
+ let publisherPrivKeyHex = undefined;
240
+ let publisherHdAccount = undefined;
241
+ if (opts.l1PublisherKey && opts.l1PublisherKey.getValue() && opts.l1PublisherKey.getValue() != NULL_KEY) {
242
+ publisherPrivKeyHex = opts.l1PublisherKey.getValue();
243
+ publisherHdAccount = privateKeyToAccount(publisherPrivKeyHex);
244
+ } else if (config.publisherPrivateKeys && config.publisherPrivateKeys.length > 0 && config.publisherPrivateKeys[0].getValue() != NULL_KEY) {
245
+ publisherPrivKeyHex = config.publisherPrivateKeys[0].getValue();
246
+ publisherHdAccount = privateKeyToAccount(publisherPrivKeyHex);
247
+ } else if (!MNEMONIC) {
248
+ throw new Error(`Mnemonic not provided and no publisher private key`);
249
+ } else {
250
+ publisherHdAccount = mnemonicToAccount(MNEMONIC, {
251
+ addressIndex: 0
252
+ });
253
+ const publisherPrivKeyRaw = publisherHdAccount.getHdKey().privateKey;
254
+ const publisherPrivKey = publisherPrivKeyRaw === null ? null : Buffer.from(publisherPrivKeyRaw);
255
+ publisherPrivKeyHex = `0x${publisherPrivKey.toString('hex')}`;
256
+ config.publisherPrivateKeys = [
257
+ new SecretValue(publisherPrivKeyHex)
258
+ ];
259
+ }
260
+ if (config.coinbase === undefined) {
261
+ config.coinbase = EthAddress.fromString(publisherHdAccount.address);
262
+ }
263
+ if (AZTEC_NODE_URL) {
264
+ // we are setting up against a remote environment, l1 contracts are assumed to already be deployed
265
+ return await setupWithRemoteEnvironment(publisherHdAccount, config, logger, numberOfAccounts);
266
+ }
267
+ // Determine which addresses to fund in genesis
268
+ const initialFundedAccounts = opts.initialFundedAccounts ?? await generateSchnorrAccounts(opts.numberOfInitialFundedAccounts ?? Math.max(numberOfAccounts, 10));
269
+ const addressesToFund = initialFundedAccounts.map((a)=>a.address);
270
+ // Optionally fund the sponsored FPC
271
+ if (opts.fundSponsoredFPC) {
272
+ const sponsoredFPCAddress = await getSponsoredFPCAddress();
273
+ addressesToFund.push(sponsoredFPCAddress);
274
+ }
275
+ const { genesisArchiveRoot, prefilledPublicData, fundingNeeded } = await getGenesisValues(addressesToFund, opts.initialAccountFeeJuice, opts.genesisPublicData);
276
+ const wasAutomining = await ethCheatCodes.isAutoMining();
277
+ const enableAutomine = opts.automineL1Setup && !wasAutomining && isAnvilTestChain(chain.id);
278
+ if (enableAutomine) {
279
+ await ethCheatCodes.setAutomine(true);
280
+ }
281
+ const l1Client = createExtendedL1Client(config.l1RpcUrls, publisherHdAccount, chain);
282
+ // Deploy Multicall3 if running locally
283
+ await deployMulticall3(l1Client, logger);
284
+ // Force viem to refresh its nonce cache to avoid "nonce too low" errors in subsequent transactions
285
+ // This is necessary because deployMulticall3 sends multiple transactions and viem may cache a stale nonce
286
+ await l1Client.getTransactionCount({
287
+ address: l1Client.account.address
288
+ });
289
+ const deployL1ContractsValues = await deployAztecL1Contracts(config.l1RpcUrls[0], publisherPrivKeyHex, chain.id, {
290
+ ...getL1ContractsConfigEnvVars(),
291
+ ...opts,
292
+ ...opts.l1ContractsArgs,
293
+ vkTreeRoot: getVKTreeRoot(),
294
+ protocolContractsHash,
295
+ genesisArchiveRoot,
296
+ initialValidators: opts.initialValidators,
297
+ feeJuicePortalInitialBalance: fundingNeeded,
298
+ realVerifier: false
299
+ });
300
+ config.l1Contracts = deployL1ContractsValues.l1ContractAddresses;
301
+ config.rollupVersion = deployL1ContractsValues.rollupVersion;
302
+ if (enableAutomine) {
303
+ await ethCheatCodes.setAutomine(false);
304
+ await ethCheatCodes.setIntervalMining(config.ethereumSlotDuration);
305
+ dateProvider.setTime(await ethCheatCodes.timestamp() * 1000);
306
+ }
307
+ if (opts.l2StartTime) {
308
+ await ethCheatCodes.warp(opts.l2StartTime, {
309
+ resetBlockInterval: true
310
+ });
311
+ }
312
+ const watcher = new AnvilTestWatcher(new EthCheatCodesWithState(config.l1RpcUrls, dateProvider), deployL1ContractsValues.l1ContractAddresses.rollupAddress, deployL1ContractsValues.l1Client, dateProvider);
313
+ if (!opts.disableAnvilTestWatcher) {
314
+ await watcher.start();
315
+ }
316
+ // Use metricsPort-based telemetry if provided, otherwise use the regular telemetry client
317
+ const telemetryClient = opts.metricsPort ? await getEndToEndTestTelemetryClient(opts.metricsPort) : await getTelemetryClient(opts.telemetryConfig);
318
+ await setupSharedBlobStorage(config);
319
+ logger.verbose('Creating and synching an aztec node', config);
320
+ const acvmConfig = await getACVMConfig(logger);
321
+ if (acvmConfig) {
322
+ config.acvmWorkingDirectory = acvmConfig.acvmWorkingDirectory;
323
+ config.acvmBinaryPath = acvmConfig.acvmBinaryPath;
324
+ }
325
+ const bbConfig = await getBBConfig(logger);
326
+ if (bbConfig) {
327
+ config.bbBinaryPath = bbConfig.bbBinaryPath;
328
+ config.bbWorkingDirectory = bbConfig.bbWorkingDirectory;
329
+ }
330
+ let mockGossipSubNetwork;
331
+ let p2pClientDeps = undefined;
332
+ if (opts.mockGossipSubNetwork) {
333
+ mockGossipSubNetwork = new MockGossipSubNetwork();
334
+ p2pClientDeps = {
335
+ p2pServiceFactory: getMockPubSubP2PServiceFactory(mockGossipSubNetwork)
336
+ };
337
+ }
338
+ // Transactions built against the genesis state must be included in block 1, otherwise they are dropped.
339
+ // To avoid test failures from dropped transactions, we ensure progression beyond genesis before proceeding.
340
+ // For account deployments, we set minTxsPerBlock=1 and deploy accounts sequentially for guaranteed success.
341
+ // If no accounts need deployment, we await an empty block to confirm network progression.
342
+ const originalMinTxsPerBlock = config.minTxsPerBlock;
343
+ if (originalMinTxsPerBlock === undefined) {
344
+ throw new Error('minTxsPerBlock is undefined in e2e test setup');
345
+ }
346
+ // Only set minTxsPerBlock=1 if we're going to deploy accounts and need reliable block inclusion
347
+ const shouldDeployAccounts = numberOfAccounts > 0 && !opts.skipAccountDeployment;
348
+ // Only set minTxsPerBlock=0 if we need an empty block (no accounts at all, not skipped deployment)
349
+ const needsEmptyBlock = numberOfAccounts === 0 && !opts.skipAccountDeployment;
350
+ config.minTxsPerBlock = shouldDeployAccounts ? 1 : needsEmptyBlock ? 0 : originalMinTxsPerBlock;
351
+ config.p2pEnabled = opts.mockGossipSubNetwork || config.p2pEnabled;
352
+ config.p2pIp = opts.p2pIp ?? config.p2pIp ?? '127.0.0.1';
353
+ if (!config.disableValidator) {
354
+ if ((config.validatorPrivateKeys?.getValue().length ?? 0) === 0) {
355
+ config.validatorPrivateKeys = new SecretValue([
356
+ generatePrivateKey()
357
+ ]);
358
+ }
359
+ }
360
+ const aztecNodeService = await AztecNodeService.createAndSync(config, {
361
+ dateProvider,
362
+ telemetry: telemetryClient,
363
+ p2pClientDeps,
364
+ logger: createLogger('node:MAIN-aztec-node')
365
+ }, {
366
+ prefilledPublicData
367
+ });
368
+ const sequencerClient = aztecNodeService.getSequencer();
369
+ if (sequencerClient) {
370
+ const publisher = sequencerClient.sequencer.publisher;
371
+ publisher.l1TxUtils = DelayedTxUtils.fromL1TxUtils(publisher.l1TxUtils, config.ethereumSlotDuration, l1Client);
372
+ }
373
+ let proverNode = undefined;
374
+ if (opts.startProverNode) {
375
+ logger.verbose('Creating and syncing a simulated prover node...');
376
+ const proverNodePrivateKey = getPrivateKeyFromIndex(2);
377
+ const proverNodePrivateKeyHex = `0x${proverNodePrivateKey.toString('hex')}`;
378
+ const proverNodeDataDirectory = path.join(directoryToCleanup, randomBytes(8).toString('hex'));
379
+ const proverNodeConfig = {
380
+ ...config.proverNodeConfig,
381
+ dataDirectory: proverNodeDataDirectory,
382
+ p2pEnabled: false
383
+ };
384
+ proverNode = await createAndSyncProverNode(proverNodePrivateKeyHex, config, proverNodeConfig, aztecNodeService, prefilledPublicData);
385
+ }
386
+ logger.verbose('Creating a pxe...');
387
+ const pxeConfig = {
388
+ ...getPXEConfig(),
389
+ ...pxeOpts
390
+ };
391
+ pxeConfig.dataDirectory = path.join(directoryToCleanup, randomBytes(8).toString('hex'));
392
+ // For tests we only want proving enabled if specifically requested
393
+ pxeConfig.proverEnabled = !!pxeOpts.proverEnabled;
394
+ const wallet = await TestWallet.create(aztecNodeService, pxeConfig);
395
+ const cheatCodes = await CheatCodes.create(config.l1RpcUrls, aztecNodeService, dateProvider);
396
+ if (opts.aztecTargetCommitteeSize && opts.aztecTargetCommitteeSize > 0 || opts.initialValidators && opts.initialValidators.length > 0) {
397
+ // We need to advance such that the committee is set up.
398
+ await cheatCodes.rollup.advanceToEpoch(EpochNumber.fromBigInt(BigInt(await cheatCodes.rollup.getEpoch()) + BigInt(config.lagInEpochsForValidatorSet + 1)));
399
+ await cheatCodes.rollup.setupEpoch();
400
+ await cheatCodes.rollup.debugRollup();
401
+ }
402
+ let accounts = [];
403
+ if (shouldDeployAccounts) {
404
+ logger.info(`${numberOfAccounts} accounts are being deployed. Reliably progressing past genesis by setting minTxsPerBlock to 1 and waiting for the accounts to be deployed`);
405
+ const accountsData = initialFundedAccounts.slice(0, numberOfAccounts);
406
+ const accountManagers = await deployFundedSchnorrAccounts(wallet, aztecNodeService, accountsData);
407
+ accounts = accountManagers.map((accountManager)=>accountManager.address);
408
+ } else if (needsEmptyBlock) {
409
+ logger.info('No accounts are being deployed, waiting for an empty block 1 to be mined');
410
+ while(await aztecNodeService.getBlockNumber() === 0){
411
+ await sleep(2000);
412
+ }
413
+ }
414
+ // If skipAccountDeployment is true, we don't deploy or wait - tests will handle account deployment later
415
+ // Now we restore the original minTxsPerBlock setting if we changed it.
416
+ if (sequencerClient && config.minTxsPerBlock !== originalMinTxsPerBlock) {
417
+ sequencerClient.getSequencer().updateConfig({
418
+ minTxsPerBlock: originalMinTxsPerBlock
419
+ });
420
+ }
421
+ if (initialFundedAccounts.length < numberOfAccounts) {
422
+ throw new Error(`Unable to deploy ${numberOfAccounts} accounts. Only ${initialFundedAccounts.length} accounts were funded.`);
423
+ }
424
+ const teardown = async ()=>{
425
+ try {
426
+ await tryStop(wallet, logger);
427
+ await tryStop(aztecNodeService, logger);
428
+ await tryStop(proverNode, logger);
429
+ if (acvmConfig?.cleanup) {
430
+ await acvmConfig.cleanup();
431
+ }
432
+ if (bbConfig?.cleanup) {
433
+ await bbConfig.cleanup();
434
+ }
435
+ await tryStop(watcher, logger);
436
+ await tryStop(anvil, logger);
437
+ await tryRmDir(directoryToCleanup, logger);
438
+ } catch (err) {
439
+ logger.error(`Error during e2e test teardown`, err);
440
+ }
441
+ };
442
+ return {
443
+ anvil,
444
+ aztecNode: aztecNodeService,
445
+ aztecNodeService,
446
+ aztecNodeAdmin: aztecNodeService,
447
+ cheatCodes,
448
+ ethCheatCodes,
449
+ config,
450
+ aztecNodeConfig: config,
451
+ dateProvider,
452
+ deployL1ContractsValues,
453
+ initialFundedAccounts,
454
+ logger,
455
+ mockGossipSubNetwork,
456
+ prefilledPublicData,
457
+ proverNode,
458
+ sequencer: sequencerClient,
459
+ teardown,
460
+ telemetryClient,
461
+ wallet,
462
+ accounts,
463
+ watcher,
464
+ acvmConfig,
465
+ bbConfig,
466
+ directoryToCleanup
467
+ };
468
+ } catch (err) {
469
+ await anvil?.stop();
470
+ throw err;
471
+ }
472
+ }
473
+ /** Returns the job name for the current test. */ function getJobName() {
474
+ return process.env.JOB_NAME ?? expect.getState().currentTestName?.split(' ')[0].replaceAll('/', '_') ?? 'unknown';
475
+ }
476
+ /**
477
+ * Returns a logger instance for the current test.
478
+ */ export function getLogger() {
479
+ const describeBlockName = expect.getState().currentTestName?.split(' ')[0].replaceAll('/', ':');
480
+ if (!describeBlockName) {
481
+ const name = expect.getState().testPath?.split('/').pop()?.split('.')[0] ?? 'unknown';
482
+ return createLogger('e2e:' + name);
483
+ }
484
+ return createLogger('e2e:' + describeBlockName);
485
+ }
486
+ /**
487
+ * Computes the address of the "canonical" SponsoredFPCContract.
488
+ */ export function getSponsoredFPCInstance() {
489
+ return Promise.resolve(getContractInstanceFromInstantiationParams(SponsoredFPCContract.artifact, {
490
+ salt: new Fr(SPONSORED_FPC_SALT)
491
+ }));
492
+ }
493
+ /**
494
+ * Computes the address of the "canonical" SponsoredFPCContract.
495
+ */ export async function getSponsoredFPCAddress() {
496
+ const sponsoredFPCInstance = await getSponsoredFPCInstance();
497
+ return sponsoredFPCInstance.address;
498
+ }
499
+ /**
500
+ * Deploy a sponsored FPC contract to a running instance.
501
+ */ export async function setupSponsoredFPC(wallet) {
502
+ const instance = await getContractInstanceFromInstantiationParams(SponsoredFPCContract.artifact, {
503
+ salt: new Fr(SPONSORED_FPC_SALT)
504
+ });
505
+ await wallet.registerContract(instance, SponsoredFPCContract.artifact);
506
+ getLogger().info(`SponsoredFPC: ${instance.address}`);
507
+ return instance;
508
+ }
509
+ /**
510
+ * Registers the SponsoredFPC in this PXE instance.
511
+ */ export async function registerSponsoredFPC(wallet) {
512
+ await wallet.registerContract(await getSponsoredFPCInstance(), SponsoredFPCContract.artifact);
513
+ }
514
+ export async function waitForProvenChain(node, targetBlock, timeoutSec = 60, intervalSec = 1) {
515
+ targetBlock ??= await node.getBlockNumber();
516
+ await retryUntil(async ()=>await node.getProvenBlockNumber() >= targetBlock, 'proven chain status', timeoutSec, intervalSec);
517
+ }
518
+ export function createAndSyncProverNode(proverNodePrivateKey, aztecNodeConfig, proverNodeConfig, aztecNode, prefilledPublicData = [], proverNodeDeps = {}) {
519
+ return withLogNameSuffix('prover-node', async ()=>{
520
+ const aztecNodeTxProvider = aztecNode && {
521
+ getTxByHash: aztecNode.getTxByHash.bind(aztecNode),
522
+ getTxsByHash: aztecNode.getTxsByHash.bind(aztecNode),
523
+ stop: ()=>Promise.resolve()
524
+ };
525
+ const blobClient = await createBlobClientWithFileStores(aztecNodeConfig, createLogger('blob-client:prover-node'));
526
+ const archiverConfig = {
527
+ ...aztecNodeConfig,
528
+ dataDirectory: proverNodeConfig.dataDirectory
529
+ };
530
+ const archiver = await createArchiver(archiverConfig, {
531
+ blobClient,
532
+ dateProvider: proverNodeDeps.dateProvider
533
+ }, {
534
+ blockUntilSync: true
535
+ });
536
+ const proverConfig = {
537
+ ...aztecNodeConfig,
538
+ txCollectionNodeRpcUrls: [],
539
+ realProofs: false,
540
+ proverAgentCount: 2,
541
+ publisherPrivateKeys: [
542
+ new SecretValue(proverNodePrivateKey)
543
+ ],
544
+ proverNodeMaxPendingJobs: 10,
545
+ proverNodeMaxParallelBlocksPerEpoch: 32,
546
+ proverNodePollingIntervalMs: 200,
547
+ txGatheringIntervalMs: 1000,
548
+ txGatheringBatchSize: 10,
549
+ txGatheringMaxParallelRequestsPerNode: 10,
550
+ txGatheringTimeoutMs: 24_000,
551
+ proverNodeFailedEpochStore: undefined,
552
+ proverId: EthAddress.fromNumber(1),
553
+ proverNodeEpochProvingDelayMs: undefined,
554
+ ...proverNodeConfig
555
+ };
556
+ const l1TxUtils = createDelayedL1TxUtils(aztecNodeConfig, proverNodePrivateKey, 'prover-node', proverNodeDeps.dateProvider);
557
+ const proverNode = await createProverNode(proverConfig, {
558
+ ...proverNodeDeps,
559
+ aztecNodeTxProvider,
560
+ archiver: archiver,
561
+ l1TxUtils
562
+ }, {
563
+ prefilledPublicData
564
+ });
565
+ getLogger().info(`Created and synced prover node`, {
566
+ publisherAddress: l1TxUtils.client.account.address
567
+ });
568
+ if (!proverNodeConfig.dontStart) {
569
+ await proverNode.start();
570
+ }
571
+ return proverNode;
572
+ });
573
+ }
574
+ function createDelayedL1TxUtils(aztecNodeConfig, privateKey, logName, dateProvider) {
575
+ const l1Client = createExtendedL1Client(aztecNodeConfig.l1RpcUrls, privateKey, foundry);
576
+ const log = createLogger(logName);
577
+ const l1TxUtils = createDelayedL1TxUtilsFromViemWallet(l1Client, log, dateProvider, aztecNodeConfig);
578
+ l1TxUtils.enableDelayer(aztecNodeConfig.ethereumSlotDuration);
579
+ return l1TxUtils;
580
+ }
581
+ export function getBalancesFn(symbol, method, from, logger) {
582
+ const balances = async (...addressLikes)=>{
583
+ const addresses = addressLikes.map((addressLike)=>'address' in addressLike ? addressLike.address : addressLike);
584
+ const b = await Promise.all(addresses.map((address)=>method(address).simulate({
585
+ from
586
+ })));
587
+ const debugString = `${symbol} balances: ${addresses.map((address, i)=>`${address}: ${b[i]}`).join(', ')}`;
588
+ logger.verbose(debugString);
589
+ return b;
590
+ };
591
+ return balances;
592
+ }
593
+ export async function expectMapping(fn, inputs, expectedOutputs) {
594
+ expect(inputs.length).toBe(expectedOutputs.length);
595
+ const outputs = await fn(...inputs);
596
+ expect(outputs).toEqual(expectedOutputs);
597
+ }
598
+ export async function expectMappingDelta(initialValues, fn, inputs, expectedDiffs) {
599
+ expect(inputs.length).toBe(expectedDiffs.length);
600
+ const outputs = await fn(...inputs);
601
+ const diffs = outputs.map((output, i)=>output - initialValues[i]);
602
+ expect(diffs).toEqual(expectedDiffs);
603
+ }
604
+ /**
605
+ * Registers the contract class used for test accounts and publicly deploys the instances requested.
606
+ * Use this when you need to make a public call to an account contract, such as for requesting a public authwit.
607
+ */ export async function ensureAccountContractsPublished(wallet, accountsToDeploy) {
608
+ const accountsAndAddresses = await Promise.all(accountsToDeploy.map(async (address)=>{
609
+ return {
610
+ address,
611
+ deployed: (await wallet.getContractMetadata(address)).isContractPublished
612
+ };
613
+ }));
614
+ const instances = (await Promise.all(accountsAndAddresses.filter(({ deployed })=>!deployed).map(({ address })=>wallet.getContractMetadata(address)))).map((contractMetadata)=>contractMetadata.instance);
615
+ const contractClass = await getContractClassFromArtifact(SchnorrAccountContractArtifact);
616
+ if (!(await wallet.getContractClassMetadata(contractClass.id)).isContractClassPubliclyRegistered) {
617
+ await (await publishContractClass(wallet, SchnorrAccountContractArtifact)).send({
618
+ from: accountsToDeploy[0]
619
+ }).wait();
620
+ }
621
+ const requests = instances.map((instance)=>publishInstance(wallet, instance));
622
+ const batch = new BatchCall(wallet, requests);
623
+ await batch.send({
624
+ from: accountsToDeploy[0]
625
+ }).wait();
626
+ }
627
+ /**
628
+ * Helper function to deploy accounts.
629
+ * Returns deployed account data that can be used by tests.
630
+ */ export const deployAccounts = (numberOfAccounts, logger)=>async ({ wallet, initialFundedAccounts })=>{
631
+ if (initialFundedAccounts.length < numberOfAccounts) {
632
+ throw new Error(`Cannot deploy more than ${initialFundedAccounts.length} initial accounts.`);
633
+ }
634
+ logger.verbose('Deploying accounts funded with fee juice...');
635
+ const deployedAccounts = initialFundedAccounts.slice(0, numberOfAccounts);
636
+ // Serial due to https://github.com/AztecProtocol/aztec-packages/issues/12045
637
+ for(let i = 0; i < deployedAccounts.length; i++){
638
+ const accountManager = await wallet.createSchnorrAccount(deployedAccounts[i].secret, deployedAccounts[i].salt, deployedAccounts[i].signingKey);
639
+ const deployMethod = await accountManager.getDeployMethod();
640
+ await deployMethod.send({
641
+ from: AztecAddress.ZERO,
642
+ skipClassPublication: i !== 0
643
+ }).wait();
644
+ }
645
+ return {
646
+ deployedAccounts
647
+ };
648
+ };
649
+ /**
650
+ * Registers the contract class used for test accounts and publicly deploys the instances requested.
651
+ * Use this when you need to make a public call to an account contract, such as for requesting a public authwit.
652
+ */ export async function publicDeployAccounts(wallet, accountsToDeploy, waitUntilProven = false, node) {
653
+ const instances = (await Promise.all(accountsToDeploy.map((account)=>wallet.getContractMetadata(account)))).map((metadata)=>metadata.instance);
654
+ const contractClass = await getContractClassFromArtifact(SchnorrAccountContractArtifact);
655
+ const alreadyRegistered = (await wallet.getContractClassMetadata(contractClass.id)).isContractClassPubliclyRegistered;
656
+ const calls = await Promise.all([
657
+ ...!alreadyRegistered ? [
658
+ publishContractClass(wallet, SchnorrAccountContractArtifact)
659
+ ] : [],
660
+ ...instances.map((instance)=>publishInstance(wallet, instance))
661
+ ]);
662
+ const batch = new BatchCall(wallet, calls);
663
+ const txReceipt = await batch.send({
664
+ from: accountsToDeploy[0]
665
+ }).wait();
666
+ if (waitUntilProven) {
667
+ if (!node) {
668
+ throw new Error('Need to provide an AztecNode to wait for proven.');
669
+ } else {
670
+ await waitForProven(node, txReceipt);
671
+ }
672
+ }
673
+ }
674
+ /**
675
+ * Destroys the current context.
676
+ */ export async function teardown(context) {
677
+ if (!context) {
678
+ return;
679
+ }
680
+ await context.teardown();
681
+ }
682
+ // Re-export for backward compatibility
683
+ export { deployAndInitializeTokenAndBridgeContracts } from '../shared/cross_chain_test_harness.js';