@aztec/end-to-end 4.0.0-nightly.20260114 → 4.0.0-nightly.20260116

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